answer
stringlengths
17
10.2M
package org.jetbrains.idea.svn; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.VcsConfiguration; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.idea.svn.api.Depth; import org.jetbrains.idea.svn.properties.PropertyValue; import org.junit.Test; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Random; import static com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.is; import static org.jetbrains.idea.svn.SvnPropertyKeys.SVN_IGNORE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; public class SvnIgnoreTest extends SvnTestCase { @Override public void setUp() throws Exception { super.setUp(); enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); enableSilentOperation(VcsConfiguration.StandardConfirmation.REMOVE); } @Test public void testOneFileCreatedDeep() throws Exception { final VirtualFile versionedParent = createDirInCommand(myWorkingCopyDir, "versionedParent"); final String name = "ign123"; File file = virtualToIoFile(versionedParent); vcs.getFactory(file).createPropertyClient().setProperty(file, SVN_IGNORE, PropertyValue.create(name + "\n"), Depth.EMPTY, true); checkin(); update(); final List<VirtualFile> ignored = new ArrayList<>(); final VirtualFile ignChild = createDirInCommand(versionedParent, name); ignored.add(ignChild); VirtualFile current = ignChild; for (int i = 0; i < 10; i++) { current = createDirInCommand(current, "dir" + i); ignored.add(current); refreshChanges(); assertNoChanges(); } testOneFile(current, "file.txt"); final Random rnd = new Random(17); for (int i = 0; i < 20; i++) { final int idx = rnd.nextInt(ignored.size()); testOneFile(ignored.get(idx), "file" + i + ".txt"); } } @Test public void testManyDeep() throws Exception { final VirtualFile versionedParent = createDirInCommand(myWorkingCopyDir, "versionedParent"); final String name = "ign123"; final String name2 = "ign321"; File file = virtualToIoFile(versionedParent); vcs.getFactory().createPropertyClient() .setProperty(file, SVN_IGNORE, PropertyValue.create(name + "\n" + name2 + "\n"), Depth.EMPTY, true); checkin(); update(); final List<VirtualFile> ignored = new ArrayList<>(); final VirtualFile ignChild = createDirInCommand(versionedParent, name); final VirtualFile ignChild2 = createDirInCommand(versionedParent, name2); ignored.add(ignChild); ignored.add(ignChild2); VirtualFile current = ignChild; for (int i = 0; i < 10; i++) { current = createDirInCommand(current, "dir" + i); ignored.add(current); } current = ignChild2; for (int i = 0; i < 10; i++) { current = createDirInCommand(current, "dir" + i); ignored.add(current); } final Random rnd = new Random(17); final List<VirtualFile> vf = new ArrayList<>(); for (int i = 0; i < 200; i++) { final int idx = rnd.nextInt(ignored.size()); vf.add(createFileInCommand(ignored.get(idx), "file" + i + ".txt", "***")); } for (int i = 0; i < 50; i++) { final VirtualFile virtualFile = vf.get(rnd.nextInt(vf.size())); testImpl(virtualFile); } } private void testOneFile(VirtualFile current, final String name) { final VirtualFile file = createFileInCommand(current, name, "123"); testImpl(file); } private void testImpl(VirtualFile file) { refreshChanges(); assertNoChanges(); dirtyScopeManager.fileDirty(file); changeListManager.ensureUpToDate(false); assertNoChanges(); final FileStatus status = changeListManager.getStatus(file); assertEquals(FileStatus.IGNORED, status); } private void assertNoChanges() { assertThat(changeListManager.getDefaultChangeList().getChanges(), is(empty())); } }
package edu.mit.streamjit.test.apps.des2; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.primitives.Ints; import edu.mit.streamjit.api.DuplicateSplitter; import edu.mit.streamjit.api.Filter; import edu.mit.streamjit.api.Identity; import edu.mit.streamjit.api.Input; import edu.mit.streamjit.api.OneToOneElement; import edu.mit.streamjit.api.Pipeline; import edu.mit.streamjit.api.Rate; import edu.mit.streamjit.api.RoundrobinJoiner; import edu.mit.streamjit.api.RoundrobinSplitter; import edu.mit.streamjit.api.Splitjoin; import edu.mit.streamjit.api.StreamCompiler; import edu.mit.streamjit.impl.compiler2.Compiler2StreamCompiler; import edu.mit.streamjit.impl.interp.DebugStreamCompiler; import edu.mit.streamjit.test.AbstractBenchmark; import edu.mit.streamjit.test.Benchmarker; import edu.mit.streamjit.test.Datasets; import java.nio.ByteOrder; import java.nio.file.Paths; /** * Rewritten StreamIt's asplos06 benchmarks. Refer STREAMIT_HOME/apps/benchmarks/asplos06/des/streamit/DES2.str for original * implementations. Each StreamIt's language constructs (i.e., pipeline, filter and splitjoin) are rewritten as classes in StreamJit. * * @author Sumanan sumanan@mit.edu * @since Mar 13, 2013 */ public final class DES2 { private DES2() {} public static void main(String[] args) throws InterruptedException { StreamCompiler sc = new DebugStreamCompiler(); Benchmarker.runBenchmark(new DES2Benchmark(), sc).get(0).print(System.out); } // used for printing descriptor in output private static final boolean PRINTINFO = false; private static final int PLAINTEXT = 0; private static final int USERKEY = 1; private static final int CIPHERTEXT = 2; // algorithm has 16 total rounds private static final int MAXROUNDS = 4; // sample user keys // int[34][2] USERKEYS public static final int[][] USERKEYS = { { 0x00000000, 0x00000000 }, // 0x0000000000000000 { 0xFFFFFFFF, 0xFFFFFFFF }, // 0xFFFFFFFFFFFFFFFF { 0x30000000, 0x00000000 }, // 0x3000000000000000 { 0x11111111, 0x11111111 }, // 0x1111111111111111 { 0x01234567, 0x89ABCDEF }, // 0x0123456789ABCDEF { 0x11111111, 0x11111111 }, // 0x1111111111111111 { 0x00000000, 0x00000000 }, // 0x0000000000000000 { 0xFEDCBA98, 0x76543210 }, // 0xFEDCBA9876543210 { 0x7CA11045, 0x4A1A6E57 }, // 0x7CA110454A1A6E57 { 0x0131D961, 0x9DC1376E }, // 0x0131D9619DC1376E { 0x07A1133E, 0x4A0B2686 }, // 0x07A1133E4A0B2686 { 0x3849674C, 0x2602319E }, // 0x3849674C2602319E { 0x04B915BA, 0x43FEB5B6 }, // 0x04B915BA43FEB5B6 { 0x0113B970, 0xFD34F2CE }, // 0x0113B970FD34F2CE { 0x0170F175, 0x468FB5E6 }, // 0x0170F175468FB5E6 { 0x43297FAD, 0x38E373FE }, // 0x43297FAD38E373FE { 0x07A71370, 0x45DA2A16 }, // 0x07A7137045DA2A16 { 0x04689104, 0xC2FD3B2F }, // 0x04689104C2FD3B2F { 0x37D06BB5, 0x16CB7546 }, // 0x37D06BB516CB7546 { 0x1F08260D, 0x1AC2465E }, // 0x1F08260D1AC2465E { 0x58402364, 0x1ABA6176 }, // 0x584023641ABA6176 { 0x02581616, 0x4629B007 }, // 0x025816164629B007 { 0x49793EBC, 0x79B3258F }, // 0x49793EBC79B3258F { 0x4FB05E15, 0x15AB73A7 }, // 0x4FB05E1515AB73A7 { 0x49E95D6D, 0x4CA229BF }, // 0x49E95D6D4CA229BF { 0x018310DC, 0x409B26D6 }, // 0x018310DC409B26D6 { 0x1C587F1C, 0x13924FEF }, // 0x1C587F1C13924FEF { 0x01010101, 0x01010101 }, // 0x0101010101010101 { 0x1F1F1F1F, 0x0E0E0E0E }, // 0x1F1F1F1F0E0E0E0E { 0xE0FEE0FE, 0xF1FEF1FE }, // 0xE0FEE0FEF1FEF1FE { 0x00000000, 0x00000000 }, // 0x0000000000000000 { 0xFFFFFFFF, 0xFFFFFFFF }, // 0xFFFFFFFFFFFFFFFF { 0x01234567, 0x89ABCDEF }, // 0x0123456789ABCDEF { 0xFEDCBA98, 0x76543210 } }; // 0xFEDCBA9876543210 // PC1 permutation for key schedule // int[56] PC1 public static final int[] PC1 = { 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 }; // PC2 permutation for key schedule // int[48] PC2 public static final int[] PC2 = { 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 }; // key rotation table for key schedule // int[16] RT public static final int[] RT = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; // initial permuation // int[64] IP public static final int[] IP = { 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 }; // expansion permutation (bit selection) // int[48] E public static final int[] E = { 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1 }; // P permutation of sbox output // int[32] P public static final int[] P = { 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 }; // inverse intial permuation // int[64] IPm1 public static final int[] IPm1 = { 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25 }; // provides sbox permutations for DES encryption // int[4][16] S1 public static final int[][] S1 = { { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 }, { 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8 }, { 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0 }, { 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 } }; // int[4][16] S2 public static final int[][] S2 = { { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 }, { 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5 }, { 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15 }, { 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 } }; // int[4][16] S3 public static final int[][] S3 = { { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 }, { 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1 }, { 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7 }, { 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 } }; // int[4][16] S4 public static final int[][] S4 = { { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 }, { 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9 }, { 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4 }, { 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 } }; // int[4][16] S5 public static final int[][] S5 = { { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 }, { 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6 }, { 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14 }, { 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 } }; // int[4][16] S6 public static final int[][] S6 = { { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 }, { 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8 }, { 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6 }, { 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 } }; // int[4][16] S7 public static final int[][] S7 = { { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 }, { 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6 }, { 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2 }, { 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 } }; // int[4][16] S8 public static final int[][] S8 = { { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 }, { 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2 }, { 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8 }, { 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 } }; public static final class DES2Benchmark extends AbstractBenchmark { public DES2Benchmark() { super("DES2", new Dataset("des.in", (Input)Input.fromBinaryFile(Paths.get("data/des.in"), Integer.class, ByteOrder.LITTLE_ENDIAN) // , (Supplier)Suppliers.ofInstance((Input)Input.fromBinaryFile(Paths.get("/home/jbosboom/streamit/streams/apps/benchmarks/asplos06/des/streamit/des2.out"), Integer.class, ByteOrder.LITTLE_ENDIAN)) )); } @Override @SuppressWarnings("unchecked") public OneToOneElement<Object, Object> instantiate() { return (OneToOneElement)new DES2Kernel(); } } private static final class DES2Kernel extends Pipeline<Integer, Integer> { private static final int testvector = 7; private DES2Kernel() { add(new DEScoder(testvector)); } } private static final class DEScoder extends Pipeline<Integer, Integer> { private DEScoder(int vector) { // initial permutation of 64 bit plain text add(new doIP()); for (int i = 0; i < DES2.MAXROUNDS; i++) add(new Splitjoin<>(new DuplicateSplitter<Integer>(), new RoundrobinJoiner<Integer>(32), new nextR(vector, i), new nextL())); add(new CrissCross()); add(new doIPm1()); } } private static final class doIP extends Filter<Integer, Integer> { private doIP() { super(64, 64, 64); // TODO: Verify the peek value } public void work() { for (int i = 0; i < 64; i++) { push(peek(IP[i] - 1)); } for (int i = 0; i < 64; i++) { pop(); } } } // L[i+1] is lower 32 bits of current 64 bit input // input is LR[i] private static final class nextL extends Filter<Integer, Integer> { private nextL() { super(64, 32); } public void work() { for (int i = 0; i < 32; i++) { push(pop()); } for (int i = 0; i < 32; i++) { pop(); // L[i] is decimated } } } // R[i+1] is f(R[i]) xor L[i] // R[i] is lower 32 bits of input stream // L[i] is upper 32 bits of input stream // input is LR[i] // output is f(R[i]) xor L[i] private static final class nextR extends Pipeline<Integer, Integer> { private nextR(int vector, int round) { add(new Splitjoin<Integer, Integer>(new RoundrobinSplitter<Integer>(32), new RoundrobinJoiner<Integer>(), new f(vector, round), new Identity<Integer>()) ); add(new Xor(2)); } } private static final class f extends Pipeline<Integer, Integer> { private f(int vector, int round) { // expand R from 32 to 48 bits and xor with key // add splitjoin { // split roundrobin(32, 0); add(new doE()); add(new KeySchedule(vector, round)); // join roundrobin; add(new Xor(2)); // apply substitutions to generate 32 bit cipher add(new Sboxes()); // permute the bits add(new doP()); } } private static final class doE extends Filter<Integer, Integer> { private doE() { super(Rate.create(32), Rate.create(48), Rate.create(Ints.min(E), Ints.max(E))); } public void work() { for (int i = 0; i < 48; i++) { push(peek(E[i] - 1)); } for (int i = 0; i < 32; i++) { pop(); } } } private static final class doP extends Filter<Integer, Integer> { private doP() { super(32, 32, 32); // TODO: Verify the peek value } public void work() { // input bit stream is from MSB ... LSB // that is LSB is head of FIFO, MSB is tail of FIFO // as in b63 b62 b61 b60 ... b3 b2 b1 b0 // but P permutation requires bit numbering from left to right // as in b1 b2 b3 b4 ... b61 b62 b63 b64 // (note indexing from 0 vs 1) // permutation P permutes the bits and emits them // in reverse order for (int i = 31; i >= 0; i push(peek(32 - P[i])); } for (int i = 0; i < 32; i++) { pop(); } } } private static final class doIPm1 extends Filter<Integer, Integer> { private doIPm1() { super(64, 64, 64); // TODO: Verify the peek value } public void work() { for (int i = 0; i < 64; i++) { push(peek(IPm1[i] - 1)); } for (int i = 0; i < 64; i++) { pop(); } } } /** * This filter represents the first anonymous filter exists inside "int->int pipeline KeySchedule" */ private static final class KeyScheduleFilter1 extends Filter<Integer, Integer> { private final int[][] keys; private final int vector; private final int round; private KeyScheduleFilter1(int vector, int round) { super(48, 96); this.vector = vector; this.round = round; keys = new int[DES2.MAXROUNDS][48]; init(); } // precalculate key schedule private void init() { int[] k64 = new int[64]; for (int w = 1; w >= 0; w int v = USERKEYS[vector][w]; // LSW first then MSW int m = 1; for (int i = 0; i < 32; i++) { if (((v & m) >> i) != 0) k64[((1 - w) * 32) + i] = 1; else k64[((1 - w) * 32) + i] = 0; m = m << 1; } } // apply PC1 int[] k56 = new int[56]; for (int i = 0; i < 56; i++) { // input bit stream is from MSB ... LSB // that is LSB is head of FIFO, MSB is tail of FIFO // as in b63 b62 b61 b60 ... b3 b2 b1 b0 // but PC1 permutation requires bit numbering from left to right // as in b1 b2 b3 b4 ... b61 b62 b63 b64 // (note indexing from 0 vs 1) k56[i] = k64[64 - PC1[i]]; } for (int r = 0; r < MAXROUNDS; r++) { // rotate left and right 28-bit bits chunks // according to round number int[] bits = new int[56]; for (int i = 0; i < 28; i++) bits[i] = k56[(i + RT[r]) % 28]; for (int i = 28; i < 56; i++) bits[i] = k56[28 + ((i + RT[r]) % 28)]; for (int i = 0; i < 56; i++) k56[i] = bits[i]; // apply PC2 and store resultant key for (int i = 47; i >= 0; i // input bit stream is from MSB ... LSB // that is LSB is head of FIFO, MSB is tail of FIFO // as in b63 b62 b61 b60 ... b3 b2 b1 b0 // permutation PC2 permutes the bits then emits them // in reverse order keys[r][47 - i] = k56[PC2[i] - 1]; } } } public void work() { for (int i = 0; i < 48; i++) { push(keys[round][i]); push(pop()); } } } /** * This filter represents the second anonymous filter exists inside "int->int pipeline KeySchedule" */ private static final class KeyScheduleFilter2 extends Filter<Integer, Integer> { private final int vector; private final int pushRate; private final int popRate; private KeyScheduleFilter2(int popRate, int pushRate, int vector) { super(popRate, pushRate); this.vector = vector; this.pushRate = pushRate; this.popRate = popRate; } public void work() { for (int i = 0; i < popRate; i++) pop(); push(USERKEYS[vector][1]); // LSW push(USERKEYS[vector][0]); // MSW } } /** * This filter represents the first anonymous pipeline exists inside "int->int pipeline KeySchedule" */ private static final class KeySchedulePipeline1 extends Pipeline<Integer, Integer> { private KeySchedulePipeline1(int popRate, int pushRate, int vector) { add(new KeyScheduleFilter2(popRate, pushRate, vector)); add(new IntoBits()); add(new HexPrinter(USERKEY, 64)); } } private static final class KeySchedule extends Pipeline<Integer, Integer> { private KeySchedule(int vector, int round) { add(new KeyScheduleFilter1(vector, round)); if (PRINTINFO && (round == 0)) { // FIXME: join roundrobin(1, 0); add(new Splitjoin<Integer, Integer>(new DuplicateSplitter<Integer>(), new RoundrobinJoiner<Integer>(), new Identity<Integer>(), new KeySchedulePipeline1(96, 2, vector))); } } } /** * This filter represents the first anonymous filter exists inside "void->int pipeline slowKeySchedule" */ private static final class slowKeyScheduleFilter1 extends Filter<Void, Integer> { private final int vector; private slowKeyScheduleFilter1(int vector) { super(0, 2); this.vector = vector; } public void work() { push(USERKEYS[vector][1]); // LSW push(USERKEYS[vector][0]); // MSW } } // inefficient but straightforward implementation of key schedule; it // recalculates all keys for all previous rounds 1...i-1 private static final class slowKeySchedule extends Pipeline<Void, Integer> { private slowKeySchedule(int vector, int round) { add(new slowKeyScheduleFilter1(vector)); add(new IntoBits()); add(new doPC1()); for (int i = 0; i < round + 1; i++) { add(new Splitjoin<Integer, Integer>(new RoundrobinSplitter<Integer>(28), new RoundrobinJoiner<Integer>(28), new LRotate(i), new LRotate(i))); } // or more simply can do: // add LRotate(i); add(new doPC2()); if (PRINTINFO && (round == 0)) { // FIXME: join roundrobin(1, 0); add(new Splitjoin<Integer, Integer>(new DuplicateSplitter<Integer>(), new RoundrobinJoiner<Integer>(), new Identity<Integer>(), new KeySchedulePipeline1(48, 2, vector))); } } } // left rotate input stream of length 28-bits by RT[round] private static final class LRotate extends Filter<Integer, Integer> { private static final int n = 28; private final int round; private final int x; private LRotate(int round) { super(n, n, n); this.round = round; x = RT[round]; } public void work() { for (int i = 0; i < n; i++) { push(peek((i + x) % n)); } for (int i = 0; i < n; i++) { pop(); } } } private static final class doPC1 extends Filter<Integer, Integer> { private doPC1() { super(64, 56, 64); // TODO: Verify the peek value } public void work() { for (int i = 0; i < 56; i++) { // input bit stream is from MSB ... LSB // that is LSB is head of FIFO, MSB is tail of FIFO // as in b63 b62 b61 b60 ... b3 b2 b1 b0 // but PC1 permutation requires bit numbering from left to right // as in b1 b2 b3 b4 ... b61 b62 b63 b64 // (note indexing from 0 vs 1) push(peek(64 - PC1[i])); } for (int i = 0; i < 64; i++) { pop(); } } } private static final class doPC2 extends Filter<Integer, Integer> { private doPC2() { super(56, 48, 48); // TODO: Verify the peek value } public void work() { // input bit stream is from MSB ... LSB // that is LSB is head of FIFO, MSB is tail of FIFO // as in b63 b62 b61 b60 ... b3 b2 b1 b0 // permutation PC2 permutes the bits then emits them // in reverse order for (int i = 47; i >= 0; i push(peek(PC2[i] - 1)); } for (int i = 0; i < 56; i++) { pop(); } } } private static final class Sboxes extends Filter<Integer, Integer> { private Sboxes() { super(6 * 8, 4 * 8); } public void work() { for (int i = 1; i <= 8; i++) { int r = pop(); // r = first and last bit int c = pop(); // c = middle four bits c = (pop() << 1) | c; c = (pop() << 2) | c; c = (pop() << 3) | c; r = (pop() << 1) | r; int out = 0; if (i == 1) out = S8[r][c]; // lower 8 bits else if (i == 2) out = S7[r][c]; // next 8 bits else if (i == 3) out = S6[r][c]; else if (i == 4) out = S5[r][c]; else if (i == 5) out = S4[r][c]; else if (i == 6) out = S3[r][c]; else if (i == 7) out = S2[r][c]; else if (i == 8) out = S1[r][c]; // last (upper) 8 bits push((int) ((out & 0x1) >> 0)); push((int) ((out & 0x2) >> 1)); push((int) ((out & 0x4) >> 2)); push((int) ((out & 0x8) >> 3)); } } } private static final class PlainTextSourceFilter1 extends Filter<Void, Integer> { private final int vector; // int[34][2] TEXT private static final int[][] TEXT = { { 0x00000000, 0x00000000 }, // 0x0000000000000000 { 0xFFFFFFFF, 0xFFFFFFFF }, // 0xFFFFFFFFFFFFFFFF { 0x10000000, 0x00000001 }, // 0x1000000000000001 { 0x11111111, 0x11111111 }, // 0x1111111111111111 { 0x11111111, 0x11111111 }, // 0x1111111111111111 { 0x01234567, 0x89ABCDEF }, // 0x0123456789ABCDEF { 0x00000000, 0x00000000 }, // 0x0000000000000000 { 0x01234567, 0x89ABCDEF }, // 0x0123456789ABCDEF { 0x01A1D6D0, 0x39776742 }, // 0x01A1D6D039776742 { 0x5CD54CA8, 0x3DEF57DA }, // 0x5CD54CA83DEF57DA { 0x0248D438, 0x06F67172 }, // 0x0248D43806F67172 { 0x51454B58, 0x2DDF440A }, // 0x51454B582DDF440A { 0x42FD4430, 0x59577FA2 }, // 0x42FD443059577FA2 { 0x059B5E08, 0x51CF143A }, // 0x059B5E0851CF143A { 0x0756D8E0, 0x774761D2 }, // 0x0756D8E0774761D2 { 0x762514B8, 0x29BF486A }, // 0x762514B829BF486A { 0x3BDD1190, 0x49372802 }, // 0x3BDD119049372802 { 0x26955F68, 0x35AF609A }, // 0x26955F6835AF609A { 0x164D5E40, 0x4F275232 }, // 0x164D5E404F275232 { 0x6B056E18, 0x759F5CCA }, // 0x6B056E18759F5CCA { 0x004BD6EF, 0x09176062 }, // 0x004BD6EF09176062 { 0x480D3900, 0x6EE762F2 }, // 0x480D39006EE762F2 { 0x437540C8, 0x698F3CFA }, // 0x437540C8698F3CFA { 0x072D43A0, 0x77075292 }, // 0x072D43A077075292 { 0x02FE5577, 0x8117F12A }, // 0x02FE55778117F12A { 0x1D9D5C50, 0x18F728C2 }, // 0x1D9D5C5018F728C2 { 0x30553228, 0x6D6F295A }, // 0x305532286D6F295A { 0x01234567, 0x89ABCDEF }, // 0x0123456789ABCDEF { 0x01234567, 0x89ABCDEF }, // 0x0123456789ABCDEF { 0x01234567, 0x89ABCDEF }, // 0x0123456789ABCDEF { 0xFFFFFFFF, 0xFFFFFFFF }, // 0xFFFFFFFFFFFFFFFF { 0x00000000, 0x00000000 }, // 0x0000000000000000 { 0x00000000, 0x00000000 }, // 0x0000000000000000 { 0xFFFFFFFF, 0xFFFFFFFF } }; // 0xFFFFFFFFFFFFFFFF private PlainTextSourceFilter1(int vector) { super(0, 2); this.vector = vector; } public void work() { push(TEXT[vector][1]); // LSW push(TEXT[vector][0]); // MSW } } private static final class PlainTextSource extends Pipeline<Void, Integer> { private PlainTextSource(int vector) { add(new PlainTextSourceFilter1(vector)); add(new IntoBits()); if (PRINTINFO) { // FIXME join roundrobin(1, 0); add(new Splitjoin<Integer, Integer>(new DuplicateSplitter<Integer>(), new RoundrobinJoiner<Integer>())); add(new Identity<Integer>()); add(new HexPrinter(PLAINTEXT, 64)); } } } // take N streams and Xor them together // the streams are assumed to be interleaved private static final class Xor extends Filter<Integer, Integer> { private final int n; private Xor(int n) { super(n, 1); this.n = n; } public void work() { int x = pop(); for (int i = 1; i < n; i++) { int y = pop(); x = x ^ y; } push(x); } } // swap two input streams each of 32 bits private static final class CrissCross extends Filter<Integer, Integer> { private CrissCross() { super(64, 64, 64); } public void work() { for (int i = 0; i < 32; i++) { push(peek(32 + i)); } for (int i = 0; i < 32; i++) { push(pop()); } for (int i = 0; i < 32; i++) { pop(); } } } // input: integer // output: LSB first ... MSB last private static final class IntoBits extends Filter<Integer, Integer> { private IntoBits() { super(1, 32); } public void work() { int v = pop(); int m = 1; for (int i = 0; i < 32; i++) { if (((v & m) >> i) != 0) push(1); else push(0); m = m << 1; } } } // input: LSB first ... MSB last // output: integer private static final class BitstoInts extends Filter<Integer, Integer> { private final int n; private BitstoInts(int n) { super(n, 1, n); this.n = n; } public void work() { int v = 0; for (int i = 0; i < n; i++) { v = v | (pop() << i); } push(v); } } // input: w words x b bits/word // output: bit i from all w words, followed by i+1 for all b bits private static final class BitSlice extends Splitjoin<Integer, Integer> { private final int w; private final int b; private BitSlice(int w, int b) { super(new RoundrobinSplitter<Integer>(), new RoundrobinJoiner<Integer>(w)); this.w = w; this.b = b; for (int l = 0; l < b; l++) { add(new Identity<Integer>()); } } } private static final class HexPrinterFilter1 extends Filter<Integer, Void> { private final int descriptor; private final int bytes; private HexPrinterFilter1(int descriptor, int bytes) { super(bytes, 0, bytes); this.bytes = bytes; this.descriptor = descriptor; } public void work() { if (PRINTINFO) { if (descriptor == PLAINTEXT) System.out.print("P: "); else if (descriptor == USERKEY) System.out.print("K: "); else if (descriptor == CIPHERTEXT) System.out.print("C: "); } for (int i = bytes - 1; i >= 0; i int v = peek(i); if (v < 10) System.out.print(v); else if (v == 10) System.out.print("A"); else if (v == 11) System.out.print("B"); else if (v == 12) System.out.print("C"); else if (v == 13) System.out.print("D"); else if (v == 14) System.out.print("E"); else if (v == 15) System.out.print("F"); else { System.out.print("ERROR: "); System.out.println(v); } } System.out.println(""); for (int i = 0; i < bytes; i++) pop(); } } // input: LSB first ... MSB last // output: none // prints: MSW first ... LSW last private static final class HexPrinter extends Pipeline<Integer, Void> { private HexPrinter(int descriptor, int n) { int bits = n; int bytes = bits / 4; add(new BitstoInts(4)); add(new HexPrinter(descriptor, bytes)); } } /** * This represents the anonymous fiter that exixtes inside "int->int splitjoin ShowIntermediate(int n)". */ private static final class ShowIntermediateFilter1 extends Filter<Integer, Void> { private final int bytes; private ShowIntermediateFilter1(int bytes) { super(bytes, 0, bytes); this.bytes = bytes; } public void work() { for (int i = bytes - 1; i >= 0; i int v = peek(i); if (v < 10) System.out.print(v); else if (v == 10) System.out.print("A"); else if (v == 11) System.out.print("B"); else if (v == 12) System.out.print("C"); else if (v == 13) System.out.print("D"); else if (v == 14) System.out.print("E"); else if (v == 15) System.out.print("F"); else { System.out.print("ERROR: "); System.out.println(v); } } System.out.println(""); for (int i = 0; i < bytes; i++) pop(); } } private static final class ShowIntermediatePipeline1 extends Pipeline<Integer, Void> { private ShowIntermediatePipeline1(int bytes) { add(new BitstoInts(4)); add(new ShowIntermediateFilter1(bytes)); } } // input: LSB first ... MSB last // output: LSB first ... MSB last (Identity) // prints: MSW first ... LSW last (HEX format) private static final class ShowIntermediate extends Splitjoin<Integer, Integer> { private ShowIntermediate(int n) { // FIXME join roundrobin(1, 0); super(new DuplicateSplitter<Integer>(), new RoundrobinJoiner<Integer>()); add(new Identity<>()); // FIXME: Need to add this. This is not the join roundrobin(1, 0) issue. The issue here is as join roundrobin(1, // 0), the second filter's output type is void. But Joiner's input type is not void and it receives the input from the // first filter. // add(new ShowIntermediatePipeline1(n / 4)); } } // input: LSB first ... MSB last // output: LSB first ... MSB last (Identity) // prints: MSB first ... LSB last (BINARY format) private static final class ShowBitStream extends Filter<Integer, Integer> { private final int n; private final int w; private ShowBitStream(int n, int w) { super(n, n, n); this.n = n; this.w = w; } public void work() { for (int i = n - 1; i >= 0; i System.out.print(peek(i)); if ((i % w) == 0) System.out.print(" "); } System.out.println(""); for (int i = 0; i < n; i++) push(pop()); } } }
package com.simplenote.android; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import com.simplenote.android.net.Api.Response; import com.simplenote.android.net.HttpCallback; import com.simplenote.android.net.SimpleNoteApi; import com.simplenote.android.persistence.SimpleNoteDao; import com.simplenote.android.thread.SyncNotesThread; public class AlarmReceiver extends BroadcastReceiver { private static final String LOGGING_TAG = Constants.TAG + "AlarmReceiver"; @Override public void onReceive(Context context, Intent intent) { final SimpleNoteDao dao = new SimpleNoteDao(context); try { Log.i(LOGGING_TAG, "Running Alarm!"); final Bundle bundle = intent.getExtras(); final String email = bundle.getString(Preferences.EMAIL); final String password = bundle.getString(Preferences.PASSWORD); SimpleNoteApi.login(email, password, new HttpCallback() { /** * @see com.simplenote.android.net.HttpCallback#on200(com.simplenote.android.net.Api.Response) */ @Override public void on200(Response response) { Log.i(Constants.TAG, "Login auth success with API server."); String auth = response.body; final Thread t = new SyncNotesThread(updateNoteHandler, dao, email, auth); t.start(); } /** * @see com.simplenote.android.net.HttpCallback#onError(com.simplenote.android.net.Api.Response) */ @Override public void onError(Response response) { super.onError(response); // post a notification about failed sync due to credentials } }); } catch (Exception e) { e.printStackTrace(); } } private Handler updateNoteHandler = new Handler() { /** * Messages are received from SyncNotesThread when a Note is updated or retrieved from the server * @see android.os.Handler#handleMessage(android.os.Message) */ @Override public void handleMessage(Message msg) { // do nothing } }; }
package org.jetbrains.idea.svn; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.VcsConfiguration; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.openapi.vcs.changes.ContentRevision; import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager; import com.intellij.openapi.vfs.VirtualFile; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.jetbrains.annotations.NonNls; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * @author yole */ public class SvnRenameTest extends SvnTestCase { @NonNls private static final String LOG_SEPARATOR = " @Test public void testSimpleRename() throws Exception { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); final VirtualFile a = createFileInCommand("a.txt", "test"); checkin(); renameFileInCommand(a, "b.txt"); verify(runSvn("status"), "A + b.txt", "D a.txt"); } // IDEADEV-18844 @Test @Ignore public void testRenameReplace() throws Exception { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); final VirtualFile a = createFileInCommand("a.txt", "old"); final VirtualFile aNew = createFileInCommand("aNew.txt", "new"); checkin(); renameFileInCommand(a, "aOld.txt"); renameFileInCommand(aNew, "a.txt"); final RunResult result = runSvn("status"); verify(result, "R + a.txt", "D aNew.txt", "A + aOld.txt"); } // IDEADEV-16251 @Test public void testRenameAddedPackage() throws Exception { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); final VirtualFile dir = createDirInCommand(myWorkingCopyDir, "child"); createFileInCommand(dir, "a.txt", "content"); renameFileInCommand(dir, "newchild"); verify(runSvn("status"), "A newchild", "A newchild\\a.txt"); } // IDEADEV-8091 @Test public void testDoubleRename() throws Exception { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); final VirtualFile a = createFileInCommand("a.txt", "test"); checkin(); renameFileInCommand(a, "b.txt"); renameFileInCommand(a, "c.txt"); verify(runSvn("status"), "A + c.txt", "D a.txt"); } // IDEADEV-15876 @Test public void testRenamePackageWithChildren() throws Exception { final VirtualFile child = prepareDirectoriesForRename(); renameFileInCommand(child, "newchild"); final RunResult result = runSvn("status"); verify(result, "D child", "D child\\grandChild", "D child\\grandChild\\b.txt", "D child\\a.txt", "A + newchild"); List<Change> changes = getAllChanges(); Assert.assertEquals(4, changes.size()); Collections.sort(changes, new Comparator<Change>() { public int compare(final Change o1, final Change o2) { return o1.getBeforeRevision().getFile().getPath().compareTo(o2.getBeforeRevision().getFile().getPath()); } }); verifyChange(changes.get(0), "child", "newchild"); verifyChange(changes.get(1), "child\\a.txt", "newchild\\a.txt"); verifyChange(changes.get(2), "child\\grandChild", "newchild\\grandChild"); verifyChange(changes.get(3), "child\\grandChild\\b.txt", "newchild\\grandChild\\b.txt"); final VirtualFile newChild = myWorkingCopyDir.findChild("newchild"); assert newChild != null; changes = getChangesForFile(newChild.findChild("a.txt")); Assert.assertEquals(1, changes.size()); verifyChange(changes.get(0), "child\\a.txt", "newchild\\a.txt"); VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty(); final ChangeListManager changeListManager = ChangeListManager.getInstance(myProject); changeListManager.ensureUpToDate(false); Assert.assertEquals(FileStatus.DELETED, changeListManager.getStatus(child)); } private VirtualFile prepareDirectoriesForRename() throws IOException { enableSilentOperation(VcsConfiguration.StandardConfirmation.ADD); final VirtualFile child = createDirInCommand(myWorkingCopyDir, "child"); final VirtualFile grandChild = createDirInCommand(child, "grandChild"); createFileInCommand(child, "a.txt", "a"); createFileInCommand(grandChild, "b.txt", "b"); checkin(); return child; } private void verifyChange(final Change c, final String beforePath, final String afterPath) { verifyRevision(c.getBeforeRevision(), beforePath); verifyRevision(c.getAfterRevision(), afterPath); } private void verifyRevision(final ContentRevision beforeRevision, final String beforePath) { File beforeFile = new File(myWorkingCopyDir.getPath(), beforePath); String beforeFullPath = FileUtil.toSystemIndependentName(beforeFile.getPath()); Assert.assertEquals(beforeFullPath, beforeRevision.getFile().getPath()); } // IDEADEV-19065 @Test public void testCommitAfterRenameDir() throws Exception { final VirtualFile child = prepareDirectoriesForRename(); renameFileInCommand(child, "newchild"); checkin(); final RunResult runResult = runSvn("log", "-q", "newchild/a.txt"); verify(runResult); final List<String> lines = StringUtil.split(runResult.stdOut, LOG_SEPARATOR); Assert.assertEquals(2, lines.size()); Assert.assertTrue(lines.get(0).startsWith("r2 |")); Assert.assertTrue(lines.get(1).startsWith("r1 |")); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates; /** * * @author RoboHawks */ public class drive { Team3373 testing = new Team3373(); tttttt }
package com.trendmicro.arthur.nio.server; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.Channel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; /** * * @author arthur */ public class NServer { private Selector selector; private Charset charset = Charset.forName("UTF-8"); public void init() throws Exception { selector = Selector.open(); ServerSocketChannel server = ServerSocketChannel.open(); InetSocketAddress isa = new InetSocketAddress("127.0.0.1", 3000); server.socket().bind(isa); server.configureBlocking(false); server.register(selector, SelectionKey.OP_ACCEPT); while (selector.select() > 0) { for (SelectionKey key : selector.selectedKeys()) { selector.selectedKeys().remove(key); if (key.isAcceptable()) { SocketChannel sc = server.accept(); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); key.interestOps(SelectionKey.OP_ACCEPT); } if (key.isReadable()) { SocketChannel sc = (SocketChannel)key.channel(); ByteBuffer buff = ByteBuffer.allocate(1024); String content = ""; try { while (sc.read(buff) > 0) { buff.flip(); content += charset.decode(buff); buff.clear(); } System.out.println("=====" + content); key.interestOps(SelectionKey.OP_READ); } catch (IOException e) { key.cancel(); if (key.channel() != null) key.channel().close(); } if (content.length() > 0) { for (SelectionKey sk : selector.keys()) { Channel targetChannel = sk.channel(); if (targetChannel instanceof SocketChannel) { SocketChannel dest = (SocketChannel)targetChannel; dest.write(charset.encode(content)); } } } else { sc.close(); key.cancel(); } } } } } public static void main(String[] args) throws Exception { new NServer().init(); } }
package org.biojava.nbio.structure.io; import org.biojava.nbio.structure.EntityInfo; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class TestMMcifOrganismParsing { @BeforeClass public static void setUp() throws Exception { AtomCache cache = new AtomCache(); cache.setUseMmCif(true); StructureIO.setAtomCache(cache); } @Test public void test1STP() throws IOException, StructureException{ String pdbId = "1stp"; checkPDB(pdbId, "1895"); } // removed this test, since entity 3 of 1a4w has no organism tax_id public void test1a4w() throws IOException, StructureException{ String pdbId = "1a4w"; checkPDB(pdbId, "9606"); } @Test public void test4hhb() throws IOException, StructureException{ String pdbId = "4hhb"; checkPDB(pdbId, "9606"); } @Test public void test3ZD6() throws IOException, StructureException { // a PDB ID that contains a synthetic entity String pdbId = "3zd6"; checkPDB(pdbId, "9606"); } private void checkPDB(String pdbId, String organismTaxId) throws IOException, StructureException { Structure s = StructureIO.getStructure(pdbId); assertNotNull(s.getEntityInformation()); assertTrue(s.getEntityInformation().size() > 0); for ( EntityInfo c : s.getEntityInformation()) { if(c.getType().equals("polymer")) { assertNotNull(c.getOrganismTaxId()); if(pdbId.equals("3zd6")){ if(c.getMolId()==2) { assertEquals(c.getOrganismTaxId(), "32630"); continue; } } assertEquals(c.getOrganismTaxId(), organismTaxId); } } } }
package org.elasticsearch.gradle.test; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.BuildTask; import org.gradle.testkit.runner.GradleRunner; import org.gradle.testkit.runner.TaskOutcome; import org.junit.Rule; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.lang.management.ManagementFactory; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.hamcrest.CoreMatchers.containsString; public abstract class GradleIntegrationTestCase extends GradleUnitTestCase { @Rule public TemporaryFolder testkitTmpDir = new TemporaryFolder(); protected File getProjectDir(String name) { File root = new File("src/testKit/"); if (root.exists() == false) { throw new RuntimeException( "Could not find resources dir for integration tests. " + "Note that these tests can only be ran by Gradle and are not currently supported by the IDE" ); } return new File(root, name).getAbsoluteFile(); } protected GradleRunner getGradleRunner(String sampleProject) { File testkit; try { testkit = testkitTmpDir.newFolder(); } catch (IOException e) { throw new UncheckedIOException(e); } return GradleRunner.create() .withProjectDir(getProjectDir(sampleProject)) .withPluginClasspath() .withTestKitDir(testkit) .withDebug(ManagementFactory.getRuntimeMXBean().getInputArguments().toString().indexOf("-agentlib:jdwp") > 0); } protected File getBuildDir(String name) { return new File(getProjectDir(name), "build"); } protected void assertOutputContains(String output, String... lines) { for (String line : lines) { assertOutputContains(output, line); } List<Integer> index = Stream.of(lines).map(line -> output.indexOf(line)).collect(Collectors.toList()); if (index.equals(index.stream().sorted().collect(Collectors.toList())) == false) { fail( "Expected the following lines to appear in this order:\n" + Stream.of(lines).map(line -> " - `" + line + "`").collect(Collectors.joining("\n")) + "\nTBut the order was different. Output is:\n\n```" + output + "\n```\n" ); } } protected void assertOutputContains(String output, Set<String> lines) { for (String line : lines) { assertOutputContains(output, line); } } protected void assertOutputContains(String output, String line) { assertThat("Expected the following line in output:\n\n" + line + "\n\nOutput is:\n" + output, output, containsString(line)); } protected void assertOutputDoesNotContain(String output, String line) { assertFalse("Expected the following line not to be in output:\n\n" + line + "\n\nOutput is:\n" + output, output.contains(line)); } protected void assertOutputDoesNotContain(String output, String... lines) { for (String line : lines) { assertOutputDoesNotContain(line); } } protected void assertTaskFailed(BuildResult result, String taskName) { assertTaskOutcome(result, taskName, TaskOutcome.FAILED); } protected void assertTaskSuccessful(BuildResult result, String... taskNames) { for (String taskName : taskNames) { assertTaskOutcome(result, taskName, TaskOutcome.SUCCESS); } } protected void assertTaskSkipped(BuildResult result, String... taskNames) { for (String taskName : taskNames) { assertTaskOutcome(result, taskName, TaskOutcome.SKIPPED); } } protected void assertTaskNoSource(BuildResult result, String... taskNames) { for (String taskName : taskNames) { assertTaskOutcome(result, taskName, TaskOutcome.NO_SOURCE); } } private void assertTaskOutcome(BuildResult result, String taskName, TaskOutcome taskOutcome) { BuildTask task = result.task(taskName); if (task == null) { fail( "Expected task `" + taskName + "` to be " + taskOutcome + ", but it did not run" + "\n\nOutput is:\n" + result.getOutput() ); } assertEquals( "Expected task `" + taskName + "` to be " + taskOutcome + " but it was: " + task.getOutcome() + "\n\nOutput is:\n" + result.getOutput(), taskOutcome, task.getOutcome() ); } protected void assertTaskUpToDate(BuildResult result, String... taskNames) { for (String taskName : taskNames) { BuildTask task = result.task(taskName); if (task == null) { fail("Expected task `" + taskName + "` to be up-to-date, but it did not run"); } assertEquals( "Expected task to be up to date but it was: " + task.getOutcome() + "\n\nOutput is:\n" + result.getOutput(), TaskOutcome.UP_TO_DATE, task.getOutcome() ); } } protected void assertNoDeprecationWarning(BuildResult result) { assertOutputDoesNotContain(result.getOutput(), "Deprecated Gradle features were used in this build"); } protected void assertBuildFileExists(BuildResult result, String projectName, String path) { Path absPath = getBuildDir(projectName).toPath().resolve(path); assertTrue( result.getOutput() + "\n\nExpected `" + absPath + "` to exists but it did not" + "\n\nOutput is:\n" + result.getOutput(), Files.exists(absPath) ); } protected void assertBuildFileDoesNotExists(BuildResult result, String projectName, String path) { Path absPath = getBuildDir(projectName).toPath().resolve(path); assertFalse( result.getOutput() + "\n\nExpected `" + absPath + "` bo to exists but it did" + "\n\nOutput is:\n" + result.getOutput(), Files.exists(absPath) ); } protected String getLocalTestDownloadsPath() { return getLocalTestPath("test.local-test-downloads-path"); } private String getLocalTestPath(String propertyName) { String property = System.getProperty(propertyName); Objects.requireNonNull(property, propertyName + " not passed to tests"); File file = new File(property); assertTrue("Expected " + property + " to exist, but it did not!", file.exists()); if (File.separator.equals("\\")) { // Use / on Windows too, the build script is not happy with \ return file.getAbsolutePath().replace(File.separator, "/"); } else { return file.getAbsolutePath(); } } public void assertOutputOnlyOnce(String output, String... text) { for (String each : text) { int i = output.indexOf(each); if (i == -1) { fail("Expected \n```" + each + "```\nto appear at most once, but it didn't at all.\n\nOutout is:\n" + output); } if (output.indexOf(each) != output.lastIndexOf(each)) { fail("Expected `" + each + "` to appear at most once, but it did multiple times.\n\nOutout is:\n" + output); } } } }
package fitnesse.slim; import java.io.PrintWriter; import java.io.StringWriter; public abstract class Jsr223StatementExecutor implements StatementExecutorInterface{ protected Jsr223Bridge bridge; private Object statementExecutorProxy; public Jsr223StatementExecutor(Jsr223Bridge bridge) { this.bridge = bridge; statementExecutorProxy = bridge.getStatementExecutor(); } protected Object getStatementExecutorProxy() { return statementExecutorProxy; } @Override public void addPath(String path) { callMethod("addPath", new Object[] {path}); } @Override public Object call(String instanceName, String methodName, Object... args) { return callMethod("call", new Object[] {instanceName, methodName, args}); } @Override public void create(String instanceName, String className, Object... args) { callMethod("create", new Object[] {instanceName, className, args}); } @Override public Object getInstance(String instanceName) { return callMethod("getInstance", new Object[] {instanceName}); } @Override public void assign(String name, Object value) { callMethod("setVariable", new Object[] {name, value}); } @Override public boolean stopHasBeenRequested() { return (Boolean) callMethod("stopHasBeenRequested"); } @Override public void reset() { callMethod("reset"); } protected Object callMethod(String method, Object... args) { try { return bridge.invokeMethod(getStatementExecutorProxy(), method, args); } catch (Throwable e) { // NOSONAR return exceptionToString(e); } } private String exceptionToString(Throwable exception) { StringWriter stringWriter = new StringWriter(); PrintWriter pw = new PrintWriter(stringWriter); exception.printStackTrace(pw); return SlimServer.EXCEPTION_TAG + stringWriter.toString(); } }
package ch.elexis.core.services.holder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import org.apache.commons.lang3.StringUtils; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import ch.elexis.core.services.IConfigService; @Component public class ConfigServiceHolder { private static IConfigService configService; @Reference public void setModelService(IConfigService modelService) { ConfigServiceHolder.configService = modelService; } public static IConfigService get() { if (configService == null) { throw new IllegalStateException("No IConfigService available"); } return configService; } public static boolean isPresent() { return configService != null; } // global access methods public static String getGlobal(String key, String defaultValue) { return configService.get(key, defaultValue); } public static String getGlobalCached(String key, String defaultValue) { return configService.get(key, defaultValue, false); } public static int getGlobal(String key, int defaultValue) { return configService.get(key, defaultValue); } public static boolean getGlobal(String key, boolean defaultValue) { return configService.get(key, defaultValue); } public static List<String> getGlobalAsList(String key) { String string = getGlobal(key, (String) null); if (string != null) { String[] split = string.split(","); if (split != null && split.length > 0) { return Arrays.asList(split); } } return Collections.emptyList(); } public static String[] getGlobalStringArray(String key) { String raw = getGlobal(key, null); if (StringUtils.isBlank(raw)) { return null; } return raw.split(","); } @Deprecated public static boolean setGlobal(String key, String value) { return configService.set(key, value); } @Deprecated public static boolean setGlobal(String key, boolean value) { return configService.set(key, value); } public static void setGlobalAsList(String key, List<String> values) { Optional<String> value = values.stream().map(o -> o.toString()).reduce((u, t) -> u + "," + t); if (value.isPresent()) { configService.set(key, value.get()); } else { configService.set(key, null); } } public static boolean setGlobal(String key, int value) { return configService.set(key, value); } public static List<String> getSubNodes(String key) { return configService.getSubNodes(key); } // active user access methods public static String getUser(String key, String defaultValue) { return configService.getActiveUserContact(key, defaultValue); } public static String getUserCached(String key, String defaultValue) { return configService.getActiveUserContact(key, defaultValue, false); } public static boolean getUser(String key, boolean defaultValue) { return configService.getActiveUserContact(key, defaultValue); } public static Integer getUser(String key, int defaultValue) { return configService.getActiveUserContact(key, defaultValue); } public static boolean setUser(String key, String value) { return configService.setActiveUserContact(key, value); } public static boolean setUser(String key, boolean value) { return configService.setActiveUserContact(key, value); } public static boolean setUser(String key, int value) { return configService.setActiveUserContact(key, value); } public static List<String> getUserAsList(String key) { String string = getUser(key, (String) null); if (string != null) { String[] split = string.split(","); if (split != null && split.length > 0) { return Arrays.asList(split); } } return Collections.emptyList(); } public static void setUserAsList(String key, List<String> values) { Optional<String> value = values.stream().map(o -> o.toString()).reduce((u, t) -> u + "," + t); if (value.isPresent()) { configService.setActiveUserContact(key, value.get()); } else { configService.setActiveUserContact(key, null); } } public static void setUserFromMap(Map<Object, Object> map) { configService.setActiveUserContact(map); } public static Map<Object, Object> getUserAsMap() { return configService.getActiveUserContactAsMap(); } // active mandator access methods public static String getMandator(String key, String defaultValue) { return configService.getActiveMandator(key, defaultValue); } public static String getMandatorCached(String key, String defaultValue) { return configService.getActiveMandator(key, defaultValue, false); } public static boolean getMandator(String key, boolean defaultValue) { return configService.getActiveMandator(key, defaultValue); } public static int getMandator(String key, int defaultValue) { return configService.getActiveMandator(key, defaultValue); } public static void setMandator(String key, String value) { configService.setActiveMandator(key, value); } public static void setMandator(String key, boolean value) { configService.setActiveMandator(key, value); } public static List<String> getMandatorAsList(String key) { String string = getMandator(key, (String) null); if (string != null) { String[] split = string.split(","); if (split != null && split.length > 0) { return Arrays.asList(split); } } return Collections.emptyList(); } // local access methods public static boolean getLocal(String key, boolean defaultValue) { return configService.getLocal(key, defaultValue); } public static String getLocal(String key, String defaultValue) { return configService.getLocal(key, defaultValue); } private static List<Runnable> waitForConfigService; public synchronized static void runIfConfigServiceAvailable(Runnable runnable) { if (configService == null) { if (waitForConfigService == null) { CompletableFuture.runAsync(() -> { // wait for configService while (configService == null) { try { Thread.sleep(100); } catch (InterruptedException e) { // ignore } } waitForConfigService.forEach(r -> r.run()); }); waitForConfigService = new ArrayList<>(); } waitForConfigService.add(runnable); } else { runnable.run(); } } }
package de.cooperateproject.ui.nature; import org.apache.log4j.Logger; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import de.cooperateproject.ui.nature.tasks.BackgroundTasksAdapter; public class ProjectOpenedListener implements IResourceChangeListener { private static final Logger LOGGER = Logger.getLogger(ProjectOpenedListener.class); @Override public void resourceChanged(IResourceChangeEvent event) { if (handleNullOrClosing(event)) { return; } try { event.getDelta().accept(new IResourceDeltaVisitor() { public boolean visit(final IResourceDelta delta) throws CoreException { if (isRelevantForClean(delta)) { IProject project = (IProject) delta.getResource(); Job rebuild = new Job("rebuild") { @Override protected IStatus run(IProgressMonitor monitor) { try { project.build(IncrementalProjectBuilder.CLEAN_BUILD, null); } catch (CoreException e) { LOGGER.error("Exception during rebuild after opening of a project", e); return Status.CANCEL_STATUS; } return Status.OK_STATUS; } }; rebuild.schedule(); } if (isRelevantForDelete(delta)) { BackgroundTasksAdapter.getManager().deregisterProject((IProject) delta.getResource()); } return true; } }); } catch (CoreException e) { LOGGER.error("Exception during rebuild after opening or closing of a project", e); } } private static boolean isRelevantForClean(IResourceDelta delta) { if ((delta.getResource().getType() & IResource.PROJECT) == 0) { return false; } if (delta.getKind() == IResourceDelta.CHANGED && (delta.getFlags() & IResourceDelta.OPEN) != 0) { return true; } return false; } private static boolean isRelevantForDelete(IResourceDelta delta) { if ((delta.getResource().getType() & IResource.PROJECT) == 0) { return false; } if (delta.getKind() == IResourceDelta.REMOVED) { return true; } return false; } private boolean handleNullOrClosing(IResourceChangeEvent event) { if (event == null) { return true; } else if (event.getDelta() == null) { if (event.getType() == IResourceChangeEvent.PRE_CLOSE) { BackgroundTasksAdapter.getManager().deregisterProject((IProject) event.getResource()); } return true; } return false; } }
package ch.elexis.core.ui.wizards; import java.util.Hashtable; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import ch.elexis.core.constants.Preferences; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.data.util.DBConnection; import ch.elexis.core.ui.icons.ImageSize; import ch.elexis.core.ui.icons.Images; import ch.elexis.data.PersistentObject; import ch.rgw.tools.StringTool; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; public class DBConnectSelectionConnectionWizardPage extends WizardPage { private Label lblConnection, lblUser, lblDriver, lblTyp; private ComboViewer cViewerConns; private TestDBConnectionGroup tdbg; private Button btnDelStoredConn; /** * @wbp.parser.constructor */ public DBConnectSelectionConnectionWizardPage(String dBConnectWizard_typeOfDB){ super(Messages.DBConnectFirstPage_Connection); setTitle(Messages.DBConnectFirstPage_Connection); setMessage(Messages.DBConnectSelectionConnectionWizardPage_this_message); setImageDescriptor(Images.lookupImageDescriptor("db_configure_banner.png", ImageSize._75x66_TitleDialogIconSize)); } @Override public void createControl(Composite parent){ Composite area = new Composite(parent, SWT.NONE); area.setLayout(new GridLayout(1, false)); setControl(area); Group grpStatCurrentConnection = new Group(area, SWT.NONE); grpStatCurrentConnection.setLayout(new GridLayout(2, true)); grpStatCurrentConnection .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); grpStatCurrentConnection .setText(Messages.DBConnectWizardPage_grpStatCurrentConnection_text); createEntityArea(grpStatCurrentConnection); Composite cmpExistConnSelector = new Composite(area, SWT.BORDER); cmpExistConnSelector.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); cmpExistConnSelector.setLayout(new GridLayout(2, false)); Label lblGespeicherteVerbindungen = new Label(cmpExistConnSelector, SWT.NONE); lblGespeicherteVerbindungen .setText(Messages.DBConnectWizardPage_lblGespeicherteVerbindungen_text); new Label(cmpExistConnSelector, SWT.NONE); cViewerConns = new ComboViewer(cmpExistConnSelector, SWT.READ_ONLY); Combo combo = cViewerConns.getCombo(); combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); cViewerConns.setContentProvider(ArrayContentProvider.getInstance()); cViewerConns.setLabelProvider(new LabelProvider() { @Override public String getText(Object element){ DBConnection dbc = (DBConnection) element; if (dbc.username != null && dbc.connectionString != null) { return dbc.username + "@" + dbc.connectionString; } else { return "Neue Verbindung erstellen"; } } }); cViewerConns.setInput(getDBConnectWizard().getStoredConnectionList()); btnDelStoredConn = new Button(cmpExistConnSelector, SWT.FLAT); btnDelStoredConn.setImage(Images.IMG_DELETE.getImage()); btnDelStoredConn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ IStructuredSelection selection = (IStructuredSelection) cViewerConns.getSelection(); if (selection.size() > 0) { Object firstElement = selection.getFirstElement(); if (firstElement != null) { getDBConnectWizard().removeConnection((DBConnection) firstElement); cViewerConns.setInput(getDBConnectWizard().getStoredConnectionList()); setCurrentSelection(); } } } }); cViewerConns.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event){ IStructuredSelection selection = (IStructuredSelection) event.getSelection(); if (selection.size() > 0) { Object firstElement = selection.getFirstElement(); if (firstElement != null) { getDBConnectWizard().setTargetedConnection((DBConnection) firstElement); btnDelStoredConn.setEnabled(!getDBConnectWizard().getCurrentConnection() .equals(getDBConnectWizard().getTargetedConnection())); } } } }); setCurrentSelection(); Label lblOderAufDer = new Label(cmpExistConnSelector, SWT.NONE); lblOderAufDer.setText(Messages.DBConnectSelectionConnectionWizardPage_lblOderAufDer_text); new Label(cmpExistConnSelector, SWT.NONE); tdbg = new TestDBConnectionGroup(area, SWT.NONE, getDBConnectWizard()); tdbg.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); } private void setCurrentSelection(){ if(getDBConnectWizard().getCurrentConnection()==null) return; cViewerConns.setSelection(new StructuredSelection(getDBConnectWizard() .getCurrentConnection())); } private void createEntityArea(Group grpEntity){ String driver = ""; String user = ""; String typ = ""; String connection = ""; Composite typArea = new Composite(grpEntity, SWT.NONE); typArea.setLayout(new GridLayout(2, false)); Label lTyp = new Label(typArea, SWT.NONE); lTyp.setImage(Images.IMG_TABLE.getImage()); lblTyp = new Label(typArea, SWT.NONE); Composite driverArea = new Composite(grpEntity, SWT.NONE); driverArea.setLayout(new GridLayout(2, false)); Label lDriver = new Label(driverArea, SWT.NONE); lDriver.setImage(Images.IMG_GEAR.getImage()); lblDriver = new Label(driverArea, SWT.NONE); Composite userArea = new Composite(grpEntity, SWT.NONE); userArea.setLayout(new GridLayout(2, false)); Label lUser = new Label(userArea, SWT.NONE); lUser.setImage(Images.IMG_USER_SILHOUETTE.getImage()); lblUser = new Label(userArea, SWT.NONE); Composite connArea = new Composite(grpEntity, SWT.NONE); connArea.setLayout(new GridLayout(2, false)); Label lConnection = new Label(connArea, SWT.NONE); lConnection.setImage(Images.IMG_NODE.getImage()); lblConnection = new Label(connArea, SWT.NONE); Hashtable<Object, Object> conn = readRunningEntityInfos(); if (conn != null) { driver = PersistentObject.checkNull(conn.get(Preferences.CFG_FOLDED_CONNECTION_DRIVER)); connection = PersistentObject.checkNull(conn .get(Preferences.CFG_FOLDED_CONNECTION_CONNECTSTRING)); user = PersistentObject.checkNull(conn.get(Preferences.CFG_FOLDED_CONNECTION_USER)); typ = PersistentObject.checkNull(conn.get(Preferences.CFG_FOLDED_CONNECTION_TYPE)); } lblTyp.setText(typ); lblDriver.setText(driver); lblUser.setText(user); lblConnection.setText(connection); } private Hashtable<Object, Object> readRunningEntityInfos(){ Hashtable<Object, Object> conn = null; String cnt = CoreHub.localCfg.get(Preferences.CFG_FOLDED_CONNECTION, null); if (cnt != null) { conn = PersistentObject.fold(StringTool.dePrintable(cnt)); return conn; } return null; } @Override public void setPageComplete(boolean complete){ super.setPageComplete(complete); } private DBConnectWizard getDBConnectWizard(){ return (DBConnectWizard) getWizard(); } }
package com.griddynamics.jagger.engine.e1.reporting; import com.griddynamics.jagger.dbapi.DatabaseService; import com.griddynamics.jagger.dbapi.dto.MetricNameDto; import com.griddynamics.jagger.engine.e1.services.DataService; import com.griddynamics.jagger.engine.e1.services.DefaultDataService; import com.griddynamics.jagger.engine.e1.services.data.service.MetricEntity; import com.griddynamics.jagger.engine.e1.services.data.service.MetricSummaryValueEntity; import com.griddynamics.jagger.engine.e1.services.data.service.TestEntity; import com.griddynamics.jagger.util.FormatCalculator; import com.griddynamics.jagger.util.MetricNamesRankingProvider; import com.griddynamics.jagger.util.StandardMetricsNamesUtil; import org.springframework.beans.factory.annotation.Required; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.*; public class SummaryReporter { private DatabaseService databaseService; private String sessionId; private Map<TestEntity, Set<MetricEntity>> metricsPerTest; private Map<String, List<SummaryDto>> summaryMap = new HashMap<String, List<SummaryDto>>(); private Map<String, List<SummaryDto>> latencyPercentilesMap = new HashMap<String, List<SummaryDto>>(); private Map<String, List<SummaryDto>> validatorsMap = new HashMap<String, List<SummaryDto>>(); private Map<TestEntity, Map<MetricEntity, MetricSummaryValueEntity>> standardMetricsMap = new HashMap<TestEntity, Map<MetricEntity, MetricSummaryValueEntity>>(); private DateFormat dateFormatter = new SimpleDateFormat(FormatCalculator.DATE_FORMAT); private int numberOfTestGroups; private boolean isMetricHighlighting; @Required public void setMetricHighlighting(boolean isMetricHighlighting) { this.isMetricHighlighting = isMetricHighlighting; } public List<SummaryDto> getSummary(String sessionId, String taskId) { getData(sessionId); if (summaryMap.containsKey(taskId)) { return summaryMap.get(taskId); } else { return null; } } public List<SummaryDto> getValidators(String sessionId, String taskId) { getData(sessionId); if (validatorsMap.containsKey(taskId)) { return validatorsMap.get(taskId); } else { return null; } } public List<SummaryDto> getLatencyPercentile(String sessionId, String taskId) { getData(sessionId); if (latencyPercentilesMap.containsKey(taskId)) { return latencyPercentilesMap.get(taskId); } else { return null; } } public Map<TestEntity, Map<MetricEntity, MetricSummaryValueEntity>> getStandardMetricsPerTest(String sessionId) { getData(sessionId); return standardMetricsMap; } public int getNumberOfTestGroups(String sessionId) { getData(sessionId); return numberOfTestGroups; } private void getData(String sessionId) { // Remember what session id was set for cashed data if (this.sessionId == null) { this.sessionId = sessionId; } // Reset data if new session id arrived if (!sessionId.equals(this.sessionId)) { metricsPerTest = null; this.sessionId = sessionId; } if (metricsPerTest == null) { Set<String> standardMetricsIds = new HashSet<String>(); standardMetricsIds.add(StandardMetricsNamesUtil.THROUGHPUT_ID); standardMetricsIds.add(StandardMetricsNamesUtil.FAIL_COUNT_ID); standardMetricsIds.add(StandardMetricsNamesUtil.SUCCESS_RATE_ID); standardMetricsIds.add(StandardMetricsNamesUtil.LATENCY_ID); standardMetricsIds.add(StandardMetricsNamesUtil.LATENCY_STD_DEV_ID); LocalRankingProvider localRankingProvider = new LocalRankingProvider(); DataService dataService = new DefaultDataService(databaseService); Set<TestEntity> testEntities = dataService.getTests(sessionId); metricsPerTest = dataService.getMetricsByTests(testEntities); Set<Long> testIds = new HashSet<Long>(); for (TestEntity testEntity : testEntities) { testIds.add(testEntity.getId()); } numberOfTestGroups = databaseService.getTestGroupIdsByTestIds(testIds).keySet().size(); for (Map.Entry<TestEntity, Set<MetricEntity>> entry : metricsPerTest.entrySet()) { List<SummaryDto> summaryList = new ArrayList<SummaryDto>(); List<SummaryDto> latencyPercentilesList = new ArrayList<SummaryDto>(); List<SummaryDto> validatorsList = new ArrayList<SummaryDto>(); Map<MetricEntity, MetricSummaryValueEntity> standardMetricsPerTest = new HashMap<MetricEntity, MetricSummaryValueEntity>(); // Metrics Map<MetricEntity, MetricSummaryValueEntity> summary = dataService.getMetricSummary(entry.getValue()); for (MetricEntity metricEntity : summary.keySet()) { SummaryDto value = new SummaryDto(); // All summary value.setKey(metricEntity.getDisplayName()); MetricSummaryValueEntity metricSummaryValueEntity = summary.get(metricEntity); Double summaryValue = metricSummaryValueEntity.getValue(); value.setValue(new DecimalFormat(FormatCalculator.getNumberFormat(summaryValue)).format(summaryValue)); if (isMetricHighlighting && metricSummaryValueEntity.getDecision() != null) { value.setDecision(metricSummaryValueEntity.getDecision().toString()); } // Validators if (metricEntity.getMetricNameDto().getOrigin().equals(MetricNameDto.Origin.VALIDATOR)) { validatorsList.add(value); } // Latency percentiles if (metricEntity.getMetricId().matches("^" + StandardMetricsNamesUtil.LATENCY_PERCENTILE_REGEX)) { // change key (name) for back compatibility value.setKey(metricEntity.getDisplayName().replace("Latency ", "").concat(" - ")); latencyPercentilesList.add(value); } else { summaryList.add(value); } // Standard metrics if (standardMetricsIds.contains(metricEntity.getMetricId())) { standardMetricsPerTest.put(metricEntity, summary.get(metricEntity)); } } localRankingProvider.sortSummaryDto(summaryList); localRankingProvider.sortSummaryDto(validatorsList); localRankingProvider.sortSummaryDto(latencyPercentilesList); // Test info SummaryDto description = new SummaryDto(); description.setKey("Test description"); description.setValue(entry.getKey().getDescription()); summaryList.add(0, description); SummaryDto startTime = new SummaryDto(); startTime.setKey("Start time"); startTime.setValue(dateFormatter.format(entry.getKey().getStartDate())); summaryList.add(0, startTime); SummaryDto termination = new SummaryDto(); termination.setKey("Termination"); termination.setValue(entry.getKey().getTerminationStrategy()); summaryList.add(0, termination); SummaryDto load = new SummaryDto(); load.setKey("Load"); load.setValue(entry.getKey().getLoad()); summaryList.add(0, load); summaryMap.put(entry.getKey().getId().toString(), summaryList); latencyPercentilesMap.put(entry.getKey().getId().toString(), latencyPercentilesList); validatorsMap.put(entry.getKey().getId().toString(), validatorsList); standardMetricsMap.put(entry.getKey(), standardMetricsPerTest); } } } private class LocalRankingProvider extends MetricNamesRankingProvider { public void sortSummaryDto(List<SummaryDto> list) { Collections.sort(list, new Comparator<SummaryDto>() { @Override public int compare(SummaryDto o, SummaryDto o2) { return LocalRankingProvider.compare(o.getKey(), o2.getKey()); } }); } } @Required public void setDatabaseService(DatabaseService databaseService) { this.databaseService = databaseService; } }
package edu.duke.cabig.c3pr.domain.factory; import org.apache.log4j.Logger; import java.util.List; import org.springframework.context.MessageSource; import edu.duke.cabig.c3pr.dao.ParticipantDao; import edu.duke.cabig.c3pr.dao.StudySubjectDao; import edu.duke.cabig.c3pr.domain.Arm; import edu.duke.cabig.c3pr.domain.CoordinatingCenterStudyStatus; import edu.duke.cabig.c3pr.domain.Epoch; import edu.duke.cabig.c3pr.domain.OrganizationAssignedIdentifier; import edu.duke.cabig.c3pr.domain.Participant; import edu.duke.cabig.c3pr.domain.ScheduledEpoch; import edu.duke.cabig.c3pr.domain.SiteStudyStatus; import edu.duke.cabig.c3pr.domain.Study; import edu.duke.cabig.c3pr.domain.StudySite; import edu.duke.cabig.c3pr.domain.StudySubject; import edu.duke.cabig.c3pr.domain.repository.StudyRepository; import edu.duke.cabig.c3pr.exception.C3PRCodedException; import edu.duke.cabig.c3pr.exception.C3PRExceptionHelper; import edu.duke.cabig.c3pr.service.ParticipantService; import edu.duke.cabig.c3pr.service.StudyService; public class StudySubjectFactory { /** * Logger for this class */ private static final Logger logger = Logger.getLogger(StudySubjectFactory.class); private C3PRExceptionHelper exceptionHelper; private MessageSource c3prErrorMessages; private final String identifierTypeValueStr = "Coordinating Center Identifier"; private final String prtIdentifierTypeValueStr = "MRN"; private StudyService studyService; private ParticipantService participantService; private StudyRepository studyRepository; private StudySubjectDao studySubjectDao; private ParticipantDao participantDao; public void setParticipantDao(ParticipantDao participantDao) { this.participantDao = participantDao; } public void setStudySubjectDao(StudySubjectDao studySubjectDao) { this.studySubjectDao = studySubjectDao; } public StudySubject buildStudySubject(StudySubject deserializedStudySubject) throws C3PRCodedException { StudySubject built = new StudySubject(); StudySite studySite = buildStudySite(deserializedStudySubject.getStudySite(), buildStudy(deserializedStudySubject.getStudySite().getStudy())); Participant participant = buildParticipant(deserializedStudySubject.getParticipant()); if (participant.getId() != null) { StudySubject exampleSS = new StudySubject(true); exampleSS.setParticipant(participant); exampleSS.setStudySite(studySite); List<StudySubject> registrations = studySubjectDao .searchBySubjectAndStudySite(exampleSS); if (registrations.size() > 0) { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.STUDYSUBJECTS_ALREADY_EXISTS.CODE")); } } else { if (participant.validateParticipant()) participantDao.save(participant); else { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.SUBJECTS_INVALID_DETAILS.CODE")); } } built.setStudySite(studySite); built.setParticipant(participant); Epoch epoch = buildEpoch(studySite.getStudy().getEpochs(), deserializedStudySubject .getScheduledEpoch()); ScheduledEpoch scheduledEpoch = buildScheduledEpoch(deserializedStudySubject .getScheduledEpoch(), epoch); built.getScheduledEpochs().add(0, scheduledEpoch); fillStudySubjectDetails(built, deserializedStudySubject); return built; } public StudySubject buildReferencedStudySubject(StudySubject deserializedStudySubject) throws C3PRCodedException { StudySubject built = new StudySubject(); StudySite studySite = buildStudySite(deserializedStudySubject.getStudySite(), buildStudy(deserializedStudySubject.getStudySite().getStudy())); Participant participant = buildParticipant(deserializedStudySubject.getParticipant()); built.setStudySite(studySite); built.setParticipant(participant); Epoch epoch = buildEpoch(studySite.getStudy().getEpochs(), deserializedStudySubject .getScheduledEpoch()); ScheduledEpoch scheduledEpoch = buildScheduledEpoch(deserializedStudySubject .getScheduledEpoch(), epoch); built.getScheduledEpochs().add(0, scheduledEpoch); fillStudySubjectDetails(built, deserializedStudySubject); return built; } public Participant buildParticipant(Participant participant) throws C3PRCodedException { if (participant.getIdentifiers() == null || participant.getIdentifiers().size() == 0) { throw exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.MISSING.SUBJECT_IDENTIFIER.CODE")); } for (OrganizationAssignedIdentifier organizationAssignedIdentifier : participant .getOrganizationAssignedIdentifiers()) { if (organizationAssignedIdentifier.getType().equals(this.prtIdentifierTypeValueStr)) { List<Participant> paList = participantService .searchByMRN(organizationAssignedIdentifier); if (paList.size() > 1) { throw exceptionHelper .getException( getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE.SUBJECTS_SAME_MRN.CODE"), new String[] { organizationAssignedIdentifier .getValue() }); } else if (paList.size() == 1) { if (logger.isDebugEnabled()) { logger .debug("buildParticipant(Participant) - Participant with the same MRN found in the database"); } Participant temp = paList.get(0); if (temp.getFirstName().equals(participant.getFirstName()) && temp.getLastName().equals(participant.getLastName()) && temp.getBirthDate().getTime() == participant.getBirthDate() .getTime()) { return temp; } else { throw exceptionHelper .getException( getCode("C3PR.EXCEPTION.REGISTRATION.INVALID.ANOTHER_SUBJECT_SAME_MRN.CODE"), new String[] { organizationAssignedIdentifier .getValue() }); } } } } return participant; } public Study buildStudy(Study study) throws C3PRCodedException { if (study.getIdentifiers() == null || study.getIdentifiers().size() == 0) { throw exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.MISSING.STUDY_IDENTIFIER.CODE")); } List<Study> studies = null; OrganizationAssignedIdentifier identifier = null; for (OrganizationAssignedIdentifier organizationAssignedIdentifier : study .getOrganizationAssignedIdentifiers()) { if (organizationAssignedIdentifier.getType().equals(this.identifierTypeValueStr)) { identifier = organizationAssignedIdentifier; studies = studyRepository .searchByCoOrdinatingCenterId(organizationAssignedIdentifier); break; } } if (identifier == null) { throw exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.MISSING.STUDY_COORDINATING_IDENTIFIER.CODE")); } if (studies == null) { throw exceptionHelper .getException( getCode("C3PR.EXCEPTION.REGISTRATION.NOTFOUND.STUDY_WITH_IDENTIFIER.CODE"), new String[] { identifier.getValue(), this.identifierTypeValueStr }); } if (studies.size() == 0) { throw exceptionHelper .getException( getCode("C3PR.EXCEPTION.REGISTRATION.NOTFOUND.STUDY_WITH_IDENTIFIER.CODE"), new String[] { identifier.getValue(), this.identifierTypeValueStr }); } if (studies.size() > 1) { throw exceptionHelper .getException( getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE.STUDY_SAME_CO_IDENTIFIER.CODE"), new String[] { identifier.getValue(), this.identifierTypeValueStr }); } if (studies.get(0).getCoordinatingCenterStudyStatus() != CoordinatingCenterStudyStatus.OPEN) { throw exceptionHelper.getException( getCode("C3PR.EXCEPTION.REGISTRATION.STUDY_NOT_ACTIVE"), new String[] { identifier.getHealthcareSite().getNciInstituteCode(), identifier.getValue() }); } return studies.get(0); } public StudySite buildStudySite(StudySite studySite, Study study) throws C3PRCodedException { for (StudySite temp : study.getStudySites()) { if (temp.getHealthcareSite().getNciInstituteCode().equals( studySite.getHealthcareSite().getNciInstituteCode())) { if (temp.getSiteStudyStatus() != SiteStudyStatus.ACTIVE) { throw exceptionHelper .getException( getCode("C3PR.EXCEPTION.REGISTRATION.STUDYSITE_NOT_ACTIVE"), new String[] { temp.getHealthcareSite() .getNciInstituteCode() }); } return temp; } } throw exceptionHelper .getException( getCode("C3PR.EXCEPTION.REGISTRATION.NOTFOUND.STUDYSITE_WITH_NCICODE.CODE"), new String[] { studySite.getHealthcareSite() .getNciInstituteCode() }); } private Epoch buildEpoch(List<Epoch> epochs, ScheduledEpoch scheduledEpoch) throws C3PRCodedException { for (Epoch epochCurr : epochs) { if (epochCurr.getName().equalsIgnoreCase(scheduledEpoch.getEpoch().getName())) { return epochCurr; } } throw exceptionHelper.getException( getCode("C3PR.EXCEPTION.REGISTRATION.NOTFOUND.EPOCH_NAME.CODE"), new String[] { scheduledEpoch.getEpoch().getName() }); } private ScheduledEpoch buildScheduledEpoch(ScheduledEpoch source, Epoch epoch) throws C3PRCodedException { ScheduledEpoch scheduledEpoch = null; if (true) { ScheduledEpoch scheduledEpochSource = source; scheduledEpoch = new ScheduledEpoch(); ScheduledEpoch scheduledTreatmentEpoch = scheduledEpoch; scheduledTreatmentEpoch.setEligibilityIndicator(true); if (scheduledEpochSource.getScheduledArm() != null && scheduledEpochSource.getScheduledArm().getArm() != null && scheduledEpochSource.getScheduledArm().getArm() .getName() != null) { Arm arm = null; for (Arm a : (epoch).getArms()) { if (a.getName().equals( scheduledEpochSource.getScheduledArm().getArm() .getName())) { arm = a; } } if (arm == null) { throw exceptionHelper .getException( getCode("C3PR.EXCEPTION.REGISTRATION.NOTFOUND.ARM_NAME.CODE"), new String[] { scheduledEpochSource .getScheduledArm() .getArm().getName(), scheduledEpochSource .getEpoch() .getName() }); } scheduledTreatmentEpoch.getScheduledArms().get(0).setArm(arm); } } scheduledEpoch.setEpoch(epoch); scheduledEpoch.setScEpochWorkflowStatus(source.getScEpochWorkflowStatus()); return scheduledEpoch; } private void fillStudySubjectDetails(StudySubject studySubject, StudySubject source) { studySubject.setInformedConsentSignedDate(source.getInformedConsentSignedDate()); studySubject.setInformedConsentVersion(source.getInformedConsentVersion()); studySubject.setStartDate(source.getStartDate()); studySubject.setStratumGroupNumber(source.getStratumGroupNumber()); studySubject.getIdentifiers().addAll(source.getIdentifiers()); studySubject.setCctsWorkflowStatus(source.getCctsWorkflowStatus()); studySubject.setMultisiteWorkflowStatus(source.getMultisiteWorkflowStatus()); } private int getCode(String errortypeString) { return Integer.parseInt(this.c3prErrorMessages.getMessage(errortypeString, null, null)); } public void setExceptionHelper(C3PRExceptionHelper exceptionHelper) { this.exceptionHelper = exceptionHelper; } public void setC3prErrorMessages(MessageSource errorMessages) { c3prErrorMessages = errorMessages; } public void setStudyService(StudyService studyService) { this.studyService = studyService; } public void setParticipantService(ParticipantService participantService) { this.participantService = participantService; } public void setStudyRepository(StudyRepository studyRepository) { this.studyRepository = studyRepository; } }
package org.jboss.as.controller.descriptions.common; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ATTRIBUTES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CHILDREN; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DESCRIPTION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NILLABLE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATIONS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REPLY_PROPERTIES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REQUEST_PROPERTIES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REQUIRED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TYPE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE_TYPE; import java.util.Locale; import java.util.ResourceBundle; import org.jboss.as.controller.parsing.Attribute; import org.jboss.as.controller.parsing.Element; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * @author anil saldhana */ public class VaultDescriptions { private static final String RESOURCE_NAME = VaultDescriptions.class.getPackage().getName() + ".LocalDescriptions"; public static ModelNode getVaultDescription(Locale locale) { final ResourceBundle bundle = getResourceBundle(locale); final ModelNode node = new ModelNode(); node.get(DESCRIPTION).set(bundle.getString("vault")); node.get(ATTRIBUTES, Attribute.CODE.getLocalName(), DESCRIPTION).set(bundle.getString("vault.code")); node.get(ATTRIBUTES, Attribute.CODE.getLocalName(), TYPE).set(ModelType.STRING); node.get(ATTRIBUTES, Attribute.CODE.getLocalName(), NILLABLE).set(true); node.get(ATTRIBUTES, Element.VAULT_OPTION.getLocalName(), DESCRIPTION).set(bundle.getString("vault.option")); node.get(ATTRIBUTES, Element.VAULT_OPTION.getLocalName(), TYPE).set(ModelType.OBJECT); node.get(ATTRIBUTES, Element.VAULT_OPTION.getLocalName(), VALUE_TYPE).set(ModelType.STRING); node.get(ATTRIBUTES, Element.VAULT_OPTION.getLocalName(), NILLABLE).set(true); node.get(OPERATIONS); // placeholder node.get(CHILDREN).setEmptyObject(); return node; } public static ModelNode getVaultAddDescription(Locale locale) { final ResourceBundle bundle = getResourceBundle(locale); final ModelNode node = new ModelNode(); node.get(OPERATION_NAME).set(ADD); node.get(DESCRIPTION).set(bundle.getString("vault.add")); node.get(REQUEST_PROPERTIES, Attribute.CODE.getLocalName(), TYPE).set(ModelType.STRING); node.get(REQUEST_PROPERTIES, Attribute.CODE.getLocalName(), DESCRIPTION).set(bundle.getString("vault.code")); node.get(REQUEST_PROPERTIES, Attribute.CODE.getLocalName(), REQUIRED).set(false); node.get(REQUEST_PROPERTIES, Element.VAULT_OPTION.getLocalName(), DESCRIPTION).set(bundle.getString("vault.option")); node.get(REQUEST_PROPERTIES, Element.VAULT_OPTION.getLocalName(), TYPE).set(ModelType.OBJECT); node.get(REQUEST_PROPERTIES, Element.VAULT_OPTION.getLocalName(), VALUE_TYPE).set(ModelType.STRING); node.get(REQUEST_PROPERTIES, Element.VAULT_OPTION.getLocalName(), REQUIRED).set(false); node.get(REPLY_PROPERTIES).setEmptyObject(); return node; } public static ModelNode getVaultRemoveDescription(Locale locale) { final ResourceBundle bundle = getResourceBundle(locale); final ModelNode node = new ModelNode(); node.get(OPERATION_NAME).set(REMOVE); node.get(DESCRIPTION).set(bundle.getString("vault.remove")); node.get(REQUEST_PROPERTIES).setEmptyObject(); node.get(REPLY_PROPERTIES).setEmptyObject(); return node; } private static ResourceBundle getResourceBundle(Locale locale) { if (locale == null) { locale = Locale.getDefault(); } return ResourceBundle.getBundle(RESOURCE_NAME, locale); } }
package org.voltcore.utils; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.Inet4Address; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantLock; import jsr166y.LinkedTransferQueue; import org.voltcore.logging.VoltLogger; import org.voltcore.network.ReverseDNSCache; import com.google_voltpatches.common.base.Preconditions; import com.google_voltpatches.common.base.Supplier; import com.google_voltpatches.common.base.Suppliers; import com.google_voltpatches.common.collect.ImmutableList; import com.google_voltpatches.common.collect.ImmutableMap; import com.google_voltpatches.common.util.concurrent.ListenableFuture; import com.google_voltpatches.common.util.concurrent.ListeningExecutorService; import com.google_voltpatches.common.util.concurrent.MoreExecutors; import com.google_voltpatches.common.util.concurrent.SettableFuture; public class CoreUtils { private static final VoltLogger hostLog = new VoltLogger("HOST"); public static final int SMALL_STACK_SIZE = 1024 * 256; public static final int MEDIUM_STACK_SIZE = 1024 * 512; public static volatile Runnable m_threadLocalDeallocator = new Runnable() { @Override public void run() { } }; public static final ListenableFuture<Object> COMPLETED_FUTURE = new ListenableFuture<Object>() { @Override public void addListener(Runnable listener, Executor executor) { executor.execute(listener); } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } @Override public Object get() { return null; } @Override public Object get(long timeout, TimeUnit unit) { return null; } }; public static final Runnable EMPTY_RUNNABLE = new Runnable() { @Override public void run() {} }; /** * Get a single thread executor that caches it's thread meaning that the thread will terminate * after keepAlive milliseconds. A new thread will be created the next time a task arrives and that will be kept * around for keepAlive milliseconds. On creation no thread is allocated, the first task creates a thread. * * Uses LinkedTransferQueue to accept tasks and has a small stack. */ public static ListeningExecutorService getCachedSingleThreadExecutor(String name, long keepAlive) { return MoreExecutors.listeningDecorator(new ThreadPoolExecutor( 0, 1, keepAlive, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), CoreUtils.getThreadFactory(null, name, SMALL_STACK_SIZE, false, null))); } /** * Create an unbounded single threaded executor */ public static ExecutorService getSingleThreadExecutor(String name) { ExecutorService ste = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), CoreUtils.getThreadFactory(null, name, SMALL_STACK_SIZE, false, null)); return ste; } public static ExecutorService getSingleThreadExecutor(String name, int size) { ExecutorService ste = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), CoreUtils.getThreadFactory(null, name, size, false, null)); return ste; } /** * Create an unbounded single threaded executor */ public static ListeningExecutorService getListeningSingleThreadExecutor(String name) { ExecutorService ste = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), CoreUtils.getThreadFactory(null, name, SMALL_STACK_SIZE, false, null)); return MoreExecutors.listeningDecorator(ste); } public static ListeningExecutorService getListeningSingleThreadExecutor(String name, int size) { ExecutorService ste = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), CoreUtils.getThreadFactory(null, name, size, false, null)); return MoreExecutors.listeningDecorator(ste); } /** * Create a bounded single threaded executor that rejects requests if more than capacity * requests are outstanding. */ public static ListeningExecutorService getBoundedSingleThreadExecutor(String name, int capacity) { LinkedBlockingQueue<Runnable> lbq = new LinkedBlockingQueue<Runnable>(capacity); ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, lbq, CoreUtils.getThreadFactory(name)); return MoreExecutors.listeningDecorator(tpe); } /* * Have shutdown actually means shutdown. Tasks that need to complete should use * futures. */ public static ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(String name, int poolSize, int stackSize) { ScheduledThreadPoolExecutor ses = new ScheduledThreadPoolExecutor(poolSize, getThreadFactory(null, name, stackSize, poolSize > 1, null)); ses.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); ses.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); return ses; } public static ListeningExecutorService getListeningExecutorService( final String name, final int threads) { return getListeningExecutorService(name, threads, new LinkedTransferQueue<Runnable>(), null); } public static ListeningExecutorService getListeningExecutorService( final String name, final int coreThreads, final int threads) { return getListeningExecutorService(name, coreThreads, threads, new LinkedTransferQueue<Runnable>(), null); } public static ListeningExecutorService getListeningExecutorService( final String name, final int threads, Queue<String> coreList) { return getListeningExecutorService(name, threads, new LinkedTransferQueue<Runnable>(), coreList); } public static ListeningExecutorService getListeningExecutorService( final String name, int threadsTemp, final BlockingQueue<Runnable> queue, final Queue<String> coreList) { if (coreList != null && !coreList.isEmpty()) { threadsTemp = coreList.size(); } final int threads = threadsTemp; if (threads < 1) { throw new IllegalArgumentException("Must specify > 0 threads"); } if (name == null) { throw new IllegalArgumentException("Name cannot be null"); } return MoreExecutors.listeningDecorator( new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS, queue, getThreadFactory(null, name, SMALL_STACK_SIZE, threads > 1 ? true : false, coreList))); } public static ListeningExecutorService getListeningExecutorService( final String name, int coreThreadsTemp, int threadsTemp, final BlockingQueue<Runnable> queue, final Queue<String> coreList) { if (coreThreadsTemp < 0) { throw new IllegalArgumentException("Must specify >= 0 core threads"); } if (coreThreadsTemp > threadsTemp) { throw new IllegalArgumentException("Core threads must be <= threads"); } if (coreList != null && !coreList.isEmpty()) { threadsTemp = coreList.size(); if (coreThreadsTemp > threadsTemp) { coreThreadsTemp = threadsTemp; } } final int coreThreads = coreThreadsTemp; final int threads = threadsTemp; if (threads < 1) { throw new IllegalArgumentException("Must specify > 0 threads"); } if (name == null) { throw new IllegalArgumentException("Name cannot be null"); } return MoreExecutors.listeningDecorator( new ThreadPoolExecutor(coreThreads, threads, 1L, TimeUnit.MINUTES, queue, getThreadFactory(null, name, SMALL_STACK_SIZE, threads > 1 ? true : false, coreList))); } /** * Create a bounded thread pool executor. The work queue is synchronous and can cause * RejectedExecutionException if there is no available thread to take a new task. * @param maxPoolSize: the maximum number of threads to allow in the pool. * @param keepAliveTime: when the number of threads is greater than the core, this is the maximum * time that excess idle threads will wait for new tasks before terminating. * @param unit: the time unit for the keepAliveTime argument. * @param threadFactory: the factory to use when the executor creates a new thread. */ public static ThreadPoolExecutor getBoundedThreadPoolExecutor(int maxPoolSize, long keepAliveTime, TimeUnit unit, ThreadFactory tFactory) { return new ThreadPoolExecutor(0, maxPoolSize, keepAliveTime, unit, new SynchronousQueue<Runnable>(), tFactory); } public static ThreadFactory getThreadFactory(String name) { return getThreadFactory(name, SMALL_STACK_SIZE); } public static ThreadFactory getThreadFactory(String groupName, String name) { return getThreadFactory(groupName, name, SMALL_STACK_SIZE, true, null); } public static ThreadFactory getThreadFactory(String name, int stackSize) { return getThreadFactory(null, name, stackSize, true, null); } /** * Creates a thread factory that creates threads within a thread group if * the group name is given. The threads created will catch any unhandled * exceptions and log them to the HOST logger. * * @param groupName * @param name * @param stackSize * @return */ public static ThreadFactory getThreadFactory( final String groupName, final String name, final int stackSize, final boolean incrementThreadNames, final Queue<String> coreList) { ThreadGroup group = null; if (groupName != null) { group = new ThreadGroup(Thread.currentThread().getThreadGroup(), groupName); } final ThreadGroup finalGroup = group; return new ThreadFactory() { private final AtomicLong m_createdThreadCount = new AtomicLong(0); private final ThreadGroup m_group = finalGroup; @Override public synchronized Thread newThread(final Runnable r) { final String threadName = name + (incrementThreadNames ? " - " + m_createdThreadCount.getAndIncrement() : ""); String coreTemp = null; if (coreList != null && !coreList.isEmpty()) { coreTemp = coreList.poll(); } final String core = coreTemp; Runnable runnable = new Runnable() { @Override public void run() { if (core != null) { // Remove Affinity for now to make this dependency dissapear from the client. // Goal is to remove client dependency on this class in the medium term. //PosixJNAAffinity.INSTANCE.setAffinity(core); } try { r.run(); } catch (Throwable t) { hostLog.error("Exception thrown in thread " + threadName, t); } finally { m_threadLocalDeallocator.run(); } } }; Thread t = new Thread(m_group, runnable, threadName, stackSize); t.setDaemon(true); return t; } }; } /** * Return the local hostname, if it's resolvable. If not, * return the IPv4 address on the first interface we find, if it exists. * If not, returns whatever address exists on the first interface. * @return the String representation of some valid host or IP address, * if we can find one; the empty string otherwise */ public static String getHostnameOrAddress() { final InetAddress addr = m_localAddressSupplier.get(); if (addr == null) return ""; return ReverseDNSCache.hostnameOrAddress(addr); } private static final Supplier<InetAddress> m_localAddressSupplier = Suppliers.memoizeWithExpiration(new Supplier<InetAddress>() { @Override public InetAddress get() { try { final InetAddress addr = InetAddress.getLocalHost(); return addr; } catch (UnknownHostException e) { try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); if (interfaces == null) { return null; } NetworkInterface intf = interfaces.nextElement(); Enumeration<InetAddress> addresses = intf.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (address instanceof Inet4Address) { return address; } } addresses = intf.getInetAddresses(); if (addresses.hasMoreElements()) { return addresses.nextElement(); } return null; } catch (SocketException e1) { return null; } } } }, 1, TimeUnit.DAYS); /** * Return the local IP address, if it's resolvable. If not, * return the IPv4 address on the first interface we find, if it exists. * If not, returns whatever address exists on the first interface. * @return the String representation of some valid host or IP address, * if we can find one; the empty string otherwise */ public static InetAddress getLocalAddress() { return m_localAddressSupplier.get(); } public static long getHSIdFromHostAndSite(int host, int site) { long HSId = site; HSId = (HSId << 32) + host; return HSId; } public static int getHostIdFromHSId(long HSId) { return (int) (HSId & 0xffffffff); } public static String hsIdToString(long hsId) { return Integer.toString((int)hsId) + ":" + Integer.toString((int)(hsId >> 32)); } public static String hsIdCollectionToString(Collection<Long> ids) { List<String> idstrings = new ArrayList<String>(); for (Long id : ids) { idstrings.add(hsIdToString(id)); } // Easy hack, sort hsIds lexically. Collections.sort(idstrings); StringBuilder sb = new StringBuilder(); boolean first = false; for (String id : idstrings) { if (!first) { first = true; } else { sb.append(", "); } sb.append(id); } return sb.toString(); } public static int getSiteIdFromHSId(long siteId) { return (int)(siteId>>32); } public static <K,V> ImmutableMap<K, ImmutableList<V>> unmodifiableMapCopy(Map<K, List<V>> m) { ImmutableMap.Builder<K, ImmutableList<V>> builder = ImmutableMap.builder(); for (Map.Entry<K, List<V>> e : m.entrySet()) { builder.put(e.getKey(), ImmutableList.<V>builder().addAll(e.getValue()).build()); } return builder.build(); } public static byte[] urlToBytes(String url) { if (url == null) { return null; } try { // get the URL/path for the deployment and prep an InputStream InputStream input = null; try { URL inputURL = new URL(url); input = inputURL.openStream(); } catch (MalformedURLException ex) { // Invalid URL. Try as a file. try { input = new FileInputStream(url); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } catch (IOException ioex) { throw new RuntimeException(ioex); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte readBytes[] = new byte[1024 * 8]; while (true) { int read = input.read(readBytes); if (read == -1) { break; } baos.write(readBytes, 0, read); } return baos.toByteArray(); } catch (Exception e) { throw new RuntimeException(e); } } public static String throwableToString(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.flush(); return sw.toString(); } public static String hsIdKeyMapToString(Map<Long, ?> m) { StringBuilder sb = new StringBuilder(); sb.append('{'); boolean first = true; for (Map.Entry<Long, ?> entry : m.entrySet()) { if (!first) sb.append(", "); first = false; sb.append(CoreUtils.hsIdToString(entry.getKey())); sb.append("->").append(entry.getValue()); } sb.append('}'); return sb.toString(); } public static String hsIdValueMapToString(Map<?, Long> m) { StringBuilder sb = new StringBuilder(); sb.append('{'); boolean first = true; for (Map.Entry<?, Long> entry : m.entrySet()) { if (!first) sb.append(", "); first = false; sb.append(entry.getKey()).append("->"); sb.append(CoreUtils.hsIdToString(entry.getValue())); } sb.append('}'); return sb.toString(); } public static String hsIdMapToString(Map<Long, Long> m) { StringBuilder sb = new StringBuilder(); sb.append('{'); boolean first = true; for (Map.Entry<Long, Long> entry : m.entrySet()) { if (!first) sb.append(", "); first = false; sb.append(CoreUtils.hsIdToString(entry.getKey())).append(" -> "); sb.append(CoreUtils.hsIdToString(entry.getValue())); } sb.append('}'); return sb.toString(); } public static int availableProcessors() { return Math.max(1, Runtime.getRuntime().availableProcessors()); } public static final class RetryException extends RuntimeException { public RetryException() {}; public RetryException(Throwable cause) { super(cause); } } /** * A helper for retrying tasks asynchronously returns a settable future * that can be used to attempt to cancel the task. * * The first executor service is used to schedule retry attempts * The second is where the task will be subsmitted for execution * If the two services are the same only the scheduled service is used * * @param maxAttempts It is the number of total attempts including the first one. * If the value is 0, that means there is no limit. */ public static final<T> ListenableFuture<T> retryHelper( final ScheduledExecutorService ses, final ExecutorService es, final Callable<T> callable, final long maxAttempts, final long startInterval, final TimeUnit startUnit, final long maxInterval, final TimeUnit maxUnit) { Preconditions.checkNotNull(maxUnit); Preconditions.checkNotNull(startUnit); Preconditions.checkArgument(startUnit.toMillis(startInterval) >= 1); Preconditions.checkArgument(maxUnit.toMillis(maxInterval) >= 1); Preconditions.checkNotNull(callable); final SettableFuture<T> retval = SettableFuture.create(); /* * Base case with no retry, attempt the task once */ es.execute(new Runnable() { @Override public void run() { try { retval.set(callable.call()); } catch (RetryException e) { //Now schedule a retry retryHelper(ses, es, callable, maxAttempts - 1, startInterval, startUnit, maxInterval, maxUnit, 0, retval); } catch (Exception e) { retval.setException(e); } } }); return retval; } private static final <T> void retryHelper( final ScheduledExecutorService ses, final ExecutorService es, final Callable<T> callable, final long maxAttempts, final long startInterval, final TimeUnit startUnit, final long maxInterval, final TimeUnit maxUnit, final long ii, final SettableFuture<T> retval) { if (maxAttempts == 0) { retval.setException(new RuntimeException("Max attempts reached")); return; } long intervalMax = maxUnit.toMillis(maxInterval); final long interval = Math.min(intervalMax, startUnit.toMillis(startInterval) * 2); ses.schedule(new Runnable() { @Override public void run() { Runnable task = new Runnable() { @Override public void run() { if (retval.isCancelled()) return; try { retval.set(callable.call()); } catch (RetryException e) { retryHelper(ses, es, callable, maxAttempts - 1, interval, TimeUnit.MILLISECONDS, maxInterval, maxUnit, ii + 1, retval); } catch (Exception e3) { retval.setException(e3); } } }; if (ses == es) task.run(); else es.execute(task); } }, interval, TimeUnit.MILLISECONDS); } public static final long LOCK_SPIN_MICROSECONDS = TimeUnit.MICROSECONDS.toNanos(Integer.getInteger("LOCK_SPIN_MICROS", 0)); /* * Spin on a ReentrantLock before blocking. Default behavior is not to spin. */ public static void spinLock(ReentrantLock lock) { if (LOCK_SPIN_MICROSECONDS > 0) { long nanos = -1; for (;;) { if (lock.tryLock()) return; if (nanos == -1) { nanos = System.nanoTime(); } else if (System.nanoTime() - nanos > LOCK_SPIN_MICROSECONDS) { lock.lock(); return; } } } else { lock.lock(); } } public static final long QUEUE_SPIN_MICROSECONDS = TimeUnit.MICROSECONDS.toNanos(Integer.getInteger("QUEUE_SPIN_MICROS", 0)); /* * Spin polling a blocking queue before blocking. Default behavior is not to spin. */ public static <T> T queueSpinTake(BlockingQueue<T> queue) throws InterruptedException { if (QUEUE_SPIN_MICROSECONDS > 0) { T retval = null; long nanos = -1; for (;;) { if ((retval = queue.poll()) != null) return retval; if (nanos == -1) { nanos = System.nanoTime(); } else if (System.nanoTime() - nanos > QUEUE_SPIN_MICROSECONDS) { return queue.take(); } } } else { return queue.take(); } } }
package org.voltdb.iv2; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeSet; import java.util.concurrent.Future; import org.voltcore.logging.VoltLogger; import org.voltcore.messaging.VoltMessage; import org.voltcore.utils.CoreUtils; import org.voltcore.utils.Pair; import org.voltdb.messaging.CompleteTransactionMessage; import org.voltdb.messaging.FragmentTaskMessage; import org.voltdb.messaging.Iv2RepairLogRequestMessage; import org.voltdb.messaging.Iv2RepairLogResponseMessage; public class MpPromoteAlgo implements RepairAlgo { static final VoltLogger tmLog = new VoltLogger("TM"); private final String m_whoami; private final InitiatorMailbox m_mailbox; private final long m_requestId = System.nanoTime(); private final List<Long> m_survivors; private long m_maxSeenTxnId = TxnEgo.makeZero(MpInitiator.MP_INIT_PID).getTxnId(); // Each Term can process at most one promotion; if promotion fails, make // a new Term and try again (if that's your big plan...) private final InaugurationFuture m_promotionResult = new InaugurationFuture(); long getRequestId() { return m_requestId; } // scoreboard for responding replica repair log responses (hsid -> response count) static class ReplicaRepairStruct { int m_receivedResponses = 0; int m_expectedResponses = -1; // (a log msg cares about this init. value) // update counters and return the number of outstanding messages. boolean update(Iv2RepairLogResponseMessage response) { m_receivedResponses++; m_expectedResponses = response.getOfTotal(); return logsComplete(); } // return 0 if all expected logs have been received. boolean logsComplete() { return (m_expectedResponses - m_receivedResponses) == 0; } } // replicas being processed and repaired. Map<Long, ReplicaRepairStruct> m_replicaRepairStructs = new HashMap<Long, ReplicaRepairStruct>(); // Determine equal repair responses by the SpHandle of the response. Comparator<Iv2RepairLogResponseMessage> m_unionComparator = new Comparator<Iv2RepairLogResponseMessage>() { @Override public int compare(Iv2RepairLogResponseMessage o1, Iv2RepairLogResponseMessage o2) { return (int)(o1.getTxnId() - o2.getTxnId()); } }; // Union of repair responses. TreeSet<Iv2RepairLogResponseMessage> m_repairLogUnion = new TreeSet<Iv2RepairLogResponseMessage>(m_unionComparator); /** * Setup a new RepairAlgo but don't take any action to take responsibility. */ public MpPromoteAlgo(List<Long> survivors, InitiatorMailbox mailbox, String whoami) { m_survivors = new ArrayList<Long>(survivors); m_mailbox = mailbox; m_whoami = whoami; } @Override public Future<Pair<Boolean, Long>> start() { try { prepareForFaultRecovery(); } catch (Exception e) { tmLog.error(m_whoami + "failed leader promotion:", e); m_promotionResult.setException(e); m_promotionResult.done(Long.MIN_VALUE); } return m_promotionResult; } @Override public boolean cancel() { return m_promotionResult.cancel(false); } /** Start fixing survivors: setup scoreboard and request repair logs. */ void prepareForFaultRecovery() { for (Long hsid : m_survivors) { m_replicaRepairStructs.put(hsid, new ReplicaRepairStruct()); } tmLog.info(m_whoami + "found " + m_survivors.size() + " surviving leaders to repair. " + " Survivors: " + CoreUtils.hsIdCollectionToString(m_survivors)); VoltMessage logRequest = makeRepairLogRequestMessage(m_requestId); m_mailbox.send(com.google.common.primitives.Longs.toArray(m_survivors), logRequest); } /** Process a new repair log response */ @Override public void deliver(VoltMessage message) { if (message instanceof Iv2RepairLogResponseMessage) { Iv2RepairLogResponseMessage response = (Iv2RepairLogResponseMessage)message; if (response.getRequestId() != m_requestId) { tmLog.info(m_whoami + "rejecting stale repair response." + " Current request id is: " + m_requestId + " Received response for request id: " + response.getRequestId()); return; } // Step 1: if the msg has a known (not MAX VALUE) handle, update m_maxSeen. if (response.getTxnId() != Long.MAX_VALUE) { m_maxSeenTxnId = Math.max(m_maxSeenTxnId, response.getTxnId()); } // Step 2: offer to the union addToRepairLog(response); // Step 3: update the corresponding replica repair struct. ReplicaRepairStruct rrs = m_replicaRepairStructs.get(response.m_sourceHSId); if (rrs.m_expectedResponses < 0) { tmLog.info(m_whoami + "collecting " + response.getOfTotal() + " repair log entries from " + CoreUtils.hsIdToString(response.m_sourceHSId)); } if (rrs.update(response)) { tmLog.info(m_whoami + "collected " + rrs.m_receivedResponses + " responses for " + rrs.m_expectedResponses + " repair log entries from " + CoreUtils.hsIdToString(response.m_sourceHSId)); if (areRepairLogsComplete()) { repairSurvivors(); } } } } /** Have all survivors supplied a full repair log? */ public boolean areRepairLogsComplete() { for (Entry<Long, ReplicaRepairStruct> entry : m_replicaRepairStructs.entrySet()) { if (!entry.getValue().logsComplete()) { return false; } } return true; } /** Send missed-messages to survivors. Exciting! */ public void repairSurvivors() { // cancel() and repair() must be synchronized by the caller (the deliver lock, // currently). If cancelled and the last repair message arrives, don't send // out corrections! if (this.m_promotionResult.isCancelled()) { tmLog.debug(m_whoami + "skipping repair message creation for cancelled Term."); return; } tmLog.info(m_whoami + "received all repair logs and is repairing surviving replicas."); for (Iv2RepairLogResponseMessage li : m_repairLogUnion) { // send the repair log union to all the survivors. SPIs will ignore // CompleteTransactionMessages for transcations which have already // completed, so this has the effect of making sure that any holes // in the repair log are filled without explicitly having to // discover and track them. tmLog.debug(m_whoami + "repairing: " + m_survivors + " with: " + TxnEgo.txnIdToString(li.getTxnId())); m_mailbox.repairReplicasWith(m_survivors, createRepairMessage(li)); } m_promotionResult.done(m_maxSeenTxnId); } // Specialization VoltMessage makeRepairLogRequestMessage(long requestId) { return new Iv2RepairLogRequestMessage(requestId, Iv2RepairLogRequestMessage.MPIREQUEST); } // Always add the first message for a transaction id and always // replace old messages with complete transaction messages. void addToRepairLog(Iv2RepairLogResponseMessage msg) { // don't add the null payload from the first message ack to the repair log if (msg.getPayload() == null) { return; } Iv2RepairLogResponseMessage prev = m_repairLogUnion.floor(msg); if (prev != null && (prev.getTxnId() != msg.getTxnId())) { prev = null; } if (prev == null) { m_repairLogUnion.add(msg); } else if (msg.getPayload() instanceof CompleteTransactionMessage) { // prefer complete messages to fragment tasks. m_repairLogUnion.remove(prev); m_repairLogUnion.add(msg); } } VoltMessage createRepairMessage(Iv2RepairLogResponseMessage msg) { if (msg.getPayload() instanceof CompleteTransactionMessage) { return msg.getPayload(); } else { FragmentTaskMessage ftm = (FragmentTaskMessage)msg.getPayload(); CompleteTransactionMessage rollback = new CompleteTransactionMessage( ftm.getInitiatorHSId(), ftm.getCoordinatorHSId(), ftm.getTxnId(), ftm.isReadOnly(), true, // Force rollback as our repair operation. false, // no acks in iv2. true); // Indicate rollback for repair. return rollback; } } }
package com.ashish; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class NumberAdditionTest { private LinkedList<Integer> sumResultList; @BeforeMethod public void setLinkedList() { sumResultList = new LinkedList<Integer>(); } /** * Solution for reverse Order */ @Test public void numberAdditionTest() { LinkedList firstNumber = new LinkedList(); LinkedList secondNumber = new LinkedList(); firstNumber.add(7); firstNumber.add(1); firstNumber.add(6); secondNumber.add(2); secondNumber.add(9); secondNumber.add(5); sumResultList = new LinkedList<Integer>(); addReverseOrderNumberLists(firstNumber, secondNumber); System.out.println(sumResultList); } /** * Solution for reverse Order sum * @param firstNumber * @param secondNumber */ private void addReverseOrderNumberLists(LinkedList firstNumber, LinkedList secondNumber) { LinkedList.Node firstNumberDigit = firstNumber.getHead(); LinkedList.Node secondNumberDigit = secondNumber.getHead(); Integer carryOver = 0; do { Integer firstDigit = 0; Integer secondDigit = 0; if (firstNumberDigit != null) { firstDigit = (Integer) firstNumberDigit.getElement(); } if (secondNumberDigit != null) { secondDigit = (Integer) secondNumberDigit.getElement(); } Integer sumOfDigit = carryOver + firstDigit + secondDigit; if (sumOfDigit > 10) { carryOver = sumOfDigit / 10; sumOfDigit = sumOfDigit % 10; } else { carryOver = 0; } sumResultList.add(sumOfDigit); firstNumberDigit = firstNumberDigit.getNext(); secondNumberDigit = secondNumberDigit.getNext(); } while (firstNumberDigit != null || secondNumberDigit != null || carryOver > 0); } /** * Solution for forward Order */ @Test public void numberForwardAdditionTest() { LinkedList firstNumber = new LinkedList(); LinkedList secondNumber = new LinkedList(); firstNumber.add(6); firstNumber.add(1); firstNumber.add(7); secondNumber.add(5); secondNumber.add(9); secondNumber.add(2); sumResultList = new LinkedList<Integer>(); addReverseOrderNumberLists(firstNumber, secondNumber); System.out.println(sumResultList); } }
//$HeadURL$ package org.deegree.services.controller; import static java.lang.Class.forName; import static org.slf4j.LoggerFactory.getLogger; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.xml.bind.JAXBElement; import org.deegree.commons.config.DeegreeWorkspace; import org.deegree.commons.xml.XMLAdapter; import org.deegree.commons.xml.jaxb.JAXBUtils; import org.deegree.services.controller.utils.StandardRequestLogger; import org.deegree.services.csw.CSWController; import org.deegree.services.jaxb.controller.AllowedServices; import org.deegree.services.jaxb.controller.ConfiguredServicesType; import org.deegree.services.jaxb.controller.DeegreeServiceControllerType; import org.deegree.services.jaxb.controller.DeegreeServiceControllerType.RequestLogging; import org.deegree.services.jaxb.controller.ServiceType; import org.deegree.services.jaxb.metadata.DeegreeServicesMetadataType; import org.deegree.services.sos.SOSController; import org.deegree.services.wcs.WCSController; import org.deegree.services.wfs.WFSController; import org.deegree.services.wms.controller.WMSController; import org.deegree.services.wps.WPService; import org.deegree.services.wpvs.controller.WPVSController; import org.slf4j.Logger; /** * * @author <a href="mailto:schmitz@lat-lon.de">Andreas Schmitz</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public class WebServicesConfiguration { private static final Logger LOG = getLogger( WebServicesConfiguration.class ); private static final String CONTROLLER_JAXB_PACKAGE = "org.deegree.services.jaxb.controller"; private static final String CONTROLLER_CONFIG_SCHEMA = "/META-INF/schemas/controller/3.0.0/controller.xsd"; private static final String METADATA_JAXB_PACKAGE = "org.deegree.services.jaxb.metadata"; private static final String METADATA_CONFIG_SCHEMA = "/META-INF/schemas/metadata/3.0.0/metadata.xsd"; // maps service names (e.g. 'WMS', 'WFS', ...) to responsible subcontrollers private final Map<AllowedServices, AbstractOGCServiceController> serviceNameToController = new HashMap<AllowedServices, AbstractOGCServiceController>(); // responsible subcontrollers private final Map<String, AbstractOGCServiceController> serviceNSToController = new HashMap<String, AbstractOGCServiceController>(); // maps request names (e.g. 'GetMap', 'DescribeFeatureType') to the responsible subcontrollers private final Map<String, AbstractOGCServiceController> requestNameToController = new HashMap<String, AbstractOGCServiceController>(); private DeegreeWorkspace workspace; private DeegreeServicesMetadataType metadataConfig; private DeegreeServiceControllerType mainConfig; private RequestLogger requestLogger; private boolean logOnlySuccessful; /** * @param workspace */ public WebServicesConfiguration( DeegreeWorkspace workspace ) { this.workspace = workspace; } /** * @throws ServletException */ public void init() throws ServletException { LOG.info( " LOG.info( "Starting webservices." ); LOG.info( " LOG.info( "" ); File metadata = new File( workspace.getLocation(), "services" + File.separator + "metadata.xml" ); File main = new File( workspace.getLocation(), "services" + File.separator + "main.xml" ); if ( !metadata.exists() ) { String msg = "No 'services/metadata.xml' file, aborting startup!"; LOG.error( msg ); throw new ServletException( msg ); } if ( !main.exists() ) { LOG.debug( "No 'services/main.xml' file, assuming defaults." ); mainConfig = new DeegreeServiceControllerType(); } else { try { metadataConfig = (DeegreeServicesMetadataType) ( (JAXBElement<?>) JAXBUtils.unmarshall( METADATA_JAXB_PACKAGE, METADATA_CONFIG_SCHEMA, metadata.toURI().toURL() ) ).getValue(); try { mainConfig = (DeegreeServiceControllerType) ( (JAXBElement<?>) JAXBUtils.unmarshall( CONTROLLER_JAXB_PACKAGE, CONTROLLER_CONFIG_SCHEMA, main.toURI().toURL() ) ).getValue(); } catch ( Exception e ) { mainConfig = new DeegreeServiceControllerType(); LOG.info( "main.xml could not be loaded. Proceeding with defaults." ); LOG.debug( "Error was: '{}'.", e.getLocalizedMessage() ); LOG.trace( "Stack trace:", e ); } } catch ( Exception e ) { String msg = "Could not unmarshall frontcontroller configuration: " + e.getMessage(); LOG.error( msg ); throw new ServletException( msg, e ); } } initRequestLogger(); ConfiguredServicesType servicesConfigured = mainConfig.getConfiguredServices(); List<ServiceType> services = null; if ( servicesConfigured != null ) { services = servicesConfigured.getService(); if ( services != null && services.size() > 0 ) { LOG.info( "The file: " + main ); LOG.info( "Provided following services:" ); for ( ServiceType s : services ) { URL configLocation = null; try { configLocation = new URL( main.toURI().toURL(), s.getConfigurationLocation() ); } catch ( MalformedURLException e ) { LOG.error( e.getMessage(), e ); return; } s.setConfigurationLocation( configLocation.toExternalForm() ); LOG.info( " - " + s.getServiceName() ); } LOG.info( "ATTENTION - Skipping the loading of all services in conf/ which are not listed above." ); } } if ( services == null || services.size() == 0 ) { LOG.info( "No service elements were supplied in the file: '" + main + "' -- trying to use the default loading mechanism." ); try { services = loadServicesFromDefaultLocation(); } catch ( MalformedURLException e ) { throw new ServletException( "Error loading service configurations: " + e.getMessage() ); } } if ( services.size() == 0 ) { LOG.info( "No deegree web services have been loaded." ); } for ( ServiceType configuredService : services ) { AbstractOGCServiceController serviceController = instantiateServiceController( configuredService ); if ( serviceController != null ) { registerSubController( configuredService, serviceController ); } } LOG.info( "" ); LOG.info( " LOG.info( "Webservices started." ); LOG.info( " } /** * Iterates over all directories in the conf/ directory and returns the service/configuration mappings as a list. * This default service loading mechanism implies the following directory structure: * <ul> * <li>conf/</li> * <li>conf/[SERVICE_NAME]/ (upper-case abbreviation of a deegree web service, please take a look at * {@link AllowedServices})</li> * <li>conf/[SERVICE_NAME]/[SERVICE_NAME]_configuration.xml</li> * </ul> * If all conditions are met the service type is added to resulting list. If none of the underlying directories meet * above criteria, an empty list will be returned. * * @return the list of services found in the conf directory. Or an empty list if the above conditions are not met * for any directory in the conf directory. * @throws MalformedURLException */ private List<ServiceType> loadServicesFromDefaultLocation() throws MalformedURLException { File serviceConfigDir = new File( workspace.getLocation(), "services" ); List<ServiceType> loadedServices = new ArrayList<ServiceType>(); if ( !serviceConfigDir.isDirectory() ) { LOG.error( "Could not read from the default service configuration directory (" + serviceConfigDir + ") because it is not a directory." ); return loadedServices; } LOG.info( "Using default directory: " + serviceConfigDir.getAbsolutePath() + " to scan for webservice configurations." ); File[] files = serviceConfigDir.listFiles(); if ( files == null || files.length == 0 ) { LOG.error( "No files found in default configuration directory, hence no services to load." ); return loadedServices; } for ( File f : files ) { if ( !f.isDirectory() ) { String fileName = f.getName(); if ( fileName != null && !"".equals( fileName.trim() ) ) { String serviceName = fileName.trim().toUpperCase(); // to avoid the ugly warning we can afford this extra s(hack) if ( serviceName.equals( ".SVN" ) || !serviceName.endsWith( ".XML" ) || serviceName.equals( "METADATA.XML" ) || serviceName.equals( "MAIN.XML" ) ) { continue; } serviceName = serviceName.substring( 0, fileName.length() - 4 ); AllowedServices as; try { as = AllowedServices.fromValue( serviceName ); } catch ( IllegalArgumentException ex ) { LOG.warn( "File '" + fileName + "' in the configuration directory " + "is not a valid deegree webservice, so skipping it." ); continue; } LOG.debug( "Trying to create a frontcontroller for service: " + fileName + " found in the configuration directory." ); ServiceType configuredService = new ServiceType(); configuredService.setConfigurationLocation( f.toURI().toURL().toString() ); configuredService.setServiceName( as ); loadedServices.add( configuredService ); } } } return loadedServices; } /** * Creates an instance of a sub controller which is valid for the given configured Service, by applying following * conventions: * <ul> * <li>The sub controller must extend {@link AbstractOGCServiceController}</li> * <li>The package of the controller is the package of this class.[SERVICE_ABBREV_lower_case]</li> * <li>The name of the controller must be [SERVICE_NAME_ABBREV]Controller</li> * <li>The controller must have a constructor with a String parameter</li> * </ul> * If all above conditions are met, the instantiated controller will be returned else <code>null</code> * * @param configuredService * @return the instantiated secured sub controller or <code>null</code> if an error occurred. */ @SuppressWarnings("unchecked") private AbstractOGCServiceController instantiateServiceController( ServiceType configuredService ) { AbstractOGCServiceController subController = null; if ( configuredService == null ) { return subController; } final String serviceName = configuredService.getServiceName().name(); // TODO outfactor this (maybe use a Map or proper SPI for plugging service implementations?) String controller = null; if ( "CSW".equals( serviceName ) ) { controller = CSWController.class.getName(); } else if ( "SOS".equals( serviceName ) ) { controller = SOSController.class.getName(); } else if ( "WCS".equals( serviceName ) ) { controller = WCSController.class.getName(); } else if ( "WFS".equals( serviceName ) ) { controller = WFSController.class.getName(); } else if ( "WMS".equals( serviceName ) ) { controller = WMSController.class.getName(); } else if ( "WPS".equals( serviceName ) ) { controller = WPService.class.getName(); } else if ( "WPVS".equals( serviceName ) ) { controller = WPVSController.class.getName(); } LOG.info( "" ); LOG.info( " LOG.info( "Starting " + serviceName + "." ); LOG.info( " LOG.info( "Configuration file: '" + configuredService.getConfigurationLocation() + "'" ); if ( configuredService.getControllerClass() != null ) { LOG.info( "Using custom controller class '{}'.", configuredService.getControllerClass() ); controller = configuredService.getControllerClass(); } try { long time = System.currentTimeMillis(); Class<AbstractOGCServiceController> subControllerClass = (Class<AbstractOGCServiceController>) Class.forName( controller, false, OGCFrontController.class.getClassLoader() ); subController = subControllerClass.newInstance(); XMLAdapter controllerConf = new XMLAdapter( new URL( configuredService.getConfigurationLocation() ) ); subController.init( controllerConf, metadataConfig, mainConfig ); LOG.info( "" ); // round to exactly two decimals, I think their should be a java method for this though double startupTime = Math.round( ( ( System.currentTimeMillis() - time ) * 0.1 ) ) * 0.01; LOG.info( serviceName + " startup successful (took: " + startupTime + " seconds)" ); } catch ( Exception e ) { LOG.error( "Initializing {} failed: {}", serviceName, e.getMessage() ); LOG.error( "Set the log level to TRACE to get the stack trace." ); LOG.trace( "Stack trace:", e ); LOG.info( "" ); LOG.info( serviceName + " startup failed." ); subController = null; } return subController; } private void registerSubController( ServiceType configuredService, AbstractOGCServiceController serviceController ) { // associate service name (abbreviation) with controller instance LOG.debug( "Service name '" + configuredService.getServiceName() + "' -> '" + serviceController.getClass().getSimpleName() + "'" ); serviceNameToController.put( configuredService.getServiceName(), serviceController ); // associate request types with controller instance for ( String request : serviceController.getHandledRequests() ) { // skip GetCapabilities requests if ( !( "GetCapabilities".equals( request ) ) ) { LOG.debug( "Request type '" + request + "' -> '" + serviceController.getClass().getSimpleName() + "'" ); requestNameToController.put( request, serviceController ); } } // associate namespaces with controller instance for ( String ns : serviceController.getHandledNamespaces() ) { LOG.debug( "Namespace '" + ns + "' -> '" + serviceController.getClass().getSimpleName() + "'" ); serviceNSToController.put( ns, serviceController ); } } /** * Determines the {@link AbstractOGCServiceController} that is responsible for handling requests to a certain * service type, e.g. WMS, WFS. * * @param serviceType * service type code, e.g. "WMS" or "WFS" * @return responsible <code>SecuredSubController</code> or null, if no responsible controller was found */ public AbstractOGCServiceController determineResponsibleControllerByServiceName( String serviceType ) { AllowedServices service = AllowedServices.fromValue( serviceType ); if ( service == null ) { return null; } return serviceNameToController.get( service ); } /** * Determines the {@link AbstractOGCServiceController} that is responsible for handling requests with a certain * name, e.g. GetMap, GetFeature. * * @param requestName * request name, e.g. "GetMap" or "GetFeature" * @return responsible <code>SecuredSubController</code> or null, if no responsible controller was found */ public AbstractOGCServiceController determineResponsibleControllerByRequestName( String requestName ) { return requestNameToController.get( requestName ); } /** * Determines the {@link AbstractOGCServiceController} that is responsible for handling requests to a certain * service type, e.g. WMS, WFS. * * @param ns * service type code, e.g. "WMS" or "WFS" * @return responsible <code>SecuredSubController</code> or null, if no responsible controller was found */ public AbstractOGCServiceController determineResponsibleControllerByNS( String ns ) { return serviceNSToController.get( ns ); } /** * Return all active service controllers. * * @return the instance of the requested service used by OGCFrontController, or null if the service is not * registered. */ public Map<String, AbstractOGCServiceController> getServiceControllers() { Map<String, AbstractOGCServiceController> nameToController = new HashMap<String, AbstractOGCServiceController>(); for ( AllowedServices serviceName : serviceNameToController.keySet() ) { nameToController.put( serviceName.value(), serviceNameToController.get( serviceName ) ); } return nameToController; } /** * Returns the service controller instance based on the class of the service controller. * * @param <T> * * @param c * class of the requested service controller, e.g. <code>WPSController.getClass()</code> * @return the instance of the requested service used by OGCFrontController, or null if no such service controller * is active */ public <T extends AbstractOGCServiceController> T getServiceController( Class<T> c ) { for ( AbstractOGCServiceController it : serviceNSToController.values() ) { if ( c == it.getClass() ) { // somehow just annotating the return expression does not work // even annotations to suppress sucking generics suck @SuppressWarnings(value = "unchecked") T result = (T) it; return result; } } return null; } public void destroy() { LOG.info( " LOG.info( "Shutting down deegree web services in context..." ); for ( AllowedServices serviceName : serviceNameToController.keySet() ) { AbstractOGCServiceController subcontroller = serviceNameToController.get( serviceName ); LOG.info( "Shutting down '" + serviceName + "'." ); try { subcontroller.destroy(); } catch ( Exception e ) { String msg = "Error destroying subcontroller '" + subcontroller.getClass().getName() + "': " + e.getMessage(); LOG.error( msg, e ); } } LOG.info( "deegree OGC webservices shut down." ); LOG.info( " } /** * @return the JAXB main configuration */ public DeegreeServiceControllerType getMainConfiguration() { return mainConfig; } private void initRequestLogger() { RequestLogging requestLogging = mainConfig.getRequestLogging(); if ( requestLogging != null ) { org.deegree.services.jaxb.controller.DeegreeServiceControllerType.RequestLogging.RequestLogger logger = requestLogging.getRequestLogger(); requestLogger = instantiateRequestLogger( logger ); this.logOnlySuccessful = requestLogging.isOnlySuccessful() != null && requestLogging.isOnlySuccessful(); } } private static RequestLogger instantiateRequestLogger( RequestLogging.RequestLogger conf ) { if ( conf != null ) { String cls = conf.getClazz(); try { Object o = conf.getConfiguration(); if ( o == null ) { return (RequestLogger) forName( cls ).newInstance(); } return (RequestLogger) forName( cls ).getDeclaredConstructor( Object.class ).newInstance( o ); } catch ( ClassNotFoundException e ) { LOG.info( "The request logger class '{}' could not be found on the classpath.", cls ); LOG.trace( "Stack trace:", e ); } catch ( ClassCastException e ) { LOG.info( "The request logger class '{}' does not implement the RequestLogger interface.", cls ); LOG.trace( "Stack trace:", e ); } catch ( InstantiationException e ) { LOG.info( "The request logger class '{}' could not be instantiated" + " (needs a default constructor without arguments if no configuration is given).", cls ); LOG.trace( "Stack trace:", e ); } catch ( IllegalAccessException e ) { LOG.info( "The request logger class '{}' could not be instantiated" + " (default constructor needs to be accessible if no configuration is given).", cls ); LOG.trace( "Stack trace:", e ); } catch ( IllegalArgumentException e ) { LOG.info( "The request logger class '{}' could not be instantiated" + " (constructor needs to take an object argument if configuration is given).", cls ); LOG.trace( "Stack trace:", e ); } catch ( java.lang.SecurityException e ) { LOG.info( "The request logger class '{}' could not be instantiated" + " (JVM does have insufficient rights to instantiate the class).", cls ); LOG.trace( "Stack trace:", e ); } catch ( InvocationTargetException e ) { LOG.info( "The request logger class '{}' could not be instantiated" + " (constructor call threw an exception).", cls ); LOG.trace( "Stack trace:", e ); } catch ( NoSuchMethodException e ) { LOG.info( "The request logger class '{}' could not be instantiated" + " (constructor needs to take an object argument if configuration is given).", cls ); LOG.trace( "Stack trace:", e ); } } return new StandardRequestLogger(); } /** * @return null, if none was configured */ public RequestLogger getRequestLogger() { return requestLogger; } /** * @return true, if the option was set in the logging configuration */ public boolean logOnlySuccessful() { return logOnlySuccessful; } }
package org.owasp.dependencycheck.data; import org.owasp.dependencycheck.update.UpdateException; /** * Defines a data source who's data is retrieved from the Internet. This data * can be downloaded and the local cache updated. * * @author Jeremy Long (jeremy.long@owasp.org) */ public interface CachedWebDataSource { /** * Determines if an update to the current data store is needed, if it is the * new data is downloaded from the Internet and imported into the current * cached data store. * * @throws UpdateException is thrown if there is an exception downloading * the data or updating the data store. */ void update() throws UpdateException; }
/** * * Contains classes used to update the data stores.<br/><br/> * * The UpdateService will load, any correctly defined CachedWebDataSource(s) and call update() on them. The Cached Data Source * must determine if it needs to be updated and if so perform the update. The sub packages contain classes used to perform the * actual updates. */ package org.owasp.dependencycheck.data.update;
import ij.plugin.filter.PlugInFilter; import java.awt.Color; import java.util.*; import java.io.*; import java.lang.Float; import ij.*; import ij.gui.*; import ij.io.*; import ij.process.*; import ij.plugin.filter.ParticleAnalyzer; import ij.plugin.filter.Analyzer; import ij.measure.*; /** * DropletTracker: An ImageJ plugin for tracking microfluidic * droplets with microscope imaging. * Travis Geis, SGTC, Stanford University, July 2013 * DropletTracker is based on MTrack2, * by Nico Stuurman, Vale Lab, UCSF/HHMI, May,June 2003 * MTrack2 is in turn based on Based on Multitracker, * based on the Object Tracker plugin filter by Wayne Rasband */ public class DropletTracker_ implements PlugInFilter, Measurements { ImagePlus imp; Calibration cal; int nParticles; float[][] ssx; float[][] ssy; String directory,filename; static int minSize = 1; // in units? static int maxSize = 999999; // in units? static int minTrackLength = 2; // in frames static boolean bSaveResultsFile = false; static float maxVelocity = 150; // in pixels per frame; this needs to be converted before filling the dialog static boolean skipDialogue = false; static double framesPerSecond = 614; public class particle { float x; float y; float area; float boundsX, boundsY, boundsWidth, boundsHeight; float perimeter; float deformationParameter; // This is (Width - Height)/(Width + Height), and shows roundness. // The Feret measures, also called "caliper" measures, indicate // the maximum length, minimum width, and angle of major // axis of a particle. The Feret deformation is the same // deformation parameter as above, but using the Feret measures. float feretLength, feretWidth, feretAngle, feretDeformation; int frameNumber; int trackNr; float velocity; boolean velocityIsValid; boolean inTrack = false; boolean flag = false; public void copy(particle source) { this.x = source.x; this.y = source.y; this.area = source.area; this.boundsX = source.boundsX; this.boundsY = source.boundsY; this.boundsWidth = source.boundsWidth; this.boundsHeight = source.boundsHeight; this.perimeter = source.perimeter; this.frameNumber = source.frameNumber; this.inTrack = source.inTrack; this.flag = source.flag; this.velocity = source.velocity; this.velocityIsValid = source.velocityIsValid; this.deformationParameter = source.deformationParameter; this.feretLength = source.feretLength; this.feretWidth = source.feretWidth; this.feretAngle = source.feretAngle; this.feretDeformation = source.feretDeformation; } public float distance (particle p) { return (float) Math.sqrt(sqr(this.x-p.x) + sqr(this.y-p.y)); } } public int setup(String arg, ImagePlus imp) { this.imp = imp; cal = imp.getCalibration(); if (IJ.versionLessThan("1.17y")) return DONE; else return DOES_8G+NO_CHANGES; } public static void setProperty (String arg1, String arg2) { if (arg1.equals("minSize")) minSize = Integer.parseInt(arg2); else if (arg1.equals("maxSize")) maxSize = Integer.parseInt(arg2); else if (arg1.equals("minTrackLength")) minTrackLength = Integer.parseInt(arg2); else if (arg1.equals("maxVelocity")) maxVelocity = Float.valueOf(arg2).floatValue(); else if (arg1.equals("saveResultsFile")) bSaveResultsFile = Boolean.valueOf(arg2); else if (arg1.equals("skipDialogue")) skipDialogue = Boolean.valueOf(arg2); } public void run(ImageProcessor ip) { if (!skipDialogue) { String unit = cal.getUnit(); GenericDialog gd = new GenericDialog("Droplet Tracker"); gd.addNumericField("Minimum Object Size", minSize, 0, 6, unit); gd.addNumericField("Maximum Object Size", maxSize, 0, 6, unit); gd.addNumericField("Maximum Velocity", maxVelocity, 0, 6, unit + "/frame"); gd.addNumericField("Minimum Track Length", minTrackLength, 0, 6, "frames"); gd.addNumericField("Frame Rate", framesPerSecond, 8, 12, "FPS"); gd.addCheckbox("Save Results File", bSaveResultsFile); gd.showDialog(); if (gd.wasCanceled()) return; minSize = (int)gd.getNextNumber(); maxSize = (int)gd.getNextNumber(); maxVelocity = (float)gd.getNextNumber(); minTrackLength = (int)gd.getNextNumber(); bSaveResultsFile = gd.getNextBoolean(); } if (bSaveResultsFile) { SaveDialog sd=new SaveDialog("Save Track Results","trackresults",".txt"); directory=sd.getDirectory(); filename=sd.getFileName(); } track(imp, minSize, maxSize, maxVelocity, directory, filename); } public void track(ImagePlus imp, int minSize, int maxSize, float maxVelocity, String directory, String filename) { int nFrames = imp.getStackSize(); if (nFrames<2) { IJ.showMessage("DropletTracker", "Stack required"); return; } // Get real-world unit label (if it is available) String unit = cal.getUnit(); ImageStack stack = imp.getStack(); int options = 0; // set all PA options false // Find centroid, area, bounding box, and perimeter using the // particle analyzer // Also, find the Feret (caliper) measures. int measurements = CENTROID+AREA+RECT+PERIMETER+FERET; // Initialize results table // ParticleAnalyzer returns the bounding rectangle // under ROI_X, ROI_Y, ROI_WIDTH, ROI_HEIGHT ResultsTable rt = new ResultsTable(); rt.reset(); // create storage for particle positions // This is a list of lists: each frame index contains a list of // all the particles found in that frame. List[] theParticles = new ArrayList[nFrames]; // Count the number of particle motion tracks int trackCount=0; // record particle positions for each frame in an ArrayList for (int iFrame=1; iFrame<=nFrames; iFrame++) { theParticles[iFrame-1]=new ArrayList(); rt.reset(); // Run the particle analysis with the measurements we want (see above). ParticleAnalyzer pa = new ParticleAnalyzer(options, measurements, rt, minSize, maxSize); pa.analyze(imp, stack.getProcessor(iFrame)); float[] sxRes = rt.getColumn(ResultsTable.X_CENTROID); float[] syRes = rt.getColumn(ResultsTable.Y_CENTROID); float[] areaRes = rt.getColumn(ResultsTable.AREA); float[] boundsXRes = rt.getColumn(ResultsTable.ROI_X); float[] boundsYRes = rt.getColumn(ResultsTable.ROI_Y); float[] boundsWidthRes = rt.getColumn(ResultsTable.ROI_WIDTH); float[] boundsHeightRes = rt.getColumn(ResultsTable.ROI_HEIGHT); float[] feretLengthRes = rt.getColumn(ResultsTable.FERET); float[] feretWidthRes = rt.getColumn(ResultsTable.MIN_FERET); float[] feretAngleRes = rt.getColumn(ResultsTable.FERET_ANGLE); float[] perimeterRes = rt.getColumn(ResultsTable.PERIMETER); if (sxRes==null) continue; for (int iPart = 0; iPart < sxRes.length; iPart++) { particle aParticle = new particle(); aParticle.x=sxRes[iPart]; aParticle.y=syRes[iPart]; aParticle.area=areaRes[iPart]; aParticle.boundsX = boundsXRes[iPart]; aParticle.boundsY = boundsYRes[iPart]; aParticle.boundsWidth = boundsWidthRes[iPart]; aParticle.boundsHeight = boundsHeightRes[iPart]; aParticle.feretLength = feretLengthRes[iPart]; aParticle.feretWidth = feretWidthRes[iPart]; aParticle.feretAngle = feretAngleRes[iPart]; aParticle.perimeter = perimeterRes[iPart]; aParticle.frameNumber = iFrame; theParticles[iFrame-1].add(aParticle); } IJ.showProgress((double)iFrame/nFrames); } // now assemble tracks out of the particle lists // Also record to which track a particle belongs in ArrayLists List theTracks = new ArrayList(); for (int i=0; i<=(nFrames-1); i++) { IJ.showProgress((double)i/nFrames); for (ListIterator j=theParticles[i].listIterator();j.hasNext();) { particle aParticle=(particle) j.next(); if (!aParticle.inTrack) { // This must be the beginning of a new track List aTrack = new ArrayList(); trackCount++; aParticle.inTrack=true; aParticle.trackNr=trackCount; aTrack.add(aParticle); // search in next frames for more particles to be added to track boolean searchOn=true; particle oldParticle=new particle(); particle tmpParticle=new particle(); oldParticle.copy(aParticle); for (int iF=i+1; iF<=(nFrames-1);iF++) { boolean foundOne=false; particle newParticle=new particle(); for (ListIterator jF=theParticles[iF].listIterator();jF.hasNext() && searchOn;) { particle testParticle =(particle) jF.next(); float distance = testParticle.distance(oldParticle); // record a particle when it is within the search radius, and when it had not yet been claimed by another track if ( (distance < maxVelocity) && !testParticle.inTrack) { // if we had not found a particle before, it is easy if (!foundOne) { tmpParticle=testParticle; testParticle.inTrack=true; testParticle.trackNr=trackCount; newParticle.copy(testParticle); foundOne=true; } else { // if we had one before, we'll take this one if it is closer. In any case, flag these particles testParticle.flag=true; if (distance < newParticle.distance(oldParticle)) { testParticle.inTrack=true; testParticle.trackNr=trackCount; newParticle.copy(testParticle); tmpParticle.inTrack=false; tmpParticle.trackNr=0; tmpParticle=testParticle; } else { newParticle.flag=true; } } } else if (distance < maxVelocity) { // this particle is already in another track but could have been part of this one // We have a number of choices here: // 1. Sort out to which track this particle really belongs (but how?) // 2. Stop this track // 3. Stop this track, and also delete the remainder of the other one // 4. Stop this track and flag this particle: testParticle.flag=true; } } if (foundOne) aTrack.add(newParticle); else searchOn=false; oldParticle.copy(newParticle); } theTracks.add(aTrack); } } } /* Now calculate velocities (and deformation parameters, while we're at it.) */ for (ListIterator iT = theTracks.listIterator(); iT.hasNext();) { List bTrack=(ArrayList) iT.next(); // filter by size; move on if too short if (bTrack.size() >= minTrackLength) { particle prevParticle = null; for (ListIterator k = bTrack.listIterator(); k.hasNext(); ) { particle aParticle=(particle) k.next(); if (prevParticle != null) { aParticle.velocity = aParticle.distance(prevParticle); aParticle.velocityIsValid = true; } else { aParticle.velocityIsValid = false; // No previous particles, so no velocity available } aParticle.deformationParameter = (aParticle.boundsWidth - aParticle.boundsHeight) / (aParticle.boundsWidth + aParticle.boundsHeight); aParticle.feretDeformation = (aParticle.feretLength - aParticle.feretWidth) / (aParticle.feretWidth + aParticle.feretLength); prevParticle = aParticle; } } } // Create the column headings based on the number of tracks // with length greater than minTrackLength // since the number of tracks can be larger than can be accomodated by Excell, we deliver the tracks in chunks of maxColumns // As a side-effect, this makes the code quite complicated String strHeadings = "Particle Number" + "\tFrame Number" + "\tX Centroid (" + unit + ")" + "\tY Centroid (" + unit + ")" + "\tArea (" + unit + "^2)" + "\tPerimeter (" + unit + ")" + "\tBounds X (" + unit + ")" + "\tBounds Y (" + unit + ")" + "\tBounds Width (" + unit + ")" + "\tBounds Height (" + unit + ")" + "\tVelocity (" + unit + "/frame)" + "\tDeformation Parameter (W-H)/(W+H)" + "\tAmbiguous Movement?" + "\tFeret Length (" + unit + ")" + "\tFeret Width (" + unit + ")" + "\tFeret Angle (degrees)" + "\tFeret Deformation (FL-FW)/(FL+FW)"; String contents=""; boolean writefile=false; if (filename != null) { File outputfile=new File (directory,filename); if (!outputfile.canWrite()) { try { outputfile.createNewFile(); } catch (IOException e) { IJ.showMessage ("Error", "Could not create " + directory + filename); } } if (outputfile.canWrite()) writefile=true; else IJ.showMessage ("Error", "Could not write to " + directory + filename); } // display the table of results IJ.setColumnHeadings(strHeadings); BufferedWriter writer = null; if (writefile) { try { File outputfile = new File (directory,filename); writer = new BufferedWriter (new FileWriter (outputfile)); writer.write(strHeadings + "\n", 0, strHeadings.length() + 1); } catch (IOException e) { if (filename != null) IJ.error ("An error occurred writing the file.\n\n" + e); else IJ.error ("The filename was null.\n\n" + e); } } // Iterate by tracks int trackNumber = 1; for (ListIterator iT = theTracks.listIterator(); iT.hasNext();) { List bTrack=(ArrayList) iT.next(); // filter by size; move on if too short if (bTrack.size() >= minTrackLength) { String strLine = ""; for (ListIterator k = bTrack.listIterator(); k.hasNext(); ) { particle aParticle=(particle) k.next(); strLine += trackNumber + "\t" + aParticle.frameNumber + "\t" + aParticle.x + "\t" + aParticle.y + "\t" + aParticle.area + "\t" + aParticle.perimeter + "\t" + aParticle.boundsX + "\t" + aParticle.boundsY + "\t" + aParticle.boundsWidth + "\t" + aParticle.boundsHeight + "\t" + (aParticle.velocityIsValid ? aParticle.velocity : "") + "\t" + aParticle.deformationParameter + "\t" + (aParticle.flag ? "true" : "") + "\t" + aParticle.feretLength + "\t" + aParticle.feretWidth + "\t" + aParticle.feretAngle + "\t" + aParticle.feretDeformation + "\n"; } IJ.write(strLine); if (writefile){ try { if (writer != null) writer.write(strLine + "\n", 0, strLine.length() + 1); } catch (IOException e) { IJ.error ("An error occurred writing the file.\n\n" + e); } } trackNumber++; } } } // Utility functions double sqr(double n) {return n*n;} int doOffset (int center, int maxSize, int displacement) { if ((center - displacement) < 2*displacement) { return (center + 4*displacement); } else { return (center - displacement); } } double s2d(String s) { Double d; try {d = new Double(s);} catch (NumberFormatException e) {d = null;} if (d!=null) return(d.doubleValue()); else return(0.0); } }
package com.payu.hackathon.discovery.server; import static org.assertj.core.api.Assertions.assertThat; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.TestingServer; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.payu.hackathon.discovery.model.Service; import com.payu.hackathon.discovery.model.ServiceSerializer; public class ServiceRegisterTest { private TestingServer zkTestServer; ServiceRegister serviceRegister; private CuratorFramework client; @Before public void startZookeeper() throws Exception { zkTestServer = new TestingServer(2181); client = CuratorFrameworkFactory.builder() .namespace(ZkDiscoveryServer.NAMESPACE) .connectString(zkTestServer.getConnectString()) .retryPolicy(new RetryOneTime(2000)) .build(); client.start(); } @After public void stopZookeeper() throws Exception { zkTestServer.stop(); } @Test public void shouldRegisterServices() throws Exception { //given serviceRegister = new ServiceRegister("com.payu.hackathon.discovery.sampledomain.service", "localhost:8080/app", zkTestServer.getConnectString()); //when serviceRegister.registerServices(); //then ServiceSerializer serviceSerializer = new ServiceSerializer(); Service service = serviceSerializer.deserializeService(client.getData().forPath("com.payu.hackathon.discovery" + ".sampledomain.service.RestServiceImpl")); assertThat(service).isNotNull(); assertThat(service.getMethods()).hasSize(3); } }
package gibstick.bukkit.discosheep; import java.util.ArrayList; import java.util.List; import org.bukkit.DyeColor; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.World; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.entity.Sheep; /** * * @author Georgiy */ public class DiscoParty { private DiscoSheep ds; private Player player; private ArrayList<Sheep> sheepList= new ArrayList<Sheep>(); private int duration, frequency = 20, numSheep = 5; private final int defaultDuration = 300; // ticks for entire party private final int defaultFrequency = 10; // ticks per state change private final int sheepSpawnRadius = 5; private final int defaultSheepAmount = 10; private DiscoUpdater updater; private static final DyeColor[] discoColours = { DyeColor.RED, DyeColor.ORANGE, DyeColor.YELLOW, DyeColor.GREEN, DyeColor.BLUE, DyeColor.LIGHT_BLUE, DyeColor.PINK, DyeColor.MAGENTA, DyeColor.LIME, DyeColor.CYAN, DyeColor.PURPLE }; public DiscoParty(DiscoSheep parent, Player player) { this.ds = parent; this.player = player; } List<Sheep> getSheep() { return sheepList; } void spawnSheep(World world, Location loc) { Sheep newSheep = (Sheep) world.spawnEntity(loc, EntityType.SHEEP); newSheep.setMaxHealth(10000); newSheep.setHealth(10000); newSheep.setColor(discoColours[(int) Math.round(Math.random() * (discoColours.length - 1))]); getSheep().add(newSheep); } // Spawn some number of sheep next to given player void spawnSheep(int num) { Location loc; World world = player.getWorld(); for (int i = 0; i < num; i++) { double x, y, z; // random x and z coordinates within a 5 block radius // safe y-coordinate x = -sheepSpawnRadius + (Math.random() * ((sheepSpawnRadius * 2) + 1)) + player.getLocation().getX(); z = -sheepSpawnRadius + (Math.random() * ((sheepSpawnRadius * 2) + 1)) + player.getLocation().getZ(); y = world.getHighestBlockYAt((int) x, (int) z); loc = new Location(world, x, y, z); spawnSheep(world, loc); } } // Mark all sheep in the sheep array for removal, then clear the array void removeAllSheep() { for (Sheep sheep : getSheep()) { sheep.setHealth(0); sheep.remove(); } getSheep().clear(); } // Set a random colour for all sheep in array void randomizeSheepColours() { for (Sheep sheep : getSheep()) { sheep.setColor(discoColours[(int) Math.round(Math.random() * (discoColours.length - 1))]); } } void playSounds() { player.playSound(player.getLocation(), Sound.NOTE_BASS_DRUM, 1.0f, 1.0f); player.playSound(player.getLocation(), Sound.BURP, frequency, (float) Math.random() + 1); } void update() { if (duration > 0) { randomizeSheepColours(); playSounds(); duration -= frequency; this.scheduleUpdate(); } else { this.stopDisco(); } } void scheduleUpdate() { updater = new DiscoUpdater(this); updater.runTaskLater(ds, this.frequency); } void startDisco(int duration) { if (this.duration > 0) { stopDisco(); } this.spawnSheep(this.defaultSheepAmount); this.frequency = this.defaultFrequency; this.duration = this.defaultDuration; this.scheduleUpdate(); ds.getPartyMap().put(this.player.getName(), this); } void startDisco() { this.startDisco(this.defaultDuration); } void stopDisco() { removeAllSheep(); this.duration = 0; if (updater != null) { updater.cancel(); } updater = null; ds.getParties().remove(this.player.getName()); } }
package org.isisaddons.module.sessionlogger.dom; import java.sql.Timestamp; import java.util.Date; import org.apache.isis.applib.AbstractService; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.Programmatic; import org.apache.isis.applib.query.QueryDefault; import org.apache.isis.applib.services.session.SessionLoggingService; /** * Implementation of the Isis {@link org.apache.isis.applib.services.session.SessionLoggingService} creates a log * entry to the database (the {@link org.isisaddons.module.sessionlogger.dom.SessionLogEntry} entity) each time a * user either logs on or logs out, or if their session expires. */ @DomainService public class SessionLoggingServiceDefault extends AbstractService implements SessionLoggingService { @Programmatic @Override public void log(final Type type, final String username, final Date date, final CausedBy causedBy, final String sessionId) { final Timestamp timestamp = new Timestamp(new Date().getTime()); final SessionLogEntry sessionLogEntry; if (type == Type.LOGIN) { sessionLogEntry = newTransientInstance(SessionLogEntry.class); sessionLogEntry.setUsername(username); sessionLogEntry.setLoginTimestamp(timestamp); sessionLogEntry.setSessionId(sessionId); } else { sessionLogEntry = firstMatch(new QueryDefault<>(SessionLogEntry.class, "findBySessionId", "sessionId", sessionId)); if (sessionLogEntry == null) { // invalidation of a never authenticated session return; } sessionLogEntry.setLogoutTimestamp(timestamp); } sessionLogEntry.setCausedBy(causedBy); persistIfNotAlready(sessionLogEntry); } }
package dk.statsbiblioteket.doms.client.objects; import dk.statsbiblioteket.doms.client.datastreams.Datastream; import dk.statsbiblioteket.doms.client.datastreams.DatastreamDeclaration; import dk.statsbiblioteket.doms.client.datastreams.DatastreamModel; import dk.statsbiblioteket.doms.client.datastreams.InternalDatastream; import dk.statsbiblioteket.doms.client.sdo.SDOParsedXmlDocument; import dk.statsbiblioteket.doms.client.sdo.SDOParsedXmlElement; import dk.statsbiblioteket.doms.client.utils.Constants; import dk.statsbiblioteket.util.xml.DOM; import org.custommonkey.xmlunit.XMLUnit; import org.junit.Ignore; import org.junit.Test; import org.w3c.dom.Document; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Set; import static junit.framework.Assert.*; public class DatastreamTest extends TestBase{ public DatastreamTest() throws MalformedURLException { super(); } @Test public void testDatastreamModel() throws Exception { ContentModelObject cmProgram = (ContentModelObject) factory.getDigitalObject("doms:ContentModel_Program"); assertTrue(cmProgram instanceof ContentModelObject); if (cmProgram instanceof ContentModelObject){ DatastreamModel dsModel = cmProgram.getDsModel(); assertTrue(dsModel.getDatastreamDeclarations().size() > 0); assertNotNull(dsModel.getMimeType()); assertNotNull(dsModel.getFormatURI()); DatastreamDeclaration dsDcl = dsModel.getDatastreamDeclarations().get(0); } } @Test public void testDatastreamModel2() throws Exception { DigitalObject template = factory.getDigitalObject("doms:Template_Program"); Set<DatastreamDeclaration> declarations = template.getDatastream("PBCORE").getDeclarations(); assertTrue(declarations.size() > 0); for (DatastreamDeclaration declaration : declarations) { assertEquals(declaration.getName(),"PBCORE"); assertTrue(declaration.getPresentation() == Constants.GuiRepresentation.editable); Datastream pbcoreSchema = declaration.getSchema(); if (pbcoreSchema != null){ assertNotNull(pbcoreSchema.getContents()); } else { fail(); } } } private void changeField(SDOParsedXmlElement doc, String field, String newvalue){ ArrayList<SDOParsedXmlElement> children = doc.getChildren(); for (SDOParsedXmlElement child : children) { if (child.isLeaf()){ if (child.getLabel().equals(field)){ child.setValue(newvalue); } } else { changeField(child, field, newvalue); } } } @org.junit.Test public void testSaveDatastream() throws Exception { String destroyed = "uuid:503d1582-0df8-4397-9e33-86c097111513"; DigitalObject object = factory.getDigitalObject(destroyed); Datastream datastream = object.getDatastream("PBCORE"); SDOParsedXmlDocument doc = datastream.getSDOParsedDocument(); object.setState(Constants.FedoraState.Inactive); object.save(); String originaldoc = doc.dumpToString(); changeField(doc.getRootSDOParsedXmlElement(),"test", "testvalue"); String unchangeddoc = doc.dumpToString(); assertTrue(XMLUnit.compareXML(originaldoc,unchangeddoc).identical()); changeField(doc.getRootSDOParsedXmlElement(),"Subject", "test of change: "+Math.random()); String changeddoc = doc.dumpToString(); assertNotSame(originaldoc, unchangeddoc); /* if (datastream instanceof InternalDatastream) { InternalDatastream internalDatastream = (InternalDatastream) datastream; internalDatastream.replace(doc.dumpToString()); } */ object.save(); setUp(); DigitalObject object2 = factory.getDigitalObject(destroyed); SDOParsedXmlDocument doc2 = object2.getDatastream("PBCORE").getSDOParsedDocument(); String rereaddoc = doc2.dumpToString(); //TODO make this comparison work, they are xml alike assertTrue(XMLUnit.compareXML(changeddoc,rereaddoc).identical()); } }
package org.jboss.as.ejb3.remote.protocol.versionone; import org.jboss.ejb.client.remoting.PackedInteger; import org.jboss.ejb.client.remoting.ProtocolV1ClassTable; import org.jboss.ejb.client.remoting.ProtocolV1ObjectTable; import org.jboss.marshalling.ByteInput; import org.jboss.marshalling.ByteOutput; import org.jboss.marshalling.ClassResolver; import org.jboss.marshalling.Marshaller; import org.jboss.marshalling.MarshallerFactory; import org.jboss.marshalling.Marshalling; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.Unmarshaller; import org.jboss.marshalling.reflect.SunReflectiveCreator; import org.jboss.remoting3.Channel; import java.io.DataInput; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; /** * @author Jaikiran Pai */ abstract class AbstractMessageHandler implements MessageHandler { protected static final byte HEADER_NO_SUCH_EJB_FAILURE = 0x0A; protected static final byte HEADER_NO_SUCH_EJB_METHOD_FAILURE = 0x0B; protected static final byte HEADER_SESSION_NOT_ACTIVE_FAILURE = 0x0C; private static final byte HEADER_INVOCATION_EXCEPTION = 0x06; protected Map<String, Object> readAttachments(final ObjectInput input) throws IOException, ClassNotFoundException { final int numAttachments = input.readByte(); if (numAttachments == 0) { return new HashMap<String, Object>(); } final Map<String, Object> attachments = new HashMap<String, Object>(numAttachments); for (int i = 0; i < numAttachments; i++) { // read the key final String key = (String) input.readObject(); // read the attachment value final Object val = input.readObject(); attachments.put(key, val); } return attachments; } protected void writeAttachments(final ObjectOutput output, final Map<String, Object> attachments) throws IOException { if (attachments == null) { output.writeByte(0); return; } // write the attachment count PackedInteger.writePackedInteger(output, attachments.size()); for (Map.Entry<String, Object> entry : attachments.entrySet()) { output.writeObject(entry.getKey()); output.writeObject(entry.getValue()); } } protected void writeException(final Channel channel, final MarshallerFactory marshallerFactory, final short invocationId, final Throwable t, final Map<String, Object> attachments) throws IOException { final DataOutputStream outputStream = new DataOutputStream(channel.writeMessage()); try { // write the header outputStream.write(HEADER_INVOCATION_EXCEPTION); // write the invocation id outputStream.writeShort(invocationId); // write out the exception final Marshaller marshaller = this.prepareForMarshalling(marshallerFactory, outputStream); marshaller.writeObject(t); // write the attachments this.writeAttachments(marshaller, attachments); // finish marshalling marshaller.finish(); } finally { outputStream.close(); } } protected void writeInvocationFailure(final Channel channel, final byte messageHeader, final short invocationId, final String failureMessage) throws IOException { final DataOutputStream dataOutputStream = new DataOutputStream(channel.writeMessage()); try { // write header dataOutputStream.writeByte(messageHeader); // write invocation id dataOutputStream.writeShort(invocationId); // write the failure message dataOutputStream.writeUTF(failureMessage); } finally { dataOutputStream.close(); } } protected void writeNoSuchEJBFailureMessage(final Channel channel, final short invocationId, final String appName, final String moduleName, final String distinctname, final String beanName, final String viewClassName) throws IOException { final StringBuffer sb = new StringBuffer("No such EJB["); sb.append("appname=").append(appName).append(","); sb.append("modulename=").append(moduleName).append(","); sb.append("distinctname=").append(distinctname).append(","); sb.append("beanname=").append(beanName); if (viewClassName != null) { sb.append(",").append("viewclassname=").append(viewClassName); } sb.append("]"); this.writeInvocationFailure(channel, HEADER_NO_SUCH_EJB_FAILURE, invocationId, sb.toString()); } protected void writeSessionNotActiveFailureMessage(final Channel channel, final short invocationId, final String appName, final String moduleName, final String distinctname, final String beanName) throws IOException { final StringBuffer sb = new StringBuffer("Session not active for EJB["); sb.append("appname=").append(appName).append(","); sb.append("modulename=").append(moduleName).append(","); sb.append("distinctname=").append(distinctname).append(","); sb.append("beanname=").append(beanName).append("]"); this.writeInvocationFailure(channel, HEADER_SESSION_NOT_ACTIVE_FAILURE, invocationId, sb.toString()); } protected void writeNoSuchEJBMethodFailureMessage(final Channel channel, final short invocationId, final String appName, final String moduleName, final String distinctname, final String beanName, final String viewClassName, final String methodName, final String[] methodParamTypes) throws IOException { final StringBuffer sb = new StringBuffer("No such method "); sb.append(methodName).append("("); if (methodParamTypes != null) { for (int i = 0; i < methodParamTypes.length; i++) { if (i != 0) { sb.append(","); } sb.append(methodParamTypes[i]); } } sb.append(") on EJB["); sb.append("appname=").append(appName).append(","); sb.append("modulename=").append(moduleName).append(","); sb.append("distinctname=").append(distinctname).append(","); sb.append("beanname=").append(beanName).append(","); sb.append("viewclassname=").append(viewClassName).append("]"); this.writeInvocationFailure(channel, HEADER_NO_SUCH_EJB_METHOD_FAILURE, invocationId, sb.toString()); } /** * Creates and returns a {@link org.jboss.marshalling.Marshaller} which is ready to be used for marshalling. The {@link org.jboss.marshalling.Marshaller#start(org.jboss.marshalling.ByteOutput)} * will be invoked by this method, to use the passed {@link java.io.DataOutput dataOutput}, before returning the marshaller. * * @param marshallerFactory The marshaller factory * @param dataOutput The {@link java.io.DataOutput} to which the data will be marshalled * @return * @throws IOException */ protected org.jboss.marshalling.Marshaller prepareForMarshalling(final org.jboss.marshalling.MarshallerFactory marshallerFactory, final DataOutput dataOutput) throws IOException { final org.jboss.marshalling.Marshaller marshaller = this.getMarshaller(marshallerFactory); final OutputStream outputStream = new OutputStream() { @Override public void write(int b) throws IOException { final int byteToWrite = b & 0xff; dataOutput.write(byteToWrite); } }; final ByteOutput byteOutput = Marshalling.createByteOutput(outputStream); // start the marshaller marshaller.start(byteOutput); return marshaller; } /** * Creates and returns a {@link org.jboss.marshalling.Marshaller} * * @param marshallerFactory The marshaller factory * @return * @throws IOException */ private org.jboss.marshalling.Marshaller getMarshaller(final org.jboss.marshalling.MarshallerFactory marshallerFactory) throws IOException { final MarshallingConfiguration marshallingConfiguration = new MarshallingConfiguration(); marshallingConfiguration.setClassTable(ProtocolV1ClassTable.INSTANCE); marshallingConfiguration.setObjectTable(ProtocolV1ObjectTable.INSTANCE); marshallingConfiguration.setVersion(2); marshallingConfiguration.setSerializedCreator(new SunReflectiveCreator()); return marshallerFactory.createMarshaller(marshallingConfiguration); } /** * Creates and returns a {@link org.jboss.marshalling.Unmarshaller} which is ready to be used for unmarshalling. The {@link org.jboss.marshalling.Unmarshaller#start(org.jboss.marshalling.ByteInput)} * will be invoked by this method, to use the passed {@link java.io.DataInput dataInput}, before returning the unmarshaller. * * @param marshallerFactory The marshaller factory * @param classResolver The {@link ClassResolver} which will be used during unmarshalling * @param dataInput The data input from which to unmarshall * @return * @throws IOException */ protected Unmarshaller prepareForUnMarshalling(final MarshallerFactory marshallerFactory, final ClassResolver classResolver, final DataInput dataInput) throws IOException { final Unmarshaller unmarshaller = this.getUnMarshaller(marshallerFactory, classResolver); final InputStream is = new InputStream() { @Override public int read() throws IOException { try { final int b = dataInput.readByte(); return b & 0xff; } catch (EOFException eof) { return -1; } } }; final ByteInput byteInput = Marshalling.createByteInput(is); // start the unmarshaller unmarshaller.start(byteInput); return unmarshaller; } /** * Creates and returns a {@link Unmarshaller} * * @param marshallerFactory The marshaller factory * @return * @throws IOException */ private Unmarshaller getUnMarshaller(final MarshallerFactory marshallerFactory, final ClassResolver classResolver) throws IOException { final MarshallingConfiguration marshallingConfiguration = new MarshallingConfiguration(); marshallingConfiguration.setVersion(2); marshallingConfiguration.setClassTable(ProtocolV1ClassTable.INSTANCE); marshallingConfiguration.setObjectTable(ProtocolV1ObjectTable.INSTANCE); marshallingConfiguration.setClassResolver(classResolver); marshallingConfiguration.setSerializedCreator(new SunReflectiveCreator()); return marshallerFactory.createUnmarshaller(marshallingConfiguration); } }
package dr.inference.markovchain; import dr.evomodel.operators.AbstractImportanceDistributionOperator; import dr.evomodel.operators.SimpleGibbsOperator; import dr.inference.model.Likelihood; import dr.inference.model.Model; import dr.inference.model.CompoundLikelihood; import dr.inference.operators.*; import dr.inference.prior.Prior; import java.util.ArrayList; import java.util.logging.Logger; /** * A concrete markov chain. This is final as the only things that should need * overriding are in the delegates (prior, likelihood, schedule and acceptor). * The design of this class is to be fairly immutable as far as settings goes. * * @author Alexei Drummond * @author Andrew Rambaut * @version $Id: MarkovChain.java,v 1.10 2006/06/21 13:34:42 rambaut Exp $ */ public final class MarkovChain { private final OperatorSchedule schedule; private final Acceptor acceptor; private final Prior prior; private final Likelihood likelihood; private boolean pleaseStop = false; private boolean isStopped = false; private double bestScore, currentScore, initialScore; private int currentLength; private boolean useCoercion = true; private final int fullEvaluationCount; public MarkovChain(Prior prior, Likelihood likelihood, OperatorSchedule schedule, Acceptor acceptor, int fullEvaluationCount, boolean useCoercion) { currentLength = 0; this.prior = prior; this.likelihood = likelihood; this.schedule = schedule; this.acceptor = acceptor; this.useCoercion = useCoercion; this.fullEvaluationCount = fullEvaluationCount; currentScore = evaluate(likelihood, prior); } /** * Resets the markov chain */ public void reset() { currentLength = 0; // reset operator acceptance levels for(int i = 0; i < schedule.getOperatorCount(); i++) { schedule.getOperator(i).reset(); } } /** * Run the chain for a given number of states. * * @param length * number of states to run the chain. * @param onTheFlyOperatorWeights * @param logOps * Hack to log likelihood change with operators to stdout */ public int chain(int length, boolean disableCoerce, int onTheFlyOperatorWeights, boolean logOps) { boolean verbose = false; currentScore = evaluate(likelihood, prior); int currentState = currentLength; final Model currentModel = likelihood.getModel(); if( currentState == 0 ) { initialScore = currentScore; bestScore = currentScore; fireBestModel(currentState, currentModel); } if( currentScore == Double.NEGATIVE_INFINITY ) { // identify which component of the score is zero... if( prior != null ) { double logPrior = prior.getLogPrior(likelihood.getModel()); if( logPrior == Double.NEGATIVE_INFINITY ) { throw new IllegalArgumentException( "The initial model is invalid because one of the priors has zero probability."); } } String message = "The initial likelihood is zero"; if( likelihood instanceof CompoundLikelihood ) { message += ": " + ((CompoundLikelihood) likelihood).getDiagnosis(); } else { message += "!"; } throw new IllegalArgumentException(message); } pleaseStop = false; isStopped = false; int otfcounter = onTheFlyOperatorWeights > 0 ? onTheFlyOperatorWeights : 0; double[] logr = {0.0}; while( !pleaseStop && (currentState < (currentLength + length)) ) { // periodically log states fireCurrentModel(currentState, currentModel); if( pleaseStop ) { isStopped = true; break; } // Get the operator final int op = schedule.getNextOperatorIndex(); final MCMCOperator mcmcOperator = schedule.getOperator(op); final double oldScore = currentScore; // not used and why must it be a "compund like"? // String oldMessage = // ((CompoundLikelihood)likelihood).getDiagnosis(); // assert Profiler.startProfile("Store"); // The current model is stored here in case the proposal fails if( currentModel != null ) { currentModel.storeModelState(); } // assert Profiler.stopProfile("Store"); boolean operatorSucceeded = true; double hastingsRatio = 1.0; boolean accept = false; logr[0] = -Double.MAX_VALUE; try { // The new model is proposed // assert Profiler.startProfile("Operate"); if( verbose ) { System.out.println("\n&& Operator: " + mcmcOperator.getOperatorName()); } if( mcmcOperator instanceof SimpleGibbsOperator ) { hastingsRatio = ((SimpleGibbsOperator) mcmcOperator).operate(prior, likelihood); } else if( mcmcOperator instanceof AbstractImportanceDistributionOperator ) { hastingsRatio = ((AbstractImportanceDistributionOperator) mcmcOperator).operate(prior, likelihood); } else { hastingsRatio = mcmcOperator.operate(); } // assert Profiler.stopProfile("Operate"); } catch( OperatorFailedException e ) { operatorSucceeded = false; } double score = 0.0; double deviation = 0.0; if( operatorSucceeded ) { // The new model is proposed // assert Profiler.startProfile("Evaluate"); if( verbose ) { System.out.println("** Evaluate"); } // The new model is evaluated score = evaluate(likelihood, prior); // assert Profiler.stopProfile("Evaluate"); // This is a test that the state is correctly restored. The // restored state is fully evaluated and the likelihood compared with // that before the operation was made. if( currentState < fullEvaluationCount ) { likelihood.makeDirty(); final double testScore = evaluate(likelihood, prior); if( Math.abs(testScore - score) > 1e-6 ) { Logger.getLogger("error").severe( "State was not correctly calculated after an operator move.\n" + "Likelihood evaluation: " + score + "\nFull Likelihood evaluation: " + testScore + "\n" + "Operator: " + mcmcOperator + " " + mcmcOperator.getOperatorName()); } } if( score > bestScore ) { bestScore = score; fireBestModel(currentState, currentModel); } // accept = mcmcOperator instanceof GibbsOperator || // acceptor.accept(oldScore, score, hastingsRatio, logr); if( mcmcOperator instanceof SimpleGibbsOperator ) { accept = acceptor.accept(oldScore, score, hastingsRatio, logr); } else { accept = mcmcOperator instanceof GibbsOperator || acceptor.accept(oldScore, score, hastingsRatio, logr); } deviation = score - oldScore; } // The new model is accepted or rejected if( accept ) { if( verbose ) { System.out.println("** Move accepted: new score = " + score + ", old score = " + oldScore); } if( logOps ) { System.err.println("##" + (score - currentScore) + " " + mcmcOperator.getOperatorName()); } mcmcOperator.accept(deviation); currentModel.acceptModelState(); currentScore = score; if( otfcounter > 0 ) { --otfcounter; if( otfcounter == 0 ) { adjustOpWeights(currentState); otfcounter = onTheFlyOperatorWeights; } } } else { if( verbose ) { System.out.println("** Move rejected: new score = " + score + ", old score = " + oldScore); } mcmcOperator.reject(); // assert Profiler.startProfile("Restore"); currentModel.restoreModelState(); // Sebastian: can't tell why but somehow the likelihood is // screwed up if the tree needs to be restored // the only way to get around this problem was -> // likelihood.makeDirty(); // Comment by AR 12/04/2009 - this problem was indicative of an // error elsewhere any by adding this line a major efficiency saving // was lost. // assert Profiler.stopProfile("Restore"); // This is a test that the state is correctly restored. The // restored state is fully evaluated and the likelihood compared with // that before the operation was made. if( currentState < fullEvaluationCount ) { likelihood.makeDirty(); final double testScore = evaluate(likelihood, prior); if( Math.abs(testScore - oldScore) > 1e-6 ) { Logger.getLogger("error").severe( "State was not correctly restored after reject step.\n" + "Likelihood before: " + oldScore + " Likelihood after: " + testScore + "\n" + "Operator: " + mcmcOperator + " " + mcmcOperator.getOperatorName()); } } } if( !disableCoerce && mcmcOperator instanceof CoercableMCMCOperator ) { coerceAcceptanceProbability((CoercableMCMCOperator) mcmcOperator, logr[0]); } currentState += 1; } currentLength = currentState; fireFinished(currentLength); // Profiler.report(); return currentLength; } private void adjustOpWeights(int currentState) { final int count = schedule.getOperatorCount(); double[] s = new double[count]; final double factor = 100; final double limitSpan = 1000; System.err.println("start cycle " + currentState); double sHas = 0.0/* , sNot = 0.0 */, nHas = 0.0; for(int no = 0; no < count; ++no) { final MCMCOperator op = schedule.getOperator(no); final double v = op.getSpan(true); if( v == 0 ) { // sNot += op.getWeight(); s[no] = 0; } else { sHas += op.getWeight(); s[no] = Math.max(factor * Math.min(v, limitSpan), 1); nHas += s[no]; } } // for(int no = 0; no < count; ++no) { // final MCMCOperator op = schedule.getOperator(no); // final double v = op.getSpan(false); // if( v == 0 ) { // System.err.println(op.getOperatorName() + " blocks"); // return; // keep sum of changed parts unchanged final double scaleHas = sHas / nHas; for(int no = 0; no < count; ++no) { final MCMCOperator op = schedule.getOperator(no); if( s[no] > 0 ) { final double val = s[no] * scaleHas; op.setWeight(val); System.err.println("set " + op.getOperatorName() + " " + val); } else { System.err.println("** " + op.getOperatorName() + " = " + op.getWeight()); } } schedule.operatorsHasBeenUpdated(); } public Prior getPrior() { return prior; } public Likelihood getLikelihood() { return likelihood; } public Model getModel() { return likelihood.getModel(); } public OperatorSchedule getSchedule() { return schedule; } public Acceptor getAcceptor() { return acceptor; } public double getInitialScore() { return initialScore; } public double getBestScore() { return bestScore; } public int getCurrentLength() { return currentLength; } public void setCurrentLength(int currentLength) { this.currentLength = currentLength; } public double getCurrentScore() { return currentScore; } public void pleaseStop() { pleaseStop = true; } public boolean isStopped() { return isStopped; } private double evaluate(Likelihood likelihood, Prior prior) { double logPosterior = 0.0; if( prior != null ) { final double logPrior = prior.getLogPrior(likelihood.getModel()); if( logPrior == Double.NEGATIVE_INFINITY ) { return Double.NEGATIVE_INFINITY; } logPosterior += logPrior; } final double logLikelihood = likelihood.getLogLikelihood(); if( Double.isNaN(logLikelihood) ) { return Double.NEGATIVE_INFINITY; } // System.err.println("** " + logPosterior + " + " + logLikelihood + // " = " + (logPosterior + logLikelihood)); logPosterior += logLikelihood; return logPosterior; } /** * Updates the proposal parameter, based on the target acceptance * probability This method relies on the proposal parameter being a * decreasing function of acceptance probability. * * @param op The operator * @param logr */ private void coerceAcceptanceProbability(CoercableMCMCOperator op, double logr) { if( isCoercable(op) ) { final double p = op.getCoercableParameter(); final double i = schedule.getOptimizationTransform(MCMCOperator.Utils.getOperationCount(op)); final double target = op.getTargetAcceptanceProbability(); final double newp = p + ((1.0 / (i + 1.0)) * (Math.exp(logr) - target)); if( newp > -Double.MAX_VALUE && newp < Double.MAX_VALUE ) { op.setCoercableParameter(newp); } } } private boolean isCoercable(CoercableMCMCOperator op) { return op.getMode() == CoercionMode.COERCION_ON || (op.getMode() != CoercionMode.COERCION_OFF && useCoercion); } public void addMarkovChainListener(MarkovChainListener listener) { listeners.add(listener); } public void removeMarkovChainListener(MarkovChainListener listener) { listeners.remove(listener); } public void fireBestModel(int state, Model bestModel) { for(MarkovChainListener listener : listeners) { listener.bestState(state, bestModel); } } public void fireCurrentModel(int state, Model currentModel) { for(MarkovChainListener listener : listeners) { listener.currentState(state, currentModel); } } public void fireFinished(int chainLength) { for(MarkovChainListener listener : listeners) { listener.finished(chainLength); } } private final ArrayList<MarkovChainListener> listeners = new ArrayList<MarkovChainListener>(); }
package edu.jhu.thrax.extraction; import java.util.List; import edu.jhu.thrax.syntax.ParseTree; import org.apache.hadoop.conf.Configuration; public class SAMTLabeler implements SpanLabeler { private boolean TARGET_IS_SAMT_SYNTAX = true; private boolean ALLOW_CONSTITUENT_LABEL = true; private boolean ALLOW_CCG_LABEL = true; private boolean ALLOW_CONCAT_LABEL = true; private boolean ALLOW_DOUBLE_CONCAT = true; private UnaryCategoryHandler unaryCategoryHandler = UnaryCategoryHandler.ALL; private ParseTree tree; private String defaultLabel; public SAMTLabeler(Configuration conf, String parse) { TARGET_IS_SAMT_SYNTAX = conf.getBoolean("thrax.target-is-samt-syntax", true); ALLOW_CONSTITUENT_LABEL = conf.getBoolean("thrax.allow-constituent-label", true); ALLOW_CCG_LABEL = conf.getBoolean("thrax.allow-ccg-label", true); ALLOW_CONCAT_LABEL = conf.getBoolean("thrax.allow-concat-label", true); ALLOW_DOUBLE_CONCAT = conf.getBoolean("thrax.allow-double-plus", true); defaultLabel = conf.get("thrax.default-nt", "X"); tree = ParseTree.fromPennFormat(parse); if (tree == null) System.err.printf("WARNING: SAMT labeler: %s is not a parse tree\n", parse); } public String getLabel(int from, int to) { if (tree == null) return defaultLabel; String label; if (ALLOW_CONSTITUENT_LABEL) { label = constituentLabel(from, to); if (label != null) return label; } if (ALLOW_CONCAT_LABEL) { label = concatenatedLabel(from, to); if (label != null) return label; } if (ALLOW_CCG_LABEL) { label = forwardSlashLabel(from, to); if (label != null) return label; label = backwardSlashLabel(from, to); if (label != null) return label; } if (ALLOW_DOUBLE_CONCAT) { label = doubleConcatenatedLabel(from, to); if (label != null) return label; } return null; } private String constituentLabel(int from, int to) { List<ParseTree.Node> nodes = tree.internalNodesWithSpan(from, to); if (nodes.isEmpty()) return null; switch (unaryCategoryHandler) { case TOP: return nodes.get(0).label(); case BOTTOM: return nodes.get(nodes.size() - 1).label(); case ALL: String result = nodes.get(0).label(); for (int i = 1; i < nodes.size(); i++) result += ":" + nodes.get(i).label(); return result; } return null; } private String concatenatedLabel(int from, int to) { for (int mid = from + 1; mid < to; mid++) { String a = constituentLabel(from, mid); String b = constituentLabel(mid, to); if (a != null && b != null) return a + "+" + b; } return null; } private String forwardSlashLabel(int from, int to) { for (int end = to + 1; end <= tree.numLeaves(); end++) { String a = constituentLabel(from, end); String b = constituentLabel(to, end); if (a != null && b != null) return a + "/" + b; } return null; } private String backwardSlashLabel(int from, int to) { for (int start = from - 1; start >= 0; start String a = constituentLabel(start, to); String b = constituentLabel(start, from); if (a != null && b != null) return a + "\\" + b; } return null; } private String doubleConcatenatedLabel(int from, int to) { for (int mid1 = from + 1; mid1 < to - 1; mid1++) { for (int mid2 = mid1 + 1; mid2 < to; mid2++) { String a = constituentLabel(from, mid1); String b = constituentLabel(mid1, mid2); String c = constituentLabel(mid2, to); if (a != null && b != null && c != null) return a + "+" + b + "+" + c; } } return null; } public enum UnaryCategoryHandler { TOP, BOTTOM, ALL; public static UnaryCategoryHandler fromString(String s) { if (s.equalsIgnoreCase("top")) return TOP; else if (s.equalsIgnoreCase("bottom")) return BOTTOM; else return ALL; } } }
package org.incode.module.document.dom.impl.docs; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.Optional; import java.util.SortedSet; import java.util.TreeSet; import javax.inject.Inject; import javax.jdo.JDOHelper; import javax.jdo.annotations.Column; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.Index; import javax.jdo.annotations.Indices; import javax.jdo.annotations.Inheritance; import javax.jdo.annotations.InheritanceStrategy; import javax.jdo.annotations.NotPersistent; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Queries; import javax.jdo.annotations.Unique; import javax.jdo.annotations.Uniques; import com.google.common.collect.Lists; import com.google.common.eventbus.Subscribe; import org.apache.commons.lang3.StringUtils; import org.axonframework.eventhandling.annotation.EventHandler; import org.joda.time.LocalDate; import org.apache.isis.applib.AbstractSubscriber; import org.apache.isis.applib.ApplicationException; import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.ActionLayout; import org.apache.isis.applib.annotation.BookmarkPolicy; import org.apache.isis.applib.annotation.Collection; import org.apache.isis.applib.annotation.Contributed; import org.apache.isis.applib.annotation.DomainObject; import org.apache.isis.applib.annotation.DomainObjectLayout; import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.Editing; import org.apache.isis.applib.annotation.MemberOrder; import org.apache.isis.applib.annotation.Mixin; import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.annotation.Parameter; import org.apache.isis.applib.annotation.ParameterLayout; import org.apache.isis.applib.annotation.Programmatic; import org.apache.isis.applib.annotation.Property; import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.annotation.Where; import org.apache.isis.applib.services.background.BackgroundService2; import org.apache.isis.applib.services.factory.FactoryService; import org.apache.isis.applib.services.i18n.TranslatableString; import org.apache.isis.applib.services.registry.ServiceRegistry2; import org.apache.isis.applib.services.title.TitleService; import org.apache.isis.applib.services.xactn.TransactionService; import org.apache.isis.applib.value.Blob; import org.apache.isis.applib.value.Clob; import org.incode.module.document.DocumentModule; import org.incode.module.document.dom.impl.applicability.Applicability; import org.incode.module.document.dom.impl.applicability.ApplicabilityRepository; import org.incode.module.document.dom.impl.applicability.AttachmentAdvisor; import org.incode.module.document.dom.impl.applicability.AttachmentAdvisorAttachToNone; import org.incode.module.document.dom.impl.applicability.RendererModelFactory; import org.incode.module.document.dom.impl.renderers.Renderer; import org.incode.module.document.dom.impl.renderers.RendererFromBytesToBytes; import org.incode.module.document.dom.impl.renderers.RendererFromBytesToBytesWithPreviewToUrl; import org.incode.module.document.dom.impl.renderers.RendererFromBytesToChars; import org.incode.module.document.dom.impl.renderers.RendererFromBytesToCharsWithPreviewToUrl; import org.incode.module.document.dom.impl.renderers.RendererFromCharsToBytes; import org.incode.module.document.dom.impl.renderers.RendererFromCharsToBytesWithPreviewToUrl; import org.incode.module.document.dom.impl.renderers.RendererFromCharsToChars; import org.incode.module.document.dom.impl.renderers.RendererFromCharsToCharsWithPreviewToUrl; import org.incode.module.document.dom.impl.rendering.RenderingStrategy; import org.incode.module.document.dom.impl.types.DocumentType; import org.incode.module.document.dom.services.ClassNameViewModel; import org.incode.module.document.dom.services.ClassService; import org.incode.module.document.dom.spi.AttachmentAdvisorClassNameService; import org.incode.module.document.dom.spi.RendererModelFactoryClassNameService; import org.incode.module.document.dom.types.AtPathType; import org.incode.module.document.dom.types.FqcnType; import org.estatio.module.invoice.dom.DocumentTemplateData; import org.estatio.module.invoice.dom.DocumentTypeData; import org.estatio.module.invoice.dom.RenderingStrategyData; import lombok.Getter; import lombok.Setter; @PersistenceCapable( identityType= IdentityType.DATASTORE, schema = "incodeDocuments" ) @Inheritance(strategy = InheritanceStrategy.NEW_TABLE) @Queries({ @javax.jdo.annotations.Query( name = "findByTypeAndAtPath", language = "JDOQL", value = "SELECT " + "FROM org.incode.module.document.dom.impl.docs.DocumentTemplate " + "WHERE typeCopy == :type " + " && atPathCopy == :atPath " + "ORDER BY date DESC" ), @javax.jdo.annotations.Query( name = "findByTypeAndAtPathAndDate", language = "JDOQL", value = "SELECT " + "FROM org.incode.module.document.dom.impl.docs.DocumentTemplate " + "WHERE typeCopy == :type " + " && atPathCopy == :atPath " + " && date == :date " ), @javax.jdo.annotations.Query( name = "findByTypeAndApplicableToAtPath", language = "JDOQL", value = "SELECT " + "FROM org.incode.module.document.dom.impl.docs.DocumentTemplate " + "WHERE typeCopy == :type " + " && :atPath.startsWith(atPathCopy) " + "ORDER BY atPathCopy DESC, date DESC " ), @javax.jdo.annotations.Query( name = "findByApplicableToAtPath", language = "JDOQL", value = "SELECT " + "FROM org.incode.module.document.dom.impl.docs.DocumentTemplate " + "WHERE :atPath.startsWith(atPathCopy) " + "ORDER BY typeCopy ASC, atPathCopy DESC, date DESC " ), @javax.jdo.annotations.Query( name = "findByTypeAndApplicableToAtPathAndCurrent", language = "JDOQL", value = "SELECT " + "FROM org.incode.module.document.dom.impl.docs.DocumentTemplate " + "WHERE typeCopy == :type " + " && :atPath.startsWith(atPathCopy) " + " && (date == null || date <= :now) " + "ORDER BY atPathCopy DESC, date DESC " ), @javax.jdo.annotations.Query( name = "findByType", language = "JDOQL", value = "SELECT " + "FROM org.incode.module.document.dom.impl.docs.DocumentTemplate " + "WHERE typeCopy == :type " + "ORDER BY atPathCopy DESC, date DESC " ), @javax.jdo.annotations.Query( name = "findByApplicableToAtPathAndCurrent", language = "JDOQL", value = "SELECT " + "FROM org.incode.module.document.dom.impl.docs.DocumentTemplate " + " && :atPath.startsWith(atPathCopy) " + " && (date == null || date <= :now) " + "ORDER BY atPathCopy DESC, typeCopy, date DESC " ) }) @Uniques({ @Unique( name = "DocumentTemplate_type_atPath_date_IDX", members = { "typeCopy", "atPathCopy", "date" } ), }) @Indices({ @Index( name = "DocumentTemplate_atPath_date_IDX", members = { "atPathCopy", "date" } ), @Index( name = "DocumentTemplate_type_date_IDX", members = { "typeCopy", "date" } ), }) @DomainObject( objectType = "incodeDocuments.DocumentTemplate", editing = Editing.DISABLED ) @DomainObjectLayout( titleUiEvent = DocumentTemplate.TitleUiEvent.class, iconUiEvent = DocumentTemplate.IconUiEvent.class, cssClassUiEvent = DocumentTemplate.CssClassUiEvent.class, bookmarking = BookmarkPolicy.AS_ROOT ) public class DocumentTemplate extends DocumentAbstract<DocumentTemplate> { //region > ui event classes public static class TitleUiEvent extends DocumentModule.TitleUiEvent<DocumentTemplate>{} public static class IconUiEvent extends DocumentModule.IconUiEvent<DocumentTemplate>{} public static class CssClassUiEvent extends DocumentModule.CssClassUiEvent<DocumentTemplate>{} //endregion //region > title, icon, cssClass /** * Implemented as a subscriber so can be overridden by consuming application if required. */ @DomainService(nature = NatureOfService.DOMAIN) public static class TitleSubscriber extends AbstractSubscriber { public String getId() { return "incodeDocuments.DocumentTemplate$TitleSubscriber"; } @EventHandler @Subscribe public void on(DocumentTemplate.TitleUiEvent ev) { if(ev.getTitle() != null) { return; } ev.setTranslatableTitle(titleOf(ev.getSource())); } private TranslatableString titleOf(final DocumentTemplate template) { if(template.getDate() != null) { return TranslatableString.tr("[{type}] ({date})", "type", template.getType().getReference(), "date", template.getDate()); } else { return TranslatableString.tr("[{type}] {name}", "name", template.getName(), "type", template.getType().getReference()); } } @Inject TitleService titleService; } /** * Implemented as a subscriber so can be overridden by consuming application if required. */ @DomainService(nature = NatureOfService.DOMAIN) public static class IconSubscriber extends AbstractSubscriber { public String getId() { return "incodeDocuments.DocumentTemplate$IconSubscriber"; } @EventHandler @Subscribe public void on(DocumentTemplate.IconUiEvent ev) { if(ev.getIconName() != null) { return; } ev.setIconName(""); } } /** * Implemented as a subscriber so can be overridden by consuming application if required. */ @DomainService(nature = NatureOfService.DOMAIN) public static class CssClassSubscriber extends AbstractSubscriber { public String getId() { return "incodeDocuments.DocumentTemplate$CssClassSubscriber"; } @EventHandler @Subscribe public void on(DocumentTemplate.CssClassUiEvent ev) { if(ev.getCssClass() != null) { return; } ev.setCssClass(""); } } //endregion //region > constructor DocumentTemplate() { // for unit testing only } public DocumentTemplate( final DocumentType type, final LocalDate date, final String atPath, final String fileSuffix, final boolean previewOnly, final Blob blob, final RenderingStrategy contentRenderingStrategy, final String subjectText, final RenderingStrategy subjectRenderingStrategy) { this(type, date, atPath, fileSuffix, previewOnly, contentRenderingStrategy, subjectText, subjectRenderingStrategy); modifyBlob(blob); } public DocumentTemplate( final DocumentType type, final LocalDate date, final String atPath, final String fileSuffix, final boolean previewOnly, final String name, final String mimeType, final String text, final RenderingStrategy contentRenderingStrategy, final String subjectText, final RenderingStrategy subjectRenderingStrategy) { this(type, date, atPath, fileSuffix, previewOnly, contentRenderingStrategy, subjectText, subjectRenderingStrategy); setTextData(name, mimeType, text); } public DocumentTemplate( final DocumentType type, final LocalDate date, final String atPath, final String fileSuffix, final boolean previewOnly, final Clob clob, final RenderingStrategy contentRenderingStrategy, final String subjectText, final RenderingStrategy subjectRenderingStrategy) { this(type, date, atPath, fileSuffix, previewOnly, contentRenderingStrategy, subjectText, subjectRenderingStrategy); modifyClob(clob); } private DocumentTemplate( final DocumentType type, final LocalDate date, final String atPath, final String fileSuffix, final boolean previewOnly, final RenderingStrategy contentRenderingStrategy, final String nameText, final RenderingStrategy nameRenderingStrategy) { super(type, atPath); this.typeCopy = type; this.atPathCopy = atPath; this.date = date; this.fileSuffix = stripLeadingDotAndLowerCase(fileSuffix); this.previewOnly = previewOnly; this.contentRenderingStrategy = contentRenderingStrategy; this.nameText = nameText; this.nameRenderingStrategy = nameRenderingStrategy; } static String stripLeadingDotAndLowerCase(final String fileSuffix) { final int lastDot = fileSuffix.lastIndexOf("."); final String stripLeadingDot = fileSuffix.substring(lastDot+1); return stripLeadingDot.toLowerCase(); } //endregion //region > typeCopy (derived property, persisted) /** * Copy of {@link #getType()}, for query purposes only. */ @Getter @Setter @Column(allowsNull = "false", name = "typeId") @Property( notPersisted = true, // ignore for auditing hidden = Where.EVERYWHERE ) private DocumentType typeCopy; //endregion //region > atPathCopy (derived property, persisted) /** * Copy of {@link #getAtPath()}, for query purposes only. */ @Getter @Setter @Column(allowsNull = "false", length = AtPathType.Meta.MAX_LEN) @Property( notPersisted = true, // ignore for auditing hidden = Where.EVERYWHERE ) private String atPathCopy; //endregion @NotPersistent private DocumentTemplateData templateData; @Programmatic public DocumentTemplateData getTemplateData() { return templateData != null ? templateData : (templateData = getTypeData().lookup(getAtPathCopy())); } @NotPersistent private DocumentTypeData typeData; @Programmatic public DocumentTypeData getTypeData() { return typeData != null ? typeData : (typeData = DocumentTypeData.reverseLookup(getTypeCopy())); } @Programmatic public RenderingStrategyData getContentRenderingStrategyData() { return getTemplateData().getContentRenderingStrategy(); } @Programmatic public RenderingStrategyData getContentRenderingStrategyApi() { return getContentRenderingStrategyData(); } @Programmatic public RenderingStrategyData getNameRenderingStrategyData() { return getTemplateData().getNameRenderingStrategy(); } @Programmatic public RenderingStrategyData getNameRenderingStrategyApi() { return getNameRenderingStrategyData(); } //region > date (property) public static class DateDomainEvent extends DocumentTemplate.PropertyDomainEvent<LocalDate> { } @Getter @Setter @Column(allowsNull = "false") @Property( domainEvent = DateDomainEvent.class, editing = Editing.DISABLED ) private LocalDate date; //endregion //region > contentRenderingStrategy (property) public static class RenderingStrategyDomainEvent extends PropertyDomainEvent<RenderingStrategy> { } @Getter @Setter @Column(allowsNull = "false", name = "contentRenderStrategyId") @Property( domainEvent = RenderingStrategyDomainEvent.class, editing = Editing.DISABLED ) private RenderingStrategy contentRenderingStrategy; public RenderingStrategy getContentRenderingStrategy() { return contentRenderingStrategy; } //endregion //region > fileSuffix (property) public static class FileSuffixDomainEvent extends PropertyDomainEvent<String> { } @Getter @Setter @Column(allowsNull = "false", length = FileSuffixType.Meta.MAX_LEN) @Property( domainEvent = FileSuffixDomainEvent.class, editing = Editing.DISABLED ) private String fileSuffix; //endregion //region > nameText (persisted property) public static class NameTextDomainEvent extends PropertyDomainEvent<Clob> { } /** * Used to determine the name of the {@link Document#getName() name} of the rendered {@link Document}. */ @Getter @Setter @javax.jdo.annotations.Column(allowsNull = "false", length = NameTextType.Meta.MAX_LEN) @Property( notPersisted = true, // exclude from auditing domainEvent = NameTextDomainEvent.class, editing = Editing.DISABLED ) private String nameText; //endregion //region > nameRenderingStrategy (property) public static class NameRenderingStrategyDomainEvent extends PropertyDomainEvent<RenderingStrategy> { } @Getter @Setter @Column(allowsNull = "false", name = "nameRenderStrategyId") @Property( domainEvent = NameRenderingStrategyDomainEvent.class, editing = Editing.DISABLED ) private RenderingStrategy nameRenderingStrategy; public RenderingStrategy getNameRenderingStrategy() { return nameRenderingStrategy; } //endregion //region > PreviewOnly (property) public static class PreviewOnlyDomainEvent extends RenderingStrategy.PropertyDomainEvent<Boolean> { } /** * Whether this template can only be previewed (not used to also create a document). */ @Getter @Setter @Column(allowsNull = "false") @Property( domainEvent = PreviewOnlyDomainEvent.class, editing = Editing.DISABLED ) private boolean previewOnly; //endregion //region > applicabilities (collection) public static class ApplicabilitiesDomainEvent extends DocumentType.CollectionDomainEvent<Applicability> { } @javax.jdo.annotations.Persistent(mappedBy = "documentTemplate", dependentElement = "true") @Collection( domainEvent = ApplicabilitiesDomainEvent.class, editing = Editing.DISABLED ) @Getter @Setter private SortedSet<Applicability> appliesTo = new TreeSet<>(); //endregion //region > applicable (action) /** * TODO: remove once moved over to using DocumentTypeData and DocumentTemplateData */ @Mixin public static class _applicable { private final DocumentTemplate documentTemplate; public _applicable(final DocumentTemplate documentTemplate) { this.documentTemplate = documentTemplate; } public static class ActionDomainEvent extends DocumentAbstract.ActionDomainEvent { } @Action(domainEvent = ActionDomainEvent.class, semantics = SemanticsOf.IDEMPOTENT) @ActionLayout(cssClassFa = "fa-plus", contributed = Contributed.AS_ACTION) @MemberOrder(name = "appliesTo", sequence = "1") public DocumentTemplate $$( @Parameter(maxLength = FqcnType.Meta.MAX_LEN, mustSatisfy = FqcnType.Meta.Specification.class) @ParameterLayout(named = "Domain type") final String domainClassName, @Parameter(maxLength = FqcnType.Meta.MAX_LEN, mustSatisfy = FqcnType.Meta.Specification.class) @ParameterLayout(named = "Renderer Model Factory") final ClassNameViewModel rendererModelFactoryClassNameViewModel, @Parameter(maxLength = FqcnType.Meta.MAX_LEN, mustSatisfy = FqcnType.Meta.Specification.class) @ParameterLayout(named = "Attachment Advisor") final ClassNameViewModel attachmentAdvisorClassNameViewModel) { applicable( domainClassName, rendererModelFactoryClassNameViewModel.getFullyQualifiedClassName(), attachmentAdvisorClassNameViewModel.getFullyQualifiedClassName()); return this.documentTemplate; } public TranslatableString disable$$() { if (rendererModelFactoryClassNameService == null) { return TranslatableString.tr( "No RendererModelFactoryClassNameService registered to locate implementations of RendererModelFactory"); } if (attachmentAdvisorClassNameService == null) { return TranslatableString.tr( "No AttachmentAdvisorClassNameService registered to locate implementations of AttachmentAdvisor"); } return null; } public List<ClassNameViewModel> choices1$$() { return rendererModelFactoryClassNameService.rendererModelFactoryClassNames(); } public List<ClassNameViewModel> choices2$$() { return attachmentAdvisorClassNameService.attachmentAdvisorClassNames(); } public TranslatableString validate0$$(final String domainTypeName) { return isApplicable(domainTypeName) ? TranslatableString.tr( "Already applicable for '{domainTypeName}'", "domainTypeName", domainTypeName) : null; } @Programmatic public Applicability applicable( final Class<?> domainClass, final Class<? extends RendererModelFactory> renderModelFactoryClass, final Class<? extends AttachmentAdvisor> attachmentAdvisorClass) { return applicable( domainClass.getName(), renderModelFactoryClass, attachmentAdvisorClass != null ? attachmentAdvisorClass : AttachmentAdvisorAttachToNone.class ); } @Programmatic public Applicability applicable( final String domainClassName, final Class<? extends RendererModelFactory> renderModelFactoryClass, final Class<? extends AttachmentAdvisor> attachmentAdvisorClass) { return applicable(domainClassName, renderModelFactoryClass.getName(), attachmentAdvisorClass.getName() ); } @Programmatic public Applicability applicable( final String domainClassName, final String renderModelFactoryClassName, final String attachmentAdvisorClassName) { Applicability applicability = existingApplicability(domainClassName); if(applicability == null) { applicability = applicabilityRepository.create(documentTemplate, domainClassName, renderModelFactoryClassName, attachmentAdvisorClassName); } else { applicability.setRendererModelFactoryClassName(renderModelFactoryClassName); applicability.setAttachmentAdvisorClassName(attachmentAdvisorClassName); } return applicability; } private boolean isApplicable(final String domainClassName) { return existingApplicability(domainClassName) != null; } private Applicability existingApplicability(final String domainClassName) { SortedSet<Applicability> applicabilities = documentTemplate.getAppliesTo(); for (Applicability applicability : applicabilities) { if (applicability.getDomainClassName().equals(domainClassName)) { return applicability; } } return null; } @Inject RendererModelFactoryClassNameService rendererModelFactoryClassNameService; @Inject AttachmentAdvisorClassNameService attachmentAdvisorClassNameService; @Inject ApplicabilityRepository applicabilityRepository; } //endregion //region > notApplicable (action) /** * TODO: remove once moved over to using DocumentTypeData and DocumentTemplateData */ @Mixin public static class _notApplicable { private final DocumentTemplate documentTemplate; public _notApplicable(final DocumentTemplate documentTemplate) { this.documentTemplate = documentTemplate; } public static class NotApplicableDomainEvent extends DocumentTemplate.ActionDomainEvent { } @Action( domainEvent = NotApplicableDomainEvent.class, semantics = SemanticsOf.IDEMPOTENT_ARE_YOU_SURE ) @ActionLayout( cssClassFa = "fa-minus" ) @MemberOrder(name = "appliesTo", sequence = "2") public DocumentTemplate $$(final Applicability applicability) { applicabilityRepository.delete(applicability); return this.documentTemplate; } public TranslatableString disable$$() { final TranslatableString tr = factoryService.mixin(_applicable.class, documentTemplate).disable$$(); if(tr != null) { return tr; } return choices0$$().isEmpty() ? TranslatableString.tr("No applicabilities to remove") : null; } public SortedSet<Applicability> choices0$$() { return documentTemplate.getAppliesTo(); } @Inject ApplicabilityRepository applicabilityRepository; @Inject FactoryService factoryService; } //endregion //region > appliesTo, newRendererModelFactory + newRendererModel, newAttachmentAdvisor + newAttachmentAdvice /** * TODO: only called by DocumentTemplateEquivalenceIntegTest, so eventually should be able to delete (along with Applicable etc). */ @Programmatic public Optional<Applicability> applicableTo(final Class<?> domainObjectClass) { return Lists.newArrayList(getAppliesTo()).stream() .filter(applicability -> applies(applicability, domainObjectClass)).findFirst(); } /** * TODO: only called indirectly by {@link #applicableTo(Class)}, itself called only by test code, so should be able to delete. */ private boolean applies( final Applicability applicability, final Class<?> domainObjectClass) { final Class<?> load = classService.load(applicability.getDomainClassName()); return load.isAssignableFrom(domainObjectClass); } private RendererModelFactory newRendererModelFactory(final Object domainObject) { final Class<?> domainClass = domainObject.getClass(); return getTemplateData().newRenderModelFactory(domainClass, classService, serviceRegistry2); } @Programmatic public AttachmentAdvisor newAttachmentAdvisor(final Object domainObject) { final Class<?> domainClass = domainObject.getClass(); return getTemplateData().newAttachmentAdvisor(domainClass, classService, serviceRegistry2); } @Programmatic public Object newRendererModel(final Object domainObject) { final RendererModelFactory rendererModelFactory = newRendererModelFactory(domainObject); if(rendererModelFactory == null) { throw new IllegalStateException(String.format( "For domain template %s, could not locate Applicability for domain object: %s", getName(), domainObject.getClass().getName())); } final Object rendererModel = rendererModelFactory.newRendererModel(this, domainObject); serviceRegistry2.injectServicesInto(rendererModel); return rendererModel; } @Programmatic public List<AttachmentAdvisor.PaperclipSpec> newAttachmentAdvice(final Document document, final Object domainObject) { final AttachmentAdvisor attachmentAdvisor = newAttachmentAdvisor(domainObject); if(attachmentAdvisor == null) { throw new IllegalStateException(String.format( "For domain template %s, could not locate Applicability for domain object: %s", getName(), domainObject.getClass().getName())); } final List<AttachmentAdvisor.PaperclipSpec> paperclipSpecs = attachmentAdvisor.advise(this, domainObject, document); return paperclipSpecs; } //endregion //region > preview, previewUrl (programmatic) @Programmatic public URL previewUrl(final Object rendererModel) throws IOException { serviceRegistry2.injectServicesInto(rendererModel); if(!getTemplateData().getContentRenderingStrategy().isPreviewsToUrl()) { throw new IllegalStateException(String.format("RenderingStrategy '%s' does not support previewing to URL", getTemplateData().getContentRenderingStrategy().getReference())); } final DocumentNature inputNature = getTemplateData().getContentRenderingStrategy().getInputNature(); final DocumentNature outputNature = getTemplateData().getContentRenderingStrategy().getOutputNature(); final Renderer renderer = getContentRenderingStrategyApi().newRenderer( classService, serviceRegistry2); switch (inputNature){ case BYTES: switch (outputNature) { case BYTES: return ((RendererFromBytesToBytesWithPreviewToUrl) renderer).previewBytesToBytes( getType(), getAtPath(), getVersion(), asBytes(), rendererModel); case CHARACTERS: return ((RendererFromBytesToCharsWithPreviewToUrl) renderer).previewBytesToChars( getType(), getAtPath(), getVersion(), asBytes(), rendererModel); default: // shouldn't happen, above switch statement is complete throw new IllegalArgumentException(String.format("Unknown output DocumentNature '%s'", outputNature)); } case CHARACTERS: switch (outputNature) { case BYTES: return ((RendererFromCharsToBytesWithPreviewToUrl) renderer).previewCharsToBytes( getType(), getAtPath(), getVersion(), asChars(), rendererModel); case CHARACTERS: return ((RendererFromCharsToCharsWithPreviewToUrl) renderer).previewCharsToChars( getType(), getAtPath(), getVersion(), asChars(), rendererModel); default: // shouldn't happen, above switch statement is complete throw new IllegalArgumentException(String.format("Unknown output DocumentNature '%s'", outputNature)); } default: // shouldn't happen, above switch statement is complete throw new IllegalArgumentException(String.format("Unknown input DocumentNature '%s'", inputNature)); } } //endregion //region > create, createAndRender, createAndScheduleRender (programmatic) @Programmatic public Document create(final Object domainObject) { final Document document = createDocumentUsingRendererModel(domainObject); transactionService.flushTransaction(); return document; } @Programmatic public Document createAndScheduleRender(final Object domainObject) { final Document document = create(domainObject); backgroundService2.execute(document).render(this, domainObject); return document; } @Programmatic public Document createAndRender(final Object domainObject) { final Document document = create(domainObject); document.render(this, domainObject); return document; } //endregion //region > createDocument (programmatic) @Programmatic public Document createDocumentUsingRendererModel( final Object domainObject) { final Object rendererModel = newRendererModel(domainObject); final String documentName = determineDocumentName(rendererModel); return createDocument(documentName); } private String determineDocumentName(final Object contentDataModel) { serviceRegistry2.injectServicesInto(contentDataModel); // subject final RendererFromCharsToChars nameRenderer = (RendererFromCharsToChars) getNameRenderingStrategyApi().newRenderer( classService, serviceRegistry2); String renderedDocumentName; try { renderedDocumentName = nameRenderer.renderCharsToChars( getType(), "name", getAtPath(), getVersion(), getNameText(), contentDataModel); } catch (IOException e) { renderedDocumentName = getName(); } return withFileSuffix(renderedDocumentName); } private Document createDocument(String documentName) { return documentRepository.create(getType(), getAtPath(), documentName, getMimeType()); } //endregion //region > renderContent (programmatic) @Programmatic public void renderContent( final Document document, final Object contentDataModel) { renderContent((DocumentLike)document, contentDataModel); } @Programmatic public void renderContent( final DocumentLike document, final Object contentDataModel) { final String documentName = determineDocumentName(contentDataModel); document.setName(documentName); final RenderingStrategyData renderingStrategy = getContentRenderingStrategyApi(); final String variant = "content"; try { final DocumentNature inputNature = renderingStrategy.getInputNature(); final DocumentNature outputNature = renderingStrategy.getOutputNature(); final Renderer renderer = renderingStrategy.newRenderer(classService, serviceRegistry2); switch (inputNature){ case BYTES: switch (outputNature) { case BYTES: final byte[] renderedBytes = ((RendererFromBytesToBytes) renderer).renderBytesToBytes( getType(), variant, getAtPath(), getVersion(), asBytes(), contentDataModel); final Blob blob = new Blob (documentName, getMimeType(), renderedBytes); document.modifyBlob(blob); return; case CHARACTERS: final String renderedChars = ((RendererFromBytesToChars) renderer).renderBytesToChars( getType(), variant, getAtPath(), getVersion(), asBytes(), contentDataModel); if(renderedChars.length() <= TextType.Meta.MAX_LEN) { document.setTextData(getName(), getMimeType(), renderedChars); } else { final Clob clob = new Clob (documentName, getMimeType(), renderedChars); document.modifyClob(clob); } return; default: // shouldn't happen, above switch statement is complete throw new IllegalArgumentException(String.format("Unknown output DocumentNature '%s'", outputNature)); } case CHARACTERS: switch (outputNature) { case BYTES: final byte[] renderedBytes = ((RendererFromCharsToBytes) renderer).renderCharsToBytes( getType(), variant, getAtPath(), getVersion(), asChars(), contentDataModel); final Blob blob = new Blob (documentName, getMimeType(), renderedBytes); document.modifyBlob(blob); return; case CHARACTERS: final String renderedChars = ((RendererFromCharsToChars) renderer).renderCharsToChars( getType(), variant, getAtPath(), getVersion(), asChars(), contentDataModel); if(renderedChars.length() <= TextType.Meta.MAX_LEN) { document.setTextData(getName(), getMimeType(), renderedChars); } else { final Clob clob = new Clob (documentName, getMimeType(), renderedChars); document.modifyClob(clob); } return; default: // shouldn't happen, above switch statement is complete throw new IllegalArgumentException(String.format("Unknown output DocumentNature '%s'", outputNature)); } default: // shouldn't happen, above switch statement is complete throw new IllegalArgumentException(String.format("Unknown input DocumentNature '%s'", inputNature)); } } catch (IOException e) { throw new ApplicationException("Unable to render document template", e); } } //endregion //region > withFileSuffix (programmatic) @Programmatic public String withFileSuffix(final String documentName) { final String suffix = getFileSuffix(); final int lastPeriod = suffix.lastIndexOf("."); final String suffixNoDot = suffix.substring(lastPeriod + 1); final String suffixWithDot = "." + suffixNoDot; if (documentName.endsWith(suffixWithDot)) { return trim(documentName, NameType.Meta.MAX_LEN); } else { return StringUtils.stripEnd(trim(documentName, NameType.Meta.MAX_LEN - suffixWithDot.length()),".") + suffixWithDot; } } private static String trim(final String name, final int length) { return name.length() > length ? name.substring(0, length) : name; } //endregion //region > getVersion (programmatic) @Programmatic private long getVersion() { return (Long)JDOHelper.getVersion(this); } //endregion //region > injected services @Inject ClassService classService; @Inject ServiceRegistry2 serviceRegistry2; @Inject TransactionService transactionService; @Inject BackgroundService2 backgroundService2; //endregion //region > types public static class FileSuffixType { private FileSuffixType() {} public static class Meta { public static final int MAX_LEN = 12; private Meta() {} } } public static class NameTextType { private NameTextType() {} public static class Meta { public static final int MAX_LEN = 255; private Meta() {} } } //endregion }
package edu.emory.cci.aiw.cvrg.eureka.services.jdbc; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import edu.emory.cci.aiw.cvrg.eureka.common.entity.Configuration; import edu.emory.cci.aiw.cvrg.eureka.services.dataprovider.CPT; import edu.emory.cci.aiw.cvrg.eureka.services.dataprovider.Encounter; import edu.emory.cci.aiw.cvrg.eureka.services.dataprovider.Icd9Diagnosis; import edu.emory.cci.aiw.cvrg.eureka.services.dataprovider.Icd9Procedure; import edu.emory.cci.aiw.cvrg.eureka.services.dataprovider.Lab; import edu.emory.cci.aiw.cvrg.eureka.services.dataprovider.Medication; import edu.emory.cci.aiw.cvrg.eureka.services.dataprovider.Observation; import edu.emory.cci.aiw.cvrg.eureka.services.dataprovider.ObservationWithResult; import edu.emory.cci.aiw.cvrg.eureka.services.dataprovider.Patient; import edu.emory.cci.aiw.cvrg.eureka.services.dataprovider.Provider; import edu.emory.cci.aiw.cvrg.eureka.services.dataprovider.Vital; /** * Inserts data into a Protempa database. * * @author hrathod * */ public class DataInserter { /** * The user's configuration, used to get database connection information. */ private final Configuration configuration; /** * Build a new object with the given configuration. * * @param inConfiguration The configuration to use for database connection * information. * @throws SQLException Thrown if there are any JDBC errors. */ public DataInserter(Configuration inConfiguration) throws SQLException { super(); this.configuration = inConfiguration; this.truncateTables(); } /** * Get a connection to the target database using the current user's * configuration. * * @return A connection to the target database. * * @throws SQLException Thrown if there are any JDBC errors. */ private Connection getConnection() throws SQLException { StringBuilder connectString = new StringBuilder(); connectString.append("jdbc:oracle:thin:@") .append(this.configuration.getProtempaHost()).append(":") .append(this.configuration.getProtempaPort()).append("/") .append(this.configuration.getProtempaDatabaseName()); return DriverManager.getConnection(connectString.toString(), this.configuration.getProtempaSchema(), this.configuration.getProtempaPass()); } /** * Truncate all the tables that we will be inserting into later. * * @throws SQLException Thrown if there are any JDBC errors. */ private void truncateTables() throws SQLException { final Connection connection = this.getConnection(); final List<String> sqlStatements = new ArrayList<String>(); sqlStatements.add("truncate table patient"); sqlStatements.add("truncate table encounter"); sqlStatements.add("truncate table provider"); sqlStatements.add("truncate table cpt_event"); sqlStatements.add("truncate table icd9d_event"); sqlStatements.add("truncate table icd9p_event"); sqlStatements.add("truncate table labs_event"); sqlStatements.add("truncate table meds_event"); sqlStatements.add("truncate table vitals_event"); for (String sql : sqlStatements) { Statement statement = connection.createStatement(); statement.executeUpdate(sql); statement.close(); } connection.commit(); connection.close(); } /** * Insert a list of patients to the data base using the given connection. * * @param patients The list of patients to insert. * @throws SQLException Thrown if there are any JDBC errors. */ public void insertPatients(List<Patient> patients) throws SQLException { int counter = 0; final Connection connection = this.getConnection(); PreparedStatement preparedStatement = connection .prepareStatement("insert into patient values (?,?,?,?,?,?,?,?)"); for (Patient patient : patients) { Date dateOfBirth; if (patient.getDateOfBirth() == null) { dateOfBirth = null; } else { dateOfBirth = new Date(patient.getDateOfBirth().getTime()); } preparedStatement.setLong(1, patient.getId().longValue()); preparedStatement.setString(2, patient.getFirstName()); preparedStatement.setString(3, patient.getLastName()); preparedStatement.setDate(4, dateOfBirth); preparedStatement.setString(5, patient.getLanguage()); preparedStatement.setString(6, patient.getMaritalStatus()); preparedStatement.setString(7, patient.getRace()); preparedStatement.setString(8, patient.getGender()); preparedStatement.addBatch(); counter++; if (counter >= 128) { preparedStatement.executeBatch(); connection.commit(); preparedStatement.clearBatch(); counter = 0; } } preparedStatement.executeBatch(); connection.commit(); preparedStatement.clearBatch(); preparedStatement.close(); connection.close(); } /** * Insert the given list of encounters to a target database using the given * connection. * * @param encounters The list of encounters to insert. * @throws SQLException Thrown if there are any JDBC errors. */ public void insertEncounters(List<Encounter> encounters) throws SQLException { int counter = 0; final Connection connection = this.getConnection(); PreparedStatement preparedStatement = connection .prepareStatement("insert into encounter values (?,?,?,?,?,?,?)"); for (Encounter encounter : encounters) { preparedStatement.setLong(1, encounter.getId().longValue()); preparedStatement.setLong(2, encounter.getPatientId().longValue()); preparedStatement.setLong(3, encounter.getProviderId().longValue()); preparedStatement.setTimestamp(4, new Timestamp(encounter .getStart().getTime())); preparedStatement.setTimestamp(5, new Timestamp(encounter.getEnd() .getTime())); preparedStatement.setString(6, encounter.getType()); preparedStatement.setString(7, encounter.getDischargeDisposition()); preparedStatement.addBatch(); counter++; if (counter >= 128) { preparedStatement.executeBatch(); connection.commit(); preparedStatement.clearBatch(); counter = 0; } } preparedStatement.executeBatch(); connection.commit(); preparedStatement.clearBatch(); preparedStatement.close(); connection.close(); } /** * Insert the given list of providers to a target database using the given * connection. * * @param providers The list of providers to insert. * @throws SQLException Thrown if there are any JDBC errors. */ public void insertProviders(List<Provider> providers) throws SQLException { int counter = 0; final Connection connection = this.getConnection(); PreparedStatement preparedStatement = connection .prepareStatement("insert into provider values (?,?,?)"); for (Provider provider : providers) { preparedStatement.setLong(1, provider.getId().longValue()); preparedStatement.setString(2, provider.getFirstName()); preparedStatement.setString(3, provider.getLastName()); preparedStatement.addBatch(); counter++; if (counter >= 128) { preparedStatement.executeBatch(); connection.commit(); preparedStatement.clearBatch(); counter = 0; } } preparedStatement.executeBatch(); connection.commit(); preparedStatement.clearBatch(); preparedStatement.close(); connection.close(); } /** * Insert the given list of CPT codes to a target database using the given * connection. * * @param cptCodes The list of CPT codes to insert. * @throws SQLException Thrown if there are any JDBC errors. */ public void insertCptCodes(List<CPT> cptCodes) throws SQLException { this.insertObservations(cptCodes, "cpt_event"); } /** * Insert the given list of ICD9 diagnosis codes to a target database using * the given connection. * * @param diagnoses The list of diagnosis codes to insert. * @throws SQLException Thrown if there are any JDBC errors. */ public void insertIcd9Diagnoses(List<Icd9Diagnosis> diagnoses) throws SQLException { this.insertObservations(diagnoses, "icd9d_event"); } /** * Insert the given list of ICD9 procedure codes to a target database using * the given connection. * * @param procedures The list of procedure codes to insert. * @throws SQLException Thrown if there are any JDBC errors. */ public void insertIcd9Procedures(List<Icd9Procedure> procedures) throws SQLException { this.insertObservations(procedures, "icd9p_event"); } /** * Insert the given list of medications to a target database using the given * connection. * * @param medications The list of medications to insert. * @throws SQLException Thrown if there are any JDBC errors. */ public void insertMedications(List<Medication> medications) throws SQLException { this.insertObservations(medications, "meds_event"); } /** * Insert the given list of lab results to a target database using the given * connection. * * @param labs The list of lab results to insert. * @throws SQLException Thrown if there are any JDBC errors. */ public void insertLabs(List<Lab> labs) throws SQLException { this.insertObservationsWithResult(labs, "labs_event"); } /** * Insert the given list of vital signs to a target database using the given * connection. * * @param vitals The list of vitals to insert. * @throws SQLException Thrown if there are any JDBC errors. */ public void insertVitals(List<Vital> vitals) throws SQLException { this.insertObservationsWithResult(vitals, "vitals_event"); } /** * Add the given list of observation objects to a target database using the * given connection. * * @param observations The list of observations to insert. * @param table The table in which the observations should be inserted. * @throws SQLException Thrown if there are any JDBC errors. */ private void insertObservations(List<? extends Observation> observations, String table) throws SQLException { int counter = 0; StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append("insert into ").append(table) .append(" values (?,?,?,?)"); final Connection connection = this.getConnection(); PreparedStatement preparedStatement = connection .prepareStatement(sqlBuilder.toString()); for (Observation observation : observations) { preparedStatement.setString(1, observation.getId()); preparedStatement.setLong(2, observation.getEncounterId() .longValue()); preparedStatement.setTimestamp(3, new Timestamp(observation .getTimestamp().getTime())); preparedStatement.setString(4, observation.getEntityId()); preparedStatement.addBatch(); counter++; if (counter >= 128) { preparedStatement.executeBatch(); connection.commit(); preparedStatement.clearBatch(); counter = 0; } } preparedStatement.executeBatch(); connection.commit(); preparedStatement.clearBatch(); preparedStatement.close(); connection.close(); } /** * Insert a list of observations and their related results to a target * database using the given connection. * * @param observations The observations to insert. * @param table The table in which the observations should be inserted. * @throws SQLException Thrown if there are any JDBC errors. */ private void insertObservationsWithResult( List<? extends ObservationWithResult> observations, String table) throws SQLException { int counter = 0; StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append("insert into ").append(table) .append(" values (?,?,?,?,?,?,?,?)"); final Connection connection = this.getConnection(); PreparedStatement preparedStatement = connection .prepareStatement(sqlBuilder.toString()); for (ObservationWithResult observation : observations) { preparedStatement.setString(1, observation.getId()); preparedStatement.setLong(2, observation.getEncounterId() .longValue()); preparedStatement.setTimestamp(3, new Timestamp(observation .getTimestamp().getTime())); preparedStatement.setString(4, observation.getEntityId()); preparedStatement.setString(5, observation.getResultAsStr()); preparedStatement.setDouble(6, observation.getResultAsNum() .doubleValue()); preparedStatement.setString(7, observation.getUnits()); preparedStatement.setString(8, observation.getFlag()); preparedStatement.addBatch(); counter++; if (counter >= 128) { preparedStatement.executeBatch(); connection.commit(); preparedStatement.clearBatch(); counter = 0; } } preparedStatement.executeBatch(); connection.commit(); preparedStatement.clearBatch(); preparedStatement.close(); connection.close(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package erp.mod.qlt.form; import erp.SClient; import erp.data.SDataConstants; import erp.data.SDataUtilities; import erp.lib.SLibConstants; import erp.mitm.data.SDataItem; import erp.mod.SModConsts; import erp.mod.SModSysConsts; import erp.mod.qlt.db.SDbLotApproved; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.JButton; import sa.lib.SLibConsts; import sa.lib.SLibUtils; import sa.lib.db.SDbRegistry; import sa.lib.gui.SGuiClient; import sa.lib.gui.SGuiConsts; import sa.lib.gui.SGuiOptionPicker; import sa.lib.gui.SGuiUtils; import sa.lib.gui.SGuiValidation; import sa.lib.gui.bean.SBeanFieldKey; import sa.lib.gui.bean.SBeanForm; public class SFormQltLotApproved extends SBeanForm implements ActionListener, ItemListener { protected SDbLotApproved moRegistry; /** * Creates new form SFormQltLotApproved * @param client * @param title */ public SFormQltLotApproved(SGuiClient client, String title) { setFormSettings(client, SGuiConsts.BEAN_FORM_EDIT, SModConsts.QLT_LOT_APR, SLibConsts.UNDEFINED, title); initComponents(); initComponentsCustom(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel3 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel14 = new javax.swing.JPanel(); jlDate = new javax.swing.JLabel(); moDate = new sa.lib.gui.bean.SBeanFieldDate(); jPanel5 = new javax.swing.JPanel(); jlBizPartner = new javax.swing.JLabel(); moKeyBizPartner = new sa.lib.gui.bean.SBeanFieldKey(); jbBizPartner = new javax.swing.JButton(); jPanel6 = new javax.swing.JPanel(); jlItem = new javax.swing.JLabel(); moKeyItem = new sa.lib.gui.bean.SBeanFieldKey(); jbItem = new javax.swing.JButton(); jPanel7 = new javax.swing.JPanel(); jlUnit = new javax.swing.JLabel(); moKeyUnit = new sa.lib.gui.bean.SBeanFieldKey(); jbUnit = new javax.swing.JButton(); jPanel8 = new javax.swing.JPanel(); jlLot = new javax.swing.JLabel(); moTextLot = new sa.lib.gui.bean.SBeanFieldText(); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del registro:")); jPanel1.setLayout(new java.awt.BorderLayout()); jPanel2.setLayout(new java.awt.GridLayout(15, 1, 0, 5)); jPanel14.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlDate.setText("Fecha:*"); jlDate.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel14.add(jlDate); jPanel14.add(moDate); jPanel2.add(jPanel14); jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlBizPartner.setText("Proveedor:*"); jlBizPartner.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel5.add(jlBizPartner); moKeyBizPartner.setPreferredSize(new java.awt.Dimension(300, 23)); jPanel5.add(moKeyBizPartner); jbBizPartner.setText("..."); jbBizPartner.setFocusable(false); jbBizPartner.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel5.add(jbBizPartner); jPanel2.add(jPanel5); jPanel6.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlItem.setText("Item:*"); jlItem.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel6.add(jlItem); moKeyItem.setPreferredSize(new java.awt.Dimension(300, 23)); jPanel6.add(moKeyItem); jbItem.setText("..."); jbItem.setFocusable(false); jbItem.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel6.add(jbItem); jPanel2.add(jPanel6); jPanel7.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlUnit.setText("Unidad:*"); jlUnit.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel7.add(jlUnit); moKeyUnit.setPreferredSize(new java.awt.Dimension(300, 23)); jPanel7.add(moKeyUnit); jbUnit.setText("..."); jbUnit.setFocusable(false); jbUnit.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel7.add(jbUnit); jPanel2.add(jPanel7); jPanel8.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlLot.setText("Lote aprobado:*"); jlLot.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel8.add(jlLot); moTextLot.setPreferredSize(new java.awt.Dimension(300, 23)); jPanel8.add(moTextLot); jPanel2.add(jPanel8); jPanel1.add(jPanel2, java.awt.BorderLayout.PAGE_START); getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel14; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JButton jbBizPartner; private javax.swing.JButton jbItem; private javax.swing.JButton jbUnit; private javax.swing.JLabel jlBizPartner; private javax.swing.JLabel jlDate; private javax.swing.JLabel jlItem; private javax.swing.JLabel jlLot; private javax.swing.JLabel jlUnit; private sa.lib.gui.bean.SBeanFieldDate moDate; private sa.lib.gui.bean.SBeanFieldKey moKeyBizPartner; private sa.lib.gui.bean.SBeanFieldKey moKeyItem; private sa.lib.gui.bean.SBeanFieldKey moKeyUnit; private sa.lib.gui.bean.SBeanFieldText moTextLot; // End of variables declaration//GEN-END:variables /* * Private methods */ private void initComponentsCustom() { SGuiUtils.setWindowBounds(this, 480, 300); moDate.setDateSettings(miClient, SGuiUtils.getLabelName(jlDate.getText()), true); moKeyBizPartner.setKeySettings(miClient, SGuiUtils.getLabelName(jlBizPartner.getText()), true); moKeyItem.setKeySettings(miClient, SGuiUtils.getLabelName(jlItem.getText()), true); moKeyUnit.setKeySettings(miClient, SGuiUtils.getLabelName(jlUnit), true); moTextLot.setTextSettings(SGuiUtils.getLabelName(jlLot.getText()), 25); moFields.addField(moDate); moFields.addField(moKeyBizPartner); moFields.addField(moKeyItem); moFields.addField(moKeyUnit); moFields.addField(moTextLot); moFields.setFormButton(jbSave); } private void actionPickItem() { int[] key = null; SGuiOptionPicker picker = null; picker = miClient.getSession().getModule(SModConsts.MOD_ITM_N).getOptionPicker(SModConsts.ITMU_ITEM, SLibConsts.UNDEFINED, null); picker.resetPicker(); picker.setPickerVisible(true); if (picker.getPickerResult() == SGuiConsts.FORM_RESULT_OK) { key = (int[]) picker.getOption(); if (key != null) { if (key[0] != SLibConsts.UNDEFINED) { moKeyItem.setValue(new int[] { key[0] }); } } } } private void actionPickUnit() { int[] key = null; SGuiOptionPicker picker = null; picker = miClient.getSession().getModule(SModConsts.MOD_ITM_N).getOptionPicker(SModConsts.ITMU_UNIT, SLibConsts.UNDEFINED, null); picker.resetPicker(); picker.setPickerVisible(true); if (picker.getPickerResult() == SGuiConsts.FORM_RESULT_OK) { key = (int[]) picker.getOption(); if (key != null) { if (key[0] != SLibConsts.UNDEFINED) { moKeyUnit.setValue(new int[] { key[0] }); } } } } private void actionPickBizPartner() { int[] key = null; SGuiOptionPicker picker = null; picker = miClient.getSession().getModule(SModConsts.MOD_BPS_N).getOptionPicker(SModConsts.BPSU_BP, SModSysConsts.BPSS_CT_BP_SUP, null); picker.resetPicker(); picker.setPickerVisible(true); if (picker.getPickerResult() == SGuiConsts.FORM_RESULT_OK) { key = (int[]) picker.getOption(); if (key != null) { if (key[0] != SLibConsts.UNDEFINED) { moKeyBizPartner.setValue(new int[] { key[0] }); } } } } private void itemStateKeyItem() { if (moKeyItem.getSelectedIndex() != 0) { SDataItem item = (SDataItem) SDataUtilities.readRegistry((SClient) miClient, SDataConstants.ITMU_ITEM, new int[] { moKeyItem.getSelectedItem().getPrimaryKey()[0] }, SLibConstants.EXEC_MODE_VERBOSE); moKeyUnit.setEnabled(true); moKeyUnit.resetField(); miClient.getSession().populateCatalogue(moKeyUnit, SModConsts.ITMU_UNIT, item.getDbmsDataUnit().getFkUnitTypeId() , null); moKeyUnit.setValue(new int[] { item.getFkUnitId() }); } else { moKeyUnit.setEnabled(false); moKeyUnit.resetField(); } } private void enabledFields(boolean enable) { moKeyItem.setEnabled(enable); jbItem.setEnabled(enable); if (moRegistry.isRegistryNew()) { moKeyUnit.setEnabled(false); jbUnit.setEnabled(false); } else { moKeyUnit.setEnabled(true); jbUnit.setEnabled(true); } moKeyBizPartner.setEnabled(enable); jbBizPartner.setEnabled(enable); moTextLot.setEnabled(enable); moDate.setEditable(enable); } /* * Public methods */ /* * Overriden methods */ @Override public void addAllListeners() { moKeyItem.addItemListener(this); jbItem.addActionListener(this); jbUnit.addActionListener(this); jbBizPartner.addActionListener(this); } @Override public void removeAllListeners() { moKeyItem.removeItemListener(this); jbItem.removeActionListener(this); jbUnit.removeActionListener(this); jbBizPartner.removeActionListener(this); } @Override public void reloadCatalogues() { miClient.getSession().populateCatalogue(moKeyBizPartner, SModConsts.BPSU_BP, SModSysConsts.BPSS_CT_BP_SUP, null); miClient.getSession().populateCatalogue(moKeyItem, SModConsts.ITMU_ITEM, SLibConsts.UNDEFINED, null); } @Override public void setRegistry(SDbRegistry registry) throws Exception { moRegistry = (SDbLotApproved) registry; mnFormResult = SLibConsts.UNDEFINED; mbFirstActivation = true; removeAllListeners(); reloadCatalogues(); if (moRegistry.isRegistryNew()) { moRegistry.initPrimaryKey(); moRegistry.setDate(miClient.getSession().getCurrentDate()); jtfRegistryKey.setText(""); } else { jtfRegistryKey.setText(SLibUtils.textKey(moRegistry.getPrimaryKey())); moRegistry.setRegistryNew(false); } moDate.setValue(moRegistry.getDate()); moKeyBizPartner.setValue(new int[] {moRegistry.getFkBizPartnerId() }); moKeyItem.setValue(new int[] { moRegistry.getFkItemId() }); if (moKeyItem.getSelectedIndex() > 0) { itemStateKeyItem(); } moKeyUnit.setValue(new int[] { moRegistry.getFkUnitId()}); moTextLot.setValue(moRegistry.getLot()); setFormEditable(true); enabledFields(true); addAllListeners(); } @Override public SDbLotApproved getRegistry() throws Exception { SDbLotApproved registry = moRegistry.clone(); registry.setDate(moDate.getValue()); registry.setFkBizPartnerId(moKeyBizPartner.getSelectedItem().getPrimaryKey()[0]); registry.setFkItemId(moKeyItem.getSelectedItem().getPrimaryKey()[0]); registry.setFkUnitId(moKeyUnit.getSelectedItem().getPrimaryKey()[0]); registry.setLot(moTextLot.getText()); return registry; } public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JButton) { JButton button = (JButton) e.getSource(); if (button == jbItem) { actionPickItem(); } else if (button == jbUnit) { actionPickUnit(); } else if (button == jbBizPartner) { actionPickBizPartner(); } } } @Override public SGuiValidation validateForm() { SGuiValidation validation = moFields.validateFields(); return validation; } @Override public void itemStateChanged(ItemEvent e) { if (e.getSource() instanceof SBeanFieldKey) { SBeanFieldKey field = (SBeanFieldKey) e.getSource(); if (field == moKeyItem) { itemStateKeyItem(); } } } }
/** * * $Id: GeneDelivery.java,v 1.10 2005-11-28 20:20:46 pandyas Exp $ * * $Log: not supported by cvs2svn $ * */ package gov.nih.nci.camod.domain; import gov.nih.nci.camod.util.Duplicatable; import gov.nih.nci.camod.util.HashCodeUtil; import java.io.Serializable; /** * @author rajputs * * TODO To change the template for this generated type comment go to Window - * Preferences - Java - Code Style - Code Templates */ public class GeneDelivery extends BaseObject implements Comparable, Serializable, Duplicatable { private static final long serialVersionUID = 3259385453799404851L; private String viralVector; private String viralVectorUnctrlVocab; private String geneInVirus; private Organ organ; private Treatment treatment; /** * @return Returns the display name. */ public String getDisplayName() { String theDisplayName = viralVector; if (theDisplayName == null && viralVectorUnctrlVocab != null) { theDisplayName = "Other - " + viralVectorUnctrlVocab; } return theDisplayName; } /** * @return Returns the treatment. */ public Treatment getTreatment() { return treatment; } /** * @param treatment * The treatment to set. */ public void setTreatment(Treatment treatment) { this.treatment = treatment; } /** * @return Returns the organ. */ public Organ getOrgan() { return organ; } /** * @param organ * The organ to set. */ public void setOrgan(Organ organ) { this.organ = organ; } /** * @return Returns the geneInVirus. */ public String getGeneInVirus() { return geneInVirus; } /** * @param geneInVirus * The geneInVirus to set. */ public void setGeneInVirus(String geneInVirus) { this.geneInVirus = geneInVirus; } /** * @return Returns the viralVector. */ public String getViralVector() { return viralVector; } /** * @param viralVector * The viralVector to set. */ public void setViralVector(String viralVector) { this.viralVector = viralVector; } /** * @return Returns the viralVectorUnctrlVocab. */ public String getViralVectorUnctrlVocab() { return viralVectorUnctrlVocab; } /** * @param viralVectorUnctrlVocab * The viralVectorUnctrlVocab to set. */ public void setViralVectorUnctrlVocab(String viralVectorUnctrlVocab) { this.viralVectorUnctrlVocab = viralVectorUnctrlVocab; } /** * @see java.lang.Object#toString() */ public String toString() { String result = super.toString() + " - "; result += this.getViralVector() + " - " + this.getViralVectorUnctrlVocab() + " - " + this.getGeneInVirus(); return result; } public boolean equals(Object o) { if (!super.equals(o)) return false; if (!(this.getClass().isInstance(o))) return false; final GeneDelivery obj = (GeneDelivery) o; if (HashCodeUtil.notEqual(this.getOrgan(), obj.getOrgan())) return false; return true; } public int hashCode() { int result = HashCodeUtil.SEED; result = HashCodeUtil.hash(result, this.getOrgan()); return result + super.hashCode(); } public int compareTo(Object o) { if ((o instanceof GeneDelivery) && (this.getOrgan() != null) && (((GeneDelivery) o).getOrgan() != null)) { int result = this.getOrgan().compareTo(((GeneDelivery) o).getOrgan()); if (result != 0) { return result; } } return super.compareTo(o); } }
package org.fao.fenix.commons.msd.dto.full; import com.fasterxml.jackson.annotation.JsonProperty; import org.fao.fenix.commons.annotations.Description; import org.fao.fenix.commons.annotations.Label; import org.fao.fenix.commons.annotations.Subject; import org.fao.fenix.commons.msd.dto.JSONEntity; import javax.persistence.Embedded; import java.io.Serializable; import java.lang.reflect.Field; import java.util.*; public class MeIdentification <T extends DSD> extends JSONEntity implements Serializable { /* Properties */ @JsonProperty @Label(en="Resource identification code") @Description(en="Resource identifier. It is a code that creates the match between the resource and the metadata it is associated to.") private String uid; @JsonProperty @Label(en="Version") @Description(en="This is the version of the metadata.") private String version; @JsonProperty @Label(en="Parent(s) metadata ID") @Description(en= "Identifier of the metadata record to which this metadata record is a subset of (i.e. parent metadata of hierarchical metadata records). The specification of the parentIdentifier allows to inherit a set of metadata information from the parent metadata record. The choice of which metadata elements must to be kept from the parent record and the one that has to be manually modified, it is subject to ad hoc controls.") private Collection<String> parentIdentifiers; @JsonProperty @Label(en="Language(s)") @Description(en= "Language used by the resource for textual information.") private OjCodeList language; @JsonProperty @Label(en="Language details") @Description(en= "Comments and additional details about the language used for the textual information of the resource. This field is addressed to highlight some particular inconsistencies in the language (or languages) used in the resource, if any. For example to alert that the resource is not completely homogeneous in the language used for textual information. Otherwise it can be leaved empty.") private Map<String, String> languageDetails; @JsonProperty @Label(en="Title") @Description(en= "Textual label used as title of the resource.") private Map<String, String> title; @JsonProperty @Label(en="Creation date") @Description(en= "Creation date of the resource.") private Date creationDate; @JsonProperty @Label(en="Character-set") @Description(en= "Full name of the character coding standard used by the resource.") private OjCodeList characterSet; @JsonProperty @Label(en="Character-set") @Description(en= "Full name of the character coding standard used by the resource.") private String metadataStandardName; @JsonProperty @Label(en="Used metadata standard") @Description(en= "Name of the metadata standard specifications used. In FENIX framework this field would be pre-compiled by 'FENIX'.") private String metadataStandardVersion; @JsonProperty @Label(en="Version of metadata standard") @Description(en= "Version of the metadata standard specifications used.") private OjCodeList metadataLanguage; @JsonProperty @Label(en="Contact(s)") @Description(en= "Responsible party that could be identify as the data source. FENIX metadata contains more than one field of the type 'ResponsibleParty' addressed to report all the information necessary to contact party(ies) playing different roles in respect to the resource. In particular this field (belonging to the Identification entity) should report the party who owns authority on the resource.") private Collection<OjResponsibleParty> contacts; @JsonProperty @Label(en="Value assigned to No-data") @Description(en= "Value assigned to the cells to represent the absence of data. Missing values are usually highlight through apposite ags, however the data matrix does not report empty cells but a prede ned combination of characters (such as 'NA', '000' . . . ) indicating the absence of data.") private String noDataValue; /* Connected entities */ @JsonProperty @Label(en="DOCUMENTS") @Description(en= "This section allows linking publications, news, or other relevant material to the considered resource.") private Collection<MeDocuments> meDocuments; @JsonProperty @Label(en="INSTITUTIONAL MANDATE") @Description(en= "This section includes the formal set of instructions assigning responsibility as well as the authority to an organization for the collection, processing, and dissemination of statistics.") private MeInstitutionalMandate meInstitutionalMandate; @JsonProperty @Label(en="ACCESSIBILITY") @Description(en= "This section reports details about data distribution and sharing mechanisms. It includes information on conditions and formal agreements under which statistical information can be obtained. In addition it provides details on available options to obtain a resource, such as user accessibility to data and dissemination periodicity.") private MeAccessibility meAccessibility; @JsonProperty @Label(en="CONTENT") @Description(en= "This section includes a summary of the content of the resource and the description of the geographical, time and sector coverage.") private MeContent meContent; @JsonProperty @Label(en="DATA QUALITY") @Description(en= "This section provides a description and evaluation of the data quality. It allows to describe the data quality assurance process, inclusive of data validation, completeness and accuracy standards. In addition an assessment of the comparability and intern coherence of the resource is considered a quality dimension.") private MeDataQuality meDataQuality; @JsonProperty @Label(en="MAINTENANCE") @Description(en= "This section provides information about the frequency of resource upgrade and metadata maintenance.") private MeMaintenance meMaintenance; @JsonProperty @Label(en="REFERENCE SYSTEM") @Description(en= "This section includes temporal and coordinate identifiers. It contains all the required information to uniquely identify a point on the earth surface. It also defines the transformations and conversions parameters to convert from one coordinate reference system (CRS) to another. This metadata entity includes the parameters specifying the geospatial references that relate information represented in the data (features) to their geographic space. The considered reference system is only based on coordinates and not on geographic identifiers.") private MeReferenceSystem meReferenceSystem; @JsonProperty @Label(en="") @Description(en= "This section lists values and metadata of the dimensions of the resource. In a data table, dimensions may refer to geographical areas, time, commodities, gender, etc. . . It includes iterative elements representing 'n' dimensions and 'm' elements of each dimension. In addition ResourceRecord allows to report information at single-value level.") private MeResourceStructure meResourceStructure; @JsonProperty @Label(en="SPATIAL REPRESENTATION") @Description(en= "This section includes information about the mechanism to represent spatial information both in raster and vector formats. It includes concepts for describing and manipulating the spatial characteristics of geographic features. This metadata entity is only valid for geospatial resources like vector and raster layers or TINs. Depending on the value assumed by its resourceRepresentationType element, it extends to GridSpatialRepresentation entity (for resourceRepresentationType = 'raster') or VectorSpatialRepresentation (for resourceRepresentationType = 'vector' or 'tin').") private MeSpatialRepresentation meSpatialRepresentation; @JsonProperty @Label(en="STATISTICAL PROCESSING") @Description(en= "This section describes the statistical operations and transformations applied to data. It includes the process used to collect data, the description of raw data and a detailed review of the process used to compute processed resource.") private MeStatisticalProcessing meStatisticalProcessing; /* DSD */ @JsonProperty private T dsd; //GET - SET public T getDsd() { return dsd; } public void setDsd(T dsd) { this.dsd = dsd; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public OjCodeList getLanguage() { return language; } @Embedded public void setLanguage(OjCodeList language) { this.language = language; } public Map<String, String> getLanguageDetails() { return languageDetails; } public void setLanguageDetails(Map<String, String> languageDetails) { this.languageDetails = languageDetails; } public Map<String, String> getTitle() { return title; } public void setTitle(Map<String, String> title) { this.title = title; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public OjCodeList getCharacterSet() { return characterSet; } @Embedded public void setCharacterSet(OjCodeList characterSet) { this.characterSet = characterSet; } public Collection<String> getParentIdentifiers() { return parentIdentifiers; } public void setParentIdentifiers(Collection<String> parentIdentifiers) { this.parentIdentifiers = parentIdentifiers; } public String getMetadataStandardName() { return metadataStandardName; } public void setMetadataStandardName(String metadataStandardName) { this.metadataStandardName = metadataStandardName; } public String getMetadataStandardVersion() { return metadataStandardVersion; } public void setMetadataStandardVersion(String metadataStandardVersion) { this.metadataStandardVersion = metadataStandardVersion; } public OjCodeList getMetadataLanguage() { return metadataLanguage; } @Embedded public void setMetadataLanguage(OjCodeList metadataLanguage) { this.metadataLanguage = metadataLanguage; } public Collection<OjResponsibleParty> getContacts() { return contacts; } @Embedded public void setContacts(Collection<OjResponsibleParty> contacts) { this.contacts = contacts; } public String getNoDataValue() { return noDataValue; } public void setNoDataValue(String noDataValue) { this.noDataValue = noDataValue; } //Connected entities public MeContent getMeContent() { return meContent; } @Embedded public void setMeContent(MeContent meContent) { this.meContent = meContent; } public Collection<MeDocuments> getMeDocuments() { return meDocuments; } @Embedded public void setMeDocuments(Collection<MeDocuments> meDocuments) { this.meDocuments = meDocuments; } public MeInstitutionalMandate getMeInstitutionalMandate() { return meInstitutionalMandate; } @Embedded public void setMeInstitutionalMandate(MeInstitutionalMandate meInstitutionalMandate) { this.meInstitutionalMandate = meInstitutionalMandate; } public MeAccessibility getMeAccessibility() { return meAccessibility; } @Embedded public void setMeAccessibility(MeAccessibility meAccessibility) { this.meAccessibility = meAccessibility; } public MeDataQuality getMeDataQuality() { return meDataQuality; } @Embedded public void setMeDataQuality(MeDataQuality meDataQuality) { this.meDataQuality = meDataQuality; } public MeMaintenance getMeMaintenance() { return meMaintenance; } @Embedded public void setMeMaintenance(MeMaintenance meMaintenance) { this.meMaintenance = meMaintenance; } public MeReferenceSystem getMeReferenceSystem() { return meReferenceSystem; } @Embedded public void setMeReferenceSystem(MeReferenceSystem meReferenceSystem) { this.meReferenceSystem = meReferenceSystem; } public MeResourceStructure getMeResourceStructure() { return meResourceStructure; } @Embedded public void setMeResourceStructure(MeResourceStructure meResourceStructure) { this.meResourceStructure = meResourceStructure; } public MeSpatialRepresentation getMeSpatialRepresentation() { return meSpatialRepresentation; } @Embedded public void setMeSpatialRepresentation(MeSpatialRepresentation meSpatialRepresentation) { this.meSpatialRepresentation = meSpatialRepresentation; } public MeStatisticalProcessing getMeStatisticalProcessing() { return meStatisticalProcessing; } @Embedded public void setMeStatisticalProcessing(MeStatisticalProcessing meStatisticalProcessing) { this.meStatisticalProcessing = meStatisticalProcessing; } //Utils public boolean isIdentificationOnly() throws IllegalAccessException { for (Field field : MeIdentification.class.getDeclaredFields()) { String fieldName = field.getName(); Object fieldValue = field.get(this); if (!fieldName.equals("uid") && !fieldName.equals("version") && fieldValue!=null) { if (fieldValue instanceof Collection) { if (((Collection)fieldValue).size()>0) return false; } else if (fieldValue instanceof Map) { if (((Map)fieldValue).size()>0) return false; } else return false; } } return true; } }
package org.voltdb.utils; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.TimeZone; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.voltdb.CLIConfig; import org.voltdb.VoltTable; import org.voltdb.VoltType; import org.voltdb.client.BatchTimeoutOverrideType; import org.voltdb.client.Client; import org.voltdb.client.ClientConfig; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientResponse; import org.voltdb.client.NoConnectionsException; import org.voltdb.client.ProcCallException; import org.voltdb.parser.SQLParser; import org.voltdb.parser.SQLParser.FileInfo; import org.voltdb.parser.SQLParser.FileOption; import org.voltdb.parser.SQLParser.ParseRecallResults; import com.google_voltpatches.common.collect.ImmutableMap; import jline.console.CursorBuffer; import jline.console.KeyMap; import jline.console.history.FileHistory; public class SQLCommand { private static boolean m_stopOnError = true; private static boolean m_debug = false; private static boolean m_interactive; private static boolean m_versionCheck = true; private static boolean m_returningToPromptAfterError = false; private static int m_exitCode = 0; private static boolean m_hasBatchTimeout = true; private static int m_batchTimeout = BatchTimeoutOverrideType.DEFAULT_TIMEOUT; private static final String m_readme = "SQLCommandReadme.txt"; public static String getReadme() { return m_readme; } private static List<String> RecallableSessionLines = new ArrayList<String>(); private static boolean m_testFrontEndOnly; private static String m_testFrontEndResult; private static String patchErrorMessageWithFile(String batchFileName, String message) { Pattern errorMessageFilePrefix = Pattern.compile("\\[.*:([0-9]+)\\]"); Matcher matcher = errorMessageFilePrefix.matcher(message); if (matcher.find()) { // This won't work right if the filename contains a "$"... message = matcher.replaceFirst("[" + batchFileName + ":$1]"); } return message; } private static ClientResponse callProcedureHelper(String procName, Object... parameters) throws NoConnectionsException, IOException, ProcCallException { ClientResponse response = null; if (m_hasBatchTimeout) { response = m_client.callProcedureWithTimeout(m_batchTimeout, procName, parameters); } else { response = m_client.callProcedure(procName, parameters); } return response; } private static void executeDDLBatch(String batchFileName, String statements) { try { if ( ! m_interactive ) { System.out.println(); System.out.println(statements); } if (! SQLParser.appearsToBeValidDDLBatch(statements)) { throw new Exception("Error: This batch begins with a non-DDL statement. " + "Currently batching is only supported for DDL."); } if (m_testFrontEndOnly) { m_testFrontEndResult += statements; return; } ClientResponse response = m_client.callProcedure("@AdHoc", statements); if (response.getStatus() != ClientResponse.SUCCESS) { throw new Exception("Execution Error: " + response.getStatusString()); } // Assert the current DDL AdHoc batch call behavior assert(response.getResults().length == 1); System.out.println("Batch command succeeded."); loadStoredProcedures(Procedures, Classlist); } catch (ProcCallException ex) { String fixedMessage = patchErrorMessageWithFile(batchFileName, ex.getMessage()); stopOrContinue(new Exception(fixedMessage)); } catch (Exception ex) { stopOrContinue(ex); } } // The main loop for interactive mode. public static void interactWithTheUser() throws Exception { final SQLConsoleReader interactiveReader = new SQLConsoleReader(new FileInputStream(FileDescriptor.in), System.out); interactiveReader.setBellEnabled(false); FileHistory historyFile = null; try { // Maintain persistent history in ~/.sqlcmd_history. historyFile = new FileHistory(new File(System.getProperty("user.home"), ".sqlcmd_history")); interactiveReader.setHistory(historyFile); // Make Ctrl-D (EOF) exit if on an empty line, otherwise delete the next character. KeyMap keyMap = interactiveReader.getKeys(); keyMap.bind(new Character(KeyMap.CTRL_D).toString(), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { CursorBuffer cursorBuffer = interactiveReader.getCursorBuffer(); if (cursorBuffer.length() == 0) { System.exit(m_exitCode); } else { try { interactiveReader.delete(); } catch (IOException e1) { } } } }); getInteractiveQueries(interactiveReader); } finally { // Flush input history to a file. if (historyFile != null) { try { historyFile.flush(); } catch (IOException e) { System.err.printf("* Unable to write history to \"%s\" *\n", historyFile.getFile().getPath()); if (m_debug) { e.printStackTrace(); } } } // Clean up jline2 resources. if (interactiveReader != null) { interactiveReader.shutdown(); } } } public static void getInteractiveQueries(SQLConsoleReader interactiveReader) throws Exception { // Reset the error state to avoid accidentally ignoring future FILE content // after a file had runtime errors (ENG-7335). m_returningToPromptAfterError = false; final StringBuilder statement = new StringBuilder(); boolean isRecall = false; while (true) { String prompt = isRecall ? "" : ((RecallableSessionLines.size() + 1) + "> "); isRecall = false; String line = interactiveReader.readLine(prompt); if (line == null) { // This used to occur in an edge case when trying to pipe an // empty file into stdin and ending up in interactive mode by // mistake. That case works differently now, so this code path // MAY be dead. If not, cut our losses by rigging a quick exit. statement.setLength(0); line = "EXIT;"; } // Was there a line-ending semicolon typed at the prompt? // This mostly matters for "non-directive" statements. boolean executeImmediate = SQLParser.isSemiColonTerminated(line); // When we are tracking the progress of a multi-line statement, // avoid coincidentally recognizing mid-statement SQL content as sqlcmd // "directives". if (statement.length() == 0) { if (line.trim().equals("") || SQLParser.isWholeLineComment(line)) { // We don't strictly have to execute or append or recall // a blank line or whole-line comment when no statement is in progress. continue; } // EXIT command - exit immediately if (SQLParser.isExitCommand(line)) { return; } // RECALL command ParseRecallResults recallParseResults = SQLParser.parseRecallStatement(line, RecallableSessionLines.size() - 1); if (recallParseResults != null) { if (recallParseResults.getError() == null) { line = RecallableSessionLines.get(recallParseResults.getLine()); interactiveReader.putString(line); interactiveReader.flush(); isRecall = true; } else { System.out.println(recallParseResults.getError()); } executeImmediate = false; // let user edit the recalled line. continue; } // Queue up the line to the recall stack //TODO: In the future, we may not want to have simple directives count as recallable // lines, so this call would move down a ways. RecallableSessionLines.add(line); if (executesAsSimpleDirective(line)) { executeImmediate = false; // return to prompt. continue; } // If the line is a FILE command - execute the content of the file FileInfo fileInfo = null; try { fileInfo = SQLParser.parseFileStatement(line); } catch (SQLParser.Exception e) { stopOrContinue(e); continue; } if (fileInfo != null) { executeScriptFile(fileInfo, interactiveReader); if (m_returningToPromptAfterError) { // executeScriptFile stopped because of an error. Wipe the slate clean. m_returningToPromptAfterError = false; } continue; } // else treat the input line as a regular database command if (executeImmediate) { executeStatements(line + "\n"); if (m_testFrontEndOnly) { break; // test mode expects this early return before end of input. } continue; } } else { // With a multi-line statement pending, // queue up the line continuation to the recall list. //TODO: arguably, it would be more useful to append continuation // lines to the last existing Lines entry to build each complete // statement as a single recallable unit. Experiments indicated // that joining the lines with a single space, while not as pretty // as a newline for very long statements, behaved perfectly for // line editing (cursor positioning). RecallableSessionLines.add(line); if (executeImmediate) { statement.append(line + "\n"); executeStatements(statement.toString()); if (m_testFrontEndOnly) { break; // test mode expects this early return before end of input. } statement.setLength(0); continue; } } // Collect lines ... statement.append(line + "\n"); //TODO: Here's where we might append to a separate buffer that uses // a single space rather than a newline as its separator to build up // a recallable multi-line statement. } } /// A stripped down variant of the processing in "interactWithTheUser" suitable for /// applying to a command script. It skips all the interactive-only options. /// It uses the same logic as the FILE directive but gets its input from stdin. public static void executeNoninteractive() throws Exception { SQLCommandLineReader stdinReader = new LineReaderAdapter(new InputStreamReader(System.in)); FileInfo fileInfo = SQLParser.FileInfo.forSystemIn(); executeScriptFromReader(fileInfo, stdinReader); } /// Simple directives require only the input line and no other context from the input loop. /// Return true if the line is a directive that has been completely handled here, so that the /// input loop can proceed to the next line. //TODO: There have been suggestions that some or all of these directives could be made // available in non-interactive contexts. This function is available to enable that. private static boolean executesAsSimpleDirective(String line) throws Exception { // SHOW or LIST <blah> statement String subcommand = SQLParser.parseShowStatementSubcommand(line); if (subcommand != null) { if (subcommand.equals("proc") || subcommand.equals("procedures")) { execListProcedures(); } else if (subcommand.equals("tables")) { execListTables(); } else if (subcommand.equals("classes")) { execListClasses(); } else if (subcommand.equals("config") || subcommand.equals("configuration")) { execListConfigurations(); } else { String errorCase = (subcommand.equals("") || subcommand.equals(";")) ? ("Incomplete SHOW command.\n") : ("Invalid SHOW command completion: '" + subcommand + "'.\n"); System.out.println(errorCase + "The valid SHOW command completions are proc, procedures, tables, or classes."); } // Consider it handled here, whether or not it was a good SHOW statement. return true; } // HELP commands - ONLY in interactive mode, close batch and parse for execution // Parser returns null if it isn't a HELP command. If no arguments are specified // the returned string will be empty. String helpSubcommand = SQLParser.parseHelpStatement(line); if (helpSubcommand != null) { // Ignore the arguments for now. if (!helpSubcommand.isEmpty()) { System.out.printf("Ignoring extra HELP argument(s): %s\n", helpSubcommand); } printHelp(System.out); // Print readme to the screen return true; } String echoArgs = SQLParser.parseEchoStatement(line); if (echoArgs != null) { System.out.println(echoArgs); return true; } String echoErrorArgs = SQLParser.parseEchoErrorStatement(line); if (echoErrorArgs != null) { System.err.println(echoErrorArgs); return true; } // It wasn't a locally-interpreted directive. return false; } private static void execListConfigurations() throws Exception { VoltTable configData = m_client.callProcedure("@SystemCatalog", "CONFIG").getResults()[0]; if (configData.getRowCount() != 0) { printConfig(configData); } } private static void execListClasses() { //TODO: since sqlcmd makes no intrinsic use of the Classlist, it would be more // efficient to load the Classlist only "on demand" from here and to cache a // complete formatted String result rather than the complex map representation. // This would save churn on startup and on DDL update. if (Classlist.isEmpty()) { System.out.println(); System.out.println(" System.out.println(); } List<String> list = new LinkedList<String>(Classlist.keySet()); Collections.sort(list); int padding = 0; for (String classname : list) { padding = Math.max(padding, classname.length()); } String format = " %1$-" + padding + "s"; String categoryHeader[] = new String[] { " " " for (int i = 0; i<3; i++) { boolean firstInCategory = true; for (String classname : list) { List<Boolean> stuff = Classlist.get(classname); // Print non-active procs first if (i == 0 && !(stuff.get(0) && !stuff.get(1))) { continue; } else if (i == 1 && !(stuff.get(0) && stuff.get(1))) { continue; } else if (i == 2 && stuff.get(0)) { continue; } if (firstInCategory) { firstInCategory = false; System.out.println(); System.out.println(categoryHeader[i]); } System.out.printf(format, classname); System.out.println(); } } System.out.println(); } private static void execListTables() throws Exception { //TODO: since sqlcmd makes no intrinsic use of the tables list, it would be more // efficient to load the list only "on demand" from here and to cache a // complete formatted String result rather than the multiple lists. // This would save churn on startup and on DDL update. Tables tables = getTables(); printTables("User Tables", tables.tables); printTables("User Views", tables.views); printTables("User Export Streams", tables.exports); System.out.println(); } private static void execListProcedures() { List<String> list = new LinkedList<String>(Procedures.keySet()); Collections.sort(list); int padding = 0; for (String procedure : list) { if (padding < procedure.length()) { padding = procedure.length(); } } padding++; String format = "%1$-" + padding + "s"; boolean firstSysProc = true; boolean firstUserProc = true; for (String procedure : list) { //TODO: it would be much easier over all to maintain sysprocs and user procs in // in two separate maps. if (procedure.startsWith("@")) { if (firstSysProc) { firstSysProc = false; System.out.println(" } } else { if (firstUserProc) { firstUserProc = false; System.out.println(); System.out.println(" } } for (List<String> parameterSet : Procedures.get(procedure).values()) { System.out.printf(format, procedure); String sep = "\t"; for (String paramType : parameterSet) { System.out.print(sep + paramType); sep = ", "; } System.out.println(); } } System.out.println(); } private static void printConfig(VoltTable configData) { System.out.println(); System.out.println(String.format("%-20s%-20s%-60s", "NAME", "VALUE", "DESCRIPTION")); for (int i=0; i<100; i++) { System.out.print('-'); } System.out.println(); while (configData.advanceRow()) { System.out.println(String.format("%-20s%-20s%-60s", configData.getString(0), configData.getString(1), configData.getString(2))); } } private static void printTables(final String name, final Collection<String> tables) { System.out.println(); System.out.println(" for (String table : tables) { System.out.println(table); } System.out.println(); } /** Adapt BufferedReader into a SQLCommandLineReader */ private static class LineReaderAdapter implements SQLCommandLineReader { private final BufferedReader m_reader; LineReaderAdapter(InputStreamReader reader) { m_reader = new BufferedReader(reader); } @Override public String readBatchLine() throws IOException { return m_reader.readLine(); } void close() { try { m_reader.close(); } catch (IOException e) { } } } /** * Reads a script file and executes its content. * Note that the "script file" could be an inline batch, * i.e., a "here document" that is coming from the same input stream * as the "file" directive. * * @param fileInfo Info on the file directive being processed * @param parentLineReader The current input stream, to be used for "here documents". */ static void executeScriptFile(FileInfo fileInfo, SQLCommandLineReader parentLineReader) { LineReaderAdapter adapter = null; SQLCommandLineReader reader = null; if ( ! m_interactive) { System.out.println(); System.out.println(fileInfo.toString()); } if (fileInfo.getOption() == FileOption.INLINEBATCH) { // File command is a "here document" so pass in the current // input stream. reader = parentLineReader; } else { try { reader = adapter = new LineReaderAdapter(new FileReader(fileInfo.getFile())); } catch (FileNotFoundException e) { System.err.println("Script file '" + fileInfo.getFile() + "' could not be found."); stopOrContinue(e); return; // continue to the next line after the FILE command } } try { executeScriptFromReader(fileInfo, reader); } catch (Exception x) { stopOrContinue(x); } finally { if (adapter != null) { adapter.close(); } } } /** * * @param fileInfo The FileInfo object describing the file command (or stdin) * @param script The line reader object to read from * @throws Exception */ private static void executeScriptFromReader(FileInfo fileInfo, SQLCommandLineReader reader) throws Exception { StringBuilder statement = new StringBuilder(); // non-interactive modes need to be more careful about discarding blank lines to // keep from throwing off diagnostic line numbers. So "statement" may be non-empty even // when a sql statement has not yet started (?) boolean statementStarted = false; StringBuilder batch = fileInfo.isBatch() ? new StringBuilder() : null; String delimiter = (fileInfo.getOption() == FileOption.INLINEBATCH) ? fileInfo.getDelimiter() : null; while (true) { String line = reader.readBatchLine(); if (delimiter != null) { if (line == null) { // We only print this nice message if the inline batch is // being executed non-interactively. For an inline batch // entered from the command line, SQLConsoleReader catches // ctrl-D and exits the process before this code can execute, // even if this code is in a "finally" block. throw new Exception("ERROR: Failed to find delimiter \"" + delimiter + "\" indicating end of inline batch. No batched statements were executed."); } if (delimiter.equals(line)) { line = null; } } if (line == null) { // No more lines. Execute whatever we got. if (statement.length() > 0) { if (batch == null) { String statementString = statement.toString(); // Trim here avoids a "missing statement" error from adhoc in an edge case // like a blank line from stdin. if ( ! statementString.trim().isEmpty()) { //* enable to debug */if (m_debug) System.out.println("DEBUG QUERY:'" + statementString + "'"); executeStatements(statementString); } } else { // This means that batch did not end with a semicolon. // Maybe it ended with a comment. // For now, treat the final semicolon as optional and // assume that we are not just adding a partial statement to the batch. batch.append(statement); executeDDLBatch(fileInfo.getFilePath(), batch.toString()); } } return; } if ( ! statementStarted) { if (line.trim().equals("") || SQLParser.isWholeLineComment(line)) { // We don't strictly have to include a blank line or whole-line // comment at the start of a statement, but when we want to preserve line // numbers (in a batch), we should at least append a newline. // Whether to echo comments or blank lines from a batch is // a grey area. if (batch != null) { statement.append(line).append("\n"); } continue; } // Recursively process FILE commands, any failure will cause a recursive failure FileInfo nestedFileInfo = SQLParser.parseFileStatement(fileInfo, line); if (nestedFileInfo != null) { // Guards must be added for FILE Batch containing batches. if (batch != null) { stopOrContinue(new RuntimeException( "A FILE command is invalid in a batch.")); continue; // continue to the next line after the FILE command } // Execute the file content or fail to but only set m_returningToPromptAfterError // if the intent is to cause a recursive failure, stopOrContinue decided to stop. executeScriptFile(nestedFileInfo, reader); if (m_returningToPromptAfterError) { // The recursive readScriptFile stopped because of an error. // Escape to the outermost readScriptFile caller so it can exit or // return to the interactive prompt. return; } // Continue after a bad nested file command by processing the next line // in the current file. continue; } // process other non-interactive directives if (executesAsSimpleDirective(line)) { continue; } // TODO: This would be a reasonable place to validate that the line // starts with a SQL command keyword, exec/execute or one of the other // known commands. // According to the current parsing rules that allow multi-statement // stacking on a line (as an undocumented feature), // this work would also have to be repeated after each // non-quoted non-commented statement-splitting semicolon. // See executeStatements. } // Process normal @AdHoc commands which may be // multi-line-statement continuations. statement.append(line).append("\n"); // Check if the current statement ends here and now. if (SQLParser.isSemiColonTerminated(line)) { if (batch == null) { String statementString = statement.toString(); // Trim here avoids a "missing statement" error from adhoc in an edge case // like a blank line from stdin. if ( ! statementString.trim().isEmpty()) { //* enable to debug */ if (m_debug) System.out.println("DEBUG QUERY:'" + statementString + "'"); executeStatements(statementString); } statement.setLength(0); } statementStarted = false; } else { // Disable directive processing until end of statement. statementStarted = true; } } } private static long m_startTime; // executeQueuedStatements is called instead of executeStatement because // multiple semicolon-separated statements are allowed on a line and because // using "line ends with semicolon" is not foolproof as a means of detecting // the end of a statement. It could give a false negative for something as // simple as an end-of-line comment. private static void executeStatements(String statements) { List<String> parsedStatements = SQLParser.parseQuery(statements); for (String statement: parsedStatements) { executeStatement(statement); } } private static void executeStatement(String statement) { if (m_testFrontEndOnly) { m_testFrontEndResult += statement + ";\n"; return; } if ( !m_interactive && m_outputShowMetadata) { System.out.println(); System.out.println(statement + ";"); } try { // EXEC <procedure> <params>... m_startTime = System.nanoTime(); SQLParser.ExecuteCallResults execCallResults = SQLParser.parseExecuteCall(statement, Procedures); if (execCallResults != null) { Object[] objectParams = execCallResults.getParameterObjects(); if (execCallResults.procedure.equals("@UpdateApplicationCatalog")) { File catfile = null; if (objectParams[0] != null) { catfile = new File((String)objectParams[0]); } File depfile = null; if (objectParams[1] != null) { depfile = new File((String)objectParams[1]); } printDdlResponse(m_client.updateApplicationCatalog(catfile, depfile)); // Need to update the stored procedures after a catalog change (could have added/removed SPs!). ENG-3726 loadStoredProcedures(Procedures, Classlist); } else if (execCallResults.procedure.equals("@UpdateClasses")) { File jarfile = null; if (objectParams[0] != null) { jarfile = new File((String)objectParams[0]); } printDdlResponse(m_client.updateClasses(jarfile, (String)objectParams[1])); // Need to reload the procedures and classes loadStoredProcedures(Procedures, Classlist); } else { // @SnapshotDelete needs array parameters. if (execCallResults.procedure.equals("@SnapshotDelete")) { objectParams[0] = new String[] { (String)objectParams[0] }; objectParams[1] = new String[] { (String)objectParams[1] }; } printResponse(callProcedureHelper(execCallResults.procedure, objectParams)); } return; } String explainStatement = SQLParser.parseExplainCall(statement); if (explainStatement != null) { // We've got a statement that starts with "explain", send the statement to // @Explain (after parseExplainCall() strips "explain"). printResponse(m_client.callProcedure("@Explain", explainStatement)); return; } String explainProcName = SQLParser.parseExplainProcCall(statement); if (explainProcName != null) { // We've got a statement that starts with "explainproc", send the statement to // @ExplainProc (now that parseExplainProcCall() has stripped out "explainproc"). printResponse(m_client.callProcedure("@ExplainProc", explainProcName)); return; } // LOAD CLASS <jar>? String loadPath = SQLParser.parseLoadClasses(statement); if (loadPath != null) { File jarfile = new File(loadPath); printDdlResponse(m_client.updateClasses(jarfile, null)); loadStoredProcedures(Procedures, Classlist); return; } // REMOVE CLASS <class-selector>? String classSelector = SQLParser.parseRemoveClasses(statement); if (classSelector != null) { printDdlResponse(m_client.updateClasses(null, classSelector)); loadStoredProcedures(Procedures, Classlist); return; } // DDL statements get forwarded to @AdHoc, // but get special post-processing. if (SQLParser.queryIsDDL(statement)) { // if the query is DDL, reload the stored procedures. printDdlResponse(m_client.callProcedure("@AdHoc", statement)); loadStoredProcedures(Procedures, Classlist); return; } // All other commands get forwarded to @AdHoc printResponse(callProcedureHelper("@AdHoc", statement)); } catch (Exception exc) { stopOrContinue(exc); } } private static void stopOrContinue(Exception exc) { System.err.println(exc.getMessage()); if (m_debug) { exc.printStackTrace(System.err); } // Let the final exit code reflect any error(s) in the run. // This is useful for debugging a script that may have multiple errors // and multiple valid statements. m_exitCode = -1; if (m_stopOnError) { if ( ! m_interactive ) { System.exit(m_exitCode); } // Setting this member to drive a fast stack unwind from // recursive readScriptFile requires explicit checks in that code, // but still seems easier than a "throw" here from a catch block that // would require additional exception handlers in the caller(s) m_returningToPromptAfterError = true; } } // Output generation private static SQLCommandOutputFormatter m_outputFormatter = new SQLCommandOutputFormatterDefault(); private static boolean m_outputShowMetadata = true; private static boolean isUpdateResult(VoltTable table) { return ((table.getColumnName(0).isEmpty() || table.getColumnName(0).equals("modified_tuples")) && table.getRowCount() == 1 && table.getColumnCount() == 1 && table.getColumnType(0) == VoltType.BIGINT); } private static void printResponse(ClientResponse response) throws Exception { if (response.getStatus() != ClientResponse.SUCCESS) { throw new Exception("Execution Error: " + response.getStatusString()); } long elapsedTime = System.nanoTime() - m_startTime; for (VoltTable t : response.getResults()) { long rowCount; if (!isUpdateResult(t)) { rowCount = t.getRowCount(); // Run it through the output formatter. m_outputFormatter.printTable(System.out, t, m_outputShowMetadata); //System.out.println("printable"); } else { rowCount = t.fetchRow(0).getLong(0); } if (m_outputShowMetadata) { System.out.printf("(Returned %d rows in %.2fs)\n", rowCount, elapsedTime / 1000000000.0); } } } private static void printDdlResponse(ClientResponse response) throws Exception { if (response.getStatus() != ClientResponse.SUCCESS) { throw new Exception("Execution Error: " + response.getStatusString()); } //TODO: In the future, if/when we change the prompt when waiting for the remainder of an unfinished command, // successful DDL commands may just silently return to a normal prompt without this verbose feedback. System.out.println("Command succeeded."); } // VoltDB connection support private static Client m_client; // Default visibility is for test purposes. static Map<String,Map<Integer, List<String>>> Procedures = Collections.synchronizedMap(new HashMap<String,Map<Integer, List<String>>>()); private static Map<String, List<Boolean>> Classlist = Collections.synchronizedMap(new HashMap<String, List<Boolean>>()); private static void loadSystemProcedures() { Procedures.put("@Pause", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@Quiesce", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@Resume", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@Shutdown", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@StopNode", ImmutableMap.<Integer, List<String>>builder().put(1, Arrays.asList("int")).build()); Procedures.put("@SnapshotDelete", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")).build() ); Procedures.put("@SnapshotRestore", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")) .put( 1, Arrays.asList("varchar")).build() ); Procedures.put("@SnapshotSave", ImmutableMap.<Integer, List<String>>builder().put( 3, Arrays.asList("varchar", "varchar", "bit")). put( 1, Arrays.asList("varchar")).build() ); Procedures.put("@SnapshotScan", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build()); Procedures.put("@Statistics", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("statisticscomponent", "bit")).build()); Procedures.put("@SystemCatalog", ImmutableMap.<Integer, List<String>>builder().put( 1,Arrays.asList("metadataselector")).build()); Procedures.put("@SystemInformation", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("sysinfoselector")).build()); Procedures.put("@UpdateApplicationCatalog", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")).build()); Procedures.put("@UpdateClasses", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")).build()); Procedures.put("@UpdateLogging", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build()); Procedures.put("@Promote", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@SnapshotStatus", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@Explain", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build()); Procedures.put("@ExplainProc", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build()); Procedures.put("@ValidatePartitioning", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("int", "varbinary")).build()); Procedures.put("@GetPartitionKeys", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build()); Procedures.put("@GC", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@ResetDR", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); } private static Client getClient(ClientConfig config, String[] servers, int port) throws Exception { final Client client = ClientFactory.createClient(config); // Only fail if we can't connect to any servers boolean connectedAnyServer = false; for (String server : servers) { try { client.createConnection(server.trim(), port); connectedAnyServer = true; } catch (UnknownHostException e) { } catch (IOException e) { } } if (!connectedAnyServer) { throw new IOException("Unable to connect to VoltDB cluster"); } return client; } // General application support private static void printUsage(String msg) { System.out.print(msg); System.out.println("\n"); printUsage(-1); } private static void printUsage(int exitCode) { System.out.println( "Usage: sqlcmd --help\n" + " or sqlcmd [--servers=comma_separated_server_list]\n" + " [--port=port_number]\n" + " [--user=user]\n" + " [--password=password]\n" + " [--kerberos=jaas_login_configuration_entry_key]\n" + " [--query=query]\n" + " [--output-format=(fixed|csv|tab)]\n" + " [--output-skip-metadata]\n" + " [--stop-on-error=(true|false)]\n" + " [--query-timeout=number_of_milliseconds]\n" + "\n" + "[--servers=comma_separated_server_list]\n" + " List of servers to connect to.\n" + " Default: localhost.\n" + "\n" + "[--port=port_number]\n" + " Client port to connect to on cluster nodes.\n" + " Default: 21212.\n" + "\n" + "[--user=user]\n" + " Name of the user for database login.\n" + " Default: (not defined - connection made without credentials).\n" + "\n" + "[--password=password]\n" + " Password of the user for database login.\n" + " Default: (not defined - connection made without credentials).\n" + "\n" + "[--kerberos=jaas_login_configuration_entry_key]\n" + " Enable kerberos authentication for user database login by specifying\n" + " the JAAS login configuration file entry name" + " Default: (not defined - connection made without credentials).\n" + "\n" + "[--query=query]\n" + " Execute a non-interactive query. Multiple query options are allowed.\n" + " Default: (runs the interactive shell when no query options are present).\n" + "\n" + "[--output-format=(fixed|csv|tab)]\n" + " Format of returned resultset data (Fixed-width, CSV or Tab-delimited).\n" + " Default: fixed.\n" + "\n" + "[--output-skip-metadata]\n" + " Removes metadata information such as column headers and row count from\n" + " produced output. Default: metadata output is enabled.\n" + "\n" + "[--stop-on-error=(true|false)]\n" + " Causes the utility to stop immediately or continue after detecting an error.\n" + " In interactive mode, a value of \"true\" discards any unprocessed input\n" + " and returns to the command prompt. Default: true.\n" + "\n" + "[--query-timeout=millisecond_number]\n" + " Read-only queries that take longer than this number of milliseconds will abort. Default: " + BatchTimeoutOverrideType.DEFAULT_TIMEOUT/1000.0 + " seconds.\n" + "\n" ); System.exit(exitCode); } // printHelp() can print readme either to a file or to the screen // depending on the argument passed in // Default visibility is for test purposes. static void printHelp(OutputStream prtStr) { try { InputStream is = SQLCommand.class.getResourceAsStream(m_readme); while (is.available() > 0) { byte[] bytes = new byte[is.available()]; // Fix for ENG-3440 is.read(bytes, 0, bytes.length); prtStr.write(bytes); // For JUnit test } } catch (Exception x) { System.err.println(x.getMessage()); System.exit(-1); } } private static class Tables { TreeSet<String> tables = new TreeSet<String>(); TreeSet<String> exports = new TreeSet<String>(); TreeSet<String> views = new TreeSet<String>(); } private static Tables getTables() throws Exception { Tables tables = new Tables(); VoltTable tableData = m_client.callProcedure("@SystemCatalog", "TABLES").getResults()[0]; while (tableData.advanceRow()) { String tableName = tableData.getString("TABLE_NAME"); String tableType = tableData.getString("TABLE_TYPE"); if (tableType.equalsIgnoreCase("EXPORT")) { tables.exports.add(tableName); } else if (tableType.equalsIgnoreCase("VIEW")) { tables.views.add(tableName); } else { tables.tables.add(tableName); } } return tables; } private static void loadStoredProcedures(Map<String,Map<Integer, List<String>>> procedures, Map<String, List<Boolean>> classlist) { VoltTable procs = null; VoltTable params = null; VoltTable classes = null; try { procs = m_client.callProcedure("@SystemCatalog", "PROCEDURES").getResults()[0]; params = m_client.callProcedure("@SystemCatalog", "PROCEDURECOLUMNS").getResults()[0]; classes = m_client.callProcedure("@SystemCatalog", "CLASSES").getResults()[0]; } catch (NoConnectionsException e) { e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } catch (ProcCallException e) { e.printStackTrace(); return; } Map<String, Integer> proc_param_counts = Collections.synchronizedMap(new HashMap<String, Integer>()); while (params.advanceRow()) { String this_proc = params.getString("PROCEDURE_NAME"); Integer curr_val = proc_param_counts.get(this_proc); if (curr_val == null) { curr_val = 1; } else { ++curr_val; } proc_param_counts.put(this_proc, curr_val); } params.resetRowPosition(); Set<String> userProcs = new HashSet<String>(); while (procs.advanceRow()) { String proc_name = procs.getString("PROCEDURE_NAME"); userProcs.add(proc_name); Integer param_count = proc_param_counts.get(proc_name); ArrayList<String> this_params = new ArrayList<String>(); // prepopulate it to make sure the size is right if (param_count != null) { for (int i = 0; i < param_count; i++) { this_params.add(null); } } else { param_count = 0; } HashMap<Integer, List<String>> argLists = new HashMap<Integer, List<String>>(); argLists.put(param_count, this_params); procedures.put(proc_name, argLists); } for (String proc_name : new ArrayList<String>(procedures.keySet())) { if (!proc_name.startsWith("@") && !userProcs.contains(proc_name)) { procedures.remove(proc_name); } } classlist.clear(); while (classes.advanceRow()) { String classname = classes.getString("CLASS_NAME"); boolean isProc = (classes.getLong("VOLT_PROCEDURE") == 1L); boolean isActive = (classes.getLong("ACTIVE_PROC") == 1L); if (!classlist.containsKey(classname)) { List<Boolean> stuff = Collections.synchronizedList(new ArrayList<Boolean>()); stuff.add(isProc); stuff.add(isActive); classlist.put(classname, stuff); } } // Retrieve the parameter types. Note we have to do some special checking // for array types. ENG-3101 params.resetRowPosition(); while (params.advanceRow()) { Map<Integer, List<String>> argLists = procedures.get(params.getString("PROCEDURE_NAME")); assert(argLists.size() == 1); List<String> this_params = argLists.values().iterator().next(); int idx = (int)params.getLong("ORDINAL_POSITION") - 1; String param_type = params.getString("TYPE_NAME").toLowerCase(); // Detect if this parameter is supposed to be an array. It's kind of clunky, we have to // look in the remarks column... String param_remarks = params.getString("REMARKS"); if (null != param_remarks) { param_type += (param_remarks.equalsIgnoreCase("ARRAY_PARAMETER") ? "_array" : ""); } this_params.set(idx, param_type); } } /// Parser unit test entry point ///TODO: it would be simpler if this testing entry point could just set up some mocking /// of io and statement "execution" -- mocking with statement capture instead of actual execution /// to better isolate the parser. /// Then it could call a new simplified version of interactWithTheUser(). /// But the current parser tests expect to call a SQLCommand function that can return for /// some progress checking before its input stream has been permanently terminated. /// They would need to be able to check parser progress in one thread while /// SQLCommand.interactWithTheUser() was awaiting further input on another thread /// (or in its own process). public static List<String> getParserTestQueries(InputStream inmocked, OutputStream outmocked) { testFrontEndOnly(); try { SQLConsoleReader reader = new SQLConsoleReader(inmocked, outmocked); getInteractiveQueries(reader); return SQLParser.parseQuery(m_testFrontEndResult); } catch (Exception ioe) {} return null; } public static void testFrontEndOnly() { m_testFrontEndOnly = true; m_testFrontEndResult = ""; } public static String getTestResult() { return m_testFrontEndResult; } private static String extractArgInput(String arg) { // the input arguments has "=" character when this function is called String[] splitStrings = arg.split("=", 2); if (splitStrings[1].isEmpty()) { printUsage("Missing input value for " + splitStrings[0]); } return splitStrings[1]; } // Application entry point public static void main(String args[]) { TimeZone.setDefault(TimeZone.getTimeZone("GMT+0")); // Initialize parameter defaults String serverList = "localhost"; int port = 21212; String user = ""; String password = ""; String kerberos = ""; List<String> queries = null; String ddlFile = ""; // Parse out parameters for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.startsWith("--servers=")) { serverList = extractArgInput(arg); } else if (arg.startsWith("--port=")) { port = Integer.valueOf(extractArgInput(arg)); } else if (arg.startsWith("--user=")) { user = extractArgInput(arg); } else if (arg.startsWith("--password=")) { password = extractArgInput(arg); } else if (arg.startsWith("--kerberos=")) { kerberos = extractArgInput(arg); } else if (arg.startsWith("--kerberos")) { kerberos = "VoltDBClient"; } else if (arg.startsWith("--query=")) { List<String> argQueries = SQLParser.parseQuery(arg.substring(8)); if (!argQueries.isEmpty()) { if (queries == null) { queries = argQueries; } else { queries.addAll(argQueries); } } } else if (arg.startsWith("--output-format=")) { String formatName = extractArgInput(arg).toLowerCase(); if (formatName.equals("fixed")) { m_outputFormatter = new SQLCommandOutputFormatterDefault(); } else if (formatName.equals("csv")) { m_outputFormatter = new SQLCommandOutputFormatterCSV(); } else if (formatName.equals("tab")) { m_outputFormatter = new SQLCommandOutputFormatterTabDelimited(); } else { printUsage("Invalid value for --output-format"); } } else if (arg.startsWith("--stop-on-error=")) { String optionName = extractArgInput(arg).toLowerCase(); if (optionName.equals("true")) { m_stopOnError = true; } else if (optionName.equals("false")) { m_stopOnError = false; } else { printUsage("Invalid value for --stop-on-error"); } } else if (arg.startsWith("--ddl-file=")) { String ddlFilePath = extractArgInput(arg); try { ddlFile = new Scanner(new File(ddlFilePath)).useDelimiter("\\Z").next(); } catch (FileNotFoundException e) { printUsage("DDL file not found at path:" + ddlFilePath); } } else if (arg.startsWith("--query-timeout=")) { m_hasBatchTimeout = true; m_batchTimeout = Integer.valueOf(extractArgInput(arg)); } // equals check starting here else if (arg.equals("--output-skip-metadata")) { m_outputShowMetadata = false; } else if (arg.equals("--debug")) { m_debug = true; } else if (arg.equals("--help")) { printHelp(System.out); // Print readme to the screen System.out.println("\n\n"); printUsage(0); } else if (arg.equals("--no-version-check")) { m_versionCheck = false; // Disable new version phone home check } else if ((arg.equals("--usage")) || (arg.equals("-?"))) { printUsage(0); } else { printUsage("Invalid Parameter: " + arg); } } // Split server list String[] servers = serverList.split(","); // Phone home to see if there is a newer version of VoltDB if (m_versionCheck) { openURLAsync(); } try { // If we need to prompt the user for a password, do so. password = CLIConfig.readPasswordIfNeeded(user, password, "Enter password: "); } catch (IOException ex) { printUsage("Unable to read password: " + ex); } // Create connection ClientConfig config = new ClientConfig(user, password); config.setProcedureCallTimeout(0); // Set procedure all to infinite timeout, see ENG-2670 try { // if specified enable kerberos if (!kerberos.isEmpty()) { config.enableKerberosAuthentication(kerberos); } m_client = getClient(config, servers, port); } catch (Exception exc) { System.err.println(exc.getMessage()); System.exit(-1); } try { if (! ddlFile.equals("")) { // fast DDL Loader mode // System.out.println("fast DDL Loader mode with DDL input:\n" + ddlFile); m_client.callProcedure("@AdHoc", ddlFile); System.exit(m_exitCode); } // Load system procedures loadSystemProcedures(); // Load user stored procs loadStoredProcedures(Procedures, Classlist); // Removed code to prevent Ctrl-C from exiting. The original code is visible // in Git history hash 837df236c059b5b4362ffca7e7a5426fba1b7f20. m_interactive = true; if (queries != null && !queries.isEmpty()) { // If queries are provided via command line options run them in // non-interactive mode. //TODO: Someday we should honor batching. m_interactive = false; for (String query : queries) { executeStatement(query); } } // This test for an interactive environment is mostly // reliable. See stackoverflow.com/questions/1403772. // It accurately detects when data is piped into the program // but it fails to distinguish the case when data is ONLY piped // OUT of the command -- that's a possible but very strange way // to run an interactive session, so it's OK that we don't support // it. Instead, in that edge case, we fall back to non-interactive // mode but IN THAT MODE, we wait on and process user input as if // from a slow pipe. Strange, but acceptable, and preferable to the // check used here in the past (System.in.available() > 0) // which would fail in the opposite direction, when a 0-length // file was piped in, showing an interactive greeting and prompt // before quitting. if (System.console() == null && m_interactive) { m_interactive = false; executeNoninteractive(); } if (m_interactive) { // Print out welcome message System.out.printf("SQL Command :: %s%s:%d\n", (user == "" ? "" : user + "@"), serverList, port); interactWithTheUser(); } } catch (Exception x) { stopOrContinue(x); } finally { try { m_client.close(); } catch (Exception x) { } } // Processing may have been continued after one or more errors. // Reflect them in the exit code. // This might be a little unconventional for an interactive session, // but it's also likely to be ignored in that case, so "no great harm done". //* enable to debug */ System.err.println("Exiting with code " + m_exitCode); System.exit(m_exitCode); } // The following two methods implement a "phone home" version check for VoltDB. // Asynchronously ping VoltDB to see what the current released version is. // If it is newer than the one running here, then notify the user in some manner TBD. // Note that this processing should not impact utility use in any way. Ignore all // errors. private static void openURLAsync() { Thread t = new Thread(new Runnable() { @Override public void run() { openURL(); } }); // Set the daemon flag so that this won't hang the process if it runs into difficulty t.setDaemon(true); t.start(); } private static void openURL() { URL url; try { // Read the response from VoltDB String a="http://community.voltdb.com/versioncheck?app=sqlcmd&ver=" + org.voltdb.VoltDB.instance().getVersionString(); url = new URL(a); URLConnection conn = url.openConnection(); // open the stream and put it into BufferedReader BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream())); while (br.readLine() != null) { // At this time do nothing, just drain the stream. // In the future we'll notify the user that a new version of VoltDB is available. } br.close(); } catch (Throwable e) { // ignore any error } } }
package org.voltdb.utils; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.TimeZone; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import jline.console.CursorBuffer; import jline.console.KeyMap; import jline.console.history.FileHistory; import org.voltdb.VoltTable; import org.voltdb.VoltType; import org.voltdb.client.Client; import org.voltdb.client.ClientConfig; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientResponse; import org.voltdb.client.NoConnectionsException; import org.voltdb.client.ProcCallException; import org.voltdb.parser.SQLParser; import org.voltdb.parser.SQLParser.FileInfo; import org.voltdb.parser.SQLParser.FileOption; import org.voltdb.parser.SQLParser.ParseRecallResults; import com.google_voltpatches.common.collect.ImmutableMap; public class SQLCommand { private static boolean m_stopOnError = true; private static boolean m_debug = false; private static boolean m_interactive; private static boolean m_returningToPromptAfterError = false; private static int m_exitCode = 0; private static final String m_readme = "SQLCommandReadme.txt"; public static String getReadme() { return m_readme; } private static List<String> RecallableSessionLines = new ArrayList<String>(); private static boolean m_testFrontEndOnly; private static String m_testFrontEndResult; private static String patchErrorMessageWithFile(String batchFileName, String message) { Pattern errorMessageFilePrefix = Pattern.compile("\\[.*:([0-9]+)\\]"); Matcher matcher = errorMessageFilePrefix.matcher(message); if (matcher.find()) { // This won't work right if the filename contains a "$"... message = matcher.replaceFirst("[" + batchFileName + ":$1]"); } return message; } private static void executeDDLBatch(String batchFileName, String statements) { try { if ( ! m_interactive ) { System.out.println(); System.out.println(statements); } if (! SQLParser.appearsToBeValidDDLBatch(statements)) { throw new Exception("Error: This batch begins with a non-DDL statement. " + "Currently batching is only supported for DDL."); } if (m_testFrontEndOnly) { m_testFrontEndResult += statements; return; } ClientResponse response = m_client.callProcedure("@AdHoc", statements); if (response.getStatus() != ClientResponse.SUCCESS) { throw new Exception("Execution Error: " + response.getStatusString()); } // Assert the current DDL AdHoc batch call behavior assert(response.getResults().length == 1); System.out.println("Batch command succeeded."); loadStoredProcedures(Procedures, Classlist); } catch (ProcCallException ex) { String fixedMessage = patchErrorMessageWithFile(batchFileName, ex.getMessage()); stopOrContinue(new Exception(fixedMessage)); } catch (Exception ex) { stopOrContinue(ex); } } // The main loop for interactive mode. public static void interactWithTheUser() throws Exception { final SQLConsoleReader interactiveReader = new SQLConsoleReader(new FileInputStream(FileDescriptor.in), System.out); interactiveReader.setBellEnabled(false); FileHistory historyFile = null; try { // Maintain persistent history in ~/.sqlcmd_history. historyFile = new FileHistory(new File(System.getProperty("user.home"), ".sqlcmd_history")); interactiveReader.setHistory(historyFile); // Make Ctrl-D (EOF) exit if on an empty line, otherwise delete the next character. KeyMap keyMap = interactiveReader.getKeys(); keyMap.bind(new Character(KeyMap.CTRL_D).toString(), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { CursorBuffer cursorBuffer = interactiveReader.getCursorBuffer(); if (cursorBuffer.length() == 0) { System.exit(m_exitCode); } else { try { interactiveReader.delete(); } catch (IOException e1) {} } } }); getInteractiveQueries(interactiveReader); } finally { // Flush input history to a file. if (historyFile != null) { try { historyFile.flush(); } catch (IOException e) { System.err.printf("* Unable to write history to \"%s\" *\n", historyFile.getFile().getPath()); if (m_debug) { e.printStackTrace(); } } } // Clean up jline2 resources. if (interactiveReader != null) { interactiveReader.shutdown(); } } } public static void getInteractiveQueries(SQLConsoleReader interactiveReader) throws Exception { // Reset the error state to avoid accidentally ignoring future FILE content // after a file had runtime errors (ENG-7335). m_returningToPromptAfterError = false; final StringBuilder statement = new StringBuilder(); boolean isRecall = false; while (true) { String prompt = isRecall ? "" : ((RecallableSessionLines.size() + 1) + "> "); isRecall = false; String line = interactiveReader.readLine(prompt); if (line == null) { // This used to occur in an edge case when trying to pipe an // empty file into stdin and ending up in interactive mode by // mistake. That case works differently now, so this code path // MAY be dead. If not, cut our losses by rigging a quick exit. statement.setLength(0); line = "EXIT;"; } // Was there a line-ending semicolon typed at the prompt? // This mostly matters for "non-directive" statements. boolean executeImmediate = SQLParser.isSemiColonTerminated(line); // When we are tracking the progress of a multi-line statement, // avoid coincidentally recognizing mid-statement SQL content as sqlcmd // "directives". if (statement.length() == 0) { if (line.trim().equals("") || SQLParser.isWholeLineComment(line)) { // We don't strictly have to execute or append or recall // a blank line or whole-line comment when no statement is in progress. continue; } // EXIT command - exit immediately if (SQLParser.isExitCommand(line)) { return; } // RECALL command ParseRecallResults recallParseResults = SQLParser.parseRecallStatement(line, RecallableSessionLines.size() - 1); if (recallParseResults != null) { if (recallParseResults.getError() == null) { line = RecallableSessionLines.get(recallParseResults.getLine()); interactiveReader.putString(line); interactiveReader.flush(); isRecall = true; } else { System.out.println(recallParseResults.getError()); } executeImmediate = false; // let user edit the recalled line. continue; } // Queue up the line to the recall stack //TODO: In the future, we may not want to have simple directives count as recallable // lines, so this call would move down a ways. RecallableSessionLines.add(line); if (executesAsSimpleDirective(line)) { executeImmediate = false; // return to prompt. continue; } // If the line is a FILE command - execute the content of the file FileInfo fileInfo = SQLParser.parseFileStatement(line); if (fileInfo != null) { executeScriptFile(fileInfo, interactiveReader); if (m_returningToPromptAfterError) { // executeScriptFile stopped because of an error. Wipe the slate clean. m_returningToPromptAfterError = false; } continue; } // else treat the input line as a regular database command if (executeImmediate) { executeStatements(line + "\n"); if (m_testFrontEndOnly) { break; // test mode expects this early return before end of input. } continue; } } else { // With a multi-line statement pending, // queue up the line continuation to the recall list. //TODO: arguably, it would be more useful to append continuation // lines to the last existing Lines entry to build each complete // statement as a single recallable unit. Experiments indicated // that joining the lines with a single space, while not as pretty // as a newline for very long statements, behaved perfectly for // line editing (cursor positioning). RecallableSessionLines.add(line); if (executeImmediate) { statement.append(line + "\n"); executeStatements(statement.toString()); if (m_testFrontEndOnly) { break; // test mode expects this early return before end of input. } statement.setLength(0); continue; } } // Collect lines ... statement.append(line + "\n"); //TODO: Here's where we might append to a separate buffer that uses // a single space rather than a newline as its separator to build up // a recallable multi-line statement. } } /// A stripped down variant of the processing in "interactWithTheUser" suitable for /// applying to a command script. It skips all the interactive-only options. /// It uses the same logic as the FILE directive but gets its input from stdin. public static void executeNoninteractive() throws Exception { SQLCommandLineReader stdinReader = new LineReaderAdapter(new InputStreamReader(System.in)); FileInfo fileInfo = SQLParser.FileInfo.forSystemIn(); executeScriptFromReader(fileInfo, stdinReader); } /// Simple directives require only the input line and no other context from the input loop. /// Return true if the line is a directive that has been completely handled here, so that the /// input loop can proceed to the next line. //TODO: There have been suggestions that some or all of these directives could be made // available in non-interactive contexts. This function is available to enable that. private static boolean executesAsSimpleDirective(String line) throws Exception { // SHOW or LIST <blah> statement String subcommand = SQLParser.parseShowStatementSubcommand(line); if (subcommand != null) { if (subcommand.equals("proc") || subcommand.equals("procedures")) { execListProcedures(); } else if (subcommand.equals("tables")) { execListTables(); } else if (subcommand.equals("classes")) { execListClasses(); } else { String errorCase = (subcommand.equals("") || subcommand.equals(";")) ? ("Incomplete SHOW command.\n") : ("Invalid SHOW command completion: '" + subcommand + "'.\n"); System.out.println(errorCase + "The valid SHOW command completions are proc, procedures, tables, or classes."); } // Consider it handled here, whether or not it was a good SHOW statement. return true; } // HELP commands - ONLY in interactive mode, close batch and parse for execution // Parser returns null if it isn't a HELP command. If no arguments are specified // the returned string will be empty. String helpSubcommand = SQLParser.parseHelpStatement(line); if (helpSubcommand != null) { // Ignore the arguments for now. if (!helpSubcommand.isEmpty()) { System.out.printf("Ignoring extra HELP argument(s): %s\n", helpSubcommand); } printHelp(System.out); // Print readme to the screen return true; } // It wasn't a locally-interpreted directive. return false; } private static void execListClasses() { //TODO: since sqlcmd makes no intrinsic use of the Classlist, it would be more // efficient to load the Classlist only "on demand" from here and to cache a // complete formatted String result rather than the complex map representation. // This would save churn on startup and on DDL update. if (Classlist.isEmpty()) { System.out.println(); System.out.println(" System.out.println(); } List<String> list = new LinkedList<String>(Classlist.keySet()); Collections.sort(list); int padding = 0; for (String classname : list) { padding = Math.max(padding, classname.length()); } String format = " %1$-" + padding + "s"; String categoryHeader[] = new String[] { " " " for (int i = 0; i<3; i++) { boolean firstInCategory = true; for (String classname : list) { List<Boolean> stuff = Classlist.get(classname); // Print non-active procs first if (i == 0 && !(stuff.get(0) && !stuff.get(1))) { continue; } else if (i == 1 && !(stuff.get(0) && stuff.get(1))) { continue; } else if (i == 2 && stuff.get(0)) { continue; } if (firstInCategory) { firstInCategory = false; System.out.println(); System.out.println(categoryHeader[i]); } System.out.printf(format, classname); System.out.println(); } } System.out.println(); } private static void execListTables() throws Exception { //TODO: since sqlcmd makes no intrinsic use of the tables list, it would be more // efficient to load the list only "on demand" from here and to cache a // complete formatted String result rather than the multiple lists. // This would save churn on startup and on DDL update. Tables tables = getTables(); printTables("User Tables", tables.tables); printTables("User Views", tables.views); printTables("User Export Streams", tables.exports); System.out.println(); } private static void execListProcedures() { List<String> list = new LinkedList<String>(Procedures.keySet()); Collections.sort(list); int padding = 0; for (String procedure : list) { if (padding < procedure.length()) { padding = procedure.length(); } } padding++; String format = "%1$-" + padding + "s"; boolean firstSysProc = true; boolean firstUserProc = true; for (String procedure : list) { //TODO: it would be much easier over all to maintain sysprocs and user procs in // in two separate maps. if (procedure.startsWith("@")) { if (firstSysProc) { firstSysProc = false; System.out.println(" } } else { if (firstUserProc) { firstUserProc = false; System.out.println(); System.out.println(" } } for (List<String> parameterSet : Procedures.get(procedure).values()) { System.out.printf(format, procedure); String sep = "\t"; for (String paramType : parameterSet) { System.out.print(sep + paramType); sep = ", "; } System.out.println(); } } System.out.println(); } private static void printTables(final String name, final Collection<String> tables) { System.out.println(); System.out.println(" for (String table : tables) { System.out.println(table); } System.out.println(); } /** Adapt BufferedReader into a SQLCommandLineReader */ private static class LineReaderAdapter implements SQLCommandLineReader { private final BufferedReader m_reader; LineReaderAdapter(InputStreamReader reader) { m_reader = new BufferedReader(reader); } @Override public String readBatchLine() throws IOException { return m_reader.readLine(); } void close() { try { m_reader.close(); } catch (IOException e) { } } } /** * Reads a script file and executes its content. * Note that the "script file" could be an inline batch, * i.e., a "here document" that is coming from the same input stream * as the "file" directive. * * @param fileInfo Info on the file directive being processed * @param parentLineReader The current input stream, to be used for "here documents". */ static void executeScriptFile(FileInfo fileInfo, SQLCommandLineReader parentLineReader) { LineReaderAdapter adapter = null; SQLCommandLineReader reader = null; if ( ! m_interactive) { System.out.println(); System.out.println(fileInfo.toString()); } if (fileInfo.getOption() == FileOption.INLINEBATCH) { // File command is a "here document" so pass in the current // input stream. reader = parentLineReader; } else { try { reader = adapter = new LineReaderAdapter(new FileReader(fileInfo.getFile())); } catch (FileNotFoundException e) { System.err.println("Script file '" + fileInfo.getFile() + "' could not be found."); stopOrContinue(e); return; // continue to the next line after the FILE command } } try { executeScriptFromReader(fileInfo, reader); } catch (Exception x) { stopOrContinue(x); } finally { if (adapter != null) { adapter.close(); } } } /** * * @param fileInfo The FileInfo object describing the file command (or stdin) * @param script The line reader object to read from * @throws Exception */ private static void executeScriptFromReader(FileInfo fileInfo, SQLCommandLineReader reader) throws Exception { StringBuilder statement = new StringBuilder(); // non-interactive modes need to be more careful about discarding blank lines to // keep from throwing off diagnostic line numbers. So "statement" may be non-empty even // when a sql statement has not yet started (?) boolean statementStarted = false; StringBuilder batch = fileInfo.isBatch() ? new StringBuilder() : null; String delimiter = (fileInfo.getOption() == FileOption.INLINEBATCH) ? fileInfo.getDelimiter() : null; while (true) { String line = reader.readBatchLine(); if (delimiter != null) { if (line == null) { // We only print this nice message if the inline batch is // being executed non-interactively. For an inline batch // entered from the command line, SQLConsoleReader catches // ctrl-D and exits the process before this code can execute, // even if this code is in a "finally" block. throw new Exception("ERROR: Failed to find delimiter \"" + delimiter + "\" indicating end of inline batch. No batched statements were executed."); } if (delimiter.equals(line)) { line = null; } } if (line == null) { // No more lines. Execute whatever we got. if (statement.length() > 0) { if (batch == null) { String statementString = statement.toString(); // Trim here avoids a "missing statement" error from adhoc in an edge case // like a blank line from stdin. if ( ! statementString.trim().isEmpty()) { //* enable to debug */if (m_debug) System.out.println("DEBUG QUERY:'" + statementString + "'"); executeStatements(statementString); } } else { // This means that batch did not end with a semicolon. // Maybe it ended with a comment. // For now, treat the final semicolon as optional and // assume that we are not just adding a partial statement to the batch. batch.append(statement); executeDDLBatch(fileInfo.getFilePath(), batch.toString()); } } return; } if ( ! statementStarted) { if (line.trim().equals("") || SQLParser.isWholeLineComment(line)) { // We don't strictly have to include a blank line or whole-line // comment at the start of a statement, but when we want to preserve line // numbers (in a batch), we should at least append a newline. // Whether to echo comments or blank lines from a batch is // a grey area. if (batch != null) { statement.append(line).append("\n"); } continue; } // Recursively process FILE commands, any failure will cause a recursive failure FileInfo nestedFileInfo = SQLParser.parseFileStatement(fileInfo, line); if (nestedFileInfo != null) { // Guards must be added for FILE Batch containing batches. if (batch != null) { stopOrContinue(new RuntimeException( "A FILE command is invalid in a batch.")); continue; // continue to the next line after the FILE command } // Execute the file content or fail to but only set m_returningToPromptAfterError // if the intent is to cause a recursive failure, stopOrContinue decided to stop. executeScriptFile(nestedFileInfo, reader); if (m_returningToPromptAfterError) { // The recursive readScriptFile stopped because of an error. // Escape to the outermost readScriptFile caller so it can exit or // return to the interactive prompt. return; } // Continue after a bad nested file command by processing the next line // in the current file. continue; } // process other non-interactive directives if (executesAsSimpleDirective(line)) { continue; } // TODO: This would be a reasonable place to validate that the line // starts with a SQL command keyword, exec/execute or one of the other // known commands. // According to the current parsing rules that allow multi-statement // stacking on a line (as an undocumented feature), // this work would also have to be repeated after each // non-quoted non-commented statement-splitting semicolon. // See executeStatements. } // Process normal @AdHoc commands which may be // multi-line-statement continuations. statement.append(line).append("\n"); // Check if the current statement ends here and now. if (SQLParser.isSemiColonTerminated(line)) { if (batch == null) { String statementString = statement.toString(); // Trim here avoids a "missing statement" error from adhoc in an edge case // like a blank line from stdin. if ( ! statementString.trim().isEmpty()) { //* enable to debug */ if (m_debug) System.out.println("DEBUG QUERY:'" + statementString + "'"); executeStatements(statementString); } statement.setLength(0); } statementStarted = false; } else { // Disable directive processing until end of statement. statementStarted = true; } } } private static long m_startTime; // executeQueuedStatements is called instead of executeStatement because // multiple semicolon-separated statements are allowed on a line and because // using "line ends with semicolon" is not foolproof as a means of detecting // the end of a statement. It could give a false negative for something as // simple as an end-of-line comment. private static void executeStatements(String statements) { List<String> parsedStatements = SQLParser.parseQuery(statements); for (String statement: parsedStatements) { executeStatement(statement); } } private static void executeStatement(String statement) { if (m_testFrontEndOnly) { m_testFrontEndResult += statement + ";\n"; return; } if ( ! m_interactive ) { System.out.println(); System.out.println(statement + ";"); } try { // EXEC <procedure> <params>... m_startTime = System.nanoTime(); SQLParser.ExecuteCallResults execCallResults = SQLParser.parseExecuteCall(statement, Procedures); if (execCallResults != null) { Object[] objectParams = execCallResults.getParameterObjects(); if (execCallResults.procedure.equals("@UpdateApplicationCatalog")) { File catfile = null; if (objectParams[0] != null) { catfile = new File((String)objectParams[0]); } File depfile = null; if (objectParams[1] != null) { depfile = new File((String)objectParams[1]); } printDdlResponse(m_client.updateApplicationCatalog(catfile, depfile)); // Need to update the stored procedures after a catalog change (could have added/removed SPs!). ENG-3726 loadStoredProcedures(Procedures, Classlist); } else if (execCallResults.procedure.equals("@UpdateClasses")) { File jarfile = null; if (objectParams[0] != null) { jarfile = new File((String)objectParams[0]); } printDdlResponse(m_client.updateClasses(jarfile, (String)objectParams[1])); // Need to reload the procedures and classes loadStoredProcedures(Procedures, Classlist); } else { // @SnapshotDelete needs array parameters. if (execCallResults.procedure.equals("@SnapshotDelete")) { objectParams[0] = new String[] { (String)objectParams[0] }; objectParams[1] = new String[] { (String)objectParams[1] }; } printResponse(m_client.callProcedure(execCallResults.procedure, objectParams)); } return; } String explainStatement = SQLParser.parseExplainCall(statement); if (explainStatement != null) { // We've got a statement that starts with "explain", send the statement to // @Explain (after parseExplainCall() strips "explain"). printResponse(m_client.callProcedure("@Explain", explainStatement)); return; } String explainProcName = SQLParser.parseExplainProcCall(statement); if (explainProcName != null) { // We've got a statement that starts with "explainproc", send the statement to // @ExplainProc (now that parseExplainProcCall() has stripped out "explainproc"). printResponse(m_client.callProcedure("@ExplainProc", explainProcName)); return; } // LOAD CLASS <jar>? String loadPath = SQLParser.parseLoadClasses(statement); if (loadPath != null) { File jarfile = new File(loadPath); printDdlResponse(m_client.updateClasses(jarfile, null)); loadStoredProcedures(Procedures, Classlist); return; } // REMOVE CLASS <class-selector>? String classSelector = SQLParser.parseRemoveClasses(statement); if (classSelector != null) { printDdlResponse(m_client.updateClasses(null, classSelector)); loadStoredProcedures(Procedures, Classlist); return; } // DDL statements get forwarded to @AdHoc, // but get special post-processing. if (SQLParser.queryIsDDL(statement)) { // if the query is DDL, reload the stored procedures. printDdlResponse(m_client.callProcedure("@AdHoc", statement)); loadStoredProcedures(Procedures, Classlist); return; } // All other commands get forwarded to @AdHoc printResponse(m_client.callProcedure("@AdHoc", statement)); } catch (Exception exc) { stopOrContinue(exc); } } private static void stopOrContinue(Exception exc) { System.err.println(exc.getMessage()); if (m_debug) { exc.printStackTrace(System.err); } // Let the final exit code reflect any error(s) in the run. // This is useful for debugging a script that may have multiple errors // and multiple valid statements. m_exitCode = -1; if (m_stopOnError) { if ( ! m_interactive ) { System.exit(m_exitCode); } // Setting this member to drive a fast stack unwind from // recursive readScriptFile requires explicit checks in that code, // but still seems easier than a "throw" here from a catch block that // would require additional exception handlers in the caller(s) m_returningToPromptAfterError = true; } } // Output generation private static SQLCommandOutputFormatter m_outputFormatter = new SQLCommandOutputFormatterDefault(); private static boolean m_outputShowMetadata = true; private static boolean isUpdateResult(VoltTable table) { return ((table.getColumnName(0).isEmpty() || table.getColumnName(0).equals("modified_tuples")) && table.getRowCount() == 1 && table.getColumnCount() == 1 && table.getColumnType(0) == VoltType.BIGINT); } private static void printResponse(ClientResponse response) throws Exception { if (response.getStatus() != ClientResponse.SUCCESS) { throw new Exception("Execution Error: " + response.getStatusString()); } long elapsedTime = System.nanoTime() - m_startTime; for (VoltTable t : response.getResults()) { long rowCount; if (!isUpdateResult(t)) { rowCount = t.getRowCount(); // Run it through the output formatter. m_outputFormatter.printTable(System.out, t, m_outputShowMetadata); } else { rowCount = t.fetchRow(0).getLong(0); } if (m_outputShowMetadata) { System.out.printf("(Returned %d rows in %.2fs)\n", rowCount, elapsedTime / 1000000000.0); } } } private static void printDdlResponse(ClientResponse response) throws Exception { if (response.getStatus() != ClientResponse.SUCCESS) { throw new Exception("Execution Error: " + response.getStatusString()); } //TODO: In the future, if/when we change the prompt when waiting for the remainder of an unfinished command, // successful DDL commands may just silently return to a normal prompt without this verbose feedback. System.out.println("Command succeeded."); } // VoltDB connection support private static Client m_client; // Default visibility is for test purposes. static Map<String,Map<Integer, List<String>>> Procedures = Collections.synchronizedMap(new HashMap<String,Map<Integer, List<String>>>()); private static Map<String, List<Boolean>> Classlist = Collections.synchronizedMap(new HashMap<String, List<Boolean>>()); private static void loadSystemProcedures() { Procedures.put("@Pause", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@Quiesce", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@Resume", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@Shutdown", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@StopNode", ImmutableMap.<Integer, List<String>>builder().put(1, Arrays.asList("int")).build()); Procedures.put("@SnapshotDelete", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")).build() ); Procedures.put("@SnapshotRestore", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")) .put( 1, Arrays.asList("varchar")).build() ); Procedures.put("@SnapshotSave", ImmutableMap.<Integer, List<String>>builder().put( 3, Arrays.asList("varchar", "varchar", "bit")). put( 1, Arrays.asList("varchar")).build() ); Procedures.put("@SnapshotScan", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build()); Procedures.put("@Statistics", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("statisticscomponent", "bit")).build()); Procedures.put("@SystemCatalog", ImmutableMap.<Integer, List<String>>builder().put( 1,Arrays.asList("metadataselector")).build()); Procedures.put("@SystemInformation", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("sysinfoselector")).build()); Procedures.put("@UpdateApplicationCatalog", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")).build()); Procedures.put("@UpdateClasses", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("varchar", "varchar")).build()); Procedures.put("@UpdateLogging", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build()); Procedures.put("@Promote", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@SnapshotStatus", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); Procedures.put("@Explain", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build()); Procedures.put("@ExplainProc", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build()); Procedures.put("@ValidatePartitioning", ImmutableMap.<Integer, List<String>>builder().put( 2, Arrays.asList("int", "varbinary")).build()); Procedures.put("@GetPartitionKeys", ImmutableMap.<Integer, List<String>>builder().put( 1, Arrays.asList("varchar")).build()); Procedures.put("@GC", ImmutableMap.<Integer, List<String>>builder().put( 0, new ArrayList<String>()).build()); } private static Client getClient(ClientConfig config, String[] servers, int port) throws Exception { final Client client = ClientFactory.createClient(config); for (String server : servers) { client.createConnection(server.trim(), port); } return client; } // General application support private static void printUsage(String msg) { System.out.print(msg); System.out.println("\n"); printUsage(-1); } private static void printUsage(int exitCode) { System.out.println( "Usage: sqlcmd --help\n" + " or sqlcmd [--servers=comma_separated_server_list]\n" + " [--port=port_number]\n" + " [--user=user]\n" + " [--password=password]\n" + " [--kerberos=jaas_login_configuration_entry_key]\n" + " [--query=query]\n" + " [--output-format=(fixed|csv|tab)]\n" + " [--output-skip-metadata]\n" + " [--stop-on-error=(true|false)]\n" + "\n" + "[--servers=comma_separated_server_list]\n" + " List of servers to connect to.\n" + " Default: localhost.\n" + "\n" + "[--port=port_number]\n" + " Client port to connect to on cluster nodes.\n" + " Default: 21212.\n" + "\n" + "[--user=user]\n" + " Name of the user for database login.\n" + " Default: (not defined - connection made without credentials).\n" + "\n" + "[--password=password]\n" + " Password of the user for database login.\n" + " Default: (not defined - connection made without credentials).\n" + "\n" + "[--kerberos=jaas_login_configuration_entry_key]\n" + " Enable kerberos authentication for user database login by specifying\n" + " the JAAS login configuration file entry name" + " Default: (not defined - connection made without credentials).\n" + "\n" + "[--query=query]\n" + " Execute a non-interactive query. Multiple query options are allowed.\n" + " Default: (runs the interactive shell when no query options are present).\n" + "\n" + "[--output-format=(fixed|csv|tab)]\n" + " Format of returned resultset data (Fixed-width, CSV or Tab-delimited).\n" + " Default: fixed.\n" + "\n" + "[--output-skip-metadata]\n" + " Removes metadata information such as column headers and row count from\n" + " produced output. Default: metadata output is enabled.\n" + "\n" + "[--stop-on-error=(true|false)]\n" + " Causes the utility to stop immediately or continue after detecting an error.\n" + " In interactive mode, a value of \"true\" discards any unprocessed input\n" + " and returns to the command prompt. Default: true.\n" + "\n" ); System.exit(exitCode); } // printHelp() can print readme either to a file or to the screen // depending on the argument passed in // Default visibility is for test purposes. static void printHelp(OutputStream prtStr) { try { InputStream is = SQLCommand.class.getResourceAsStream(m_readme); while (is.available() > 0) { byte[] bytes = new byte[is.available()]; // Fix for ENG-3440 is.read(bytes, 0, bytes.length); prtStr.write(bytes); // For JUnit test } } catch (Exception x) { System.err.println(x.getMessage()); System.exit(-1); } } private static class Tables { TreeSet<String> tables = new TreeSet<String>(); TreeSet<String> exports = new TreeSet<String>(); TreeSet<String> views = new TreeSet<String>(); } private static Tables getTables() throws Exception { Tables tables = new Tables(); VoltTable tableData = m_client.callProcedure("@SystemCatalog", "TABLES").getResults()[0]; while (tableData.advanceRow()) { String tableName = tableData.getString("TABLE_NAME"); String tableType = tableData.getString("TABLE_TYPE"); if (tableType.equalsIgnoreCase("EXPORT")) { tables.exports.add(tableName); } else if (tableType.equalsIgnoreCase("VIEW")) { tables.views.add(tableName); } else { tables.tables.add(tableName); } } return tables; } private static void loadStoredProcedures(Map<String,Map<Integer, List<String>>> procedures, Map<String, List<Boolean>> classlist) { VoltTable procs = null; VoltTable params = null; VoltTable classes = null; try { procs = m_client.callProcedure("@SystemCatalog", "PROCEDURES").getResults()[0]; params = m_client.callProcedure("@SystemCatalog", "PROCEDURECOLUMNS").getResults()[0]; classes = m_client.callProcedure("@SystemCatalog", "CLASSES").getResults()[0]; } catch (NoConnectionsException e) { e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } catch (ProcCallException e) { e.printStackTrace(); return; } Map<String, Integer> proc_param_counts = Collections.synchronizedMap(new HashMap<String, Integer>()); while (params.advanceRow()) { String this_proc = params.getString("PROCEDURE_NAME"); Integer curr_val = proc_param_counts.get(this_proc); if (curr_val == null) { curr_val = 1; } else { ++curr_val; } proc_param_counts.put(this_proc, curr_val); } params.resetRowPosition(); while (procs.advanceRow()) { String proc_name = procs.getString("PROCEDURE_NAME"); Integer param_count = proc_param_counts.get(proc_name); ArrayList<String> this_params = new ArrayList<String>(); // prepopulate it to make sure the size is right if (param_count != null) { for (int i = 0; i < param_count; i++) { this_params.add(null); } } else { param_count = 0; } HashMap<Integer, List<String>> argLists = new HashMap<Integer, List<String>>(); argLists.put(param_count, this_params); procedures.put(proc_name, argLists); } classlist.clear(); while (classes.advanceRow()) { String classname = classes.getString("CLASS_NAME"); boolean isProc = (classes.getLong("VOLT_PROCEDURE") == 1L); boolean isActive = (classes.getLong("ACTIVE_PROC") == 1L); if (!classlist.containsKey(classname)) { List<Boolean> stuff = Collections.synchronizedList(new ArrayList<Boolean>()); stuff.add(isProc); stuff.add(isActive); classlist.put(classname, stuff); } } // Retrieve the parameter types. Note we have to do some special checking // for array types. ENG-3101 params.resetRowPosition(); while (params.advanceRow()) { Map<Integer, List<String>> argLists = procedures.get(params.getString("PROCEDURE_NAME")); assert(argLists.size() == 1); List<String> this_params = argLists.values().iterator().next(); int idx = (int)params.getLong("ORDINAL_POSITION") - 1; String param_type = params.getString("TYPE_NAME").toLowerCase(); // Detect if this parameter is supposed to be an array. It's kind of clunky, we have to // look in the remarks column... String param_remarks = params.getString("REMARKS"); if (null != param_remarks) { param_type += (param_remarks.equalsIgnoreCase("ARRAY_PARAMETER") ? "_array" : ""); } this_params.set(idx, param_type); } } /// Parser unit test entry point ///TODO: it would be simpler if this testing entry point could just set up some mocking /// of io and statement "execution" -- mocking with statement capture instead of actual execution /// to better isolate the parser. /// Then it could call a new simplified version of interactWithTheUser(). /// But the current parser tests expect to call a SQLCommand function that can return for /// some progress checking before its input stream has been permanently terminated. /// They would need to be able to check parser progress in one thread while /// SQLCommand.interactWithTheUser() was awaiting further input on another thread /// (or in its own process). public static List<String> getParserTestQueries(InputStream inmocked, OutputStream outmocked) { testFrontEndOnly(); try { SQLConsoleReader reader = new SQLConsoleReader(inmocked, outmocked); getInteractiveQueries(reader); return SQLParser.parseQuery(m_testFrontEndResult); } catch (Exception ioe) {} return null; } public static void testFrontEndOnly() { m_testFrontEndOnly = true; m_testFrontEndResult = ""; } public static String getTestResult() { return m_testFrontEndResult; } private static String extractArgInput(String arg) { // the input arguments has "=" character when this function is called String[] splitStrings = arg.split("=", 2); if (splitStrings[1].isEmpty()) { printUsage("Missing input value for " + splitStrings[0]); } return splitStrings[1]; } // Application entry point public static void main(String args[]) { TimeZone.setDefault(TimeZone.getTimeZone("GMT+0")); // Initialize parameter defaults String serverList = "localhost"; int port = 21212; String user = ""; String password = ""; String kerberos = ""; List<String> queries = null; String ddlFile = ""; // Parse out parameters for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.startsWith("--servers=")) { serverList = extractArgInput(arg); } else if (arg.startsWith("--port=")) { port = Integer.valueOf(extractArgInput(arg)); } else if (arg.startsWith("--user=")) { user = extractArgInput(arg); } else if (arg.startsWith("--password=")) { password = extractArgInput(arg); } else if (arg.startsWith("--kerberos=")) { kerberos = extractArgInput(arg); } else if (arg.startsWith("--kerberos")) { kerberos = "VoltDBClient"; } else if (arg.startsWith("--query=")) { List<String> argQueries = SQLParser.parseQuery(arg.substring(8)); if (!argQueries.isEmpty()) { if (queries == null) { queries = argQueries; } else { queries.addAll(argQueries); } } } else if (arg.startsWith("--output-format=")) { String formatName = extractArgInput(arg).toLowerCase(); if (formatName.equals("fixed")) { m_outputFormatter = new SQLCommandOutputFormatterDefault(); } else if (formatName.equals("csv")) { m_outputFormatter = new SQLCommandOutputFormatterCSV(); } else if (formatName.equals("tab")) { m_outputFormatter = new SQLCommandOutputFormatterTabDelimited(); } else { printUsage("Invalid value for --output-format"); } } else if (arg.equals("--output-skip-metadata")) { m_outputShowMetadata = false; } else if (arg.equals("--debug")) { m_debug = true; } else if (arg.startsWith("--stop-on-error=")) { String optionName = extractArgInput(arg).toLowerCase(); if (optionName.equals("true")) { m_stopOnError = true; } else if (optionName.equals("false")) { m_stopOnError = false; } else { printUsage("Invalid value for --stop-on-error"); } } else if (arg.startsWith("--ddl-file=")) { String ddlFilePath = extractArgInput(arg); try { ddlFile = new Scanner(new File(ddlFilePath)).useDelimiter("\\Z").next(); } catch (FileNotFoundException e) { printUsage("DDL file not found at path:" + ddlFilePath); } } else if (arg.equals("--help")) { printHelp(System.out); // Print readme to the screen System.out.println("\n\n"); printUsage(0); } else if ((arg.equals("--usage")) || (arg.equals("-?"))) { printUsage(0); } else { printUsage("Invalid Parameter: " + arg); } } // Split server list String[] servers = serverList.split(","); // Phone home to see if there is a newer version of VoltDB openURLAsync(); // Create connection ClientConfig config = new ClientConfig(user, password); config.setProcedureCallTimeout(0); // Set procedure all to infinite timeout, see ENG-2670 try { // if specified enable kerberos if (!kerberos.isEmpty()) { config.enableKerberosAuthentication(kerberos); } m_client = getClient(config, servers, port); } catch (Exception exc) { System.err.println(exc.getMessage()); System.exit(-1); } try { if (! ddlFile.equals("")) { // fast DDL Loader mode // System.out.println("fast DDL Loader mode with DDL input:\n" + ddlFile); m_client.callProcedure("@AdHoc", ddlFile); System.exit(m_exitCode); } // Load system procedures loadSystemProcedures(); // Load user stored procs loadStoredProcedures(Procedures, Classlist); // Removed code to prevent Ctrl-C from exiting. The original code is visible // in Git history hash 837df236c059b5b4362ffca7e7a5426fba1b7f20. m_interactive = true; if (queries != null && !queries.isEmpty()) { // If queries are provided via command line options run them in // non-interactive mode. //TODO: Someday we should honor batching. m_interactive = false; for (String query : queries) { executeStatement(query); } } // This test for an interactive environment is mostly // reliable. See stackoverflow.com/questions/1403772. // It accurately detects when data is piped into the program // but it fails to distinguish the case when data is ONLY piped // OUT of the command -- that's a possible but very strange way // to run an interactive session, so it's OK that we don't support // it. Instead, in that edge case, we fall back to non-interactive // mode but IN THAT MODE, we wait on and process user input as if // from a slow pipe. Strange, but acceptable, and preferable to the // check used here in the past (System.in.available() > 0) // which would fail in the opposite direction, when a 0-length // file was piped in, showing an interactive greeting and prompt // before quitting. if (System.console() == null) { m_interactive = false; executeNoninteractive(); } if (m_interactive) { // Print out welcome message System.out.printf("SQL Command :: %s%s:%d\n", (user == "" ? "" : user + "@"), serverList, port); interactWithTheUser(); } } catch (Exception x) { stopOrContinue(x); } finally { try { m_client.close(); } catch (Exception x) { } } // Processing may have been continued after one or more errors. // Reflect them in the exit code. // This might be a little unconventional for an interactive session, // but it's also likely to be ignored in that case, so "no great harm done". //* enable to debug */ System.err.println("Exiting with code " + m_exitCode); System.exit(m_exitCode); } // The following two methods implement a "phone home" version check for VoltDB. // Asynchronously ping VoltDB to see what the current released version is. // If it is newer than the one running here, then notify the user in some manner TBD. // Note that this processing should not impact utility use in any way. Ignore all // errors. private static void openURLAsync() { Thread t = new Thread(new Runnable() { @Override public void run() { openURL(); } }); // Set the daemon flag so that this won't hang the process if it runs into difficulty t.setDaemon(true); t.start(); } private static void openURL() { URL url; try { // Read the response from VoltDB String a="http://community.voltdb.com/versioncheck?app=sqlcmd&ver=" + org.voltdb.VoltDB.instance().getVersionString(); url = new URL(a); URLConnection conn = url.openConnection(); // open the stream and put it into BufferedReader BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream())); while (br.readLine() != null) { // At this time do nothing, just drain the stream. // In the future we'll notify the user that a new version of VoltDB is available. } br.close(); } catch (Throwable e) { // ignore any error } } }
package heufybot.core.events; import java.util.Date; import heufybot.core.Channel; import heufybot.core.HeufyBot; import heufybot.core.Logger; import heufybot.core.User; import heufybot.core.events.types.*; import heufybot.utils.StringUtils; import heufybot.utils.WhoisBuilder; public class LoggingInterface extends EventListenerAdapter { private HeufyBot bot; public LoggingInterface(HeufyBot bot) { this.bot = bot; } public void onAction(ActionEvent event) { Logger.log("* " + event.getUser().getNickname() + " " + event.getMessage(), event.getChannel().getName(), bot.getIRC().getServerInfo().getNetwork()); } public void onBotMessage(BotMessageEvent event) { User user = event.getUser(); Channel channel = bot.getIRC().getChannel(event.getTarget()); if(channel == null && event.getUser() == null) { //Don't log this. It was probably a message to an authentication service return; } else if(channel == null) { String sourceNick = event.getUser().getNickname(); Logger.log("<" + sourceNick + "> " + event.getMessage(), event.getTarget(), bot.getIRC().getServerInfo().getNetwork()); return; } String modes = channel.getModesOnUser(user); if(!modes.equals("")) { Logger.log("<" + bot.getIRC().getServerInfo().getUserPrefixes().get(bot.getIRC().getAccessLevelOnUser(channel, user)) + user.getNickname() + "> " + event.getMessage(), channel.getName(), bot.getIRC().getServerInfo().getNetwork()); } else { Logger.log("<" + user.getNickname() + "> " + event.getMessage(), channel.getName(), bot.getIRC().getServerInfo().getNetwork()); } } public void onChannelNotice(ChannelNoticeEvent event) { Logger.log("[Notice] --" + event.getSource() + "-- [" + event.getChannel().getName() + "] " + event.getMessage(), event.getChannel().getName(), bot.getIRC().getServerInfo().getNetwork()); } public void onCTCPRequest(CTCPRequestEvent event) { Logger.log("[" + event.getUser().getNickname() + " " + event.getType() + "]"); } public void onError(ErrorEvent event) { Logger.log(event.getMessage()); } public void onInvite(InviteEvent event) { User inviter = event.getInviter(); Logger.log("-- " + inviter.getNickname() + " (" + inviter.getLogin() + "@" + inviter.getHostname() + ") invites " + event.getInvitee() + " to join " + event.getChannel()); } public void onJoin(JoinEvent event) { User user = event.getUser(); Logger.log(">> " + user.getNickname() + " (" + user.getLogin() + "@" + user.getHostname() + ") has joined " + event.getChannel().getName(), event.getChannel().getName(), bot.getIRC().getServerInfo().getNetwork()); } public void onKick(KickEvent event) { Logger.log("-- " + event.getRecipient().getNickname() + " was kicked from " + event.getChannel().getName() + " by " + event.getKicker().getNickname() + " (" + event.getMessage() + ")", event.getChannel().getName(), bot.getIRC().getServerInfo().getNetwork()); } public void onMessage(MessageEvent event) { User user = event.getUser(); Channel channel = event.getChannel(); String modes = channel.getModesOnUser(user); if(!modes.equals("")) { Logger.log("<" + bot.getIRC().getServerInfo().getUserPrefixes().get(bot.getIRC().getAccessLevelOnUser(channel, user)) + user.getNickname() + "> " + event.getMessage(), channel.getName(), bot.getIRC().getServerInfo().getNetwork()); } else { Logger.log("<" + user.getNickname() + "> " + event.getMessage(), channel.getName(), bot.getIRC().getServerInfo().getNetwork()); } } public void onModeChange(ModeEvent event) { if(event.getChannel() == null) { Logger.log("-- " + event.getSetter() + " sets mode: " + event.getMode()); } else { Logger.log("-- " + event.getSetter() + " sets mode: " + event.getMode(), event.getChannel().getName(), bot.getIRC().getServerInfo().getNetwork()); } } public void onNickChange(NickChangeEvent event) { for(Channel channel : bot.getIRC().getChannels()) { User user = channel.getUser(event.getUser().getNickname()); if(user != null) { Logger.log("-- " + event.getOldNick() + " is now known as " + event.getNewNick(), channel.getName(), bot.getIRC().getServerInfo().getNetwork()); } } } public void onNotice(NoticeEvent event) { Logger.log("[Notice] --" + event.getSource() + "-- " + event.getMessage()); } public void onPart(PartEvent event) { User user = event.getUser(); String channel = event.getChannel().getName(); if(event.getMessage().equals("")) { Logger.log("<< " + user.getNickname() + " (" + user.getLogin() + "@" + user.getHostname() + ") has left " + channel, channel, bot.getIRC().getServerInfo().getNetwork()); } else { Logger.log("<< " + user.getNickname() + " (" + user.getLogin() + "@" + user.getHostname() + ") has left " + channel + " (" + event.getMessage() + ")", channel, bot.getIRC().getServerInfo().getNetwork()); } } public void onPMAction(PMActionEvent event) { Logger.log("* " + event.getUser().getNickname() + " " + event.getMessage(), event.getUser().getNickname(), bot.getIRC().getServerInfo().getNetwork()); } public void onPMMessage(PMMessageEvent event) { String sourceNick = event.getUser().getNickname(); Logger.log("<" + sourceNick + "> " + event.getMessage(), sourceNick, bot.getIRC().getServerInfo().getNetwork()); } public void onQuit(QuitEvent event) { for(Channel channel : bot.getIRC().getChannels()) { User user = channel.getUser(event.getUser().getNickname()); if(user != null) { Logger.log("<< " + user.getNickname() + " (" + user.getLogin() + "@" + user.getHostname() + ") has quit IRC (" + event.getMessage() + ")", channel.getName(), bot.getIRC().getServerInfo().getNetwork()); } } } public void onServerChannelResponse(ServerResponseChannelEvent event) { Logger.log(event.getLine(), event.getChannel().getName(), bot.getIRC().getServerInfo().getNetwork()); } public void onServerResponse(ServerResponseEvent event) { Logger.log(event.getLine()); } public void onTopicChange(TopicEvent event) { Logger.log("-- " + event.getSource() + " changes topic to \'" + event.getMessage() + "\'", event.getChannel().getName(), bot.getIRC().getServerInfo().getNetwork()); } public void onWhois(WhoisEvent event) { WhoisBuilder builder = event.getWhoisBuilder(); Logger.log("-- Start of /WHOIS"); Logger.log(builder.getNickname() + " is " + builder.getNickname() + "!" + builder.getLogin() + "@" + builder.getHostname()); Logger.log(builder.getNickname() + "'s real name is " + builder.getRealname()); Logger.log(builder.getNickname() + "'s channels: " + StringUtils.join(builder.getChannels(), ", ")); Logger.log(builder.getNickname() + "'s server is " + builder.getServer() + " - " + builder.getServerInfo()); if(builder.getOperPrivs() != null) { Logger.log(builder.getNickname() + " " + builder.getOperPrivs()); } Logger.log(builder.getNickname() + "'s idle time is " + builder.getIdleSeconds() + " seconds"); if(builder.getSignOnTime() != -1) { Logger.log(builder.getNickname() + "'s sign on time is " + new Date(builder.getSignOnTime() * 1000)); } Logger.log("-- End of /WHOIS"); } }
package gov.nih.nci.nautilus.query; import gov.nih.nci.nautilus.view.Viewable; /** * @author SahniH * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public interface Queriable { public Viewable getAssociatedView(); public void setAssociatedView(Viewable view); public String toString(); }
package net.sf.samtools; import net.sf.samtools.util.BlockCompressedFilePointerUtil; import java.io.File; import java.io.IOException; import java.util.List; /** * Metadata about the bam index contained within the bam index. * One instance created per index file. */ public class BAMIndexMetaData { // information for the entire index. // stored at the end of the index private long noCoordinateRecords = 0; // information for each reference. // stored in two chunks in bin # MAX_BINS private long firstOffset = -1; private long lastOffset = 0; private int alignedRecords = 0; private int unAlignedRecords = 0; // unmapped, but associated with this reference /** * Constructor used when writing an index * construct one instance for each index generated */ BAMIndexMetaData() { noCoordinateRecords = 0; newReference(); } /** * Constructor used when reading an index * construct one instance for each index generated */ BAMIndexMetaData(List<Chunk> chunkList) { noCoordinateRecords = 0; if (chunkList == null || chunkList.size() == 0) { // System.out.println("No metadata chunks"); } else if (chunkList.size() != 2) { throw new SAMException("Unexpected number of metadata chunks " + (chunkList.size())); } // fill in the first/lastOffset un/alignedRecords from this boolean firstChunk = true; if (chunkList != null) { for (Chunk c : chunkList) { long start = c.getChunkStart(); long end = c.getChunkEnd(); if (firstChunk) { firstOffset = start; lastOffset = end; firstChunk = false; } else { firstChunk = true; alignedRecords = (int) start; unAlignedRecords = (int) end; } } } } /** * Call for each new reference sequence encountered */ void newReference() { firstOffset = -1; lastOffset = 0; alignedRecords = 0; unAlignedRecords = 0; } /** * Extract relevant metaData from the record and its filePointer * Call only once per record in the file being indexed * * @param rec */ void recordMetaData(final SAMRecord rec) { final int alignmentStart = rec.getAlignmentStart(); if (alignmentStart == SAMRecord.NO_ALIGNMENT_START) { incrementNoCoordinateRecordCount(); return; } if (rec.getFileSource() == null){ throw new SAMException("BAM cannot be indexed without setting a fileSource for record " + rec); } final Chunk newChunk = ((BAMFileSpan) rec.getFileSource().getFilePointer()).getSingleChunk(); final long start = newChunk.getChunkStart(); final long end = newChunk.getChunkEnd(); if (rec.getReadUnmappedFlag()) { unAlignedRecords++; } else { alignedRecords++; } if (BlockCompressedFilePointerUtil.compare(start, firstOffset) < 1 || firstOffset == -1) { this.firstOffset = start; } if (BlockCompressedFilePointerUtil.compare(lastOffset, end) < 1) { this.lastOffset = end; } } /** * Call whenever a reference with no coordinate information is encountered in the bam file */ void incrementNoCoordinateRecordCount() { noCoordinateRecords++; } /** * Call whenever a reference with no coordinate information is encountered in the bam file */ void setNoCoordinateRecordCount(long count) { noCoordinateRecords = count; } /** * @return the count of records with no coordinate information in the bam file */ long getNoCoordinateRecordCount() { return noCoordinateRecords; } /** * @return the first virtual file offset used by this reference */ long getFirstOffset() { return firstOffset; } /** * @return the last virtual file offset used by this reference */ long getLastOffset() { return lastOffset; } /** * @return the count of unaligned records associated with this reference */ int getUnalignedRecordCount() { return unAlignedRecords; } /** * @return the count of aligned records associated with this reference */ int getAlignedRecordCount() { return alignedRecords; } /** * Prints meta-data statistics from BAM index (.bai) file * Statistics include count of aligned and unaligned reads for each reference sequence * and a count of all records with no start coordinate */ static public void printIndexStats(final File inputBamFile) { try { final BAMFileReader bam = new BAMFileReader(inputBamFile, null, false, SAMFileReader.ValidationStringency.SILENT); if (!bam.hasIndex()) { throw new SAMException("No index for bam file " + inputBamFile); } BAMIndexMetaData[] data = getIndexStats(bam); // read through all the bins of every reference. int nRefs = bam.getFileHeader().getSequenceDictionary().size(); for (int i = 0; i < nRefs; i++) { final SAMSequenceRecord seq = bam.getFileHeader().getSequence(i); if (seq == null) continue; final String sequenceName = seq.getSequenceName(); final int sequenceLength = seq.getSequenceLength(); System.out.print(sequenceName + ' ' + "length=\t" + sequenceLength); if (data[i] == null) { System.out.println(); continue; } System.out.println("\tAligned= " + data[i].getAlignedRecordCount() + "\tUnaligned= " + data[i].getUnalignedRecordCount()); } System.out.println("NoCoordinateCount= " + data[0].getNoCoordinateRecordCount()); } catch (IOException e) { throw new SAMException("Exception in getting index statistics", e); } } /** * Prints meta-data statistics from BAM index (.bai) file * Statistics include count of aligned and unaligned reads for each reference sequence * and a count of all records with no start coordinate */ static public BAMIndexMetaData[] getIndexStats(final BAMFileReader bam) { AbstractBAMFileIndex index = (AbstractBAMFileIndex) bam.getIndex(); // read through all the bins of every reference. int nRefs = index.getNumberOfReferences(); BAMIndexMetaData[] result = new BAMIndexMetaData[nRefs == 0 ? 1 : nRefs]; for (int i = 0; i < nRefs; i++) { BAMIndexContent content = index.query(i, 0, -1); // todo: it would be faster just to skip to the last bin result[i] = content.getMetaData(); } if (result[0] == null){ result[0] = new BAMIndexMetaData(); } result[0].setNoCoordinateRecordCount(index.getNoCoordinateCount()); return result; } }
/* NOTE TO ANY READERS: Check out "Rogue - Atlantic". It's a pretty sweet song though I must say that Flo Rida has some pretty good songs too. Either way, I'd recommend some music if you're considering reading through this hell. Honestly, I feel like even my not-so-messy code is extremely messy just because of how I work. I mean, I try to make the code readable but people always tell me that it's virtually unreadable and it doesn't help that It's difficult to explain to them what the code does without them losing interest. */ package Launcher; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.stage.StageStyle; public class Main extends Application { private double xOffset = 0, yOffset = 0; // Offsets for dragging private Button exit, min; // Define buttons private Rectangle dragBar; // Draggable top bar @Override public void start(Stage primaryStage) throws Exception{ primaryStage.initStyle(StageStyle.UNDECORATED); Parent root = FXMLLoader.load(getClass().getResource("Main_Launcher.fxml")); primaryStage.setTitle("Team-Avion Launcher [WIP]"); primaryStage.setScene(new Scene(root, 900, 500)); primaryStage.show(); // Field initialization exit = (Button) root.lookup("#exit"); min = (Button) root.lookup("#min"); dragBar = (Rectangle) root.lookup("#rectangle"); // Infrastructural navigation exit.setOnMouseClicked(event -> primaryStage.close()); min.setOnMouseClicked(event -> primaryStage.setIconified(true)); // Drag dragBar.setOnMousePressed(event -> { xOffset = event.getSceneX(); yOffset = event.getSceneY(); }); dragBar.setOnMouseDragged(event -> { primaryStage.setX(event.getScreenX() - xOffset); primaryStage.setY(event.getScreenY() - yOffset); }); } public static void main(String[] args) { launch(args); } }
package org.jboss.as.console.client.standalone.deployment; import com.google.gwt.cell.client.ImageResourceCell; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.cellview.client.TextColumn; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.LayoutPanel; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.view.client.ListDataProvider; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.core.SuspendableViewImpl; import org.jboss.as.console.client.shared.deployment.DeploymentCommand; import org.jboss.as.console.client.shared.deployment.DeploymentCommandColumn; import org.jboss.as.console.client.shared.model.DeploymentRecord; import org.jboss.as.console.client.widgets.ContentHeaderLabel; import org.jboss.as.console.client.widgets.TabHeader; import org.jboss.as.console.client.widgets.TitleBar; import org.jboss.as.console.client.widgets.icons.Icons; import org.jboss.as.console.client.widgets.tables.DefaultCellTable; import org.jboss.as.console.client.widgets.tools.ToolButton; import org.jboss.as.console.client.widgets.tools.ToolStrip; import java.util.List; /** * @author Heiko Braun * @author Stan Silvert * @date 3/14/11 */ public class DeploymentListView extends SuspendableViewImpl implements DeploymentListPresenter.MyView{ private DeploymentListPresenter presenter; private DefaultCellTable<DeploymentRecord> deploymentTable; private ListDataProvider<DeploymentRecord> deploymentProvider; @Override public void setPresenter(DeploymentListPresenter presenter) { this.presenter = presenter; } @Override public void updateDeploymentInfo(List<DeploymentRecord> deployments) { deploymentProvider.setList(deployments); } @Override public Widget createWidget() { LayoutPanel layout = new LayoutPanel(); TitleBar titleBar = new TitleBar(Console.CONSTANTS.common_label_deployments()); layout.add(titleBar); layout.setWidgetTopHeight(titleBar, 0, Style.Unit.PX, 28, Style.Unit.PX); final ToolStrip toolStrip = new ToolStrip(); toolStrip.addToolButtonRight(new ToolButton(Console.CONSTANTS.common_label_addContent(), new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.launchNewDeploymentDialoge(); } })); layout.add(toolStrip); layout.setWidgetTopHeight(toolStrip, 28, Style.Unit.PX, 30, Style.Unit.PX); VerticalPanel panel = new VerticalPanel(); panel.setStyleName("rhs-content-panel"); ContentHeaderLabel nameLabel = new ContentHeaderLabel(Console.CONSTANTS.common_label_deployments()); HorizontalPanel horzPanel = new HorizontalPanel(); horzPanel.getElement().setAttribute("style", "width:100%;"); horzPanel.add(nameLabel); panel.add(horzPanel); deploymentTable = new DefaultCellTable<DeploymentRecord>(20); deploymentProvider = new ListDataProvider<DeploymentRecord>(); deploymentProvider.addDataDisplay(deploymentTable); TextColumn<DeploymentRecord> dplNameColumn = new TextColumn<DeploymentRecord>() { @Override public String getValue(DeploymentRecord record) { return record.getName(); } }; TextColumn<DeploymentRecord> dplRuntimeColumn = new TextColumn<DeploymentRecord>() { @Override public String getValue(DeploymentRecord record) { return record.getRuntimeName(); } }; deploymentTable.addColumn(dplNameColumn, Console.CONSTANTS.common_label_name()); deploymentTable.addColumn(dplRuntimeColumn, Console.CONSTANTS.common_label_runtimeName()); deploymentTable.addColumn(makeEnabledColumn(), Console.CONSTANTS.common_label_enabled()); deploymentTable.addColumn(new DeploymentCommandColumn(this.presenter, DeploymentCommand.ENABLE_DISABLE), Console.CONSTANTS.common_label_enOrDisable()); deploymentTable.addColumn(new DeploymentCommandColumn(this.presenter, DeploymentCommand.REMOVE_FROM_STANDALONE), Console.CONSTANTS.common_label_remove()); panel.add(deploymentTable); ScrollPanel scroll = new ScrollPanel(); scroll.add(panel); layout.add(scroll); layout.setWidgetTopHeight(scroll, 55, Style.Unit.PX, 65, Style.Unit.PCT); return layout; } // Refactor Me! Copied from org.jboss.as.console.client.domain.groups.deployment.DeploymentsOverview private Column makeEnabledColumn() { return new Column<DeploymentRecord, ImageResource>(new ImageResourceCell()) { @Override public ImageResource getValue(DeploymentRecord deployment) { ImageResource res = null; if (deployment.isEnabled()) { res = Icons.INSTANCE.statusGreen_small(); } else { res = Icons.INSTANCE.statusRed_small(); } return res; } }; } }
package it.unimi.dsi.sux4j.bits; import it.unimi.dsi.bits.BitVector; import it.unimi.dsi.bits.LongArrayBitVector; import it.unimi.dsi.fastutil.longs.LongIterator; import it.unimi.dsi.util.LongBigList; /** An opportunistic select implementation for sparse arrays. * * <p>The code is based on a 64-bit reimplementation of the <code>sdarray</code> structure * described by Daisuke Okanohara and Kunihiko Sadakane in &ldquo;Practical Entropy-CompressedRank/SelectDictionary&rdquo;, In <i>Proc. of the * Workshop on Algorithm Engineering and Experiments, ALENEX 2007</i>. SIAM, 2007. * * <p>The positions of the <var>{@linkplain #m}</var> ones in a bit array of <var>{@linkplain #n}</var> bits are stored explicitly * by storing separately * the lower <var>{@linkplain #l}</var> = &lceil; log <var>{@linkplain #n}</var> / <var>{@linkplain #m} )</var> &rceil; bits * and the remaining upper bits. * The lower bits are stored in a bit array, whereas the upper bits are stored in an array * of 2<var>{@linkplain #m}</var> bits by setting, if the <var>i</var>-th one is at position * <var>p</var>, the bit of index <var>p</var> / 2<sup><var>l</var></sup> + <var>i</var>; the value can then be recovered * by selecting the <var>i</var>-th bit of the resulting dense (but small) bit array and subtracting <var>i</var> (note that this will * work because the upper bits are nondecreasing). * * <p>This implementation uses {@link SimpleSelect} to support selection inside the dense array. The resulting data structure uses * <var>m</var> &lceil; log(<var>n</var>/<var>m</var>) &rceil; + 2.25 <var>m</var> bits, and <em>does not store the original bit vector</em>. * * <p>Note that some data is shared with {@link SparseRank}: correspondingly, a suitable {@linkplain #SparseSelect(SparseRank) constructor} * makes it possible to build an instance using an underlying {@link SparseRank} instance. */ public class SparseSelect implements Select { private static final long serialVersionUID = 2L; /** The length of the underlying bit array. */ protected final long n; /** The number of ones in the underlying bit array. */ protected final long m; /** The number of lower bits. */ protected final int l; /** The list of lower bits of the position of each one, stored explicitly. */ protected final LongBigList lowerBits; /** The select structure used to extract the upper bits. */ protected final SimpleSelect selectUpper; /** Creates a new <code>sdarray</code> select structure using a long array. * * <p>The resulting structure keeps no reference to the original array. * * @param bits a long array containing the bits. * @param length the number of valid bits in <code>bits</code>. */ public SparseSelect( final long[] bits, final long length ) { this( LongArrayBitVector.wrap( bits, length ) ); } /** Creates a new <code>sdarray</code> select structure using a bit vector. * * <p>The resulting structure keeps no reference to the original bit vector. * * @param bitVector the input bit vector. */ public SparseSelect( final BitVector bitVector ) { this( bitVector.length(), bitVector.count(), bitVector.asLongSet().iterator() ); } /** Creates a new <code>sdarray</code> select structure using an {@linkplain LongIterator iterator}. * * <p>This constructor is particularly useful if the positions of the ones are provided by * some sequential source. * * @param n the number of bits in the underlying bit vector. * @param m the number of ones in the underlying bit vector. * @param iterator an iterator returning the positions of the ones in the underlying bit vector in increasing order. */ public SparseSelect( final long n, long m, final LongIterator iterator ) { long pos = -1; this.m = m; this.n = n; int l = 0; if ( m > 0 ) { while( m < n ) { m *= 2; l++; } } this.l = l; final long lowerBitsMask = ( 1L << l ) - 1; lowerBits = LongArrayBitVector.getInstance().asLongBigList( l ).length( this.m ); final BitVector upperBits = LongArrayBitVector.getInstance().length( this.m * 2 ); long last = 0; for( long i = 0; i < this.m; i++ ) { pos = iterator.nextLong(); if ( pos >= n ) throw new IllegalArgumentException( "Position too large for " + n + " bits: " + pos ); if ( pos < last ) throw new IllegalArgumentException( "Positions are not nondecreasing: " + pos + " < " + last ); if ( l != 0 ) lowerBits.set( i, pos & lowerBitsMask ); upperBits.set( ( pos >> l ) + i ); last = pos; } if ( iterator.hasNext() ) throw new IllegalArgumentException( "There are more than " + this.m + " positions in the provided iterator" ); selectUpper = new SimpleSelect( upperBits ); } /** Creates a new <code>sdarray</code> select structure using a {@link SparseRank}. * * @param sparseRank a sparse rank structure. */ public SparseSelect( final SparseRank sparseRank ) { n = sparseRank.n; m = sparseRank.m; l = sparseRank.l; lowerBits = sparseRank.lowerBits; selectUpper = new SimpleSelect( sparseRank.upperBits ); } public long numBits() { return selectUpper.numBits() + selectUpper.bitVector().length() + lowerBits.length() * l; } public long select( final long rank ) { if ( rank >= m ) return -1; return ( selectUpper.select( rank ) - rank ) << l | lowerBits.getLong( rank ); } /** Returns the bit vector indexed; since the bits are not stored in this data structure, * a copy is built on purpose and returned. * * @return a copy of the underlying bit vector. */ public BitVector bitVector() { final LongArrayBitVector result = LongArrayBitVector.getInstance( n ).length( n ); for( long i = m; i-- != 0; ) result.set( select( i ) ); return result; } }
package ibis.satin; /** Constants for the configuration of Satin. */ public interface Config { /* Enable or disable statistics. */ static final boolean SPAWN_STATS = true; static final boolean STEAL_STATS = true; static final boolean ABORT_STATS = true; static final boolean TUPLE_STATS = true; /* Enable or disable timings */ static final boolean STEAL_TIMING = true; static final boolean ABORT_TIMING = true; static final boolean IDLE_TIMING = false; static final boolean POLL_TIMING = false; static final boolean TUPLE_TIMING = true; /* The poll frequency in nanoseconds. A frequency of 0 means do not poll. */ // static final long POLL_FREQ = 100*1000000L; static final long POLL_FREQ = 0; /* poll Ibis, or poll the satin receiveport */ static final boolean POLL_RECEIVEPORT = false; /* Enable or disable asserts. */ static final boolean ASSERTS = false; /* Enable or disable aborts and inlets. */ static final boolean ABORTS = true; /* Enable or disable an optimization for aborts. */ static final boolean HANDLE_ABORTS_IN_LATENCY = false; /* Support the combination of upcalls and polling */ static final boolean SUPPORT_UPCALL_POLLING = false; /* Use multicast to update the tuple space */ static final boolean SUPPORT_TUPLE_MULTICAST = true; /* Enable or disable debug prints. */ static final boolean COMM_DEBUG = false; static final boolean STEAL_DEBUG = false; static final boolean SPAWN_DEBUG = false; static final boolean INLET_DEBUG = false; static final boolean ABORT_DEBUG = false; static final boolean TUPLE_DEBUG = false; }
package com.threerings.gwt.ui; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.Widget; /** * Displays a popup informational message. */ public class InfoPopup extends PopupPanel { /** * Computes a reasonable delay after which it should be safe to automatically clear a transient * informational message. */ public static int computeAutoClearDelay (String message) { return Math.max(MIN_AUTO_CLEAR_DELAY, message.length() * PER_CHAR_CLEAR_DELAY); } /** * Creates an info popup with the supplied message. It will automatically dismiss itself after * a time proportional to the length of the message has elapsed. */ public InfoPopup (String message) { this(new Label(message)); _autoClearTimeout = computeAutoClearDelay(message); } /** * Creates an info popup with the supplied contents. */ public InfoPopup (Widget contents) { super(true); setStyleName("infoPopup"); setWidget(contents); } /** * Converts this info popup into an error popup (via a CSS style change) and returns self. */ public InfoPopup toError () { setStyleName("errorPopup"); return this; } /** * Displays this info popup directly below the specified widget. */ public void showNear (Widget parent) { setPopupPosition(parent.getAbsoluteLeft(), parent.getAbsoluteTop() + parent.getOffsetHeight() + NEAR_GAP); show(); } /** * Displays this info popup in the center of the page. */ public void showCentered () { center(); // this will show us } protected void onAttach () { super.onAttach(); new Timer() { public void run () { hide(); } }.schedule(_autoClearTimeout); } // we use an int here because that's what Timer wants; whee! protected int _autoClearTimeout = DEFAULT_AUTO_CLEAR_DELAY; protected static final int MIN_AUTO_CLEAR_DELAY = 3000; protected static final int DEFAULT_AUTO_CLEAR_DELAY = 5000; protected static final int PER_CHAR_CLEAR_DELAY = 50; protected static final int NEAR_GAP = 5; }
import java.util.*; import java.util.regex.*; public class MIPSGenerator{ private List<Quad> mipsCode; private final MIPSRegisterBank rb; private TigerScope scope; private final String dataSegment = ".data\n"; private final String textSegment = ".text\n"; private final String mainSegment = ".globl main\nmain:\n"; private final String exitProgram = "li $v0, 10\nsyscall\n"; private Map<String, String> tempRegMap; public MIPSGenerator(TigerScope scope){ this.mipsCode = new ArrayList<Quad>(); this.rb = MIPSRegisterBank.getMIPSRegisterBank(); this.scope = scope; this.tempRegMap = new HashMap<String, String>(); } private String naiveRegAllocation(Map<Quad, Boolean> ir){ String res = ""; for(Map.Entry<Quad, Boolean> entry: ir.entrySet()){ if(!entry.getValue()){ if(entry.getKey().getOp().equals("assign")){ Operand op1 = new Operand(entry.getKey().getAddr1()); Operand op2 = new Operand(entry.getKey().getAddr2()); /*Load the value*/ res += naiveLoad(op1); /*if RHS is *not* a value then we need to load it*/ if(!isNumeric(op2.getName())){ res += naiveLoad(op2); } /* Assign the value * Either assign a numeric value addi $d, $zero, 2 * Or copy between two registers addi $d, $s, 0 */ res += "addi " + op1.getValReg() + ", "; if(isNumeric(op2.getName())){ res += "$zero " + ", " + op2.getName(); } else{ res += op2.getValReg() + ", " + "0"; } res += "\n"; /*Store the value to the memory location*/ res += naiveStore(op1); /*Free the regs to make them resuable*/ freeRegs(op1); freeRegs(op2); } else if(isArithmeticOp(entry.getKey().getOp())){ Operand op1 = new Operand(entry.getKey().getAddr1()); Operand op2 = new Operand(entry.getKey().getAddr2()); Operand op3 = new Operand(entry.getKey().getAddr3()); /*Load */ res += naiveLoad(op1); res += naiveLoad(op2); res += naiveLoad(op3); String inst = entry.getKey().getOp(); if(inst.equals("mult")){ inst = "mul"; } res += inst + " " + op3.getValReg() + ", " + op1.getValReg() + ", " + op2.getValReg() + "\n"; res += naiveStore(op3); /*Free Regs*/ freeRegs(op1); freeRegs(op2); freeRegs(op3); } else if(entry.getKey().getOp().equals("call")){ if(entry.getKey().getAddr1().equals("printi")){ res += "li $v0 1\n"; res += "lw $a0 " + entry.getKey().getParam() + "\n"; res += "syscall" + "\n"; res += "li $v0 4\n"; res += "la $a0 newline\n"; res += "syscall" + "\n"; } } else if(isLabel(entry.getKey().getOp())){ res += entry.getKey().getOp() + "\n"; } else if(entry.getKey().getOp().equals("goto")){ res += "j " + entry.getKey().getAddr1() + "\n"; } else if(isRelationalOp(entry.getKey().getOp())){ Operand op1 = new Operand(entry.getKey().getAddr1()); Operand op2 = new Operand(entry.getKey().getAddr2()); res += naiveLoad(op1); res += naiveLoad(op2); String inst = entry.getKey().getOp(); if(inst.equals("breq")){ inst = "beq"; } else if(inst.equals("brneq")){ inst = "bne"; } res += inst + " " + op1.getValReg() + ", " + op2.getValReg() + ", " + entry.getKey().getAddr3() + "\n"; /*Free*/ freeRegs(op1); freeRegs(op2); } } } return res; } private boolean isArithmeticOp(String op){ return op.equals("add") || op.equals("sub") || op.equals("mult") || op.equals("div") || op.equals("and") || op.equals("or"); } private boolean isRelationalOp(String op){ return op.equals("breq") || op.equals("brneq") || op.equals("brlt") || op.equals("brgt") || op.equals("brgeq") || op.equals("brleq"); } private boolean isLabel(String op){ return op.matches("L\\d*:"); } public static boolean isNumeric(String str){ return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal. } private String naiveLoad(Operand o){ if(isNumeric(o.getName())){ String valReg = this.rb.regBank.get("TEMPS").getReg(); String res = ""; res += "li " + valReg + ", " + o.getName() + "\n"; o.setValReg(valReg); return res; } if(isTemp(o.getName())){ int offset = getTempNum(o.getName()); String res = ""; String addReg = this.rb.regBank.get("TEMPS").getReg(); String valueReg = this.rb.regBank.get("TEMPS").getReg(); res += "la " + addReg + ", itemp\n"; res += "lw " + valueReg + ", " + Integer.toString(offset) + "(" + addReg + ")\n"; o.setAddReg(addReg); o.setValReg(valueReg); return res; } else{ String loadMips = ""; String addReg = this.rb.regBank.get("TEMPS").getReg(); String valueReg = this.rb.regBank.get("TEMPS").getReg(); loadMips += "la " + addReg + ", " + o.getName() + "\n"; loadMips += "lw " + valueReg + ", " + "0(" + addReg + ")\n"; o.setAddReg(addReg); o.setValReg(valueReg); return loadMips; } } private int getTempNum(String temp){ String tnum = temp.substring(1); Integer i = Integer.parseInt(tnum); return i * 4; } private void freeRegs(Operand o){ this.rb.regBank.get("TEMPS").freeReg(o.getValReg()); if(!isNumeric(o.getName())) this.rb.regBank.get("TEMPS").freeReg(o.getAddReg()); } private String naiveStore(Operand o){ String storeMips = ""; int offset = 0; if(isTemp(o.getName())){ offset = getTempNum(o.getName()); } storeMips += "sw " + o.getValReg() + ", "+ offset +"(" + o.getAddReg() + ")\n"; return storeMips; } public String genDataSection(Map<Quad, Boolean> ir){ Set<String> variables = new HashSet<String>(); String dataSection = ".data\n"; for(Map.Entry<Quad, Boolean> entry: ir.entrySet()){ if(entry.getKey().getOp().equals("assign") && !isTemp(entry.getKey().getAddr1())){ variables.add(entry.getKey().getAddr1()); } } for(Map.Entry<Quad, Boolean> entry: ir.entrySet()){ if(entry.getKey().getOp().equals("assign")){ if(variables.contains(entry.getKey().getAddr1())){ dataSection += entry.getKey().getAddr1() + ":\t" + ".word\t" + entry.getKey().getAddr2() + "\n"; variables.remove(entry.getKey().getAddr1()); ir.put(entry.getKey(), true); } } } return dataSection; } private String addTempData(){ return "itemp: .word 1000\n"; } private String addNewline(){ return "newline: .asciiz \"\\n\"\n"; } private boolean isTemp(String var){ Pattern p = Pattern.compile("t\\d*"); Matcher m = p.matcher(var); return m.matches(); } public String getMIPSCode(List<Quad> ir){ /*All instructions not/"false" processed*/ Map<Quad, Boolean> irCode = new LinkedHashMap<Quad, Boolean>(); for(Quad q: ir){ irCode.put(q, false); } String mipsCode = ""; mipsCode += genDataSection(irCode); mipsCode += addTempData(); mipsCode += addNewline(); mipsCode += textSegment; mipsCode += mainSegment; mipsCode += naiveRegAllocation(irCode); mipsCode += exitProgram; return mipsCode; } }
package org.apache.lenya.cms.ac; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.configuration.DefaultConfiguration; import org.apache.log4j.Category; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Hashtable; import java.util.Properties; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttributes; import javax.naming.ldap.InitialLdapContext; import javax.naming.ldap.LdapContext; /** * @author egli * * */ public class LDAPUser extends FileUser { private static Properties defaultProperties = null; private static Category log = Category.getInstance(LDAPUser.class); public static final String LDAP_ID = "ldapid"; private static String PROVIDER_URL = "provider-url"; private static String MGR_DN = "mgr-dn"; private static String MGR_PW = "mgr-pw"; private static String PARTIAL_USER_DN = "partial-user-dn"; private static String KEY_STORE = "key-store"; private static String SECURITY_PROTOCOL = "security-protocol"; private static String SECURITY_AUTHENTICATION = "security-authentication"; private String ldapId; private String ldapName; /** * Creates a new LDAPUser object. */ public LDAPUser() { } /** * Creates a new LDAPUser object. * @param configurationDirectory The configuration directory. */ public LDAPUser(File configurationDirectory) { setConfigurationDirectory(configurationDirectory); } /** * Create an LDAPUser * * @param configurationDirectory * where the user will be attached to * @param id * user id of LDAPUser * @param email * of LDAPUser * @param ldapId * of LDAPUser * @throws ConfigurationException * if the properties could not be read */ public LDAPUser(File configurationDirectory, String id, String email, String ldapId) throws ConfigurationException { super(configurationDirectory, id, null, email, null); this.ldapId = ldapId; initialize(); } /** * Create a new LDAPUser from a configuration * * @param config * the <code>Configuration</code> specifying the user details * @throws ConfigurationException * if the user could not be instantiated */ public void configure(Configuration config) throws ConfigurationException { super.configure(config); ldapId = config.getChild(LDAP_ID).getValue(); initialize(); } /** * Checks if a user exists. * @param ldapId The LDAP id. * @return A boolean value. * @throws AccessControlException when an error occurs. * FIXME: This method does not work. */ public boolean existsUser(String ldapId) throws AccessControlException { boolean exists = false; LdapContext context = null; try { readProperties(); context = bind(defaultProperties.getProperty(MGR_DN), defaultProperties.getProperty(MGR_PW)); String peopleName = "ou=People"; Attributes attributes = new BasicAttributes("uid", ldapId); NamingEnumeration enumeration = context.search(peopleName, attributes); exists = enumeration.hasMoreElements(); } catch (Exception e) { throw new AccessControlException("Exception during search: ", e); } finally { try { if (context != null) { close(context); } } catch (NamingException e) { throw new AccessControlException("Closing context failed: ", e); } } return exists; } /** * Initializes this user. * * @throws ConfigurationException * when something went wrong. */ protected void initialize() throws ConfigurationException { LdapContext context = null; try { readProperties(); String name = null; context = bind(defaultProperties.getProperty(MGR_DN), defaultProperties.getProperty(MGR_PW)); String[] attrs = new String[1]; attrs[0] = "gecos"; /* users full name */ String searchString = "uid=" + ldapId + ",ou=People"; Attributes answer = context.getAttributes(searchString, attrs); if (answer != null) { Attribute attr = answer.get("gecos"); if (attr != null) { for (NamingEnumeration enum = attr.getAll(); enum.hasMore(); enum.next()) { name = (String) attr.get(); } } } this.ldapName = name; } catch (Exception e) { throw new ConfigurationException("Could not read properties", e); } finally { try { if (context != null) { close(context); } } catch (NamingException e) { throw new ConfigurationException("Closing context failed: ", e); } } } /** * (non-Javadoc) * * @see org.apache.lenya.cms.ac.FileUser#createConfiguration() */ protected Configuration createConfiguration() { DefaultConfiguration config = (DefaultConfiguration) super.createConfiguration(); // add ldap_id node DefaultConfiguration child = new DefaultConfiguration(LDAP_ID); child.setValue(ldapId); config.addChild(child); return config; } /** * Get the ldap id * * @return the ldap id */ public String getLdapId() { return ldapId; } /** * Set the ldap id * * @param string * the new ldap id */ public void setLdapId(String string) { ldapId = string; } /** * (non-Javadoc) * * @see org.apache.lenya.cms.ac.User#authenticate(java.lang.String) */ public boolean authenticate(String password) { String principal = "uid=" + getLdapId() + "," + defaultProperties.getProperty(PARTIAL_USER_DN); Context ctx; log.debug("Authenticating with principal [" + principal + "]"); try { ctx = bind(principal, password); close(ctx); log.debug("Context closed."); } catch (NamingException e) { // log this failure // StringWriter writer = new StringWriter(); // e.printStackTrace(new PrintWriter(writer)); log.info("Bind for user " + principal + " to Ldap server failed: ", e); } return true; } /** * @see org.apache.lenya.cms.ac.Item#getName() */ public String getName() { return ldapName; } /** * LDAP Users fetch their name information from the LDAP server, so we don't store it locally. * Since we only have read access we basically can't set the name, i.e. any request to change * the name is ignored. * * @param string * is ignored */ public void setName(String string) { // we do not have write access to LDAP, so we ignore // change request to the name. } /** * The LDAPUser doesn't store any passwords as they are handled by LDAP * * @param plainTextPassword * is ignored */ public void setPassword(String plainTextPassword) { setEncryptedPassword(null); } /** * The LDAPUser doesn't store any passwords as they are handled by LDAP * * @param encryptedPassword * is ignored */ protected void setEncryptedPassword(String encryptedPassword) { encryptedPassword = null; } /** * Connect to the LDAP server * * @param principal * the principal string for the LDAP connection * @param credentials * the credentials for the LDAP connection * @return a <code>LdapContext</code> * @throws NamingException * if there are problems establishing the Ldap connection */ private LdapContext bind(String principal, String credentials) throws NamingException { log.info("Binding principal: [" + principal + "]"); Hashtable env = new Hashtable(); System.setProperty( "javax.net.ssl.trustStore", getConfigurationDirectory().getAbsolutePath() + File.separator + defaultProperties.getProperty(KEY_STORE)); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, defaultProperties.getProperty(PROVIDER_URL)); env.put(Context.SECURITY_PROTOCOL, defaultProperties.getProperty(SECURITY_PROTOCOL)); env.put( Context.SECURITY_AUTHENTICATION, defaultProperties.getProperty(SECURITY_AUTHENTICATION)); env.put(Context.SECURITY_PRINCIPAL, principal); env.put(Context.SECURITY_CREDENTIALS, credentials); LdapContext ctx = new InitialLdapContext(env, null); log.info("Finished binding principal."); return ctx; } /** * Close the connection to the LDAP server * * @param ctx * the context that was returned from the bind * @throws NamingException * if there is a problem communicating to the LDAP server */ private void close(Context ctx) throws NamingException { ctx.close(); } /** * Read the properties * * @throws IOException * if the properties cannot be found. */ private void readProperties() throws IOException { // create and load default properties File propertiesFile = new File(getConfigurationDirectory(), "ldap.properties"); if (defaultProperties == null) { defaultProperties = new Properties(); FileInputStream in; in = new FileInputStream(propertiesFile); defaultProperties.load(in); in.close(); } } }
package nl.mpi.arbil; import nl.mpi.arbil.data.ImdiTreeObject; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.MouseEvent; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import javax.swing.JComponent; import javax.swing.JToolTip; import javax.swing.JTree; import javax.swing.ToolTipManager; import javax.swing.TransferHandler; import javax.swing.table.TableCellEditor; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.ExpandVetoException; import javax.swing.tree.TreePath; public class ImdiTree extends JTree { JListToolTip listToolTip = new JListToolTip(); public ImdiTree() { this.addMouseListener(new java.awt.event.MouseAdapter() { // public void mouseClicked(java.awt.event.MouseEvent evt) { // treeMouseClick(evt); @Override public void mousePressed(java.awt.event.MouseEvent evt) { treeMousePressedReleased(evt); } @Override public void mouseReleased(java.awt.event.MouseEvent evt) { treeMousePressedReleased(evt); } }); this.addKeyListener(new java.awt.event.KeyAdapter() { // TODO: this is failing to get the menu key event // @Override // public void keyReleased(KeyEvent evt) { // treeKeyTyped(evt); @Override public void keyTyped(java.awt.event.KeyEvent evt) { treeKeyTyped(evt); }// @Override // public void keyPressed(java.awt.event.KeyEvent evt) { // treeKeyTyped(evt); }); this.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { @Override public void mouseDragged(java.awt.event.MouseEvent evt) { if (evt.getModifiers() == 0 && evt.getButton() == MouseEvent.BUTTON1) { System.out.println("jTree1MouseDragged"); JComponent c = (JComponent) evt.getSource(); TransferHandler th = c.getTransferHandler(); th.exportAsDrag(c, evt, TransferHandler.COPY); } } }); this.addTreeExpansionListener(new javax.swing.event.TreeExpansionListener() { public void treeExpanded(javax.swing.event.TreeExpansionEvent evt) { DefaultMutableTreeNode parentNode = null; if (evt.getPath() == null) { //There is no selection. } else { parentNode = (DefaultMutableTreeNode) (evt.getPath().getLastPathComponent()); // load imdi data if not already loaded ImdiTree.this.requestResort(); // TreeHelper.getSingleInstance().addToSortQueue(parentNode); } } public void treeCollapsed(javax.swing.event.TreeExpansionEvent evt) { } }); this.addTreeWillExpandListener(new javax.swing.event.TreeWillExpandListener() { public void treeWillCollapse(javax.swing.event.TreeExpansionEvent evt) throws javax.swing.tree.ExpandVetoException { if (evt.getPath().getPathCount() == 1) { System.out.println("root node cannot be collapsed"); throw new ExpandVetoException(evt, "root node cannot be collapsed"); } } public void treeWillExpand(javax.swing.event.TreeExpansionEvent evt) throws javax.swing.tree.ExpandVetoException { // DefaultMutableTreeNode parentNode = null; // if (evt.getPath() == null) { // //There is no selection. // } else { // parentNode = (DefaultMutableTreeNode) (evt.getPath().getLastPathComponent()); // // load imdi data if not already loaded // TreeHelper.getSingleInstance().addToSortQueue(parentNode); } }); this.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() { public void valueChanged(javax.swing.event.TreeSelectionEvent evt) { if (PreviewSplitPanel.previewTableShown && PreviewSplitPanel.previewTable != null) { TableCellEditor currentCellEditor = PreviewSplitPanel.previewTable.getCellEditor(); // stop any editing so the changes get stored if (currentCellEditor != null) { currentCellEditor.stopCellEditing(); } ((ImdiTableModel) PreviewSplitPanel.previewTable.getModel()).removeAllImdiRows(); ((ImdiTableModel) PreviewSplitPanel.previewTable.getModel()).addSingleImdiObject(((ImdiTree) evt.getSource()).getLeadSelectionNode()); } } }); // enable tool tips. ToolTipManager.sharedInstance().registerComponent(this); // enable the tree icons this.setCellRenderer(new ImdiTreeRenderer()); // enable drag and drop ArbilDragDrop.getSingleInstance().addDrag(this); } private void treeMousePressedReleased(java.awt.event.MouseEvent evt) { // TODO add your handling code here: // test if click was over a selected node javax.swing.tree.TreePath clickedNodePath = ((javax.swing.JTree) evt.getSource()).getPathForLocation(evt.getX(), evt.getY()); int clickedNodeInt = ((javax.swing.JTree) evt.getSource()).getClosestRowForLocation(evt.getX(), evt.getY()); int leadSelectedInt = ((javax.swing.JTree) evt.getSource()).getLeadSelectionRow(); boolean clickedPathIsSelected = (((javax.swing.JTree) evt.getSource()).isPathSelected(clickedNodePath)); if (evt.isPopupTrigger() /* evt.getButton() == MouseEvent.BUTTON3 || evt.isMetaDown()*/) { // this is simplified and made to match the same type of actions as the imditable if (!evt.isShiftDown() && !evt.isControlDown() && !clickedPathIsSelected) { ((javax.swing.JTree) evt.getSource()).clearSelection(); ((javax.swing.JTree) evt.getSource()).addSelectionPath(clickedNodePath); } } // if (evt.isPopupTrigger() ) { if (evt.isPopupTrigger() /* evt.getButton() == MouseEvent.BUTTON3 || evt.isMetaDown()*/) {
package hu.qgears.review.eclipse.ui.actions; import hu.qgears.review.eclipse.ui.util.UtilLog; import hu.qgears.review.eclipse.ui.util.UtilWorkspace; import hu.qgears.review.eclipse.ui.views.model.ReviewSourceSetView; import hu.qgears.review.eclipse.ui.views.model.SourceTreeElement; import hu.qgears.review.model.ReviewSource; import java.io.File; import org.eclipse.core.resources.IFile; import org.eclipse.jdt.ui.ISharedImages; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorDescriptor; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.FileEditorInput; /** * Action that opens a {@link ReviewSource source file} with default editor. * * @author agostoni * */ public class OpenJavaTypeAction extends Action{ private Viewer viewer; private Shell shell; private static final String DEFAULT_TEXT_EDITOR_ID = "org.eclipse.ui.DefaultTextEditor"; public OpenJavaTypeAction(Viewer viewer) { super(); this.viewer = viewer; this.shell = viewer.getControl().getShell(); setText("Open type"); setImageDescriptor(JavaUI.getSharedImages().getImageDescriptor(ISharedImages.IMG_OBJS_CFILE)); } private void openTypeSearchDialog() { ISelection s = viewer.getSelection(); if (s != null && !s.isEmpty() && s instanceof StructuredSelection){ Object e = ((StructuredSelection) s).getFirstElement(); if (e instanceof SourceTreeElement){ SourceTreeElement ste = (SourceTreeElement) e; File file = ste.getModelElement().getFileInWorkingCopy(); try { IFile wsFile = UtilWorkspace.getFileInWorkspace(file); if (wsFile != null && wsFile.exists()){ IEditorDescriptor ed = PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(wsFile.getName()); if (ed == null){ ed = PlatformUI.getWorkbench().getEditorRegistry().findEditor(DEFAULT_TEXT_EDITOR_ID); } if (ed == null) { UtilLog.showErrorDialog("No editor found for opening "+wsFile.getName(),null); } else { PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().openEditor(new FileEditorInput(wsFile), ed.getId()); } } else { openAutoImportQuestionDialog(file,ste); } } catch (Exception e1) { UtilLog.showErrorDialog("Error during file open: "+file.getAbsolutePath(), e1); } } } } private void openAutoImportQuestionDialog(File file, SourceTreeElement ste) { ReviewSourceSetView sourceset = ste.getParent(); String rset = sourceset.getModelElement().id; boolean doIt = MessageDialog.openQuestion(shell, "Open review source", "The file "+file+" is currently not imported into workspace.\nDo you wan't to import projects of source set '"+rset+"' now?"); if (doIt) { new ImportProjectForSourcesetAction(sourceset, viewer).run(); } } @Override public void run() { openTypeSearchDialog(); } }
package net.sf.picard.sam; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import net.sf.picard.cmdline.CommandLineProgram; import net.sf.picard.cmdline.Option; import net.sf.picard.cmdline.Usage; import net.sf.picard.cmdline.StandardOptionDefinitions; import net.sf.picard.io.IoUtil; import net.sf.picard.util.Log; import net.sf.picard.PicardException; import net.sf.samtools.*; /** * Reads a SAM or BAM file and combines the output to one file * * @author Tim Fennell */ public class MergeSamFiles extends CommandLineProgram { private static final Log log = Log.getInstance(MergeSamFiles.class); // Usage and parameters @Usage public String USAGE = "Merges multiple SAM/BAM files into one file.\n"; @Option(shortName="I", doc="SAM or BAM input file", minElements=1) public List<File> INPUT = new ArrayList<File>(); @Option(shortName="O", doc="SAM or BAM file to write merged result to") public File OUTPUT; @Option(shortName=StandardOptionDefinitions.SORT_ORDER_SHORT_NAME, doc="Sort order of output file", optional=true) public SAMFileHeader.SortOrder SORT_ORDER = SAMFileHeader.SortOrder.coordinate; @Option(doc="If true, assume that the input files are in the same sort order as the requested output sort order, even if their headers say otherwise.", shortName = StandardOptionDefinitions.ASSUME_SORTED_SHORT_NAME) public boolean ASSUME_SORTED = false; @Option(shortName="MSD", doc="Merge the seqeunce dictionaries", optional=true) public boolean MERGE_SEQUENCE_DICTIONARIES = false; @Option(doc="Option to enable a simple two-thread producer consumer version of the merge algorithm that " + "uses one thread to read and merge the records from the input files and another thread to encode, " + "compress and write to disk the output file. The threaded version uses about 20% more CPU and decreases " + "runtime by ~20% when writing out a compressed BAM file.") public boolean USE_THREADING = false; @Option(doc="Comment(s) to include in the merged output file's header.", optional=true, shortName="CO") public List<String> COMMENT = new ArrayList<String>(); private static final int PROGRESS_INTERVAL = 1000000; /** Required main method implementation. */ public static void main(final String[] argv) { System.exit(new MergeSamFiles().instanceMain(argv)); } /** Combines multiple SAM/BAM files into one. */ @Override protected int doWork() { boolean matchedSortOrders = true; // Open the files for reading and writing final List<SAMFileReader> readers = new ArrayList<SAMFileReader>(); final List<SAMFileHeader> headers = new ArrayList<SAMFileHeader>(); { SAMSequenceDictionary dict = null; // Used to try and reduce redundant SDs in memory for (final File inFile : INPUT) { IoUtil.assertFileIsReadable(inFile); final SAMFileReader in = new SAMFileReader(inFile); readers.add(in); headers.add(in.getFileHeader()); // A slightly hackish attempt to keep memory consumption down when merging multiple files with // large sequence dictionaries (10,000s of sequences). If the dictionaries are identical, then // replace the duplicate copies with a single dictionary to reduce the memory footprint. if (dict == null) { dict = in.getFileHeader().getSequenceDictionary(); } else if (dict.equals(in.getFileHeader().getSequenceDictionary())) { in.getFileHeader().setSequenceDictionary(dict); } matchedSortOrders = matchedSortOrders && in.getFileHeader().getSortOrder() == SORT_ORDER; } } // If all the input sort orders match the output sort order then just merge them and // write on the fly, otherwise setup to merge and sort before writing out the final file IoUtil.assertFileIsWritable(OUTPUT); final boolean presorted; final SAMFileHeader.SortOrder headerMergerSortOrder; final boolean mergingSamRecordIteratorAssumeSorted; if (matchedSortOrders || SORT_ORDER == SAMFileHeader.SortOrder.unsorted || ASSUME_SORTED) { log.info("Input files are in same order as output so sorting to temp directory is not needed."); headerMergerSortOrder = SORT_ORDER; mergingSamRecordIteratorAssumeSorted = ASSUME_SORTED; presorted = true; } else { log.info("Sorting input files using temp directory " + TMP_DIR); headerMergerSortOrder = SAMFileHeader.SortOrder.unsorted; mergingSamRecordIteratorAssumeSorted = false; presorted = false; } final SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(headerMergerSortOrder, headers, MERGE_SEQUENCE_DICTIONARIES); final MergingSamRecordIterator iterator = new MergingSamRecordIterator(headerMerger, readers, mergingSamRecordIteratorAssumeSorted); final SAMFileHeader header = headerMerger.getMergedHeader(); for (String comment : COMMENT) { header.addComment(comment); } header.setSortOrder(SORT_ORDER); final SAMFileWriter out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, presorted, OUTPUT); // Lastly loop through and write out the records if (USE_THREADING) { final BlockingQueue<SAMRecord> queue = new ArrayBlockingQueue<SAMRecord>(10000); final AtomicBoolean producerSuccceeded = new AtomicBoolean(false); final AtomicBoolean consumerSuccceeded = new AtomicBoolean(false); Runnable producer = new Runnable() { public void run() { try { while (iterator.hasNext()) { queue.put(iterator.next()); } producerSuccceeded.set(true); } catch (InterruptedException ie) { throw new PicardException("Interrupted reading SAMRecord to merge.", ie); } } }; Runnable consumer = new Runnable() { public void run() { try { long i = 0; while (!producerSuccceeded.get()) { SAMRecord rec = queue.poll(15, TimeUnit.SECONDS); if (rec != null) { out.addAlignment(rec); if (++i % PROGRESS_INTERVAL == 0) log.info(i + " records processed."); } } consumerSuccceeded.set(true); } catch (InterruptedException ie) { throw new PicardException("Interrupted writing SAMRecord to output file.", ie); } } }; Thread producerThread = new Thread(producer); Thread consumerThread = new Thread(consumer); producerThread.start(); consumerThread.start(); try { consumerThread.join(); producerThread.join(); } catch (InterruptedException ie) { throw new PicardException("Interrupted while waiting for threads to finished writing.", ie); } if (!producerSuccceeded.get()) { throw new PicardException("Error reading or merging inputs."); } if (!consumerSuccceeded.get()) { throw new PicardException("Error writing output"); } } else { for (long numRecords = 1; iterator.hasNext(); ++numRecords) { final SAMRecord record = iterator.next(); out.addAlignment(record); if (numRecords % PROGRESS_INTERVAL == 0) { log.info(numRecords + " records read."); } } } log.info("Finished reading inputs."); out.close(); return 0; } @Override protected String[] customCommandLineValidation() { if (CREATE_INDEX && SORT_ORDER != SAMFileHeader.SortOrder.coordinate) { return new String[]{"Can't CREATE_INDEX unless SORT_ORDER is coordinate"}; } return null; } }
// @formatter:off // @formatter:on package org.stuygfx; import static org.stuygfx.CONSTANTS.ANSI_RED; import static org.stuygfx.CONSTANTS.ANSI_RESET; import static org.stuygfx.CONSTANTS.ANSI_YELLOW; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.Iterator; import java.util.Set; import org.stuygfx.graphics.Draw; import org.stuygfx.graphics.EdgeMatrix; import org.stuygfx.graphics.Image; import org.stuygfx.graphics.Pixel; import org.stuygfx.graphics.Point; import org.stuygfx.graphics.PolygonMatrix; import org.stuygfx.graphics.TransformationStack; import org.stuygfx.math.Transformations; import org.stuygfx.parser.ParseException; import org.stuygfx.parser.tables.OPBasename; import org.stuygfx.parser.tables.OPBox; import org.stuygfx.parser.tables.OPCode; import org.stuygfx.parser.tables.OPDisplay; import org.stuygfx.parser.tables.OPFrames; import org.stuygfx.parser.tables.OPLine; import org.stuygfx.parser.tables.OPMove; import org.stuygfx.parser.tables.OPPop; import org.stuygfx.parser.tables.OPPush; import org.stuygfx.parser.tables.OPRotate; import org.stuygfx.parser.tables.OPSave; import org.stuygfx.parser.tables.OPScale; import org.stuygfx.parser.tables.OPSphere; import org.stuygfx.parser.tables.OPTorus; import org.stuygfx.parser.tables.OPTrans; import org.stuygfx.parser.tables.OPVary; import org.stuygfx.parser.tables.SymbolTable; public class MDLReader { private ArrayList<OPCode> opcodes; private SymbolTable symbols; private Set<String> symKeys; private TransformationStack origins; private Image canvas; private EdgeMatrix em; private PolygonMatrix pm; private String basename; private String formatString; // For animation private boolean isAnimated; private int numFrames; private Hashtable<String, Double[]> knobs; public MDLReader(ArrayList<OPCode> o, SymbolTable s) { opcodes = o; symbols = s; symKeys = s.keySet(); canvas = new Image(); canvas.shouldRelectOverX(true); em = new EdgeMatrix(); pm = new PolygonMatrix(); origins = new TransformationStack(); basename = ""; isAnimated = false; numFrames = -1; knobs = new Hashtable<String, Double[]>(); } /** * Prints all commands that have been parsed by MDL */ public void printCommands() { for (OPCode op : opcodes) { System.out.println(op); } } /** * Prints all systems that have been parsed by MDL */ public void printSymbols() { System.out.println("Symbol Table:"); for (String key : symKeys) { Object value = symbols.get(key); System.out.println(key + " = " + value); } } /** * Prints the matrix values in the stack */ public void printStack() { origins.print(); } /** * Prints knobs and knob values for each frame (for debugging purposes) */ public void printKnobs() { for (String key : knobs.keySet()) { System.out.printf("%s: %s\n", key, Arrays.toString(knobs.get(key))); } } public void printWarning(String message) { System.out.printf("%s[WARNING] %s%s", ANSI_YELLOW, message, ANSI_RESET); } public void printError(String message) { System.out.printf("%s[ERROR] %s%s", ANSI_RED, message, ANSI_RESET); } public void throwError(String message) throws ParseException { printError(message); throw new ParseException(); } public void checkForAnimation() throws ParseException { for (OPCode opc : opcodes) { if (opc instanceof OPFrames) { if (numFrames != -1) { // -1 is the value for unset frame value printWarning("Number of animation frames set multiple times"); } isAnimated = true; numFrames = ((OPFrames) opc).getNum(); } else if (opc instanceof OPBasename) { if (basename.length() != 0) { printWarning("Animation frame / image file basename set multiple times"); } isAnimated = true; basename = ((OPBasename) opc).getName(); } else if (opc instanceof OPVary) { isAnimated = true; } } } public void animationPass() throws ParseException, IOException { // Ensure isAnimated is set to false beforehand isAnimated = false; checkForAnimation(); if (!isAnimated) { numFrames = 1; return; } // Error check if (numFrames == -1) { throwError("Number of frames for animation not set"); } if (basename.length() == 0) { throwError("Animation frame / image file basename not set"); } // Get knob values for (OPCode opc : opcodes) { if (opc instanceof OPVary) { Double[] knobValues = knobs.get(((OPVary) opc).getKnob()); // Create the knob values if not yet created if (knobValues == null) { knobValues = new Double[numFrames]; } int start = ((OPVary) opc).getStartframe(); int end = ((OPVary) opc).getEndframe(); double startVal = ((OPVary) opc).getStartval(); double endVal = ((OPVary) opc).getEndval(); // Throw error if start frame is not within bounds if (start < 0 || end >= numFrames) { throwError("Frame start or end [" + ((OPVary) opc).getKnob() + "] is out of bounds"); } for (int frame = start; frame <= end; frame++) { knobValues[frame] = startVal; // Add rate of change: startVal += (endVal - startVal) / (end - start + 1); } knobs.put(((OPVary) opc).getKnob(), knobValues); } } PPMGenerator.setUpOutputDirectory(basename); int numberLength = Integer.toString(numFrames).length(); formatString = basename + "/" + basename + "-%0" + numberLength + "d"; } public double getKnobAtFrame(OPCode opc, int frame) throws ParseException { if (isAnimated && ((OPMove) opc).getKnob() != null) { Double[] knobValues = knobs.get(((OPTrans) opc).getKnob()); if (knobValues == null) { throwError("Knob " + ((OPTrans) opc).getKnob() + " does not exist"); } Double knobValue = knobValues[frame]; if (knobValue == null) { throwError("Knob " + ((OPTrans) opc).getKnob() + " does not have a value for frame " + frame); } return knobValue; } else { return 1.0; } } public void process() throws ParseException, IOException { process(false); } public void process(boolean debug) throws ParseException, IOException { animationPass(); for (int frame = 0; frame < numFrames; frame++) { Iterator<OPCode> i = opcodes.iterator(); OPCode opc; while (i.hasNext()) { opc = (OPCode) i.next(); if (debug) { System.out.println("============== BEGIN OPERATION ============="); } System.out.println(opc.getClass()); // Get the knobValue. This will make it 1.0 if knobValue is // inapplicable for the current operation double knobValue = getKnobAtFrame(opc, frame); if (opc instanceof OPPush) { origins.push(); } else if (opc instanceof OPPop) { origins.pop(); } else if (opc instanceof OPMove) { double[] values = ((OPMove) opc).getValues(); double dx = values[0] * knobValue; double dy = values[1] * knobValue; double dz = values[2] * knobValue; origins.addTranslate(dx, dy, dz); } else if (opc instanceof OPScale) { double[] values = ((OPScale) opc).getValues(); double xFac = values[0] * knobValue; double yFac = values[1] * knobValue; double zFac = values[2] * knobValue; origins.addScale(xFac, yFac, zFac); } else if (opc instanceof OPRotate) { char axis = ((OPRotate) opc).getAxis(); double degrees = ((OPRotate) opc).getDeg() * knobValue; switch (axis) { case 'x': origins.addRotX(degrees); break; case 'y': origins.addRotY(degrees); break; case 'z': origins.addRotZ(degrees); break; default: System.err.println("INVALID AXIS!!!"); System.exit(1); } } else if (opc instanceof OPBox) { OPBox opb = (OPBox) opc; double[] loc = opb.getRootCoor(); double x = loc[0]; double y = loc[1]; double z = loc[2]; double[] dim = opb.getDimensions(); double dx = dim[0]; double dy = dim[1]; double dz = dim[2]; pm.addRectPrism((int) x, (int) y, (int) z, (int) dx, (int) dy, (int) dz); } else if (opc instanceof OPSphere) { OPSphere ops = (OPSphere) opc; double[] center = ops.getCenter(); double cx = center[0]; double cy = center[1]; double cz = center[2]; double radius = ops.getRadius(); pm.addSphere(cx, cy, cz, radius); } else if (opc instanceof OPTorus) { OPTorus opt = (OPTorus) opc; double[] center = opt.getCenter(); double cx = center[0]; double cy = center[1]; double cz = center[2]; double outerRadius = opt.getOuterRadius(); double crossSectionRadius = opt.getCrossSectionRadius(); pm.addTorus(cx, cy, cz, outerRadius, crossSectionRadius); } else if (opc instanceof OPLine) { double[] start = ((OPLine) opc).getP1(); double x0 = start[0]; double y0 = start[1]; double z0 = start[2]; double[] end = ((OPLine) opc).getP2(); double x1 = end[0]; double y1 = end[1]; double z1 = end[2]; em.addEdge(new Point((int) x0, (int) y0, (int) z0), new Point((int) x1, (int) y1, (int) z1)); } else if (opc instanceof OPSave) { String filename = ((OPSave) opc).getName(); save(filename); } else if (opc instanceof OPDisplay) { save(CONSTANTS.TMP_FILE_NAME); try { Runtime.getRuntime().exec("display " + CONSTANTS.TMP_FILE_NAME).waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // Apply if (debug) { System.out.println("APPLYING TRANSFORMATIONS USING " + origins.peek().toString()); } Transformations.applyTransformation(origins.peek(), em); Transformations.applyTransformation(origins.peek(), pm); // Draw Draw.polygonMatrix(canvas, new Pixel(255, 20, 255), pm); Draw.edgeMatrix(canvas, new Pixel(255, 0, 0), em); // Empty em.empty(); pm.empty(); if (debug) { System.out.println("=============== END OPERATION =============="); System.out.println("\n\n"); } } if (isAnimated) { String filename = String.format(formatString, frame); save(filename); canvas.resetCanvas(); em.empty(); pm.empty(); origins.reset(); } } System.out.println("FINISHED PROCESSING"); } private void save(String filename) { try { PPMGenerator.createPPM(filename, canvas); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } }
package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Cursor; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractListModel; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.JProgressBar; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.UIManager; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.auth.DefaultUserNameStore; import org.jdesktop.swingx.auth.LoginAdapter; import org.jdesktop.swingx.auth.LoginEvent; import org.jdesktop.swingx.auth.LoginService; import org.jdesktop.swingx.auth.PasswordStore; import org.jdesktop.swingx.auth.UserNameStore; import org.jdesktop.swingx.plaf.JXLoginPanelAddon; import org.jdesktop.swingx.plaf.LoginPanelUI; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.util.WindowUtils; /** * <p>JXLoginPanel is a JPanel that implements a Login dialog with * support for saving passwords supplied for future use in a secure * manner. It is intended to work with <strong>LoginService</strong> * and <strong>PasswordStore</strong> to implement the * authentication.</p> * * <p> In order to perform the authentication, <strong>JXLoginPanel</strong> * calls the <code>authenticate</code> method of the <strong>LoginService * </strong>. In order to perform the persistence of the password, * <strong>JXLoginPanel</strong> calls the put method of the * <strong>PasswordStore</strong> object that is supplied. If * the <strong>PasswordStore</strong> is <code>null</code>, then the password * is not saved. Similarly, if a <strong>PasswordStore</strong> is * supplied and the password is null, then the <strong>PasswordStore</strong> * will be queried for the password using the <code>get</code> method. * * @author Bino George * @author Shai Almog * @author rbair */ public class JXLoginPanel extends JXImagePanel { /** * The Logger */ private static final Logger LOG = Logger.getLogger(JXLoginPanel.class.getName()); /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 3544949969896288564L; /** * UI Class ID */ public final static String uiClassID = "LoginPanelUI"; /** * Action key for an Action in the ActionMap that initiates the Login * procedure */ public static final String LOGIN_ACTION_COMMAND = "login"; /** * Action key for an Action in the ActionMap that cancels the Login * procedure */ public static final String CANCEL_LOGIN_ACTION_COMMAND = "cancel-login"; /** * The JXLoginPanel can attempt to save certain user information such as * the username, password, or both to their respective stores. * This type specifies what type of save should be performed. */ public static enum SaveMode {NONE, USER_NAME, PASSWORD, BOTH}; /** * Returns the status of the login process */ public enum Status {NOT_STARTED, IN_PROGRESS, FAILED, CANCELLED, SUCCEEDED}; /** * Used as a prefix when pulling data out of UIManager for i18n */ private static String CLASS_NAME; /** * The current login status for this panel */ private Status status = Status.NOT_STARTED; /** * An optional banner at the top of the panel */ private JXImagePanel banner; /** * Text that should appear on the banner */ private String bannerText = "Login"; /** * Custom label allowing the developer to display some message to the user */ private JLabel messageLabel; /** * Shows an error message such as "user name or password incorrect" or * "could not contact server" or something like that if something * goes wrong */ private JLabel errorMessageLabel; /** * A Panel containing all of the input fields, check boxes, etc necessary * for the user to do their job. The items on this panel change whenever * the SaveMode changes, so this panel must be recreated at runtime if the * SaveMode changes. Thus, I must maintain this reference so I can remove * this panel from the content panel at runtime. */ private JXPanel loginPanel; /** * The panel on which the input fields, messageLabel, and errorMessageLabel * are placed. While the login thread is running, this panel is removed * from the dialog and replaced by the progressPanel */ private JXPanel contentPanel; /** * This is the area in which the name field is placed. That way it can toggle on the fly * between text field and a combo box depending on the situation, and have a simple * way to get the user name */ private NameComponent namePanel; /** * The password field presented allowing the user to enter their password */ private JPasswordField passwordField; /** * A combo box presenting the user with a list of servers to which they * may log in. This is an optional feature, which is only enabled if * the List of servers supplied to the JXLoginPanel has a length greater * than 1. */ private JComboBox serverCombo; /** * Check box presented if a PasswordStore is used, allowing the user to decide whether to * save their password */ private JCheckBox saveCB; /** * A special panel that displays a progress bar and cancel button, and * which notify the user of the login process, and allow them to cancel * that process. */ private JXPanel progressPanel; /** * A JLabel on the progressPanel that is used for informing the user * of the status of the login procedure (logging in..., cancelling login...) */ private JLabel progressMessageLabel; /** * The LoginService to use. This must be specified for the login dialog to operate. * If no LoginService is defined, a default login service is used that simply * allows all users access. This is useful for demos or prototypes where a proper login * server is not available. */ private LoginService loginService; /** * Optional: a PasswordStore to use for storing and retrieving passwords for a specific * user. */ private PasswordStore passwordStore; /** * Optional: a UserNameStore to use for storing user names and retrieving them */ private UserNameStore userNameStore; /** * A list of servers where each server is represented by a String. If the * list of Servers is greater than 1, then a combo box will be presented to * the user to choose from. If any servers are specified, the selected one * (or the only one if servers.size() == 1) will be passed to the LoginService */ private List<String> servers; /** * Whether to save password or username or both */ private SaveMode saveMode; /** * Listens to login events on the LoginService. Updates the UI and the * JXLoginPanel.state as appropriate */ private LoginListenerImpl loginListener; /** * Tracks the cursor at the time that authentication was started, and restores to that * cursor after authentication ends, or is cancelled; */ private Cursor oldCursor; /** * Creates a default JXLoginPanel instance */ static { LookAndFeelAddons.contribute(new JXLoginPanelAddon()); // Popuplate UIDefaults with the localizable Strings we will use // in the Login panel. CLASS_NAME = JXLoginPanel.class.getCanonicalName(); String lookup; ResourceBundle res = ResourceBundle.getBundle("org.jdesktop.swingx.auth.resources.resources"); Enumeration<String> keys = res.getKeys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); lookup = CLASS_NAME + "." + key; if (UIManager.getString(lookup) == null) { UIManager.put(lookup, res.getString(key)); } } } /** * Create a new JXLoginPanel */ public JXLoginPanel() { this(null); } /** * Create a new JXLoginPanel * @param service The LoginService to use for logging in */ public JXLoginPanel(LoginService service) { this(service, null, null); } /** * Create a new JXLoginPanel * @param service * @param passwordStore * @param userStore */ public JXLoginPanel(LoginService service, PasswordStore passwordStore, UserNameStore userStore) { this(service, passwordStore, userStore, null); } /** * Create a new JXLoginPanel * @param service * @param passwordStore * @param userStore * @param servers */ public JXLoginPanel(LoginService service, PasswordStore passwordStore, UserNameStore userStore, List<String> servers) { this.loginService = service == null ? new NullLoginService() : service; this.passwordStore = passwordStore == null ? new NullPasswordStore() : passwordStore; this.userNameStore = userStore == null ? new DefaultUserNameStore() : userStore; this.servers = servers == null ? new ArrayList<String>() : servers; //create the login and cancel actions, and add them to the action map getActionMap().put(LOGIN_ACTION_COMMAND, createLoginAction()); getActionMap().put(CANCEL_LOGIN_ACTION_COMMAND, createCancelAction()); //initialize the save mode if (passwordStore != null && userStore != null) { saveMode = SaveMode.BOTH; } else if (passwordStore != null) { saveMode = SaveMode.PASSWORD; } else if (userStore != null) { saveMode = SaveMode.USER_NAME; } else { saveMode = SaveMode.NONE; } loginListener = new LoginListenerImpl(); this.loginService.addLoginListener(loginListener); // initialize banner text bannerText = UIManager.getString(CLASS_NAME + ".bannerString"); updateUI(); initComponents(); } /** * @inheritDoc */ public LoginPanelUI getUI() { return (LoginPanelUI)super.getUI(); } /** * Returns the name of the L&F class that renders this component. * * @return the string {@link #uiClassID} * @see javax.swing.JComponent#getUIClassID * @see javax.swing.UIDefaults#getUI */ public String getUIClassID() { return uiClassID; } /** * Recreates the login panel, and replaces the current one with the new one */ protected void recreateLoginPanel() { contentPanel.remove(loginPanel); loginPanel = createLoginPanel(); loginPanel.setBorder(BorderFactory.createEmptyBorder(0, 36, 7, 11)); contentPanel.add(loginPanel, 1); } /** * Creates and returns a new LoginPanel, based on the SaveMode state of * the login panel. Whenever the SaveMode changes, the panel is recreated. * I do this rather than hiding/showing components, due to a cleaner * implementation (no invisible components, components are not sharing * locations in the LayoutManager, etc). */ private JXPanel createLoginPanel() { JXPanel loginPanel = new JXPanel(); //create the NameComponent if (saveMode == SaveMode.NONE) { namePanel = new SimpleNamePanel(); } else { namePanel = new ComboNamePanel(userNameStore); } JLabel nameLabel = new JLabel(UIManager.getString(CLASS_NAME + ".nameString")); nameLabel.setLabelFor(namePanel.getComponent()); //create the password component passwordField = new JPasswordField("", 15); JLabel passwordLabel = new JLabel(UIManager.getString(CLASS_NAME + ".passwordString")); passwordLabel.setLabelFor(passwordField); //create the server combo box if necessary // JLabel serverLabel = new JLabel(UIManager.getString(CLASS_NAME + ".serverString")); JLabel serverLabel = new JLabel("Server"); if (servers.size() > 1) { serverCombo = new JComboBox(servers.toArray()); serverLabel.setLabelFor(serverCombo); } else { serverCombo = null; } //create the save check box. By default, it is not selected saveCB = new JCheckBox(UIManager.getString(CLASS_NAME + ".rememberPasswordString")); saveCB.setSelected(false); //TODO should get this from prefs!!! And, it should be based on the user //determine whether to show/hide the save check box based on the SaveMode saveCB.setVisible(saveMode == SaveMode.PASSWORD || saveMode == SaveMode.BOTH); loginPanel.setLayout(new GridBagLayout()); GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(0, 0, 5, 11); loginPanel.add(nameLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 5, 0); loginPanel.add(namePanel.getComponent(), gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(0, 0, 5, 11); loginPanel.add(passwordLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 5, 0); loginPanel.add(passwordField, gridBagConstraints); if (serverCombo != null) { gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(0, 0, 5, 11); loginPanel.add(serverLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 5, 0); loginPanel.add(serverCombo, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(6, 0, 0, 0); loginPanel.add(saveCB, gridBagConstraints); } else { gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(6, 0, 0, 0); loginPanel.add(saveCB, gridBagConstraints); } return loginPanel; } /** * This method adds functionality to support bidi languages within this * component */ public void setComponentOrientation(ComponentOrientation orient) { // this if is used to avoid needless creations of the image if(orient != super.getComponentOrientation()) { super.setComponentOrientation(orient); banner.setImage(createLoginBanner()); progressPanel.applyComponentOrientation(orient); } } /** * Create all of the UI components for the login panel */ private void initComponents() { //create the default banner banner = new JXImagePanel(); banner.setImage(createLoginBanner()); //create the default label messageLabel = new JLabel(" "); messageLabel.setOpaque(true); messageLabel.setFont(messageLabel.getFont().deriveFont(Font.BOLD)); //create the main components loginPanel = createLoginPanel(); //create the message and hyperlink and hide them errorMessageLabel = new JLabel(UIManager.getString(CLASS_NAME + ".errorMessage")); errorMessageLabel.setIcon(UIManager.getIcon("JXLoginDialog.error.icon")); errorMessageLabel.setVerticalTextPosition(SwingConstants.TOP); errorMessageLabel.setOpaque(true); errorMessageLabel.setBackground(new Color(255, 215, 215));//TODO get from UIManager errorMessageLabel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(errorMessageLabel.getBackground().darker()), BorderFactory.createEmptyBorder(5, 7, 5, 5))); //TODO get color from UIManager errorMessageLabel.setVisible(false); //aggregate the optional message label, content, and error label into //the contentPanel contentPanel = new JXPanel(new VerticalLayout()); messageLabel.setBorder(BorderFactory.createEmptyBorder(12, 12, 7, 11)); contentPanel.add(messageLabel); loginPanel.setBorder(BorderFactory.createEmptyBorder(0, 36, 7, 11)); contentPanel.add(loginPanel); errorMessageLabel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(0, 36, 0, 11, contentPanel.getBackground()), errorMessageLabel.getBorder())); contentPanel.add(errorMessageLabel); //create the progress panel progressPanel = new JXPanel(new GridBagLayout()); progressMessageLabel = new JLabel(UIManager.getString(CLASS_NAME + ".pleaseWait")); progressMessageLabel.setFont(progressMessageLabel.getFont().deriveFont(Font.BOLD)); //TODO get from UIManager JProgressBar pb = new JProgressBar(); pb.setIndeterminate(true); JButton cancelButton = new JButton(getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND)); progressPanel.add(progressMessageLabel, new GridBagConstraints(0, 0, 2, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(12, 12, 11, 11), 0, 0)); progressPanel.add(pb, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 24, 11, 7), 0, 0)); progressPanel.add(cancelButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 11, 11), 0, 0)); //layout the panel setLayout(new BorderLayout()); add(banner, BorderLayout.NORTH); add(contentPanel, BorderLayout.CENTER); } /** * Create and return an image to use for the Banner. This may be overridden * to return any image you like */ protected Image createLoginBanner() { return getUI() == null ? null : getUI().getBanner(); } /** * Create and return an Action for logging in */ protected Action createLoginAction() { return new LoginAction(this); } /** * Create and return an Action for canceling login */ protected Action createCancelAction() { return new CancelAction(this); } //TODO need to fire property change events!!! /** * @return Returns the saveMode. */ public SaveMode getSaveMode() { return saveMode; } /** * The save mode indicates whether the "save" password is checked by default. This method * makes no difference if the passwordStore is null. * * @param saveMode The saveMode to set either SAVE_NONE, SAVE_PASSWORD or SAVE_USERNAME */ public void setSaveMode(SaveMode saveMode) { this.saveMode = saveMode; recreateLoginPanel(); } /** * @return the List of servers */ public List<String> getServers() { return Collections.unmodifiableList(servers); } /** * Sets the list of servers. See the servers field javadoc for more info */ public void setServers(List<String> servers) { if (this.servers != servers) { List<String> old = this.servers; this.servers = servers == null ? new ArrayList<String>() : servers; recreateLoginPanel(); firePropertyChange("servers", old, servers); } } /** * Sets the <strong>LoginService</strong> for this panel. * * @param service service */ public void setLoginService(LoginService service) { loginService = service; } /** * Gets the <strong>LoginService</strong> for this panel. * * @return service service */ public LoginService getLoginService() { return loginService; } /** * Sets the <strong>PasswordStore</strong> for this panel. * * @param store PasswordStore */ public void setPasswordStore(PasswordStore store) { passwordStore = store; } /** * Gets the <strong>PasswordStore</strong> for this panel. * * @return store PasswordStore */ public PasswordStore getPasswordStore() { return passwordStore; } /** * Sets the <strong>User name</strong> for this panel. * * @param username User name */ public void setUserName(String username) { if (namePanel != null) { namePanel.setUserName(username); } } /** * Gets the <strong>User name</strong> for this panel. * @return the user name */ public String getUserName() { return namePanel == null ? null : namePanel.getUserName(); } /** * Sets the <strong>Password</strong> for this panel. * * @param password Password */ public void setPassword(char[] password) { passwordField.setText(new String(password)); } /** * Gets the <strong>Password</strong> for this panel. * * @return password Password */ public char[] getPassword() { return passwordField.getPassword(); } /** * Return the image used as the banner */ public Image getBanner() { return banner.getImage(); } /** * Set the image to use for the banner */ public void setBanner(Image img) { banner.setImage(img); } /** * Set the text to use when creating the banner. If a custom banner image * is specified, then this is ignored */ public void setBannerText(String text) { if (text == null) { text = ""; } if (!this.bannerText.equals(text)) { String oldText = this.bannerText; this.bannerText = text; //fix the login banner banner.setImage(createLoginBanner()); firePropertyChange("bannerText", oldText, text); } } /** * Returns text used when creating the banner */ public String getBannerText() { return bannerText; } /** * Returns the custom message for this login panel */ public String getMessage() { return messageLabel.getText(); } /** * Sets a custom message for this login panel */ public void setMessage(String message) { messageLabel.setText(message); } /** * Returns the error message for this login panel */ public String getErrorMessage() { return errorMessageLabel.getText(); } /** * Sets the error message for this login panel */ public void setErrorMessage(String errorMessage) { errorMessageLabel.setText(errorMessage); } /** * Returns the panel's status */ public Status getStatus() { return status; } /** * Change the status */ protected void setStatus(Status newStatus) { if (status != newStatus) { Status oldStatus = status; status = newStatus; firePropertyChange("status", oldStatus, newStatus); } } /** * Initiates the login procedure. This method is called internally by * the LoginAction. This method handles cursor management, and actually * calling the LoginService's startAuthentication method. */ protected void startLogin() { oldCursor = getCursor(); try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); progressMessageLabel.setText(UIManager.getString(CLASS_NAME + ".pleaseWait")); String name = getUserName(); char[] password = getPassword(); String server = servers.size() == 1 ? servers.get(0) : serverCombo == null ? null : (String)serverCombo.getSelectedItem(); loginService.startAuthentication(name, password, server); } catch(Exception ex) { //The status is set via the loginService listener, so no need to set //the status here. Just log the error. LOG.log(Level.WARNING, "Authentication exception while logging in", ex); } finally { setCursor(oldCursor); } } /** * Cancels the login procedure. Handles cursor management and interfacing * with the LoginService's cancelAuthentication method */ protected void cancelLogin() { progressMessageLabel.setText(UIManager.getString(CLASS_NAME + ".cancelWait")); getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).setEnabled(false); loginService.cancelAuthentication(); setCursor(oldCursor); } /** * TODO */ protected void savePassword() { if (saveCB.isSelected() && (saveMode == SaveMode.BOTH || saveMode == SaveMode.PASSWORD) && passwordStore != null) { passwordStore.set(getUserName(),getLoginService().getServer(),getPassword()); } } /* For Login (initiated in LoginAction): 0) set the status 1) Immediately disable the login action 2) Immediately disable the close action (part of enclosing window) 3) initialize the progress pane a) enable the cancel login action b) set the message text 4) hide the content pane, show the progress pane When cancelling (initiated in CancelAction): 0) set the status 1) Disable the cancel login action 2) Change the message text on the progress pane When cancel finishes (handled in LoginListener): 0) set the status 1) hide the progress pane, show the content pane 2) enable the close action (part of enclosing window) 3) enable the login action When login fails (handled in LoginListener): 0) set the status 1) hide the progress pane, show the content pane 2) enable the close action (part of enclosing window) 3) enable the login action 4) Show the error message 5) resize the window (part of enclosing window) When login succeeds (handled in LoginListener): 0) set the status 1) close the dialog/frame (part of enclosing window) */ /** * Listener class to track state in the LoginService */ protected class LoginListenerImpl extends LoginAdapter { public void loginSucceeded(LoginEvent source) { //save the user names and passwords String userName = namePanel.getUserName(); savePassword(); if (getSaveMode() == SaveMode.USER_NAME && userName != null && !userName.trim().equals("")) { userNameStore.addUserName(userName); userNameStore.saveUserNames(); } setStatus(Status.SUCCEEDED); } public void loginStarted(LoginEvent source) { getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(false); getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).setEnabled(true); remove(contentPanel); add(progressPanel, BorderLayout.CENTER); revalidate(); repaint(); setStatus(Status.IN_PROGRESS); } public void loginFailed(LoginEvent source) { remove(progressPanel); add(contentPanel, BorderLayout.CENTER); getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(true); errorMessageLabel.setVisible(true); revalidate(); repaint(); setStatus(Status.FAILED); } public void loginCanceled(LoginEvent source) { remove(progressPanel); add(contentPanel, BorderLayout.CENTER); getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(true); errorMessageLabel.setVisible(false); revalidate(); repaint(); setStatus(Status.CANCELLED); } } /** * Action that initiates a login procedure. Delegates to JXLoginPanel.startLogin */ private static final class LoginAction extends AbstractActionExt { private JXLoginPanel panel; public LoginAction(JXLoginPanel p) { super(UIManager.getString(CLASS_NAME + ".loginString"), LOGIN_ACTION_COMMAND); this.panel = p; } public void actionPerformed(ActionEvent e) { panel.startLogin(); } public void itemStateChanged(ItemEvent e) {} } /** * Action that cancels the login procedure. */ private static final class CancelAction extends AbstractActionExt { private JXLoginPanel panel; public CancelAction(JXLoginPanel p) { super(UIManager.getString(CLASS_NAME + ".cancelLogin"), CANCEL_LOGIN_ACTION_COMMAND); this.panel = p; this.setEnabled(false); } public void actionPerformed(ActionEvent e) { panel.cancelLogin(); } public void itemStateChanged(ItemEvent e) {} } /** * Simple login service that allows everybody to login. This is useful in demos and allows * us to avoid having to check for LoginService being null */ private static final class NullLoginService extends LoginService { public boolean authenticate(String name, char[] password, String server) throws Exception { return true; } } /** * Simple PasswordStore that does not remember passwords */ private static final class NullPasswordStore extends PasswordStore { private static final char[] EMPTY = new char[0]; public boolean set(String username, String server, char[] password) { //null op return false; } public char[] get(String username, String server) { return EMPTY; } } public static interface NameComponent { public String getUserName(); public void setUserName(String userName); public JComponent getComponent(); } /** * If a UserNameStore is not used, then this text field is presented allowing the user * to simply enter their user name */ public static final class SimpleNamePanel extends JTextField implements NameComponent { public SimpleNamePanel() { super("", 15); } public String getUserName() { return getText(); } public void setUserName(String userName) { setText(userName); } public JComponent getComponent() { return this; } } /** * If a UserNameStore is used, then this combo box is presented allowing the user * to select a previous login name, or type in a new login name */ public static final class ComboNamePanel extends JComboBox implements NameComponent { private UserNameStore userNameStore; public ComboNamePanel(UserNameStore userNameStore) { super(); this.userNameStore = userNameStore; setModel(new NameComboBoxModel()); setEditable(true); } public String getUserName() { Object item = getModel().getSelectedItem(); return item == null ? null : item.toString(); } public void setUserName(String userName) { getModel().setSelectedItem(userName); } public void setUserNames(String[] names) { setModel(new DefaultComboBoxModel(names)); } public JComponent getComponent() { return this; } private final class NameComboBoxModel extends AbstractListModel implements ComboBoxModel { private Object selectedItem; public void setSelectedItem(Object anItem) { selectedItem = anItem; fireContentsChanged(this, -1, -1); } public Object getSelectedItem() { return selectedItem; } public Object getElementAt(int index) { return userNameStore.getUserNames()[index]; } public int getSize() { return userNameStore.getUserNames().length; } } } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc) { return showLoginDialog(parent, svc, null, null); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc, PasswordStore ps, UserNameStore us) { return showLoginDialog(parent, svc, ps, us, null); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc, PasswordStore ps, UserNameStore us, List<String> servers) { JXLoginPanel panel = new JXLoginPanel(svc, ps, us, servers); return showLoginDialog(parent, panel); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, JXLoginPanel panel) { Window w = WindowUtils.findWindow(parent); JXLoginDialog dlg = null; if (w == null) { dlg = new JXLoginDialog((Frame)null, panel); } else if (w instanceof Dialog) { dlg = new JXLoginDialog((Dialog)w, panel); } else if (w instanceof Frame) { dlg = new JXLoginDialog((Frame)w, panel); } dlg.setVisible(true); return dlg.getStatus(); } /** * Shows a login frame. A JFrame is not modal, and thus does not block */ public static JXLoginFrame showLoginFrame(LoginService svc) { return showLoginFrame(svc, null, null); } public static JXLoginFrame showLoginFrame(LoginService svc, PasswordStore ps, UserNameStore us) { return showLoginFrame(svc, ps, us, null); } public static JXLoginFrame showLoginFrame(LoginService svc, PasswordStore ps, UserNameStore us, List<String> servers) { JXLoginPanel panel = new JXLoginPanel(svc, ps, us, servers); return showLoginFrame(panel); } public static JXLoginFrame showLoginFrame(JXLoginPanel panel) { return new JXLoginFrame(panel); } public static final class JXLoginDialog extends JDialog { private JXLoginPanel panel; public JXLoginDialog(Frame parent, JXLoginPanel p) { super(parent, true); init(p); } public JXLoginDialog(Dialog parent, JXLoginPanel p) { super(parent, true); init(p); } protected void init(JXLoginPanel p) { setTitle(UIManager.getString(CLASS_NAME + ".titleString")); this.panel = p; initWindow(this, panel); } public JXLoginPanel.Status getStatus() { return panel.getStatus(); } } public static final class JXLoginFrame extends JFrame { private JXLoginPanel panel; public JXLoginFrame(JXLoginPanel p) { super(UIManager.getString(CLASS_NAME + ".titleString")); this.panel = p; initWindow(this, panel); } public JXLoginPanel.Status getStatus() { return panel.getStatus(); } public JXLoginPanel getPanel() { return panel; } } /** * Utility method for initializing a Window for displaying a LoginDialog. * This is particularly useful because the differences between JFrame and * JDialog are so minor. * * Note: This method is package private for use by JXLoginDialog (proper, * not JXLoginPanel.JXLoginDialog). Change to private if JXLoginDialog is * removed. */ static void initWindow(final Window w, final JXLoginPanel panel) { w.setLayout(new BorderLayout()); w.add(panel, BorderLayout.CENTER); JButton okButton = new JButton(panel.getActionMap().get(LOGIN_ACTION_COMMAND)); final JButton cancelButton = new JButton(UIManager.getString(CLASS_NAME + ".cancelString")); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //change panel status to cancelled! panel.status = JXLoginPanel.Status.CANCELLED; w.setVisible(false); w.dispose(); } }); panel.addPropertyChangeListener("status", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { JXLoginPanel.Status status = (JXLoginPanel.Status)evt.getNewValue(); switch (status) { case NOT_STARTED: break; case IN_PROGRESS: cancelButton.setEnabled(false); break; case CANCELLED: cancelButton.setEnabled(true); w.pack(); break; case FAILED: cancelButton.setEnabled(true); w.pack(); break; case SUCCEEDED: w.setVisible(false); w.dispose(); } for (PropertyChangeListener l : w.getPropertyChangeListeners("status")) { PropertyChangeEvent pce = new PropertyChangeEvent(w, "status", evt.getOldValue(), evt.getNewValue()); l.propertyChange(pce); } } }); cancelButton.setText(UIManager.getString(CLASS_NAME + ".cancelString")); int prefWidth = Math.max(cancelButton.getPreferredSize().width, okButton.getPreferredSize().width); cancelButton.setPreferredSize(new Dimension(prefWidth, okButton.getPreferredSize().height)); okButton.setPreferredSize(new Dimension(prefWidth, okButton.getPreferredSize().height)); JXPanel buttonPanel = new JXPanel(new GridBagLayout()); buttonPanel.add(okButton, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_END, GridBagConstraints.NONE, new Insets(17, 12, 11, 5), 0, 0)); buttonPanel.add(cancelButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_END, GridBagConstraints.NONE, new Insets(17, 0, 11, 11), 0, 0)); w.add(buttonPanel, BorderLayout.SOUTH); w.addWindowListener(new WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { panel.cancelLogin(); } }); if (w instanceof JFrame) { final JFrame f = (JFrame)w; f.getRootPane().setDefaultButton(okButton); f.setResizable(false); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); ActionListener closeAction = new ActionListener() { public void actionPerformed(ActionEvent e) { f.setVisible(false); f.dispose(); } }; f.getRootPane().registerKeyboardAction(closeAction, ks, JComponent.WHEN_IN_FOCUSED_WINDOW); } else if (w instanceof JDialog) { final JDialog d = (JDialog)w; d.getRootPane().setDefaultButton(okButton); d.setResizable(false); KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); ActionListener closeAction = new ActionListener() { public void actionPerformed(ActionEvent e) { d.setVisible(false); } }; d.getRootPane().registerKeyboardAction(closeAction, ks, JComponent.WHEN_IN_FOCUSED_WINDOW); } w.pack(); w.setLocation(WindowUtils.getPointForCentering(w)); } }
package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Cursor; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractListModel; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.JProgressBar; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.UIManager; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.auth.DefaultUserNameStore; import org.jdesktop.swingx.auth.LoginAdapter; import org.jdesktop.swingx.auth.LoginEvent; import org.jdesktop.swingx.auth.LoginListener; import org.jdesktop.swingx.auth.LoginService; import org.jdesktop.swingx.auth.PasswordStore; import org.jdesktop.swingx.auth.UserNameStore; import org.jdesktop.swingx.plaf.JXLoginPanelAddon; import org.jdesktop.swingx.plaf.LoginPanelUI; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.util.WindowUtils; /** * <p>JXLoginPanel is a JPanel that implements a Login dialog with * support for saving passwords supplied for future use in a secure * manner. It is intended to work with <strong>LoginService</strong> * and <strong>PasswordStore</strong> to implement the * authentication.</p> * * <p> In order to perform the authentication, <strong>JXLoginPanel</strong> * calls the <code>authenticate</code> method of the <strong>LoginService * </strong>. In order to perform the persistence of the password, * <strong>JXLoginPanel</strong> calls the put method of the * <strong>PasswordStore</strong> object that is supplied. If * the <strong>PasswordStore</strong> is <code>null</code>, then the password * is not saved. Similarly, if a <strong>PasswordStore</strong> is * supplied and the password is null, then the <strong>PasswordStore</strong> * will be queried for the password using the <code>get</code> method. * * @author Bino George * @author Shai Almog * @author rbair * @author Karl Schaefer */ public class JXLoginPanel extends JXImagePanel { /** * The Logger */ private static final Logger LOG = Logger.getLogger(JXLoginPanel.class.getName()); /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 3544949969896288564L; /** * UI Class ID */ public final static String uiClassID = "LoginPanelUI"; /** * Action key for an Action in the ActionMap that initiates the Login * procedure */ public static final String LOGIN_ACTION_COMMAND = "login"; /** * Action key for an Action in the ActionMap that cancels the Login * procedure */ public static final String CANCEL_LOGIN_ACTION_COMMAND = "cancel-login"; /** * The JXLoginPanel can attempt to save certain user information such as * the username, password, or both to their respective stores. * This type specifies what type of save should be performed. */ public static enum SaveMode {NONE, USER_NAME, PASSWORD, BOTH} /** * Returns the status of the login process */ public enum Status {NOT_STARTED, IN_PROGRESS, FAILED, CANCELLED, SUCCEEDED} /** * Used as a prefix when pulling data out of UIManager for i18n */ private static String CLASS_NAME = JXLoginPanel.class.getCanonicalName(); /** * The current login status for this panel */ private Status status = Status.NOT_STARTED; /** * An optional banner at the top of the panel */ private JXImagePanel banner; /** * Text that should appear on the banner */ private String bannerText; /** * Custom label allowing the developer to display some message to the user */ private JLabel messageLabel; /** * Shows an error message such as "user name or password incorrect" or * "could not contact server" or something like that if something * goes wrong */ private JLabel errorMessageLabel; /** * A Panel containing all of the input fields, check boxes, etc necessary * for the user to do their job. The items on this panel change whenever * the SaveMode changes, so this panel must be recreated at runtime if the * SaveMode changes. Thus, I must maintain this reference so I can remove * this panel from the content panel at runtime. */ private JXPanel loginPanel; /** * The panel on which the input fields, messageLabel, and errorMessageLabel * are placed. While the login thread is running, this panel is removed * from the dialog and replaced by the progressPanel */ private JXPanel contentPanel; /** * This is the area in which the name field is placed. That way it can toggle on the fly * between text field and a combo box depending on the situation, and have a simple * way to get the user name */ private NameComponent namePanel; /** * The password field presented allowing the user to enter their password */ private JPasswordField passwordField; /** * A combo box presenting the user with a list of servers to which they * may log in. This is an optional feature, which is only enabled if * the List of servers supplied to the JXLoginPanel has a length greater * than 1. */ private JComboBox serverCombo; /** * Check box presented if a PasswordStore is used, allowing the user to decide whether to * save their password */ private JCheckBox saveCB; /** * A special panel that displays a progress bar and cancel button, and * which notify the user of the login process, and allow them to cancel * that process. */ private JXPanel progressPanel; /** * A JLabel on the progressPanel that is used for informing the user * of the status of the login procedure (logging in..., cancelling login...) */ private JLabel progressMessageLabel; /** * The LoginService to use. This must be specified for the login dialog to operate. * If no LoginService is defined, a default login service is used that simply * allows all users access. This is useful for demos or prototypes where a proper login * server is not available. */ private LoginService loginService; /** * Optional: a PasswordStore to use for storing and retrieving passwords for a specific * user. */ private PasswordStore passwordStore; /** * Optional: a UserNameStore to use for storing user names and retrieving them */ private UserNameStore userNameStore; /** * A list of servers where each server is represented by a String. If the * list of Servers is greater than 1, then a combo box will be presented to * the user to choose from. If any servers are specified, the selected one * (or the only one if servers.size() == 1) will be passed to the LoginService */ private List<String> servers; /** * Whether to save password or username or both */ private SaveMode saveMode; /** * Tracks the cursor at the time that authentication was started, and restores to that * cursor after authentication ends, or is cancelled; */ private Cursor oldCursor; /** * The default login listener used by this panel. */ private LoginListener defaultLoginListener; /** * Creates a default JXLoginPanel instance */ static { LookAndFeelAddons.contribute(new JXLoginPanelAddon()); } /** * Popuplate UIDefaults with the localizable Strings we will use * in the Login panel. */ private void reinitLocales(Locale l) { ResourceBundle res = ResourceBundle.getBundle("org.jdesktop.swingx.auth.resources.resources", l); Enumeration<String> keys = res.getKeys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); UIManager.put(CLASS_NAME + "." + key, res.getString(key)); } setBannerText(UIManager.getString(CLASS_NAME + ".bannerString")); banner.setImage(createLoginBanner()); errorMessageLabel.setText(UIManager.getString(CLASS_NAME + ".errorMessage")); progressMessageLabel.setText(UIManager.getString(CLASS_NAME + ".pleaseWait")); recreateLoginPanel(); Window w = SwingUtilities.getWindowAncestor(this); if (w instanceof JXLoginFrame) { JXLoginFrame f = (JXLoginFrame) w; f.setTitle(UIManager.getString(CLASS_NAME + ".titleString")); for (Component c : f.getContentPane().getComponents()) { if (c instanceof JXBtnPanel) { JXBtnPanel p = (JXBtnPanel) c; p.getOk().setText(UIManager.getString(CLASS_NAME + ".loginString")); p.getCancel().setText(UIManager.getString(CLASS_NAME + ".cancelString")); int h = p.getOk().getPreferredSize().height; p.getOk().setPreferredSize(null); p.getCancel().setPreferredSize(null); int prefWidth = Math.max(p.getCancel().getPreferredSize().width, p.getOk().getPreferredSize().width); p.getCancel().setPreferredSize(new Dimension(prefWidth, h)); p.getOk().setPreferredSize(new Dimension(prefWidth, p.getOk().getPreferredSize().height)); p.invalidate(); } } } JLabel lbl = (JLabel) passwordField.getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManager.getString(CLASS_NAME + ".passwordString")); } lbl = (JLabel) namePanel.getComponent().getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManager.getString(CLASS_NAME + ".nameString")); } if (serverCombo != null) { lbl = (JLabel) serverCombo.getClientProperty("labeledBy"); if (lbl != null) { lbl.setText(UIManager.getString(CLASS_NAME + ".serverString")); } } saveCB.setText(UIManager.getString(CLASS_NAME + ".rememberPasswordString")); } /** * Create a {@code JXLoginPanel} that always accepts the user, never stores * passwords or user ids, and has no target servers. * <p> * This constructor should <i>NOT</i> be used in a real application. It is * provided for compliance to the bean specification and for use with visual * editors. */ public JXLoginPanel() { this(null); } /** * Create a {@code JXLoginPanel} with the specified {@code LoginService} * that does not store user ids or passwords and has no target servers. * * @param service * the {@code LoginService} to use for logging in */ public JXLoginPanel(LoginService service) { this(service, null, null); } /** * Create a {@code JXLoginPanel} with the specified {@code LoginService}, * {@code PasswordStore}, and {@code UserNameStore}, but without a server * list. * <p> * If you do not want to store passwords or user ids, those parameters can * be {@code null}. {@code SaveMode} is autoconfigured from passed in store * parameters. * * @param service * the {@code LoginService} to use for logging in * @param passwordStore * the {@code PasswordStore} to use for storing password * information * @param userStore * the {@code UserNameStore} to use for storing user information */ public JXLoginPanel(LoginService service, PasswordStore passwordStore, UserNameStore userStore) { this(service, passwordStore, userStore, null); } /** * Create a {@code JXLoginPanel} with the specified {@code LoginService}, * {@code PasswordStore}, {@code UserNameStore}, and server list. * <p> * If you do not want to store passwords or user ids, those parameters can * be {@code null}. {@code SaveMode} is autoconfigured from passed in store * parameters. * <p> * Setting the server list to {@code null} will unset all of the servers. * The server list is guaranteed to be non-{@code null}. * * @param service * the {@code LoginService} to use for logging in * @param passwordStore * the {@code PasswordStore} to use for storing password * information * @param userStore * the {@code UserNameStore} to use for storing user information * @param servers * a list of servers to authenticate against */ public JXLoginPanel(LoginService service, PasswordStore passwordStore, UserNameStore userStore, List<String> servers) { setLoginService(service); setPasswordStore(passwordStore); setUserNameStore(userStore); setServers(servers); //create the login and cancel actions, and add them to the action map getActionMap().put(LOGIN_ACTION_COMMAND, createLoginAction()); getActionMap().put(CANCEL_LOGIN_ACTION_COMMAND, createCancelAction()); //initialize the save mode if (passwordStore != null && userStore != null) { saveMode = SaveMode.BOTH; } else if (passwordStore != null) { saveMode = SaveMode.PASSWORD; } else if (userStore != null) { saveMode = SaveMode.USER_NAME; } else { saveMode = SaveMode.NONE; } updateUI(); //initLocales(getDefaultLocale()); initComponents(); } /** * {@inheritDoc} */ public LoginPanelUI getUI() { return (LoginPanelUI) super.getUI(); } /** * Sets the look and feel (L&F) object that renders this component. * * @param ui the LoginPanelUI L&F object * @see javax.swing.UIDefaults#getUI */ public void setUI(LoginPanelUI ui) { super.setUI(ui); } /** * Notification from the <code>UIManager</code> that the L&F has changed. * Replaces the current UI object with the latest version from the * <code>UIManager</code>. * * @see javax.swing.JComponent#updateUI */ @Override public void updateUI() { setUI((LoginPanelUI) LookAndFeelAddons.getUI(this, LoginPanelUI.class)); } /** * Returns the name of the L&F class that renders this component. * * @return the string {@link #uiClassID} * @see javax.swing.JComponent#getUIClassID * @see javax.swing.UIDefaults#getUI */ public String getUIClassID() { return uiClassID; } /** * Recreates the login panel, and replaces the current one with the new one */ protected void recreateLoginPanel() { contentPanel.remove(loginPanel); loginPanel = createLoginPanel(); loginPanel.setBorder(BorderFactory.createEmptyBorder(0, 36, 7, 11)); contentPanel.add(loginPanel, 1); } /** * Creates and returns a new LoginPanel, based on the SaveMode state of * the login panel. Whenever the SaveMode changes, the panel is recreated. * I do this rather than hiding/showing components, due to a cleaner * implementation (no invisible components, components are not sharing * locations in the LayoutManager, etc). */ private JXPanel createLoginPanel() { JXPanel loginPanel = new JXPanel(); //create the NameComponent if (saveMode == SaveMode.NONE) { namePanel = new SimpleNamePanel(); } else { namePanel = new ComboNamePanel(userNameStore); } JLabel nameLabel = new JLabel(UIManager.getString(CLASS_NAME + ".nameString")); nameLabel.setLabelFor(namePanel.getComponent()); //create the password component passwordField = new JPasswordField("", 15); JLabel passwordLabel = new JLabel(UIManager.getString(CLASS_NAME + ".passwordString")); passwordLabel.setLabelFor(passwordField); //create the server combo box if necessary JLabel serverLabel = new JLabel(UIManager.getString(CLASS_NAME + ".serverString")); if (servers.size() > 1) { serverCombo = new JComboBox(servers.toArray()); serverLabel.setLabelFor(serverCombo); } else { serverCombo = null; } //create the save check box. By default, it is not selected saveCB = new JCheckBox(UIManager.getString(CLASS_NAME + ".rememberPasswordString")); saveCB.setSelected(false); //TODO should get this from prefs!!! And, it should be based on the user //determine whether to show/hide the save check box based on the SaveMode saveCB.setVisible(saveMode == SaveMode.PASSWORD || saveMode == SaveMode.BOTH); loginPanel.setLayout(new GridBagLayout()); GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(0, 0, 5, 11); loginPanel.add(nameLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 5, 0); loginPanel.add(namePanel.getComponent(), gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(0, 0, 5, 11); loginPanel.add(passwordLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 5, 0); loginPanel.add(passwordField, gridBagConstraints); if (serverCombo != null) { gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.insets = new Insets(0, 0, 5, 11); loginPanel.add(serverLabel, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 1; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(0, 0, 5, 0); loginPanel.add(serverCombo, gridBagConstraints); gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(6, 0, 0, 0); loginPanel.add(saveCB, gridBagConstraints); } else { gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new Insets(6, 0, 0, 0); loginPanel.add(saveCB, gridBagConstraints); } return loginPanel; } /** * This method adds functionality to support bidi languages within this * component */ public void setComponentOrientation(ComponentOrientation orient) { // this if is used to avoid needless creations of the image if(orient != super.getComponentOrientation()) { super.setComponentOrientation(orient); banner.setImage(createLoginBanner()); progressPanel.applyComponentOrientation(orient); } } /** * Create all of the UI components for the login panel */ private void initComponents() { //create the default banner banner = new JXImagePanel(); setBannerText(UIManager.getString(CLASS_NAME + ".bannerString")); banner.setImage(createLoginBanner()); //create the default label messageLabel = new JLabel(" "); messageLabel.setOpaque(true); messageLabel.setFont(messageLabel.getFont().deriveFont(Font.BOLD)); //create the main components loginPanel = createLoginPanel(); //create the message and hyperlink and hide them errorMessageLabel = new JLabel(UIManager.getString(CLASS_NAME + ".errorMessage")); errorMessageLabel.setIcon(UIManager.getIcon("JXLoginDialog.error.icon")); errorMessageLabel.setVerticalTextPosition(SwingConstants.TOP); errorMessageLabel.setOpaque(true); errorMessageLabel.setBackground(new Color(255, 215, 215));//TODO get from UIManager errorMessageLabel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(errorMessageLabel.getBackground().darker()), BorderFactory.createEmptyBorder(5, 7, 5, 5))); //TODO get color from UIManager errorMessageLabel.setVisible(false); //aggregate the optional message label, content, and error label into //the contentPanel contentPanel = new JXPanel(new VerticalLayout()); messageLabel.setBorder(BorderFactory.createEmptyBorder(12, 12, 7, 11)); contentPanel.add(messageLabel); loginPanel.setBorder(BorderFactory.createEmptyBorder(0, 36, 7, 11)); contentPanel.add(loginPanel); errorMessageLabel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(0, 36, 0, 11, contentPanel.getBackground()), errorMessageLabel.getBorder())); contentPanel.add(errorMessageLabel); //create the progress panel progressPanel = new JXPanel(new GridBagLayout()); progressMessageLabel = new JLabel(UIManager.getString(CLASS_NAME + ".pleaseWait")); progressMessageLabel.setFont(progressMessageLabel.getFont().deriveFont(Font.BOLD)); //TODO get from UIManager JProgressBar pb = new JProgressBar(); pb.setIndeterminate(true); JButton cancelButton = new JButton(getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND)); progressPanel.add(progressMessageLabel, new GridBagConstraints(0, 0, 2, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(12, 12, 11, 11), 0, 0)); progressPanel.add(pb, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 24, 11, 7), 0, 0)); progressPanel.add(cancelButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 11, 11), 0, 0)); //layout the panel setLayout(new BorderLayout()); add(banner, BorderLayout.NORTH); add(contentPanel, BorderLayout.CENTER); } /** * Create and return an image to use for the Banner. This may be overridden * to return any image you like */ protected Image createLoginBanner() { return getUI() == null ? null : getUI().getBanner(); } /** * Create and return an Action for logging in */ protected Action createLoginAction() { return new LoginAction(this); } /** * Create and return an Action for canceling login */ protected Action createCancelAction() { return new CancelAction(this); } //TODO need to fire property change events!!! /** * @return Returns the saveMode. */ public SaveMode getSaveMode() { return saveMode; } /** * The save mode indicates whether the "save" password is checked by default. This method * makes no difference if the passwordStore is null. * * @param saveMode The saveMode to set either SAVE_NONE, SAVE_PASSWORD or SAVE_USERNAME */ public void setSaveMode(SaveMode saveMode) { if (this.saveMode != saveMode) { SaveMode oldMode = getSaveMode(); this.saveMode = saveMode; recreateLoginPanel(); firePropertyChange("saveMode", oldMode, getSaveMode()); } } /** * @return the List of servers */ public List<String> getServers() { return Collections.unmodifiableList(servers); } /** * Sets the list of servers. See the servers field javadoc for more info */ public void setServers(List<String> servers) { //only at startup if (this.servers == null) { this.servers = servers == null ? new ArrayList<String>() : servers; } else if (this.servers != servers) { List<String> old = getServers(); this.servers = servers == null ? new ArrayList<String>() : servers; recreateLoginPanel(); firePropertyChange("servers", old, getServers()); } } private LoginListener getDefaultLoginListener() { if (defaultLoginListener == null) { defaultLoginListener = new LoginListenerImpl(); } return defaultLoginListener; } /** * Sets the {@code LoginService} for this panel. Setting the login service * to {@code null} will actually set the service to use * {@code NullLoginService}. * * @param service * the service to set. If {@code service == null}, then a * {@code NullLoginService} is used. */ public void setLoginService(LoginService service) { LoginService oldService = getLoginService(); LoginService newService = service == null ? new NullLoginService() : service; //newService is guaranteed to be nonnull if (!newService.equals(oldService)) { if (oldService != null) { oldService.removeLoginListener(getDefaultLoginListener()); } loginService = newService; this.loginService.addLoginListener(getDefaultLoginListener()); firePropertyChange("loginService", oldService, getLoginService()); } } /** * Gets the <strong>LoginService</strong> for this panel. * * @return service service */ public LoginService getLoginService() { return loginService; } /** * Sets the <strong>PasswordStore</strong> for this panel. * * @param store PasswordStore */ public void setPasswordStore(PasswordStore store) { PasswordStore oldStore = getPasswordStore(); PasswordStore newStore = store == null ? new NullPasswordStore() : store; //newStore is guaranteed to be nonnull if (!newStore.equals(oldStore)) { passwordStore = newStore; firePropertyChange("passwordStore", oldStore, getPasswordStore()); } } /** * Gets the {@code UserNameStore} for this panel. * * @return the {@code UserNameStore} */ public UserNameStore getUserNameStore() { return userNameStore; } /** * Sets the user name store for this panel. * @param store */ public void setUserNameStore(UserNameStore store) { UserNameStore oldStore = getUserNameStore(); UserNameStore newStore = store == null ? new DefaultUserNameStore() : store; //newStore is guaranteed to be nonnull if (!newStore.equals(oldStore)) { userNameStore = newStore; firePropertyChange("userNameStore", oldStore, getUserNameStore()); } } /** * Gets the <strong>PasswordStore</strong> for this panel. * * @return store PasswordStore */ public PasswordStore getPasswordStore() { return passwordStore; } /** * Sets the <strong>User name</strong> for this panel. * * @param username User name */ public void setUserName(String username) { if (namePanel != null) { namePanel.setUserName(username); } } /** * Gets the <strong>User name</strong> for this panel. * @return the user name */ public String getUserName() { return namePanel == null ? null : namePanel.getUserName(); } /** * Sets the <strong>Password</strong> for this panel. * * @param password Password */ public void setPassword(char[] password) { passwordField.setText(new String(password)); } /** * Gets the <strong>Password</strong> for this panel. * * @return password Password */ public char[] getPassword() { return passwordField.getPassword(); } /** * Return the image used as the banner */ public Image getBanner() { return banner.getImage(); } /** * Set the image to use for the banner. If the {@code img} is {@code null}, * then no image will be displayed. * * @param img * the image to display */ public void setBanner(Image img) { // we do not expose the ImagePanel, so we will produce property change // events here Image oldImage = getBanner(); if (oldImage != img) { banner.setImage(img); firePropertyChange("banner", oldImage, getBanner()); } } /** * Set the text to use when creating the banner. If a custom banner image is * specified, then this is ignored. If {@code text} is {@code null}, then * no text is displayed. * * @param text * the text to display */ public void setBannerText(String text) { if (text == null) { text = ""; } if (!text.equals(this.bannerText)) { String oldText = this.bannerText; this.bannerText = text; //fix the login banner banner.setImage(createLoginBanner()); firePropertyChange("bannerText", oldText, text); } } /** * Returns text used when creating the banner */ public String getBannerText() { return bannerText; } /** * Returns the custom message for this login panel */ public String getMessage() { return messageLabel.getText(); } /** * Sets a custom message for this login panel */ public void setMessage(String message) { messageLabel.setText(message); } /** * Returns the error message for this login panel */ public String getErrorMessage() { return errorMessageLabel.getText(); } /** * Sets the error message for this login panel */ public void setErrorMessage(String errorMessage) { errorMessageLabel.setText(errorMessage); } /** * Returns the panel's status */ public Status getStatus() { return status; } /** * Change the status */ protected void setStatus(Status newStatus) { if (status != newStatus) { Status oldStatus = status; status = newStatus; firePropertyChange("status", oldStatus, newStatus); } } @Override public void setLocale(Locale l) { super.setLocale(l); reinitLocales(l); } /** * Initiates the login procedure. This method is called internally by * the LoginAction. This method handles cursor management, and actually * calling the LoginService's startAuthentication method. */ protected void startLogin() { oldCursor = getCursor(); try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); progressMessageLabel.setText(UIManager.getString(CLASS_NAME + ".pleaseWait")); String name = getUserName(); char[] password = getPassword(); String server = servers.size() == 1 ? servers.get(0) : serverCombo == null ? null : (String)serverCombo.getSelectedItem(); loginService.startAuthentication(name, password, server); } catch(Exception ex) { //The status is set via the loginService listener, so no need to set //the status here. Just log the error. LOG.log(Level.WARNING, "Authentication exception while logging in", ex); } finally { setCursor(oldCursor); } } /** * Cancels the login procedure. Handles cursor management and interfacing * with the LoginService's cancelAuthentication method */ protected void cancelLogin() { progressMessageLabel.setText(UIManager.getString(CLASS_NAME + ".cancelWait")); getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).setEnabled(false); loginService.cancelAuthentication(); setCursor(oldCursor); } /** * TODO */ protected void savePassword() { if (saveCB.isSelected() && (saveMode == SaveMode.BOTH || saveMode == SaveMode.PASSWORD) && passwordStore != null) { passwordStore.set(getUserName(),getLoginService().getServer(),getPassword()); } } /* For Login (initiated in LoginAction): 0) set the status 1) Immediately disable the login action 2) Immediately disable the close action (part of enclosing window) 3) initialize the progress pane a) enable the cancel login action b) set the message text 4) hide the content pane, show the progress pane When cancelling (initiated in CancelAction): 0) set the status 1) Disable the cancel login action 2) Change the message text on the progress pane When cancel finishes (handled in LoginListener): 0) set the status 1) hide the progress pane, show the content pane 2) enable the close action (part of enclosing window) 3) enable the login action When login fails (handled in LoginListener): 0) set the status 1) hide the progress pane, show the content pane 2) enable the close action (part of enclosing window) 3) enable the login action 4) Show the error message 5) resize the window (part of enclosing window) When login succeeds (handled in LoginListener): 0) set the status 1) close the dialog/frame (part of enclosing window) */ /** * Listener class to track state in the LoginService */ protected class LoginListenerImpl extends LoginAdapter { public void loginSucceeded(LoginEvent source) { //save the user names and passwords String userName = namePanel.getUserName(); savePassword(); if ((getSaveMode() == SaveMode.USER_NAME || getSaveMode() == SaveMode.BOTH) && userName != null && !userName.trim().equals("")) { userNameStore.addUserName(userName); userNameStore.saveUserNames(); } setStatus(Status.SUCCEEDED); } public void loginStarted(LoginEvent source) { getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(false); getActionMap().get(CANCEL_LOGIN_ACTION_COMMAND).setEnabled(true); remove(contentPanel); add(progressPanel, BorderLayout.CENTER); revalidate(); repaint(); setStatus(Status.IN_PROGRESS); } public void loginFailed(LoginEvent source) { remove(progressPanel); add(contentPanel, BorderLayout.CENTER); getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(true); errorMessageLabel.setVisible(true); revalidate(); repaint(); setStatus(Status.FAILED); } public void loginCanceled(LoginEvent source) { remove(progressPanel); add(contentPanel, BorderLayout.CENTER); getActionMap().get(LOGIN_ACTION_COMMAND).setEnabled(true); errorMessageLabel.setVisible(false); revalidate(); repaint(); setStatus(Status.CANCELLED); } } /** * Action that initiates a login procedure. Delegates to JXLoginPanel.startLogin */ private static final class LoginAction extends AbstractActionExt { private JXLoginPanel panel; public LoginAction(JXLoginPanel p) { super(UIManager.getString(CLASS_NAME + ".loginString"), LOGIN_ACTION_COMMAND); this.panel = p; } public void actionPerformed(ActionEvent e) { panel.startLogin(); } public void itemStateChanged(ItemEvent e) {} } /** * Action that cancels the login procedure. */ private static final class CancelAction extends AbstractActionExt { private JXLoginPanel panel; public CancelAction(JXLoginPanel p) { super(UIManager.getString(CLASS_NAME + ".cancelLogin"), CANCEL_LOGIN_ACTION_COMMAND); this.panel = p; this.setEnabled(false); } public void actionPerformed(ActionEvent e) { panel.cancelLogin(); } public void itemStateChanged(ItemEvent e) {} } /** * Simple login service that allows everybody to login. This is useful in demos and allows * us to avoid having to check for LoginService being null */ private static final class NullLoginService extends LoginService { public boolean authenticate(String name, char[] password, String server) throws Exception { return true; } public boolean equals(Object obj) { return obj instanceof NullLoginService; } public int hashCode() { return 7; } } /** * Simple PasswordStore that does not remember passwords */ private static final class NullPasswordStore extends PasswordStore { private static final char[] EMPTY = new char[0]; public boolean set(String username, String server, char[] password) { //null op return false; } public char[] get(String username, String server) { return EMPTY; } public boolean equals(Object obj) { return obj instanceof NullPasswordStore; } public int hashCode() { return 7; } } public static interface NameComponent { public String getUserName(); public void setUserName(String userName); public JComponent getComponent(); } /** * If a UserNameStore is not used, then this text field is presented allowing the user * to simply enter their user name */ public static final class SimpleNamePanel extends JTextField implements NameComponent { public SimpleNamePanel() { super("", 15); } public String getUserName() { return getText(); } public void setUserName(String userName) { setText(userName); } public JComponent getComponent() { return this; } } /** * If a UserNameStore is used, then this combo box is presented allowing the user * to select a previous login name, or type in a new login name */ public static final class ComboNamePanel extends JComboBox implements NameComponent { private UserNameStore userNameStore; public ComboNamePanel(UserNameStore userNameStore) { super(); this.userNameStore = userNameStore; setModel(new NameComboBoxModel()); setEditable(true); } public String getUserName() { Object item = getModel().getSelectedItem(); return item == null ? null : item.toString(); } public void setUserName(String userName) { getModel().setSelectedItem(userName); } public void setUserNames(String[] names) { setModel(new DefaultComboBoxModel(names)); } public JComponent getComponent() { return this; } private final class NameComboBoxModel extends AbstractListModel implements ComboBoxModel { private Object selectedItem; public void setSelectedItem(Object anItem) { selectedItem = anItem; fireContentsChanged(this, -1, -1); } public Object getSelectedItem() { return selectedItem; } public Object getElementAt(int index) { return userNameStore.getUserNames()[index]; } public int getSize() { return userNameStore.getUserNames().length; } } } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc) { return showLoginDialog(parent, svc, null, null); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc, PasswordStore ps, UserNameStore us) { return showLoginDialog(parent, svc, ps, us, null); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, LoginService svc, PasswordStore ps, UserNameStore us, List<String> servers) { JXLoginPanel panel = new JXLoginPanel(svc, ps, us, servers); return showLoginDialog(parent, panel); } /** * Shows a login dialog. This method blocks. * @return The status of the login operation */ public static Status showLoginDialog(Component parent, JXLoginPanel panel) { Window w = WindowUtils.findWindow(parent); JXLoginDialog dlg = null; if (w == null) { dlg = new JXLoginDialog((Frame)null, panel); } else if (w instanceof Dialog) { dlg = new JXLoginDialog((Dialog)w, panel); } else if (w instanceof Frame) { dlg = new JXLoginDialog((Frame)w, panel); } else { throw new AssertionError("Shouldn't be able to happen"); } dlg.setVisible(true); return dlg.getStatus(); } /** * Shows a login frame. A JFrame is not modal, and thus does not block */ public static JXLoginFrame showLoginFrame(LoginService svc) { return showLoginFrame(svc, null, null); } public static JXLoginFrame showLoginFrame(LoginService svc, PasswordStore ps, UserNameStore us) { return showLoginFrame(svc, ps, us, null); } public static JXLoginFrame showLoginFrame(LoginService svc, PasswordStore ps, UserNameStore us, List<String> servers) { JXLoginPanel panel = new JXLoginPanel(svc, ps, us, servers); return showLoginFrame(panel); } public static JXLoginFrame showLoginFrame(JXLoginPanel panel) { return new JXLoginFrame(panel); } public static final class JXLoginDialog extends JDialog { private JXLoginPanel panel; public JXLoginDialog(Frame parent, JXLoginPanel p) { super(parent, true); init(p); } public JXLoginDialog(Dialog parent, JXLoginPanel p) { super(parent, true); init(p); } protected void init(JXLoginPanel p) { setTitle(UIManager.getString(CLASS_NAME + ".titleString")); this.panel = p; initWindow(this, panel); } public JXLoginPanel.Status getStatus() { return panel.getStatus(); } } public static final class JXLoginFrame extends JFrame { private JXLoginPanel panel; public JXLoginFrame(JXLoginPanel p) { super(UIManager.getString(CLASS_NAME + ".titleString")); this.panel = p; initWindow(this, panel); } public JXLoginPanel.Status getStatus() { return panel.getStatus(); } public JXLoginPanel getPanel() { return panel; } } /** * Utility method for initializing a Window for displaying a LoginDialog. * This is particularly useful because the differences between JFrame and * JDialog are so minor. * * Note: This method is package private for use by JXLoginDialog (proper, * not JXLoginPanel.JXLoginDialog). Change to private if JXLoginDialog is * removed. */ static void initWindow(final Window w, final JXLoginPanel panel) { w.setLayout(new BorderLayout()); w.add(panel, BorderLayout.CENTER); JButton okButton = new JButton(panel.getActionMap().get(LOGIN_ACTION_COMMAND)); final JButton cancelButton = new JButton(UIManager.getString(CLASS_NAME + ".cancelString")); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //change panel status to cancelled! panel.status = JXLoginPanel.Status.CANCELLED; w.setVisible(false); w.dispose(); } }); panel.addPropertyChangeListener("status", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { JXLoginPanel.Status status = (JXLoginPanel.Status)evt.getNewValue(); switch (status) { case NOT_STARTED: break; case IN_PROGRESS: cancelButton.setEnabled(false); break; case CANCELLED: cancelButton.setEnabled(true); w.pack(); break; case FAILED: cancelButton.setEnabled(true); w.pack(); break; case SUCCEEDED: w.setVisible(false); w.dispose(); } for (PropertyChangeListener l : w.getPropertyChangeListeners("status")) { PropertyChangeEvent pce = new PropertyChangeEvent(w, "status", evt.getOldValue(), evt.getNewValue()); l.propertyChange(pce); } } }); cancelButton.setText(UIManager.getString(CLASS_NAME + ".cancelString")); okButton.setText(UIManager.getString(CLASS_NAME + ".loginString")); int prefWidth = Math.max(cancelButton.getPreferredSize().width, okButton.getPreferredSize().width); cancelButton.setPreferredSize(new Dimension(prefWidth, okButton.getPreferredSize().height)); okButton.setPreferredSize(new Dimension(prefWidth, okButton.getPreferredSize().height)); JXPanel buttonPanel = new JXBtnPanel(new GridBagLayout(), okButton, cancelButton); buttonPanel.add(okButton, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_END, GridBagConstraints.NONE, new Insets(17, 12, 11, 5), 0, 0)); buttonPanel.add(cancelButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_END, GridBagConstraints.NONE, new Insets(17, 0, 11, 11), 0, 0)); w.add(buttonPanel, BorderLayout.SOUTH); w.addWindowListener(new WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { panel.cancelLogin(); } }); if (w instanceof JFrame) { final JFrame f = (JFrame)w; f.getRootPane().setDefaultButton(okButton); f.setResizable(false); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); ActionListener closeAction = new ActionListener() { public void actionPerformed(ActionEvent e) { f.setVisible(false); f.dispose(); } }; f.getRootPane().registerKeyboardAction(closeAction, ks, JComponent.WHEN_IN_FOCUSED_WINDOW); } else if (w instanceof JDialog) { final JDialog d = (JDialog)w; d.getRootPane().setDefaultButton(okButton); d.setResizable(false); KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); ActionListener closeAction = new ActionListener() { public void actionPerformed(ActionEvent e) { d.setVisible(false); } }; d.getRootPane().registerKeyboardAction(closeAction, ks, JComponent.WHEN_IN_FOCUSED_WINDOW); } w.pack(); w.setLocation(WindowUtils.getPointForCentering(w)); } private static class JXBtnPanel extends JXPanel { private JButton cancel; private JButton ok; public JXBtnPanel(GridBagLayout layout, JButton okButton, JButton cancelButton) { super(layout); this.ok = okButton; this.cancel = cancelButton; } /** * @return the cancel */ public JButton getCancel() { return cancel; } /** * @return the ok */ public JButton getOk() { return ok; } } }
package org.jaxen.test; import junit.framework.TestCase; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.jaxen.JaxenException; import org.jaxen.SimpleVariableContext; import org.jaxen.XPath; import org.jaxen.dom.DOMXPath; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; public class DOMXPathTest extends TestCase { private static final String BASIC_XML = "xml/basic.xml"; private Document doc; private DocumentBuilderFactory factory; public DOMXPathTest(String name) { super( name ); } public void setUp() throws ParserConfigurationException { factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); doc = factory.newDocumentBuilder().newDocument(); } public void testConstruction() throws JaxenException { DOMXPath xpath = new DOMXPath( "/foo/bar/baz" ); assertEquals("/foo/bar/baz", xpath.toString()); } public void testJaxen193() throws JaxenException { DOMXPath xpath = new DOMXPath( "count(/*/@*)" ); List result = xpath.selectNodes(doc); assertEquals(0, result.size()); } // see JAXEN-105 public void testConsistentNamespaceDeclarations() throws JaxenException { Element root = doc.createElement("root"); doc.appendChild(root); Element child = doc.createElementNS("http: root.appendChild(child); // different prefix child.setAttributeNS("http: XPath xpath = new DOMXPath("//namespace::node()"); List result = xpath.selectNodes(doc); assertEquals(4, result.size()); } // see JAXEN-105 public void testInconsistentNamespaceDeclarations() throws JaxenException { Element root = doc.createElement("root"); doc.appendChild(root); Element child = doc.createElementNS("http: root.appendChild(child); // same prefix child.setAttributeNS("http: XPath xpath = new DOMXPath("//namespace::node()"); List result = xpath.selectNodes(doc); assertEquals(3, result.size()); } // see JAXEN-105 public void testIntrinsicNamespaceDeclarationOfElementBeatsContradictoryXmlnsPreAttr() throws JaxenException { Element root = doc.createElement("root"); doc.appendChild(root); Element child = doc.createElementNS("http: root.appendChild(child); // same prefix child.setAttributeNS("http: XPath xpath = new DOMXPath("//namespace::node()[name(.)='foo']"); List result = xpath.selectNodes(doc); assertEquals(1, result.size()); Node node = (Node) result.get(0); assertEquals("http: } // see JAXEN-105 public void testIntrinsicNamespaceDeclarationOfAttrBeatsContradictoryXmlnsPreAttr() throws JaxenException { Element root = doc.createElement("root"); doc.appendChild(root); root.setAttributeNS("http: // same prefix, different namespace root.setAttributeNS("http: XPath xpath = new DOMXPath("//namespace::node()[name(.)='foo']"); List result = xpath.selectNodes(doc); assertEquals(1, result.size()); Node node = (Node) result.get(0); assertEquals("http: } // see JAXEN-105 public void testIntrinsicNamespaceDeclarationOfElementBeatsContradictoryIntrinsicNamespaceOfAttr() throws JaxenException { Element root = doc.createElementNS("http: doc.appendChild(root); // same prefix root.setAttributeNS("http: XPath xpath = new DOMXPath("//namespace::node()[name(.)='pre']"); List result = xpath.selectNodes(doc); assertEquals(1, result.size()); Node node = (Node) result.get(0); assertEquals("http: } // Jaxen-54 public void testUpdateDOMNodesReturnedBySelectNodes() throws JaxenException { Element root = doc.createElementNS("http: doc.appendChild(root); root.appendChild(doc.createComment("data")); DOMXPath xpath = new DOMXPath( "//comment()" ); List results = xpath.selectNodes(doc); Node backroot = (Node) results.get(0); backroot.setNodeValue("test"); assertEquals("test", backroot.getNodeValue()); } public void testSelection() throws JaxenException, ParserConfigurationException, SAXException, IOException { XPath xpath = new DOMXPath( "/foo/bar/baz" ); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse( BASIC_XML ); List results = xpath.selectNodes( document ); assertEquals( 3, results.size() ); Iterator iter = results.iterator(); assertEquals( "baz", ((Element)iter.next()).getLocalName() ); assertEquals( "baz", ((Element)iter.next()).getLocalName() ); assertEquals( "baz", ((Element)iter.next()).getLocalName() ); assertTrue( ! iter.hasNext() ); } // Jaxen-22 public void testPrecedingAxisWithPositionalPredicate() throws JaxenException, ParserConfigurationException, SAXException, IOException { XPath xpath = new DOMXPath( "//c/preceding::*[1][name()='d']" ); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse( "xml/web2.xml" ); List result = xpath.selectNodes(document); assertEquals(1, result.size()); } // Jaxen-22 public void testJaxen22() throws JaxenException, ParserConfigurationException, SAXException, IOException { XPath xpath = new DOMXPath( "name(//c/preceding::*[1])" ); DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse("xml/web2.xml"); Object result = xpath.evaluate(doc); assertEquals("d", result); } public void testJaxen207() throws JaxenException { XPath xpath = new DOMXPath( "contains($FinResp, \"NS_Payables_Associate\") or" + "contains($FinResp, \"NS_Payables_Manager\") or" + "contains($FinResp, \"NS_Payment_Processing\") or" + "contains($FinResp, \"NS_Vendor_Maintenance\") or" + "contains($FinResp, \"NS_IB_Receivables_Manager\") or" + "contains($FinResp, \"NS_IB_Receivables_User\") or" + "contains($FinResp, \"NS_Receivables_Manager\") or" + "contains($FinResp, \"NS_Receivables_User\") or" + "contains($FinResp, \"NS_Cash_Management_User\") or" + "contains($FinResp, \"NS_Cost_Management\") or" + "contains($FinResp, \"NS_Fixed_Assets_Manager\") or" + "contains($FinResp, \"NS_Fixed_Asset_User\") or" + "contains($FinResp, \"NS_General_Ledger_Inquiry\") or" + "contains($FinResp, \"NS_General_Ledger_User\") or" + "contains($FinResp, \"NS_General_Ledger_Supervisor\") or" + "contains($FinResp, \"NS_IB_General_Ledger_User\") or" + "contains($FinResp, \"NS_IB_Oracle_Web_ADI\") or" + "contains($FinResp, \"NS_Oracle_Web_ADI\") or" + "contains($FinResp, \"NS_CRM_Resource_Manager\") or" + "contains($FinResp, \"NS_Distributor_Manager\") or" + "contains($FinResp, \"NS_OIC_User\") or" + "contains($FinResp, \" NS_Operations_Buyer\") or" + "contains($FinResp, \"NS_Purchasing_Buyer\") or" + "contains($FinResp, \"NS_Vendor_Maintenance\") or " + "contains($FinResp, \"SL_Payables_Manager\") or" + "contains($FinResp, \"SL_Payables_Super_User\") or" + "contains($FinResp, \"SL_Payment_Processing\") or" + "contains($FinResp, \"SL_Vendor_Maintenance\") or" + "contains($InvResp, \"SL_Inventory_Super_User\") or" + "contains($FinResp, \"\") or" + "contains($FinResp, \"SL_Receivables_Supervisor\") or" + "contains($FinResp, \"SL_Receivables_User\") or" + "contains($FinResp, \"NS_Cost_Management_Inquiry\") or" + "contains($FinResp, \"SL_Fixed_Asset_User\") or" + "contains($FinResp, \"SL_Fixed_Assets_Manager\") or" + "contains($FinResp, \"SL_General_Ledger_Inquiry\") or" + "contains($FinResp, \"SL_General_Ledger_Supervisor\") or" + "contains($FinResp, \"SL_General_Ledger_User\") or" + "contains($FinResp, \"SL_Oracle_Web_ADI\") or" + "contains($FinResp, \"SL_Buyer\") or" + "contains($FinResp, \"SL_Purchasing_Inquiry\") or" + "contains($FinResp, \"SL_Payables_Manager\") or" + "contains($FinResp, \"SL_Payables_Super_User\") or" + "contains($FinResp, \"SL_Payment_Processing\") or" + "contains($FinResp, \"SL_Vendor_Maintenance\") or" + "contains($InvResp, \"SL_Inventory_Super_User\") or" + "contains($FinResp, \"\") or" + "contains($FinResp, \"SL_Receivables_Supervisor\") or" + "contains($FinResp, \"SL_Receivables_User\") or" + "contains($FinResp, \"NS_Cost_Management_Inquiry\") or" + "contains($FinResp, \"SL_Fixed_Asset_User\") or" + "contains($FinResp, \"SL_Fixed_Assets_Manager\") or" + "contains($FinResp, \"SL_General_Ledger_Inquiry\") or" + "contains($FinResp, \"SL_General_Ledger_Supervisor\") or" + "contains($FinResp, \"SL_General_Ledger_User\") or" + "contains($FinResp, \"SL_Oracle_Web_ADI\") or" + "contains($FinResp, \"SL_Buyer\") or" + "contains($FinResp, \"SL_Purchasing_Inquiry\")"); } public void testImplictCastFromTextInARelationalExpression() throws JaxenException, ParserConfigurationException, SAXException, IOException { XPath implicitCast = new DOMXPath("//lat[(text() >= 37)]"); XPath explicitCast = new DOMXPath("//lat[(number(text()) >= 37)]"); DocumentBuilder builder = factory.newDocumentBuilder(); ByteArrayInputStream in = new ByteArrayInputStream("<geo><lat>39</lat></geo>".getBytes("UTF-8")); Document document = builder.parse(in); List result = explicitCast.selectNodes(document); assertEquals(1, result.size()); result = implicitCast.selectNodes(document); assertEquals(1, result.size()); } public void testImplictCastFromCommentInARelationalExpression() throws JaxenException, ParserConfigurationException, SAXException, IOException { XPath implicitCast = new DOMXPath("//lat[(comment() >= 37)]"); XPath explicitCast = new DOMXPath("//lat[(number(comment()) >= 37)]"); DocumentBuilder builder = factory.newDocumentBuilder(); ByteArrayInputStream in = new ByteArrayInputStream("<geo><lat></lat></geo>".getBytes("UTF-8")); Document document = builder.parse(in); List result = explicitCast.selectNodes(document); assertEquals(1, result.size()); result = implicitCast.selectNodes(document); assertEquals(1, result.size()); } public void testImplictCastFromProcessingInstructionInARelationalExpression() throws JaxenException, ParserConfigurationException, SAXException, IOException { XPath implicitCast = new DOMXPath("//lat[(processing-instruction() >= 37)]"); XPath explicitCast = new DOMXPath("//lat[(number(processing-instruction()) >= 37)]"); DocumentBuilder builder = factory.newDocumentBuilder(); ByteArrayInputStream in = new ByteArrayInputStream("<geo><lat><?test 39?></lat></geo>".getBytes("UTF-8")); Document document = builder.parse(in); List result = explicitCast.selectNodes(document); assertEquals(1, result.size()); result = implicitCast.selectNodes(document); assertEquals(1, result.size()); } public void testPrecedingAxisInDocumentOrder() throws JaxenException { XPath xpath = new DOMXPath( "preceding::*" ); Element root = doc.createElement("root"); doc.appendChild(root); Element a = doc.createElement("a"); root.appendChild(a); Element b = doc.createElement("b"); root.appendChild(b); Element c = doc.createElement("c"); a.appendChild(c); List result = xpath.selectNodes(b); assertEquals(2, result.size()); assertEquals(a, result.get(0)); assertEquals(c, result.get(1)); } }
package org.chai.kevin.form; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.chai.kevin.LanguageService; import org.chai.kevin.Period; import org.chai.kevin.Translation; import org.chai.kevin.data.RawDataElement; import org.chai.kevin.data.Type; import org.chai.kevin.data.Type.ValuePredicate; import org.chai.kevin.form.FormValidationService.ValidatableLocator; import org.chai.kevin.location.DataLocation; import org.chai.kevin.value.RawDataElementValue; import org.chai.kevin.value.Value; import org.chai.kevin.value.ValueService; @Entity(name = "FormElement") @Table(name = "dhsst_form_element") @Inheritance(strategy = InheritanceType.JOINED) public class FormElement { protected Long id; private RawDataElement rawDataElement; private List<FormValidationRule> validationRules = new ArrayList<FormValidationRule>(); private Map<String, Translation> headers = new HashMap<String, Translation>(); public FormElement() { super(); } @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } @ManyToOne(targetEntity = RawDataElement.class, optional = false) @JoinColumn(nullable = false) public RawDataElement getRawDataElement() { return rawDataElement; } public void setRawDataElement(RawDataElement rawDataElement) { this.rawDataElement = rawDataElement; } @OneToMany(mappedBy = "formElement", targetEntity = FormValidationRule.class, orphanRemoval=true) public List<FormValidationRule> getValidationRules() { return validationRules; } public void setValidationRules(List<FormValidationRule> validationRules) { this.validationRules = validationRules; } public void addValidationRule(FormValidationRule validationRule) { validationRule.setFormElement(this); validationRules.add(validationRule); } @ElementCollection(targetClass = Translation.class) @JoinTable(name = "dhsst_form_element_headers") public Map<String, Translation> getHeaders() { return headers; } public void setHeaders(Map<String, Translation> headers) { this.headers = headers; } @Transient public String getDescriptionTemplate() { return "/entity/form/formElementDescription"; } @Transient public String getLabel(LanguageService languageService) { return languageService.getText(getRawDataElement().getNames()); } @Transient public <T extends FormElement> void deepCopy(T copy, FormCloner cloner) { copy.setRawDataElement(getRawDataElement()); } @Transient public void copyRules(FormElement copy, FormCloner cloner) { for (FormValidationRule rule : getValidationRules()) { copy.getValidationRules().add(cloner.getValidationRule(rule)); } for (Entry<String, Translation> entry : getHeaders().entrySet()) { copy.getHeaders().put(entry.getKey(), entry.getValue()); } } @Transient public void validate(DataLocation dataLocation, ElementCalculator calculator) { Set<FormValidationRule> validationRules = calculator.getFormElementService().searchValidationRules(this, dataLocation.getType()); for (FormValidationRule validationRule : validationRules) { validationRule.evaluate(dataLocation, calculator); } } @Transient public void executeSkip(DataLocation dataLocation, ElementCalculator calculator) { Set<FormSkipRule> skipRules = calculator.getFormElementService().searchSkipRules(this); for (FormSkipRule skipRule: skipRules) { skipRule.evaluate(dataLocation, calculator); } } @Transient protected Value getValue(DataLocation dataLocation, final ElementSubmitter submitter) { FormEnteredValue enteredValue = submitter.getFormElementService().getOrCreateFormEnteredValue(dataLocation, this); final Type type = enteredValue.getType(); Value valueToSave = new Value(enteredValue.getValue().getJsonValue()); type.transformValue(valueToSave, new ValuePredicate() { @Override public boolean transformValue(Value currentValue, Type currentType, String currentPrefix) { return submitter.transformValue(currentValue, currentType, currentPrefix); } }); return valueToSave; } @Transient public void submit(DataLocation dataLocation, Period period, ElementSubmitter submitter) { Value valueToSave = getValue(dataLocation, submitter); RawDataElementValue rawDataElementValue = submitter.getValueService().getDataElementValue(getRawDataElement(), dataLocation, period); if (rawDataElementValue == null) { rawDataElementValue = new RawDataElementValue(getRawDataElement(), dataLocation, period, null); } rawDataElementValue.setValue(valueToSave); submitter.getValueService().save(rawDataElementValue); } public static class ElementSubmitter { private FormElementService formElementService; private ValueService valueService; public ElementSubmitter(FormElementService formElementService, ValueService valueService) { this.formElementService = formElementService; this.valueService = valueService; } public boolean transformValue(Value currentValue, Type currentType, String currentPrefix) { // if it is skipped we return NULL if (currentValue.getAttribute("skipped") != null) currentValue.setJsonValue(Value.NULL_INSTANCE().getJsonValue()); // we remove the attributes currentValue.setAttribute("skipped", null); currentValue.setAttribute("invalid", null); currentValue.setAttribute("warning", null); return true; } public ValueService getValueService() { return valueService; } public FormElementService getFormElementService() { return formElementService; } } public static class ElementCalculator { private FormValidationService formValidationService; private FormElementService formElementService; private ValidatableLocator validatableLocator; private List<FormEnteredValue> affectedValues; public ElementCalculator(List<FormEnteredValue> affectedValues, FormValidationService formValidationService, FormElementService formElementService, ValidatableLocator validatableLocator) { this.formElementService = formElementService; this.formValidationService = formValidationService; this.validatableLocator = validatableLocator; this.affectedValues = affectedValues; } public List<FormEnteredValue> getAffectedValues() { return affectedValues; } public ValidatableLocator getValidatableLocator() { return validatableLocator; } public FormElementService getFormElementService() { return formElementService; } public FormValidationService getFormValidationService() { return formValidationService; } public void addAffectedValue(FormEnteredValue value) { this.affectedValues.add(value); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof FormElement)) return false; FormElement other = (FormElement) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
package org.jdesktop.swingx; import java.awt.Component; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Enumeration; import java.util.EventObject; import java.util.List; import java.util.logging.Logger; import javax.swing.ActionMap; import javax.swing.DefaultListSelectionModel; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.JTree; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.event.TreeSelectionListener; import javax.swing.event.TreeWillExpandListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeSelectionModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.FilterPipeline; import org.jdesktop.swingx.decorator.SelectionMapper; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; import org.jdesktop.swingx.treetable.TreeTableCellEditor; import org.jdesktop.swingx.treetable.TreeTableModel; public class JXTreeTable extends JXTable { @SuppressWarnings("unused") private static final Logger LOG = Logger.getLogger(JXTreeTable.class .getName()); /** * Key for clientProperty to decide whether to apply hack around #168-jdnc. */ public static final String DRAG_HACK_FLAG_KEY = "treeTable.dragHackFlag"; /** * Renderer used to render cells within the * {@link #isHierarchical(int) hierarchical} column. * renderer extends JXTree and implements TableCellRenderer */ private TreeTableCellRenderer renderer; /** * Editor used to edit cells within the * {@link #isHierarchical(int) hierarchical} column. */ private TreeTableCellEditor hierarchicalEditor; private TreeTableHacker treeTableHacker; private boolean consumedOnPress; /** * Constructs a JXTreeTable using a * {@link org.jdesktop.swingx.treetable.DefaultTreeTableModel}. */ public JXTreeTable() { this(new DefaultTreeTableModel()); } /** * Constructs a JXTreeTable using the specified * {@link org.jdesktop.swingx.treetable.TreeTableModel}. * * @param treeModel model for the JXTreeTable */ public JXTreeTable(TreeTableModel treeModel) { this(new JXTreeTable.TreeTableCellRenderer(treeModel)); } /** * Constructs a <code>JXTreeTable</code> using the specified * {@link org.jdesktop.swingx.JXTreeTable.TreeTableCellRenderer}. * * @param renderer * cell renderer for the tree portion of this JXTreeTable * instance. */ private JXTreeTable(TreeTableCellRenderer renderer) { // To avoid unnecessary object creation, such as the construction of a // DefaultTableModel, it is better to invoke // super(TreeTableModelAdapter) directly, instead of first invoking // super() followed by a call to setTreeTableModel(TreeTableModel). // Adapt tree model to table model before invoking super() super(new TreeTableModelAdapter(renderer)); // renderer-related initialization init(renderer); // private method initActions(); // disable sorting super.setSortable(false); // no grid setShowGrid(false, false); hierarchicalEditor = new TreeTableCellEditor(renderer); // // No grid. // setShowGrid(false); // superclass default is "true" // // Default intercell spacing // setIntercellSpacing(spacing); // for both row margin and column margin } /** * Initializes this JXTreeTable and permanently binds the specified renderer * to it. * * @param renderer private tree/renderer permanently and exclusively bound * to this JXTreeTable. */ private void init(TreeTableCellRenderer renderer) { this.renderer = renderer; assert ((TreeTableModelAdapter) getModel()).tree == this.renderer; // Force the JTable and JTree to share their row selection models. ListToTreeSelectionModelWrapper selectionWrapper = new ListToTreeSelectionModelWrapper(); // JW: when would that happen? if (renderer != null) { renderer.bind(this); // IMPORTANT: link back! renderer.setSelectionModel(selectionWrapper); } // adjust the tree's rowHeight to this.rowHeight adjustTreeRowHeight(getRowHeight()); setSelectionModel(selectionWrapper.getListSelectionModel()); // propagate the lineStyle property to the renderer PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { JXTreeTable.this.renderer.putClientProperty(evt.getPropertyName(), evt.getNewValue()); } }; addPropertyChangeListener("JTree.lineStyle", l); } private void initActions() { // Register the actions that this class can handle. ActionMap map = getActionMap(); map.put("expand-all", new Actions("expand-all")); map.put("collapse-all", new Actions("collapse-all")); } /** * A small class which dispatches actions. * TODO: Is there a way that we can make this static? */ private class Actions extends UIAction { Actions(String name) { super(name); } public void actionPerformed(ActionEvent evt) { if ("expand-all".equals(getName())) { expandAll(); } else if ("collapse-all".equals(getName())) { collapseAll(); } } } /** * overridden to do nothing. * * TreeTable is not sortable by default, because * Sorters/Filters currently don't work properly. * */ @Override public void setSortable(boolean sortable) { // no-op } /** * overridden to do nothing. * * TreeTable is not sortable by default, because * Sorters/Filters currently don't work properly. * */ @Override public void setFilters(FilterPipeline pipeline) { } /** * Overriden to invoke repaint for the particular location if * the column contains the tree. This is done as the tree editor does * not fill the bounds of the cell, we need the renderer to paint * the tree in the background, and then draw the editor over it. * You should not need to call this method directly. <p> * * Additionally, there is tricksery involved to expand/collapse * the nodes. * * {@inheritDoc} */ @Override public boolean editCellAt(int row, int column, EventObject e) { getTreeTableHacker().hitHandleDetectionFromEditCell(column, e); // RG: Fix Issue 49! boolean canEdit = super.editCellAt(row, column, e); if (canEdit && isHierarchical(column)) { repaint(getCellRect(row, column, false)); } return canEdit; } /** * Overridden to enable hit handle detection a mouseEvent which triggered * a expand/collapse. */ @Override protected void processMouseEvent(MouseEvent e) { // BasicTableUI selects on released if the pressed had been // consumed. So we try to fish for the accompanying released // here and consume it as wll. if ((e.getID() == MouseEvent.MOUSE_RELEASED) && consumedOnPress) { consumedOnPress = false; e.consume(); return; } if (getTreeTableHacker().hitHandleDetectionFromProcessMouse(e)) { // Issue #332-swing: hacking around selection loss. // prevent the // _table_ selection by consuming the mouseEvent // if it resulted in a expand/collapse consumedOnPress = true; e.consume(); return; } consumedOnPress = false; super.processMouseEvent(e); } protected TreeTableHacker getTreeTableHacker() { if (treeTableHacker == null) { treeTableHacker = createTreeTableHacker(); } return treeTableHacker; } protected TreeTableHacker createTreeTableHacker() { // return new TreeTableHacker(); return new TreeTableHackerExt(); // return new TreeTableHackerExt2(); } /** * Temporary class to have all the hacking at one place. Naturally, it will * change a lot. The base class has the "stable" behaviour as of around * jun2006 (before starting the fix for 332-swingx). <p> * * specifically: * * <ol> * <li> hitHandleDetection triggeredn in editCellAt * </ol> * */ public class TreeTableHacker { protected boolean expansionChangedFlag; /** * Decision whether the handle hit detection * should be done in processMouseEvent or editCellAt. * Here: returns false. * * @return true for handle hit detection in processMouse, false * for editCellAt. */ protected boolean isHitDetectionFromProcessMouse() { return false; } /** * Entry point for hit handle detection called from editCellAt, * does nothing if isHitDetectionFromProcessMouse is true; * * @see #isHitDetectionFromProcessMouse() */ public void hitHandleDetectionFromEditCell(int column, EventObject e) { if (!isHitDetectionFromProcessMouse()) { expandOrCollapseNode(column, e); } } /** * Entry point for hit handle detection called from processMouse. * Does nothing if isHitDetectionFromProcessMouse is false. * * @return true if the mouseEvent triggered an expand/collapse in * the renderer, false otherwise. * * @see #isHitDetectionFromProcessMouse() */ public boolean hitHandleDetectionFromProcessMouse(MouseEvent e) { if (!isHitDetectionFromProcessMouse()) return false; int col = columnAtPoint(e.getPoint()); return ((col >= 0) && expandOrCollapseNode(columnAtPoint(e .getPoint()), e)); } /** * complete editing if collapsed/expanded. * Here: any editing is always cancelled. * This is a rude fix to #120-jdnc: data corruption on * collapse/expand if editing. This is called from * the renderer after expansion related state has changed. * PENDING JW: should it take the old editing path as parameter? * Might be possible to be a bit more polite, and internally * reset the editing coordinates? On the other hand: the rudeness * is the table's usual behaviour - which is often removing the editor * as first reaction to incoming events. * */ protected void completeEditing() { if (isEditing()) { getCellEditor().cancelCellEditing(); } } /** * Tricksery to make the tree expand/collapse. * <p> * * This might be - indirectly - called from one of two places: * <ol> * <li> editCellAt: original, stable but buggy (#332, #222) the table's * own selection had been changed due to the click before even entering * into editCellAt so all tree selection state is lost. * * <li> processMouseEvent: the idea is to catch the mouseEvent, check * if it triggered an expanded/collapsed, consume and return if so or * pass to super if not. * </ol> * * <p> * widened access for testing ... * * * @param column the column index under the event, if any. * @param e the event which might trigger a expand/collapse. * * @return this methods evaluation as to whether the event triggered a * expand/collaps */ protected boolean expandOrCollapseNode(int column, EventObject e) { if (!isHierarchical(column)) return false; if (!mightBeExpansionTrigger(e)) return false; boolean changedExpansion = false; MouseEvent me = (MouseEvent) e; if (hackAroundDragEnabled(me)) { /* * Hack around #168-jdnc: dirty little hack mentioned in the * forum discussion about the issue: fake a mousePressed if drag * enabled. The usability is slightly impaired because the * expand/collapse is effectively triggered on released only * (drag system intercepts and consumes all other). */ me = new MouseEvent((Component) me.getSource(), MouseEvent.MOUSE_PRESSED, me.getWhen(), me .getModifiers(), me.getX(), me.getY(), me .getClickCount(), me.isPopupTrigger()); } // If the modifiers are not 0 (or the left mouse button), // tree may try and toggle the selection, and table // will then try and toggle, resulting in the // selection remaining the same. To avoid this, we // only dispatch when the modifiers are 0 (or the left mouse // button). if (me.getModifiers() == 0 || me.getModifiers() == InputEvent.BUTTON1_MASK) { MouseEvent pressed = new MouseEvent(renderer, me.getID(), me .getWhen(), me.getModifiers(), me.getX() - getCellRect(0, column, false).x, me.getY(), me .getClickCount(), me.isPopupTrigger()); renderer.dispatchEvent(pressed); // For Mac OS X, we need to dispatch a MOUSE_RELEASED as well MouseEvent released = new MouseEvent(renderer, java.awt.event.MouseEvent.MOUSE_RELEASED, pressed .getWhen(), pressed.getModifiers(), pressed .getX(), pressed.getY(), pressed .getClickCount(), pressed.isPopupTrigger()); renderer.dispatchEvent(released); if (expansionChangedFlag) { changedExpansion = true; } } expansionChangedFlag = false; return changedExpansion; } protected boolean mightBeExpansionTrigger(EventObject e) { if (!(e instanceof MouseEvent)) return false; MouseEvent me = (MouseEvent) e; if (!SwingUtilities.isLeftMouseButton(me)) return false; return me.getID() == MouseEvent.MOUSE_PRESSED; } /** * called from the renderer's setExpandedPath after * all expansion-related updates happend. * */ protected void expansionChanged() { expansionChangedFlag = true; } } /** * * Note: currently this class looks a bit funny (only overriding * the hit decision method). That's because the "experimental" code * as of the last round moved to stable. But I expect that there's more * to come, so I leave it here. * * <ol> * <li> hit handle detection in processMouse * </ol> */ public class TreeTableHackerExt extends TreeTableHacker { /** * Here: returns true. * @inheritDoc */ @Override protected boolean isHitDetectionFromProcessMouse() { return true; } } /** * Patch for #471-swingx: no selection on click in hierarchical column * outside of node-text. Mar 2007. * <p> * * Note: this solves the selection issue but is not bidi-compliant - in RToL * contexts the expansion/collapse handles aren't detected and consequently * are disfunctional. * * @author tiberiu@dev.java.net */ public class TreeTableHackerExt2 extends TreeTableHackerExt { @Override protected boolean expandOrCollapseNode(int column, EventObject e) { if (!isHierarchical(column)) return false; if (!mightBeExpansionTrigger(e)) return false; boolean changedExpansion = false; MouseEvent me = (MouseEvent) e; if (hackAroundDragEnabled(me)) { /* * Hack around #168-jdnc: dirty little hack mentioned in the * forum discussion about the issue: fake a mousePressed if drag * enabled. The usability is slightly impaired because the * expand/collapse is effectively triggered on released only * (drag system intercepts and consumes all other). */ me = new MouseEvent((Component) me.getSource(), MouseEvent.MOUSE_PRESSED, me.getWhen(), me .getModifiers(), me.getX(), me.getY(), me .getClickCount(), me.isPopupTrigger()); } // If the modifiers are not 0 (or the left mouse button), // tree may try and toggle the selection, and table // will then try and toggle, resulting in the // selection remaining the same. To avoid this, we // only dispatch when the modifiers are 0 (or the left mouse // button). if (me.getModifiers() == 0 || me.getModifiers() == InputEvent.BUTTON1_MASK) { // compute where the mouse point is relative to the tree // renderer Point treeMousePoint = new Point(me.getX() - getCellRect(0, column, false).x, me.getY()); int treeRow = renderer.getRowForLocation(treeMousePoint.x, treeMousePoint.y); int row = 0; if (treeRow < 0) { row = renderer.getClosestRowForLocation(treeMousePoint.x, treeMousePoint.y); Rectangle bounds = renderer.getRowBounds(row); if (bounds == null) { row = -1; } else { if ((bounds.y + bounds.height < treeMousePoint.y) || bounds.x > treeMousePoint.x) { row = -1; } } // make sure the expansionChangedFlag is set to false for // the case that up in the tree nothing happens expansionChangedFlag = false; } if ((treeRow >= 0) || ((treeRow < 0) && (row < 0))) { // default selection MouseEvent pressed = new MouseEvent(renderer, me.getID(), me.getWhen(), me.getModifiers(), treeMousePoint.x, treeMousePoint.y, me.getClickCount(), me .isPopupTrigger()); renderer.dispatchEvent(pressed); // For Mac OS X, we need to dispatch a MOUSE_RELEASED as // well MouseEvent released = new MouseEvent(renderer, java.awt.event.MouseEvent.MOUSE_RELEASED, pressed .getWhen(), pressed.getModifiers(), pressed .getX(), pressed.getY(), pressed .getClickCount(), pressed.isPopupTrigger()); renderer.dispatchEvent(released); } if (expansionChangedFlag) { changedExpansion = true; } } expansionChangedFlag = false; return changedExpansion; } } /** * decides whether we want to apply the hack for #168-jdnc. here: returns * true if dragEnabled() and the improved drag handling is not activated (or * the system property is not accessible). The given mouseEvent is not * analysed. * * PENDING: Mustang? * * @param me the mouseEvent that triggered a editCellAt * @return true if the hack should be applied. */ protected boolean hackAroundDragEnabled(MouseEvent me) { Boolean dragHackFlag = (Boolean) getClientProperty(DRAG_HACK_FLAG_KEY); if (dragHackFlag == null) { // access and store the system property as a client property once String priority = null; try { priority = System.getProperty("sun.swing.enableImprovedDragGesture"); } catch (Exception ex) { // found some foul expression or failed to read the property } dragHackFlag = (priority == null); putClientProperty(DRAG_HACK_FLAG_KEY, dragHackFlag); } return getDragEnabled() && dragHackFlag; } /** * Overridden to provide a workaround for BasicTableUI anomaly. Make sure * the UI never tries to resize the editor. The UI currently uses different * techniques to paint the renderers and editors. So, overriding setBounds() * is not the right thing to do for an editor. Returning -1 for the * editing row in this case, ensures the editor is never painted. * * {@inheritDoc} */ @Override public int getEditingRow() { return isHierarchical(editingColumn) ? -1 : editingRow; } /** * Returns the actual row that is editing as <code>getEditingRow</code> * will always return -1. */ private int realEditingRow() { return editingRow; } /** * Sets the data model for this JXTreeTable to the specified * {@link org.jdesktop.swingx.treetable.TreeTableModel}. The same data model * may be shared by any number of JXTreeTable instances. * * @param treeModel data model for this JXTreeTable */ public void setTreeTableModel(TreeTableModel treeModel) { TreeTableModel old = getTreeTableModel(); // boolean rootVisible = isRootVisible(); // setRootVisible(false); renderer.setModel(treeModel); // setRootVisible(rootVisible); firePropertyChange("treeTableModel", old, getTreeTableModel()); } /** * Returns the underlying TreeTableModel for this JXTreeTable. * * @return the underlying TreeTableModel for this JXTreeTable */ public TreeTableModel getTreeTableModel() { return (TreeTableModel) renderer.getModel(); } @Override public final void setModel(TableModel tableModel) { // note final keyword if (tableModel instanceof TreeTableModelAdapter) { if (((TreeTableModelAdapter) tableModel).getTreeTable() == null) { // Passing the above test ensures that this method is being // invoked either from JXTreeTable/JTable constructor or from // setTreeTableModel(TreeTableModel) super.setModel(tableModel); // invoke superclass version ((TreeTableModelAdapter) tableModel).bind(this); // permanently bound // Once a TreeTableModelAdapter is bound to any JXTreeTable instance, // invoking JXTreeTable.setModel() with that adapter will throw an // that a TreeTableModelAdapter is NOT shared by another JXTreeTable. } else { throw new IllegalArgumentException("model already bound"); } } else { throw new IllegalArgumentException("unsupported model type"); } } @Override public void tableChanged(TableModelEvent e) { if (isStructureChanged(e) || isUpdate(e)) { super.tableChanged(e); } else { resizeAndRepaint(); } } /** * Overridden to return a do-nothing mapper. * */ @Override public SelectionMapper getSelectionMapper() { // JW: don't want to change super assumption // (mapper != null) - the selection mapping will change // anyway in Mustang (using core functionality) return NO_OP_SELECTION_MANAGER ; } private static final SelectionMapper NO_OP_SELECTION_MANAGER = new SelectionMapper() { private ListSelectionModel viewSelectionModel = new DefaultListSelectionModel(); public ListSelectionModel getViewSelectionModel() { return viewSelectionModel; } public void setViewSelectionModel(ListSelectionModel viewSelectionModel) { this.viewSelectionModel = viewSelectionModel; } public void setFilters(FilterPipeline pipeline) { // do nothing } public void insertIndexInterval(int start, int length, boolean before) { // do nothing } public void removeIndexInterval(int start, int end) { // do nothing } public void setEnabled(boolean enabled) { // do nothing } public boolean isEnabled() { return false; } public void clearModelSelection() { // do nothing } }; /** * Throws UnsupportedOperationException because variable height rows are * not supported. * * @param row ignored * @param rowHeight ignored * @throws UnsupportedOperationException because variable height rows are * not supported */ @Override public final void setRowHeight(int row, int rowHeight) { throw new UnsupportedOperationException("variable height rows not supported"); } /** * Sets the row height for this JXTreeTable and forwards the * row height to the renderering tree. * * @param rowHeight height of a row. */ @Override public void setRowHeight(int rowHeight) { super.setRowHeight(rowHeight); adjustTreeRowHeight(getRowHeight()); } /** * Forwards tableRowHeight to tree. * * @param tableRowHeight height of a row. */ protected void adjustTreeRowHeight(int tableRowHeight) { if (renderer != null && renderer.getRowHeight() != tableRowHeight) { renderer.setRowHeight(tableRowHeight); } } /** * Forwards treeRowHeight to table. This is for completeness only: the * rendering tree is under our total control, so we don't expect * any external call to tree.setRowHeight. * * @param treeRowHeight height of a row. */ protected void adjustTableRowHeight(int treeRowHeight) { if (getRowHeight() != treeRowHeight) { adminSetRowHeight(treeRowHeight); } } /** * <p>Overridden to ensure that private renderer state is kept in sync with the * state of the component. Calls the inherited version after performing the * necessary synchronization. If you override this method, make sure you call * this version from your version of this method.</p> * * <p>This version maps the selection mode used by the renderer to match the * selection mode specified for the table. Specifically, the modes are mapped * as follows: * <pre> * ListSelectionModel.SINGLE_INTERVAL_SELECTION: TreeSelectionModel.CONTIGUOUS_TREE_SELECTION; * ListSelectionModel.MULTIPLE_INTERVAL_SELECTION: TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION; * any other (default): TreeSelectionModel.SINGLE_TREE_SELECTION; * </pre> * * {@inheritDoc} * * @param mode any of the table selection modes */ @Override public void setSelectionMode(int mode) { if (renderer != null) { switch (mode) { case ListSelectionModel.SINGLE_INTERVAL_SELECTION: { renderer.getSelectionModel().setSelectionMode( TreeSelectionModel.CONTIGUOUS_TREE_SELECTION); break; } case ListSelectionModel.MULTIPLE_INTERVAL_SELECTION: { renderer.getSelectionModel().setSelectionMode( TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); break; } default: { renderer.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION); break; } } } super.setSelectionMode(mode); } /** * Overrides superclass version to provide support for cell decorators. * * @param renderer the <code>TableCellRenderer</code> to prepare * @param row the row of the cell to render, where 0 is the first row * @param column the column of the cell to render, where 0 is the first column * @return the <code>Component</code> used as a stamp to render the specified cell */ @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component component = super.prepareRenderer(renderer, row, column); return applyRenderer(component, getComponentAdapter(row, column)); } /** * Performs necessary housekeeping before the renderer is actually applied. * * @param component * @param adapter component data adapter * @throws NullPointerException if the specified component or adapter is null */ protected Component applyRenderer(Component component, ComponentAdapter adapter) { if (component == null) { throw new IllegalArgumentException("null component"); } if (adapter == null) { throw new IllegalArgumentException("null component data adapter"); } if (isHierarchical(adapter.column)) { // After all decorators have been applied, make sure that relevant // attributes of the table cell renderer are applied to the // tree cell renderer before the hierarchical column is rendered! TreeCellRenderer tcr = renderer.getCellRenderer(); if (tcr instanceof JXTree.DelegatingRenderer) { tcr = ((JXTree.DelegatingRenderer) tcr).getDelegateRenderer(); } if (tcr instanceof DefaultTreeCellRenderer) { DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer) tcr); if (adapter.isSelected()) { dtcr.setTextSelectionColor(component.getForeground()); dtcr.setBackgroundSelectionColor(component.getBackground()); } else { dtcr.setTextNonSelectionColor(component.getForeground()); dtcr.setBackgroundNonSelectionColor(component.getBackground()); } } } return component; } /** * Sets the specified TreeCellRenderer as the Tree cell renderer. * * @param cellRenderer to use for rendering tree cells. */ public void setTreeCellRenderer(TreeCellRenderer cellRenderer) { if (renderer != null) { renderer.setCellRenderer(cellRenderer); } } public TreeCellRenderer getTreeCellRenderer() { return renderer.getCellRenderer(); } @Override public String getToolTipText(MouseEvent event) { int column = columnAtPoint(event.getPoint()); if (isHierarchical(column)) { int row = rowAtPoint(event.getPoint()); return renderer.getToolTipText(event, row, column); } return super.getToolTipText(event); } /** * Sets the specified icon as the icon to use for rendering collapsed nodes. * * @param icon to use for rendering collapsed nodes */ public void setCollapsedIcon(Icon icon) { renderer.setCollapsedIcon(icon); } /** * Sets the specified icon as the icon to use for rendering expanded nodes. * * @param icon to use for rendering expanded nodes */ public void setExpandedIcon(Icon icon) { renderer.setExpandedIcon(icon); } /** * Sets the specified icon as the icon to use for rendering open container nodes. * * @param icon to use for rendering open nodes */ public void setOpenIcon(Icon icon) { renderer.setOpenIcon(icon); } /** * Sets the specified icon as the icon to use for rendering closed container nodes. * * @param icon to use for rendering closed nodes */ public void setClosedIcon(Icon icon) { renderer.setClosedIcon(icon); } /** * Sets the specified icon as the icon to use for rendering leaf nodes. * * @param icon to use for rendering leaf nodes */ public void setLeafIcon(Icon icon) { renderer.setLeafIcon(icon); } /** * Overridden to ensure that private renderer state is kept in sync with the * state of the component. Calls the inherited version after performing the * necessary synchronization. If you override this method, make sure you call * this version from your version of this method. */ @Override public void clearSelection() { if (renderer != null) { renderer.clearSelection(); } super.clearSelection(); } /** * Collapses all nodes in the treetable. */ public void collapseAll() { renderer.collapseAll(); } /** * Expands all nodes in the treetable. */ public void expandAll() { renderer.expandAll(); } /** * Collapses the node at the specified path in the treetable. * * @param path path of the node to collapse */ public void collapsePath(TreePath path) { renderer.collapsePath(path); } /** * Expands the the node at the specified path in the treetable. * * @param path path of the node to expand */ public void expandPath(TreePath path) { renderer.expandPath(path); } /** * Makes sure all the path components in path are expanded (except * for the last path component) and scrolls so that the * node identified by the path is displayed. Only works when this * <code>JTree</code> is contained in a <code>JScrollPane</code>. * * (doc copied from JTree) * * PENDING: JW - where exactly do we want to scroll? Here: the scroll * is in vertical direction only. Might need to show the tree column? * * @param path the <code>TreePath</code> identifying the node to * bring into view */ public void scrollPathToVisible(TreePath path) { renderer.scrollPathToVisible(path); // if (path == null) return; // renderer.makeVisible(path); // int row = getRowForPath(path); // scrollRowToVisible(row); } /** * Collapses the row in the treetable. If the specified row index is * not valid, this method will have no effect. */ public void collapseRow(int row) { renderer.collapseRow(row); } /** * Expands the specified row in the treetable. If the specified row index is * not valid, this method will have no effect. */ public void expandRow(int row) { renderer.expandRow(row); } /** * Returns true if the value identified by path is currently viewable, which * means it is either the root or all of its parents are expanded. Otherwise, * this method returns false. * * @return true, if the value identified by path is currently viewable; * false, otherwise */ public boolean isVisible(TreePath path) { return renderer.isVisible(path); } /** * Returns true if the node identified by path is currently expanded. * Otherwise, this method returns false. * * @param path path * @return true, if the value identified by path is currently expanded; * false, otherwise */ public boolean isExpanded(TreePath path) { return renderer.isExpanded(path); } /** * Returns true if the node at the specified display row is currently expanded. * Otherwise, this method returns false. * * @param row row * @return true, if the node at the specified display row is currently expanded. * false, otherwise */ public boolean isExpanded(int row) { return renderer.isExpanded(row); } /** * Returns true if the node identified by path is currently collapsed, * this will return false if any of the values in path are currently not * being displayed. * * @param path path * @return true, if the value identified by path is currently collapsed; * false, otherwise */ public boolean isCollapsed(TreePath path) { return renderer.isCollapsed(path); } /** * Returns true if the node at the specified display row is collapsed. * * @param row row * @return true, if the node at the specified display row is currently collapsed. * false, otherwise */ public boolean isCollapsed(int row) { return renderer.isCollapsed(row); } /** * Returns an <code>Enumeration</code> of the descendants of the * path <code>parent</code> that * are currently expanded. If <code>parent</code> is not currently * expanded, this will return <code>null</code>. * If you expand/collapse nodes while * iterating over the returned <code>Enumeration</code> * this may not return all * the expanded paths, or may return paths that are no longer expanded. * * @param parent the path which is to be examined * @return an <code>Enumeration</code> of the descendents of * <code>parent</code>, or <code>null</code> if * <code>parent</code> is not currently expanded */ public Enumeration<?> getExpandedDescendants(TreePath parent) { return renderer.getExpandedDescendants(parent); } /** * Returns the TreePath for a given x,y location. * * @param x x value * @param y y value * * @return the <code>TreePath</code> for the givern location. */ public TreePath getPathForLocation(int x, int y) { int row = rowAtPoint(new Point(x,y)); if (row == -1) { return null; } return renderer.getPathForRow(row); } /** * Returns the TreePath for a given row. * * @param row * * @return the <code>TreePath</code> for the given row. */ public TreePath getPathForRow(int row) { return renderer.getPathForRow(row); } /** * Returns the row for a given TreePath. * * @param path * @return the row for the given <code>TreePath</code>. */ public int getRowForPath(TreePath path) { return renderer.getRowForPath(path); } /** * Determines whether or not the root node from the TreeModel is visible. * * @param visible true, if the root node is visible; false, otherwise */ public void setRootVisible(boolean visible) { renderer.setRootVisible(visible); // JW: the revalidate forces the root to appear after a // toggling a visible from an initially invisible root. // JTree fires a propertyChange on the ROOT_VISIBLE_PROPERTY // BasicTreeUI reacts by (ultimately) calling JTree.treeDidChange // which revalidate the tree part. // Might consider to listen for the propertyChange (fired only if there // actually was a change) instead of revalidating unconditionally. revalidate(); repaint(); } /** * Returns true if the root node of the tree is displayed. * * @return true if the root node of the tree is displayed */ public boolean isRootVisible() { return renderer.isRootVisible(); } /** * Sets the value of the <code>scrollsOnExpand</code> property for the tree * part. This property specifies whether the expanded paths should be scrolled * into view. In a look and feel in which a tree might not need to scroll * when expanded, this property may be ignored. * * @param scroll true, if expanded paths should be scrolled into view; * false, otherwise */ public void setScrollsOnExpand(boolean scroll) { renderer.setScrollsOnExpand(scroll); } /** * Returns the value of the <code>scrollsOnExpand</code> property. * * @return the value of the <code>scrollsOnExpand</code> property */ public boolean getScrollsOnExpand() { return renderer.getScrollsOnExpand(); } /** * Sets the value of the <code>showsRootHandles</code> property for the tree * part. This property specifies whether the node handles should be displayed. * If handles are not supported by a particular look and feel, this property * may be ignored. * * @param visible true, if root handles should be shown; false, otherwise */ public void setShowsRootHandles(boolean visible) { renderer.setShowsRootHandles(visible); repaint(); } /** * Returns the value of the <code>showsRootHandles</code> property. * * @return the value of the <code>showsRootHandles</code> property */ public boolean getShowsRootHandles() { return renderer.getShowsRootHandles(); } /** * Sets the value of the <code>expandsSelectedPaths</code> property for the tree * part. This property specifies whether the selected paths should be expanded. * * @param expand true, if selected paths should be expanded; false, otherwise */ public void setExpandsSelectedPaths(boolean expand) { renderer.setExpandsSelectedPaths(expand); } /** * Returns the value of the <code>expandsSelectedPaths</code> property. * * @return the value of the <code>expandsSelectedPaths</code> property */ public boolean getExpandsSelectedPaths() { return renderer.getExpandsSelectedPaths(); } /** * Returns the number of mouse clicks needed to expand or close a node. * * @return number of mouse clicks before node is expanded */ public int getToggleClickCount() { return renderer.getToggleClickCount(); } /** * Sets the number of mouse clicks before a node will expand or close. * The default is two. * * @param clickCount the number of clicks required to expand/collapse a node. */ public void setToggleClickCount(int clickCount) { renderer.setToggleClickCount(clickCount); } /** * Returns true if the tree is configured for a large model. * The default value is false. * * @return true if a large model is suggested * @see #setLargeModel */ public boolean isLargeModel() { return renderer.isLargeModel(); } /** * Specifies whether the UI should use a large model. * (Not all UIs will implement this.) <p> * * <strong>NOTE</strong>: this method is exposed for completeness - * currently it's not recommended * to use a large model because there are some issues * (not yet fully understood), namely * issue #25-swingx, and probably #270-swingx. * * @param newValue true to suggest a large model to the UI */ public void setLargeModel(boolean newValue) { renderer.setLargeModel(newValue); // JW: random method calling ... doesn't help // renderer.treeDidChange(); // revalidate(); // repaint(); } /** * Adds a listener for <code>TreeExpansion</code> events. * * TODO (JW): redirect event source to this. * * @param tel a TreeExpansionListener that will be notified * when a tree node is expanded or collapsed */ public void addTreeExpansionListener(TreeExpansionListener tel) { renderer.addTreeExpansionListener(tel); } /** * Removes a listener for <code>TreeExpansion</code> events. * @param tel the <code>TreeExpansionListener</code> to remove */ public void removeTreeExpansionListener(TreeExpansionListener tel) { renderer.removeTreeExpansionListener(tel); } /** * Adds a listener for <code>TreeSelection</code> events. * TODO (JW): redirect event source to this. * * @param tsl a TreeSelectionListener that will be notified * when a tree node is selected or deselected */ public void addTreeSelectionListener(TreeSelectionListener tsl) { renderer.addTreeSelectionListener(tsl); } /** * Removes a listener for <code>TreeSelection</code> events. * @param tsl the <code>TreeSelectionListener</code> to remove */ public void removeTreeSelectionListener(TreeSelectionListener tsl) { renderer.removeTreeSelectionListener(tsl); } /** * Adds a listener for <code>TreeWillExpand</code> events. * TODO (JW): redirect event source to this. * * @param tel a TreeWillExpandListener that will be notified * when a tree node will be expanded or collapsed */ public void addTreeWillExpandListener(TreeWillExpandListener tel) { renderer.addTreeWillExpandListener(tel); } /** * Removes a listener for <code>TreeWillExpand</code> events. * @param tel the <code>TreeWillExpandListener</code> to remove */ public void removeTreeWillExpandListener(TreeWillExpandListener tel) { renderer.removeTreeWillExpandListener(tel); } /** * Returns the selection model for the tree portion of the this treetable. * * @return selection model for the tree portion of the this treetable */ public TreeSelectionModel getTreeSelectionModel() { return renderer.getSelectionModel(); // RG: Fix JDNC issue 41 } /** * Overriden to invoke supers implementation, and then, * if the receiver is editing a Tree column, the editors bounds is * reset. The reason we have to do this is because JTable doesn't * think the table is being edited, as <code>getEditingRow</code> returns * -1, and therefore doesn't automaticly resize the editor for us. */ @Override public void sizeColumnsToFit(int resizingColumn) { /** TODO: Review wrt doLayout() */ super.sizeColumnsToFit(resizingColumn); // rg:changed if (getEditingColumn() != -1 && isHierarchical(editingColumn)) { Rectangle cellRect = getCellRect(realEditingRow(), getEditingColumn(), false); Component component = getEditorComponent(); component.setBounds(cellRect); component.validate(); } } public boolean isHierarchical(int column) { if (column < 0 || column >= getColumnCount()) { throw new IllegalArgumentException("column must be valid, was" + column); } return (getHierarchicalColumn() == column); } /** * Returns the index of the hierarchical column. This is the column that is * displayed as the tree. * * @return the index of the hierarchical column, -1 if there is * no hierarchical column * */ public int getHierarchicalColumn() { return convertColumnIndexToView(((TreeTableModel) renderer.getModel()).getHierarchicalColumn()); } /** * {@inheritDoc} */ @Override public TableCellRenderer getCellRenderer(int row, int column) { if (isHierarchical(column)) { return renderer; } return super.getCellRenderer(row, column); } /** * {@inheritDoc} */ @Override public TableCellEditor getCellEditor(int row, int column) { if (isHierarchical(column)) { return hierarchicalEditor; } return super.getCellEditor(row, column); } /** * ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel * to listen for changes in the ListSelectionModel it maintains. Once * a change in the ListSelectionModel happens, the paths are updated * in the DefaultTreeSelectionModel. */ class ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel { /** Set to true when we are updating the ListSelectionModel. */ protected boolean updatingListSelectionModel; public ListToTreeSelectionModelWrapper() { super(); getListSelectionModel().addListSelectionListener (createListSelectionListener()); } /** * Returns the list selection model. ListToTreeSelectionModelWrapper * listens for changes to this model and updates the selected paths * accordingly. */ ListSelectionModel getListSelectionModel() { return listSelectionModel; } /** * This is overridden to set <code>updatingListSelectionModel</code> * and message super. This is the only place DefaultTreeSelectionModel * alters the ListSelectionModel. */ @Override public void resetRowSelection() { if (!updatingListSelectionModel) { updatingListSelectionModel = true; try { super.resetRowSelection(); } finally { updatingListSelectionModel = false; } } // Notice how we don't message super if // updatingListSelectionModel is true. If // updatingListSelectionModel is true, it implies the // ListSelectionModel has already been updated and the // paths are the only thing that needs to be updated. } /** * Creates and returns an instance of ListSelectionHandler. */ protected ListSelectionListener createListSelectionListener() { return new ListSelectionHandler(); } /** * If <code>updatingListSelectionModel</code> is false, this will * reset the selected paths from the selected rows in the list * selection model. */ protected void updateSelectedPathsFromSelectedRows() { if (!updatingListSelectionModel) { updatingListSelectionModel = true; try { if (listSelectionModel.isSelectionEmpty()) { clearSelection(); } else { // This is way expensive, ListSelectionModel needs an // enumerator for iterating. int min = listSelectionModel.getMinSelectionIndex(); int max = listSelectionModel.getMaxSelectionIndex(); List<TreePath> paths = new ArrayList<TreePath>(); for (int counter = min; counter <= max; counter++) { if (listSelectionModel.isSelectedIndex(counter)) { TreePath selPath = renderer.getPathForRow( counter); if (selPath != null) { paths.add(selPath); } } } setSelectionPaths(paths.toArray(new TreePath[paths.size()])); // need to force here: usually the leadRow is adjusted // in resetRowSelection which is disabled during this method leadRow = leadIndex; } } finally { updatingListSelectionModel = false; } } } /** * Class responsible for calling updateSelectedPathsFromSelectedRows * when the selection of the list changse. */ class ListSelectionHandler implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { updateSelectedPathsFromSelectedRows(); } } } } protected static class TreeTableModelAdapter extends AbstractTableModel { private TreeModelListener treeModelListener; TreeTableModelAdapter(JTree tree) { assert tree != null; this.tree = tree; // need tree to implement getRowCount() tree.getModel().addTreeModelListener(getTreeModelListener()); tree.addTreeExpansionListener(new TreeExpansionListener() { // Don't use fireTableRowsInserted() here; the selection model // would get updated twice. public void treeExpanded(TreeExpansionEvent event) { updateAfterExpansionEvent(event); } public void treeCollapsed(TreeExpansionEvent event) { updateAfterExpansionEvent(event); } }); tree.addPropertyChangeListener("model", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { TreeTableModel model = (TreeTableModel) evt.getOldValue(); model.removeTreeModelListener(getTreeModelListener()); model = (TreeTableModel) evt.getNewValue(); model.addTreeModelListener(getTreeModelListener()); fireTableStructureChanged(); } }); } /** * updates the table after having received an TreeExpansionEvent.<p> * * @param event the TreeExpansionEvent which triggered the method call. */ protected void updateAfterExpansionEvent(TreeExpansionEvent event) { // moved to let the renderer handle directly // treeTable.getTreeTableHacker().setExpansionChangedFlag(); // JW: delayed fire leads to a certain sluggishness occasionally? fireTableDataChanged(); } /** * Returns the JXTreeTable instance to which this TreeTableModelAdapter is * permanently and exclusively bound. For use by * {@link org.jdesktop.swingx.JXTreeTable#setModel(javax.swing.table.TableModel)}. * * @return JXTreeTable to which this TreeTableModelAdapter is permanently bound */ protected JXTreeTable getTreeTable() { return treeTable; } /** * Immutably binds this TreeTableModelAdapter to the specified JXTreeTable. * * @param treeTable the JXTreeTable instance that this adapter is bound to. */ protected final void bind(JXTreeTable treeTable) { // Suppress potentially subversive invocation! // Prevent clearing out the deck for possible hijack attempt later! if (treeTable == null) { throw new IllegalArgumentException("null treeTable"); } if (this.treeTable == null) { this.treeTable = treeTable; } else { throw new IllegalArgumentException("adapter already bound"); } } // Wrappers, implementing TableModel interface. // TableModelListener management provided by AbstractTableModel superclass. @Override public Class<?> getColumnClass(int column) { return ((TreeTableModel) tree.getModel()).getColumnClass(column); } public int getColumnCount() { return ((TreeTableModel) tree.getModel()).getColumnCount(); } @Override public String getColumnName(int column) { return ((TreeTableModel) tree.getModel()).getColumnName(column); } public int getRowCount() { return tree.getRowCount(); } public Object getValueAt(int row, int column) { // Issue #270-swingx: guard against invisible row Object node = nodeForRow(row); return node != null ? ((TreeTableModel) tree.getModel()).getValueAt(node, column) : null; } @Override public boolean isCellEditable(int row, int column) { // Issue #270-swingx: guard against invisible row Object node = nodeForRow(row); return node != null ? ((TreeTableModel) tree.getModel()).isCellEditable(node, column) : false; } @Override public void setValueAt(Object value, int row, int column) { // Issue #270-swingx: guard against invisible row Object node = nodeForRow(row); if (node != null) { ((TreeTableModel) tree.getModel()).setValueAt(value, node, column); } } protected Object nodeForRow(int row) { // Issue #270-swingx: guard against invisible row TreePath path = tree.getPathForRow(row); return path != null ? path.getLastPathComponent() : null; } /** * @return <code>TreeModelListener</code> */ private TreeModelListener getTreeModelListener() { if (treeModelListener == null) { treeModelListener = new TreeModelListener() { public void treeNodesChanged(TreeModelEvent e) { // LOG.info("got tree event: changed " + e); delayedFireTableDataUpdated(e); } // We use delayedFireTableDataChanged as we can // not be guaranteed the tree will have finished processing // the event before us. public void treeNodesInserted(TreeModelEvent e) { delayedFireTableDataChanged(e, 1); } public void treeNodesRemoved(TreeModelEvent e) { // LOG.info("got tree event: removed " + e); delayedFireTableDataChanged(e, 2); } public void treeStructureChanged(TreeModelEvent e) { // ?? should be mapped to structureChanged -- JW if (isTableStructureChanged(e)) { delayedFireTableStructureChanged(); } else { delayedFireTableDataChanged(); } } }; } return treeModelListener; } /** * Decides if the given treeModel structureChanged should * trigger a table structureChanged. Returns true if the * source path is the root or null, false otherwise.<p> * * PENDING: need to refine? "Marker" in Event-Object? * * @param e the TreeModelEvent received in the treeModelListener's * treeStructureChanged * @return a boolean indicating whether the given TreeModelEvent * should trigger a structureChanged. */ private boolean isTableStructureChanged(TreeModelEvent e) { if ((e.getTreePath() == null) || (e.getTreePath().getParentPath() == null)) return true; return false; } /** * Invokes fireTableDataChanged after all the pending events have been * processed. SwingUtilities.invokeLater is used to handle this. */ private void delayedFireTableStructureChanged() { SwingUtilities.invokeLater(new Runnable() { public void run() { fireTableStructureChanged(); } }); } /** * Invokes fireTableDataChanged after all the pending events have been * processed. SwingUtilities.invokeLater is used to handle this. */ private void delayedFireTableDataChanged() { SwingUtilities.invokeLater(new Runnable() { public void run() { fireTableDataChanged(); } }); } /** * Invokes fireTableDataChanged after all the pending events have been * processed. SwingUtilities.invokeLater is used to handle this. * Allowed event types: 1 for insert, 2 for delete */ private void delayedFireTableDataChanged(final TreeModelEvent tme, final int typeChange) { if ((typeChange < 1 ) || (typeChange > 2)) throw new IllegalArgumentException("Event type must be 1 or 2, was " + typeChange); // expansion state before invoke may be different // from expansion state in invoke final boolean expanded = tree.isExpanded(tme.getTreePath()); // quick test if tree throws for unrelated path. Seems like not. // tree.getRowForPath(new TreePath("dummy")); SwingUtilities.invokeLater(new Runnable() { public void run() { int indices[] = tme.getChildIndices(); TreePath path = tme.getTreePath(); // quick test to see if bailing out is an option // if (false) { if (indices != null) { if (expanded) { // Dont bother to update if the parent // node is collapsed // indices must in ascending order, as per TreeEvent/Listener doc int min = indices[0]; int max = indices[indices.length - 1]; int startingRow = tree.getRowForPath(path) + 1; min = startingRow + min; max = startingRow + max; switch (typeChange) { case 1: // LOG.info("rows inserted: path " + path + "/" + min + "/" // + max); fireTableRowsInserted(min, max); break; case 2: // LOG.info("rows deleted path " + path + "/" + min + "/" // + max); fireTableRowsDeleted(min, max); break; } } else if (path.getParentPath() == null && !tree.isRootVisible() && tree.isCollapsed(path)) { //#612 must expand invisible collapsed root tree.expandPath(path); } else { // not expanded - but change might effect appearance // of parent // Issue #82-swingx int row = tree.getRowForPath(path); // fix Issue #247-swingx: prevent accidental // structureChanged // for collapsed path // in this case row == -1, which == // TableEvent.HEADER_ROW if (row >= 0) fireTableRowsUpdated(row, row); } } else { // case where the event is fired to identify // root. fireTableDataChanged(); } } }); } /** * This is used for updated only. PENDING: not necessary to delay? * Updates are never structural changes which are the critical. * * @param e */ protected void delayedFireTableDataUpdated(final TreeModelEvent tme) { final boolean expanded = tree.isExpanded(tme.getTreePath()); SwingUtilities.invokeLater(new Runnable() { public void run() { int indices[] = tme.getChildIndices(); TreePath path = tme.getTreePath(); if (indices != null) { if (expanded) { // Dont bother to update if the parent // node is collapsed Object children[] = tme.getChildren(); // can we be sure that children.length > 0? // int min = tree.getRowForPath(path.pathByAddingChild(children[0])); // int max = tree.getRowForPath(path.pathByAddingChild(children[children.length -1])); int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int i = 0; i < indices.length; i++) { Object child = children[i]; TreePath childPath = path .pathByAddingChild(child); int index = tree.getRowForPath(childPath); if (index < min) { min = index; } if (index > max) { max = index; } } // LOG.info("Updated: parentPath/min/max" + path + "/" + min + "/" + max); // JW: the index is occasionally - 1 - need further digging fireTableRowsUpdated(Math.max(0, min), Math.max(0, max)); } else { // not expanded - but change might effect appearance // of parent Issue #82-swingx int row = tree.getRowForPath(path); // fix Issue #247-swingx: prevent accidental structureChanged // for collapsed path in this case row == -1, // which == TableEvent.HEADER_ROW if (row >= 0) fireTableRowsUpdated(row, row); } } else { // case where the event is fired to identify // root. fireTableDataChanged(); } } }); } private final JTree tree; // immutable private JXTreeTable treeTable = null; // logically immutable } static class TreeTableCellRenderer extends JXTree implements TableCellRenderer // need to implement RolloverRenderer // PENDING JW: method name clash rolloverRenderer.isEnabled and // component.isEnabled .. don't extend, use? And change // the method name in rolloverRenderer? // commented - so doesn't show the rollover cursor. // , RolloverRenderer { private PropertyChangeListener rolloverListener; // Force user to specify TreeTableModel instead of more general // TreeModel public TreeTableCellRenderer(TreeTableModel model) { super(model); putClientProperty("JTree.lineStyle", "None"); setRootVisible(false); // superclass default is "true" setShowsRootHandles(true); // superclass default is "false" /** * TODO: Support truncated text directly in * DefaultTreeCellRenderer. */ setOverwriteRendererIcons(true); // setCellRenderer(new DefaultTreeRenderer()); setCellRenderer(new ClippedTreeCellRenderer()); } /** * Hack around #297-swingx: tooltips shown at wrong row. * * The problem is that - due to much tricksery when rendering the tree - * the given coordinates are rather useless. As a consequence, super * maps to wrong coordinates. This takes over completely. * * PENDING: bidi? * * @param event the mouseEvent in treetable coordinates * @param row the view row index * @param column the view column index * @return the tooltip as appropriate for the given row */ private String getToolTipText(MouseEvent event, int row, int column) { if (row < 0) return null; TreeCellRenderer renderer = getCellRenderer(); TreePath path = getPathForRow(row); Object lastPath = path.getLastPathComponent(); Component rComponent = renderer.getTreeCellRendererComponent (this, lastPath, isRowSelected(row), isExpanded(row), getModel().isLeaf(lastPath), row, true); if(rComponent instanceof JComponent) { Rectangle pathBounds = getPathBounds(path); Rectangle cellRect = treeTable.getCellRect(row, column, false); // JW: what we are after // is the offset into the hierarchical column // then intersect this with the pathbounds Point mousePoint = event.getPoint(); // translate to coordinates relative to cell mousePoint.translate(-cellRect.x, -cellRect.y); // translate horizontally to mousePoint.translate(-pathBounds.x, 0); // show tooltip only if over renderer? // if (mousePoint.x < 0) return null; // p.translate(-pathBounds.x, -pathBounds.y); MouseEvent newEvent = new MouseEvent(rComponent, event.getID(), event.getWhen(), event.getModifiers(), mousePoint.x, mousePoint.y, // p.x, p.y, event.getClickCount(), event.isPopupTrigger()); return ((JComponent)rComponent).getToolTipText(newEvent); } return null; } /** * Immutably binds this TreeTableModelAdapter to the specified JXTreeTable. * For internal use by JXTreeTable only. * * @param treeTable the JXTreeTable instance that this renderer is bound to */ public final void bind(JXTreeTable treeTable) { // Suppress potentially subversive invocation! // Prevent clearing out the deck for possible hijack attempt later! if (treeTable == null) { throw new IllegalArgumentException("null treeTable"); } if (this.treeTable == null) { this.treeTable = treeTable; // commented because still has issus // bindRollover(); } else { throw new IllegalArgumentException("renderer already bound"); } } /** * Install rollover support. * Not used - still has issues. * - not bidi-compliant * - no coordinate transformation for hierarchical column != 0 * - method name clash enabled * - keyboard triggered click unreliable (triggers the treetable) * ... */ private void bindRollover() { setRolloverEnabled(treeTable.isRolloverEnabled()); treeTable.addPropertyChangeListener(getRolloverListener()); } /** * @return */ private PropertyChangeListener getRolloverListener() { if (rolloverListener == null) { rolloverListener = createRolloverListener(); } return rolloverListener; } /** * Creates and returns a property change listener for * table's rollover related properties. * * This implementation * - Synchs the tree's rolloverEnabled * - maps rollover cell from the table to the cell * (still incomplete: first column only) * * @return */ protected PropertyChangeListener createRolloverListener() { PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ((treeTable == null) || (treeTable != evt.getSource())) return; if ("rolloverEnabled".equals(evt.getPropertyName())) { setRolloverEnabled(((Boolean) evt.getNewValue()).booleanValue()); } if (RolloverProducer.ROLLOVER_KEY.equals(evt.getPropertyName())){ rollover(evt); } } private void rollover(PropertyChangeEvent evt) { boolean isHierarchical = isHierarchical((Point)evt.getNewValue()); putClientProperty(evt.getPropertyName(), isHierarchical ? new Point((Point) evt.getNewValue()) : null); } private boolean isHierarchical(Point point) { if (point != null) { int column = point.x; if (column >= 0) { return treeTable.isHierarchical(column); } } return false; } Point rollover = new Point(-1, -1); }; return l; } /** * {@inheritDoc} <p> * * Overridden to produce clicked client props only. The * rollover are produced by a propertyChangeListener to * the table's corresponding prop. * */ @Override protected RolloverProducer createRolloverProducer() { return new RolloverProducer() { /** * Overridden to do nothing. * * @param e * @param property */ @Override protected void updateRollover(MouseEvent e, String property) { if (CLICKED_KEY.equals(property)) { super.updateRollover(e, property); } } protected void updateRolloverPoint(JComponent component, Point mousePoint) { JXTree tree = (JXTree) component; int row = tree.getClosestRowForLocation(mousePoint.x, mousePoint.y); Rectangle bounds = tree.getRowBounds(row); if (bounds == null) { row = -1; } else { if ((bounds.y + bounds.height < mousePoint.y) || bounds.x > mousePoint.x) { row = -1; } } int col = row < 0 ? -1 : 0; rollover.x = col; rollover.y = row; } }; } @Override public void scrollRectToVisible(Rectangle aRect) { treeTable.scrollRectToVisible(aRect); } @Override protected void setExpandedState(TreePath path, boolean state) { super.setExpandedState(path, state); treeTable.getTreeTableHacker().expansionChanged(); treeTable.getTreeTableHacker().completeEditing(); } /** * updateUI is overridden to set the colors of the Tree's renderer * to match that of the table. */ @Override public void updateUI() { super.updateUI(); // Make the tree's cell renderer use the table's cell selection // colors. // TODO JW: need to revisit... // a) the "real" of a JXTree is always wrapped into a DelegatingRenderer // consequently the if-block never executes // b) even if it does it probably (?) should not // unconditionally overwrite custom selection colors. // Check for UIResources instead. TreeCellRenderer tcr = getCellRenderer(); if (tcr instanceof DefaultTreeCellRenderer) { DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer) tcr); // For 1.1 uncomment this, 1.2 has a bug that will cause an // exception to be thrown if the border selection color is null. dtcr.setBorderSelectionColor(null); dtcr.setTextSelectionColor( UIManager.getColor("Table.selectionForeground")); dtcr.setBackgroundSelectionColor( UIManager.getColor("Table.selectionBackground")); } } /** * Sets the row height of the tree, and forwards the row height to * the table. * * */ @Override public void setRowHeight(int rowHeight) { // JW: can't ... updateUI invoked with rowHeight = 0 // hmmm... looks fishy ... // if (rowHeight <= 0) throw super.setRowHeight(rowHeight); if (rowHeight > 0) { if (treeTable != null) { treeTable.adjustTableRowHeight(rowHeight); } } } /** * This is overridden to set the height to match that of the JTable. */ @Override public void setBounds(int x, int y, int w, int h) { if (treeTable != null) { y = 0; // It is not enough to set the height to treeTable.getHeight() h = treeTable.getRowCount() * this.getRowHeight(); } super.setBounds(x, y, w, h); } /** * Sublcassed to translate the graphics such that the last visible row * will be drawn at 0,0. */ @Override public void paint(Graphics g) { Rectangle cellRect = treeTable.getCellRect(visibleRow, 0, false); g.translate(0, -cellRect.y); hierarchicalColumnWidth = getWidth(); super.paint(g); // Draw the Table border if we have focus. if (highlightBorder != null) { // #170: border not drawn correctly // JW: position the border to be drawn in translated area // still not satifying in all cases... // RG: Now it satisfies (at least for the row margins) // Still need to make similar adjustments for column margins... highlightBorder.paintBorder(this, g, 0, cellRect.y, getWidth(), cellRect.height); } } public void doClick() { if ((getCellRenderer() instanceof RolloverRenderer) && ((RolloverRenderer) getCellRenderer()).isEnabled()) { ((RolloverRenderer) getCellRenderer()).doClick(); } } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { assert table == treeTable; if (isSelected) { setBackground(table.getSelectionBackground()); setForeground(table.getSelectionForeground()); } else { setBackground(table.getBackground()); setForeground(table.getForeground()); } highlightBorder = null; if (treeTable != null) { if (treeTable.realEditingRow() == row && treeTable.getEditingColumn() == column) { } else if (hasFocus) { highlightBorder = UIManager.getBorder( "Table.focusCellHighlightBorder"); } } visibleRow = row; return this; } private class ClippedTreeCellRenderer extends DefaultTreeCellRenderer { private boolean inpainting; private String shortText; public void paint(Graphics g) { String fullText = super.getText(); // getText() calls tree.convertValueToText(); // tree.convertValueToText() should call treeModel.convertValueToText(), if possible shortText = SwingUtilities.layoutCompoundLabel( this, g.getFontMetrics(), fullText, getIcon(), getVerticalAlignment(), getHorizontalAlignment(), getVerticalTextPosition(), getHorizontalTextPosition(), getItemRect(itemRect), iconRect, textRect, getIconTextGap()); /** TODO: setText is more heavyweight than we want in this * situation. Make JLabel.text protected instead of private. */ try { inpainting = true; // TODO JW: don't - override getText to return the short version // during painting setText(shortText); // temporarily truncate text super.paint(g); } finally { inpainting = false; setText(fullText); // restore full text } } private Rectangle getItemRect(Rectangle itemRect) { getBounds(itemRect); // LOG.info("rect" + itemRect); itemRect.width = hierarchicalColumnWidth - itemRect.x; return itemRect; } @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { Object val = value; if (treeTable != null) { int treeColumn = treeTable.getTreeTableModel().getHierarchicalColumn(); Object o = null; // LOG.info("value ? " + value); if (treeColumn >= 0) { // following is unreliable during a paint cycle // somehow interferes with BasicTreeUIs painting cache // o = treeTable.getValueAt(row, treeColumn); // ask the model - that's always okay // might blow if the TreeTableModel is strict in // checking the containment of the value and // this renderer is called for sizing with a prototype o = treeTable.getTreeTableModel().getValueAt(value, treeColumn); } // LOG.info("value ? " + value); // JW: why this? null may be a valid value? // removed - didn't see it after asking the model // if (o != null) { // val = o; val = o; } return super.getTreeCellRendererComponent(tree, val, sel, expanded, leaf, row, hasFocus); } // Rectangles filled in by SwingUtilities.layoutCompoundLabel(); private final Rectangle iconRect = new Rectangle(); private final Rectangle textRect = new Rectangle(); // Rectangle filled in by this.getItemRect(); private final Rectangle itemRect = new Rectangle(); } /** Border to draw around the tree, if this is non-null, it will * be painted. */ protected Border highlightBorder = null; protected JXTreeTable treeTable = null; protected int visibleRow = 0; // A JXTreeTable may not have more than one hierarchical column private int hierarchicalColumnWidth = 0; } /** * Returns the adapter that knows how to access the component data model. * The component data adapter is used by filters, sorters, and highlighters. * * @return the adapter that knows how to access the component data model */ @Override protected ComponentAdapter getComponentAdapter() { if (dataAdapter == null) { dataAdapter = new TreeTableDataAdapter(this); } return dataAdapter; } protected static class TreeTableDataAdapter extends JXTable.TableAdapter { private final JXTreeTable table; /** * Constructs a <code>TreeTableDataAdapter</code> for the specified * target component. * * @param component the target component */ public TreeTableDataAdapter(JXTreeTable component) { super(component); table = component; } public JXTreeTable getTreeTable() { return table; } /** * {@inheritDoc} */ @Override public boolean isExpanded() { return table.isExpanded(row); } /** * {@inheritDoc} */ @Override public int getDepth() { return table.getPathForRow(row).getPathCount() - 1; } /** * {@inheritDoc} */ @Override public boolean isLeaf() { // Issue #270-swingx: guard against invisible row TreePath path = table.getPathForRow(row); if (path != null) { return table.getTreeTableModel().isLeaf(path.getLastPathComponent()); } // JW: this is the same as BasicTreeUI.isLeaf. // Shouldn't happen anyway because must be called for visible rows only. return true; } /** * * @return true if the cell identified by this adapter displays hierarchical * nodes; false otherwise */ @Override public boolean isHierarchical() { return table.isHierarchical(column); } } }
package org.jdesktop.swingx; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Enumeration; import java.util.EventObject; import java.util.List; import java.util.logging.Logger; import javax.swing.ActionMap; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.JTree; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.DefaultListSelectionModel; import javax.swing.border.Border; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.event.TreeSelectionListener; import javax.swing.event.TreeWillExpandListener; import javax.swing.plaf.UIResource; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeSelectionModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.FilterPipeline; import org.jdesktop.swingx.decorator.SelectionMapper; import org.jdesktop.swingx.treetable.AbstractTreeTableModel; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; import org.jdesktop.swingx.treetable.TreeTableCellEditor; import org.jdesktop.swingx.treetable.TreeTableModel; public class JXTreeTable extends JXTable { private static final Logger LOG = Logger.getLogger(JXTreeTable.class .getName()); /** * Key for clientProperty to decide whether to apply hack around #168-jdnc. */ public static final String DRAG_HACK_FLAG_KEY = "treeTable.dragHackFlag"; /** * Renderer used to render cells within the * {@link #isHierarchical(int) hierarchical} column. * renderer extends JXTree and implements TableCellRenderer */ private TreeTableCellRenderer renderer; private TreeTableHacker treeTableHacker; private boolean consumedOnPress; /** * Constructs a JXTreeTable using a * {@link org.jdesktop.swingx.treetable.DefaultTreeTableModel}. */ public JXTreeTable() { this(new DefaultTreeTableModel()); } /** * Constructs a JXTreeTable using the specified * {@link org.jdesktop.swingx.treetable.TreeTableModel}. * * @param treeModel model for the JXTreeTable */ public JXTreeTable(TreeTableModel treeModel) { // Implementation note: // Make sure that the SAME instance of treeModel is passed to the // constructor for TreeTableCellRenderer as is passed in the first // argument to the following chained constructor for this JXTreeTable: this(treeModel, new JXTreeTable.TreeTableCellRenderer(treeModel)); } private JXTreeTable(TreeTableModel treeModel, TreeTableCellRenderer renderer) { // To avoid unnecessary object creation, such as the construction of a // DefaultTableModel, it is better to invoke super(TreeTableModelAdapter) // directly, instead of first invoking super() followed by a call to // setTreeTableModel(TreeTableModel). // Adapt tree model to table model before invoking super() super(new TreeTableModelAdapter(treeModel, renderer)); // Enforce referential integrity; bail on fail if (treeModel != renderer.getModel()) { // do not use assert here! throw new IllegalArgumentException("Mismatched TreeTableModel"); } // renderer-related initialization init(renderer); // private method initActions(); // disable sorting super.setSortable(false); // no grid setDefaultMargins(false, false); // // No grid. // setShowGrid(false); // superclass default is "true" // // Default intercell spacing // setIntercellSpacing(spacing); // for both row margin and column margin } /** * Initializes this JXTreeTable and permanently binds the specified renderer * to it. * * @param renderer private tree/renderer permanently and exclusively bound * to this JXTreeTable. */ private void init(TreeTableCellRenderer renderer) { this.renderer = renderer; // Force the JTable and JTree to share their row selection models. ListToTreeSelectionModelWrapper selectionWrapper = new ListToTreeSelectionModelWrapper(); // JW: when would that happen? if (renderer != null) { renderer.bind(this); // IMPORTANT: link back! renderer.setSelectionModel(selectionWrapper); } // adjust the tree's rowHeight to this.rowHeight adjustTreeRowHeight(getRowHeight()); setSelectionModel(selectionWrapper.getListSelectionModel()); // install the renderer as default for hierarchicalColumn setDefaultRenderer(AbstractTreeTableModel.hierarchicalColumnClass, renderer); // Install the default editor. setDefaultEditor(AbstractTreeTableModel.hierarchicalColumnClass, new TreeTableCellEditor(renderer)); // propagate the lineStyle property to the renderer PropertyChangeListener l = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { JXTreeTable.this.renderer.putClientProperty(evt.getPropertyName(), evt.getNewValue()); } }; addPropertyChangeListener("JTree.lineStyle", l); } private void initActions() { // Register the actions that this class can handle. ActionMap map = getActionMap(); map.put("expand-all", new Actions("expand-all")); map.put("collapse-all", new Actions("collapse-all")); } /** * A small class which dispatches actions. * TODO: Is there a way that we can make this static? */ private class Actions extends UIAction { Actions(String name) { super(name); } public void actionPerformed(ActionEvent evt) { if ("expand-all".equals(getName())) { expandAll(); } else if ("collapse-all".equals(getName())) { collapseAll(); } } } /** * overridden to do nothing. * * TreeTable is not sortable by default, because * Sorters/Filters currently don't work properly. * */ @Override public void setSortable(boolean sortable) { // no-op } /** * overridden to do nothing. * * TreeTable is not sortable by default, because * Sorters/Filters currently don't work properly. * */ @Override public void setFilters(FilterPipeline pipeline) { } /** * Overriden to invoke repaint for the particular location if * the column contains the tree. This is done as the tree editor does * not fill the bounds of the cell, we need the renderer to paint * the tree in the background, and then draw the editor over it. * You should not need to call this method directly. <p> * * Additionally, there is tricksery involved to expand/collapse * the nodes. * * {@inheritDoc} */ @Override public boolean editCellAt(int row, int column, EventObject e) { getTreeTableHacker().hitHandleDetectionFromEditCell(column, e); // RG: Fix Issue 49! boolean canEdit = super.editCellAt(row, column, e); if (canEdit && isHierarchical(column)) { repaint(getCellRect(row, column, false)); } return canEdit; } /** * Overridden to enable hit handle detection a mouseEvent which triggered * a expand/collapse. */ @Override protected void processMouseEvent(MouseEvent e) { // BasicTableUI selects on released if the pressed had been // consumed. So we try to fish for the accompanying released // here and consume it as wll. if ((e.getID() == MouseEvent.MOUSE_RELEASED) && consumedOnPress) { consumedOnPress = false; e.consume(); return; } if (getTreeTableHacker().hitHandleDetectionFromProcessMouse(e)) { // Issue #332-swing: hacking around selection loss. // prevent the // _table_ selection by consuming the mouseEvent // if it resulted in a expand/collapse consumedOnPress = true; e.consume(); return; } consumedOnPress = false; super.processMouseEvent(e); } protected TreeTableHacker getTreeTableHacker() { if (treeTableHacker == null) { treeTableHacker = createTreeTableHacker(); } return treeTableHacker; } protected TreeTableHacker createTreeTableHacker() { // return new TreeTableHacker(); return new TreeTableHackerExt(); } /** * Temporary class to have all the hacking at one place. Naturally, it will * change a lot. The base class has the "stable" behaviour as of around * jun2006 (before starting the fix for 332-swingx). <p> * * specifically: * * <ol> * <li> hitHandleDetection triggeredn in editCellAt * </ol> * */ public class TreeTableHacker { protected boolean expansionChangedFlag; /** * Decision whether the handle hit detection * should be done in processMouseEvent or editCellAt. * Here: returns false. * * @return true for handle hit detection in processMouse, false * for editCellAt. */ protected boolean isHitDetectionFromProcessMouse() { return false; } /** * Entry point for hit handle detection called from editCellAt, * does nothing if isHitDetectionFromProcessMouse is true; * * @see #editCellAt(int, int, EventObject) * @see #isHitDetectionFromProcessMouse() */ public void hitHandleDetectionFromEditCell(int column, EventObject e) { if (!isHitDetectionFromProcessMouse()) { expandOrCollapseNode(column, e); } } /** * Entry point for hit handle detection called from processMouse. * Does nothing if isHitDetectionFromProcessMouse is false. * * @return true if the mouseEvent triggered an expand/collapse in * the renderer, false otherwise. * * @see #processMouseEvent(MouseEvent) * @see #isHitDetectionFromProcessMouse() */ public boolean hitHandleDetectionFromProcessMouse(MouseEvent e) { if (!isHitDetectionFromProcessMouse()) return false; int col = columnAtPoint(e.getPoint()); boolean hit = ((col >= 0) && expandOrCollapseNode(columnAtPoint(e .getPoint()), e)); return hit; } /** * complete editing if collapsed/expanded. * Here: any editing is always cancelled. * This is a rude fix to #120-jdnc: data corruption on * collapse/expand if editing. This is called from * the renderer after expansion related state has changed. * PENDING JW: should it take the old editing path as parameter? * Might be possible to be a bit more polite, and internally * reset the editing coordinates? On the other hand: the rudeness * is the table's usual behaviour - which is often removing the editor * as first reaction to incoming events. * */ protected void completeEditing() { if (isEditing()) { getCellEditor().cancelCellEditing(); } } /** * Tricksery to make the tree expand/collapse. * <p> * * This might be - indirectly - called from one of two places: * <ol> * <li> editCellAt: original, stable but buggy (#332, #222) the table's * own selection had been changed due to the click before even entering * into editCellAt so all tree selection state is lost. * * <li> processMouseEvent: the idea is to catch the mouseEvent, check * if it triggered an expanded/collapsed, consume and return if so or * pass to super if not. * </ol> * * <p> * widened access for testing ... * * * @param column the column index under the event, if any. * @param e the event which might trigger a expand/collapse. * * @return this methods evaluation as to whether the event triggered a * expand/collaps */ protected boolean expandOrCollapseNode(int column, EventObject e) { if (!isHierarchical(column)) return false; if (!mightBeExpansionTrigger(e)) return false; boolean changedExpansion = false; MouseEvent me = (MouseEvent) e; if (hackAroundDragEnabled(me)) { /* * Hack around #168-jdnc: dirty little hack mentioned in the * forum discussion about the issue: fake a mousePressed if drag * enabled. The usability is slightly impaired because the * expand/collapse is effectively triggered on released only * (drag system intercepts and consumes all other). */ me = new MouseEvent((Component) me.getSource(), MouseEvent.MOUSE_PRESSED, me.getWhen(), me .getModifiers(), me.getX(), me.getY(), me .getClickCount(), me.isPopupTrigger()); } // If the modifiers are not 0 (or the left mouse button), // tree may try and toggle the selection, and table // will then try and toggle, resulting in the // selection remaining the same. To avoid this, we // only dispatch when the modifiers are 0 (or the left mouse // button). if (me.getModifiers() == 0 || me.getModifiers() == InputEvent.BUTTON1_MASK) { MouseEvent pressed = new MouseEvent(renderer, me.getID(), me .getWhen(), me.getModifiers(), me.getX() - getCellRect(0, column, false).x, me.getY(), me .getClickCount(), me.isPopupTrigger()); renderer.dispatchEvent(pressed); // For Mac OS X, we need to dispatch a MOUSE_RELEASED as well MouseEvent released = new MouseEvent(renderer, java.awt.event.MouseEvent.MOUSE_RELEASED, pressed .getWhen(), pressed.getModifiers(), pressed .getX(), pressed.getY(), pressed .getClickCount(), pressed.isPopupTrigger()); renderer.dispatchEvent(released); if (expansionChangedFlag) { changedExpansion = true; } } expansionChangedFlag = false; return changedExpansion; } protected boolean mightBeExpansionTrigger(EventObject e) { if (!(e instanceof MouseEvent)) return false; MouseEvent me = (MouseEvent) e; if (!SwingUtilities.isLeftMouseButton(me)) return false; return me.getID() == MouseEvent.MOUSE_PRESSED; } /** * called from the renderer's setExpandedPath after * all expansion-related updates happend. * */ protected void expansionChanged() { expansionChangedFlag = true; } } /** * * Note: currently this class looks a bit funny (only overriding * the hit decision method). That's because the "experimental" code * as of the last round moved to stable. But I expect that there's more * to come, so I leave it here. * * <ol> * <li> hit handle detection in processMouse * </ol> */ public class TreeTableHackerExt extends TreeTableHacker { /** * Here: returns true. * @inheritDoc */ @Override protected boolean isHitDetectionFromProcessMouse() { return true; } } /** * decides whether we want to apply the hack for #168-jdnc. here: returns * true if dragEnabled() and the improved drag handling is not activated (or * the system property is not accessible). The given mouseEvent is not * analysed. * * PENDING: Mustang? * * @param me the mouseEvent that triggered a editCellAt * @return true if the hack should be applied. */ protected boolean hackAroundDragEnabled(MouseEvent me) { Boolean dragHackFlag = (Boolean) getClientProperty(DRAG_HACK_FLAG_KEY); if (dragHackFlag == null) { // access and store the system property as a client property once String priority = null; try { priority = System.getProperty("sun.swing.enableImprovedDragGesture"); } catch (Exception ex) { // found some foul expression or failed to read the property } dragHackFlag = (priority == null); putClientProperty(DRAG_HACK_FLAG_KEY, dragHackFlag); } return getDragEnabled() && dragHackFlag; } /** * Overridden to provide a workaround for BasicTableUI anomaly. Make sure * the UI never tries to resize the editor. The UI currently uses different * techniques to paint the renderers and editors. So, overriding setBounds() * is not the right thing to do for an editor. Returning -1 for the * editing row in this case, ensures the editor is never painted. * * {@inheritDoc} */ @Override public int getEditingRow() { return isHierarchical(editingColumn) ? -1 : editingRow; } /** * Returns the actual row that is editing as <code>getEditingRow</code> * will always return -1. */ private int realEditingRow() { return editingRow; } /** * Sets the data model for this JXTreeTable to the specified * {@link org.jdesktop.swingx.treetable.TreeTableModel}. The same data model * may be shared by any number of JXTreeTable instances. * * @param treeModel data model for this JXTreeTable */ public void setTreeTableModel(TreeTableModel treeModel) { TreeTableModel old = getTreeTableModel(); renderer.setModel(treeModel); ((TreeTableModelAdapter)getModel()).setTreeTableModel(treeModel); // Enforce referential integrity; bail on fail // JW: when would that happen? we just set it... if (treeModel != renderer.getModel()) { // do not use assert here! throw new IllegalArgumentException("Mismatched TreeTableModel"); } firePropertyChange("treeTableModel", old, getTreeTableModel()); } /** * Returns the underlying TreeTableModel for this JXTreeTable. * * @return the underlying TreeTableModel for this JXTreeTable */ public TreeTableModel getTreeTableModel() { return ((TreeTableModelAdapter) getModel()).getTreeTableModel(); } @Override public final void setModel(TableModel tableModel) { // note final keyword if (tableModel instanceof TreeTableModelAdapter) { if (((TreeTableModelAdapter) tableModel).getTreeTable() == null) { // Passing the above test ensures that this method is being // invoked either from JXTreeTable/JTable constructor or from // setTreeTableModel(TreeTableModel) super.setModel(tableModel); // invoke superclass version ((TreeTableModelAdapter) tableModel).bind(this); // permanently bound // Once a TreeTableModelAdapter is bound to any JXTreeTable instance, // invoking JXTreeTable.setModel() with that adapter will throw an // that a TreeTableModelAdapter is NOT shared by another JXTreeTable. } else { throw new IllegalArgumentException("model already bound"); } } else { throw new IllegalArgumentException("unsupported model type"); } } @Override public void tableChanged(TableModelEvent e) { if (isStructureChanged(e) || isUpdate(e)) { super.tableChanged(e); } else { resizeAndRepaint(); } } /** * Overridden to return a do-nothing mapper. * */ @Override public SelectionMapper getSelectionMapper() { // JW: don't want to change super assumption // (mapper != null) - the selection mapping will change // anyway in Mustang (using core functionality) return NO_OP_SELECTION_MANAGER ; } private static final SelectionMapper NO_OP_SELECTION_MANAGER = new SelectionMapper() { private ListSelectionModel viewSelectionModel = new DefaultListSelectionModel(); public ListSelectionModel getViewSelectionModel() { return viewSelectionModel; } public void setViewSelectionModel(ListSelectionModel viewSelectionModel) { this.viewSelectionModel = viewSelectionModel; } public void setFilters(FilterPipeline pipeline) { // do nothing } public void insertIndexInterval(int start, int length, boolean before) { // do nothing } public void removeIndexInterval(int start, int end) { // do nothing } public void setEnabled(boolean enabled) { // do nothing } public boolean isEnabled() { return false; } public void clearModelSelection() { // do nothing } }; /** * Throws UnsupportedOperationException because variable height rows are * not supported. * * @param row ignored * @param rowHeight ignored * @throws UnsupportedOperationException because variable height rows are * not supported */ @Override public final void setRowHeight(int row, int rowHeight) { throw new UnsupportedOperationException("variable height rows not supported"); } /** * Sets the row height for this JXTreeTable and forwards the * row height to the renderering tree. * * @param rowHeight height of a row. */ @Override public void setRowHeight(int rowHeight) { super.setRowHeight(rowHeight); adjustTreeRowHeight(getRowHeight()); } /** * Forwards tableRowHeight to tree. * * @param tableRowHeight height of a row. */ protected void adjustTreeRowHeight(int tableRowHeight) { if (renderer != null && renderer.getRowHeight() != tableRowHeight) { renderer.setRowHeight(tableRowHeight); } } /** * Forwards treeRowHeight to table. This is for completeness only: the * rendering tree is under our total control, so we don't expect * any external call to tree.setRowHeight. * * @param treeRowHeight height of a row. */ protected void adjustTableRowHeight(int treeRowHeight) { if (getRowHeight() != treeRowHeight) { adminSetRowHeight(treeRowHeight); } } /** * <p>Overridden to ensure that private renderer state is kept in sync with the * state of the component. Calls the inherited version after performing the * necessary synchronization. If you override this method, make sure you call * this version from your version of this method.</p> * * <p>This version maps the selection mode used by the renderer to match the * selection mode specified for the table. Specifically, the modes are mapped * as follows: * <pre> * ListSelectionModel.SINGLE_INTERVAL_SELECTION: TreeSelectionModel.CONTIGUOUS_TREE_SELECTION; * ListSelectionModel.MULTIPLE_INTERVAL_SELECTION: TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION; * any other (default): TreeSelectionModel.SINGLE_TREE_SELECTION; * </pre> * * {@inheritDoc} * * @param mode any of the table selection modes */ @Override public void setSelectionMode(int mode) { if (renderer != null) { switch (mode) { case ListSelectionModel.SINGLE_INTERVAL_SELECTION: { renderer.getSelectionModel().setSelectionMode( TreeSelectionModel.CONTIGUOUS_TREE_SELECTION); break; } case ListSelectionModel.MULTIPLE_INTERVAL_SELECTION: { renderer.getSelectionModel().setSelectionMode( TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); break; } default: { renderer.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION); break; } } } super.setSelectionMode(mode); } /** * Overrides superclass version to provide support for cell decorators. * * @param renderer the <code>TableCellRenderer</code> to prepare * @param row the row of the cell to render, where 0 is the first row * @param column the column of the cell to render, where 0 is the first column * @return the <code>Component</code> used as a stamp to render the specified cell */ @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component component = super.prepareRenderer(renderer, row, column); return applyRenderer(component, getComponentAdapter(row, column)); } /** * Performs necessary housekeeping before the renderer is actually applied. * * @param component * @param adapter component data adapter * @throws NullPointerException if the specified component or adapter is null */ protected Component applyRenderer(Component component, ComponentAdapter adapter) { if (component == null) { throw new IllegalArgumentException("null component"); } if (adapter == null) { throw new IllegalArgumentException("null component data adapter"); } if (isHierarchical(adapter.column)) { // After all decorators have been applied, make sure that relevant // attributes of the table cell renderer are applied to the // tree cell renderer before the hierarchical column is rendered! TreeCellRenderer tcr = renderer.getCellRenderer(); if (tcr instanceof JXTree.DelegatingRenderer) { tcr = ((JXTree.DelegatingRenderer) tcr).getDelegateRenderer(); } if (tcr instanceof DefaultTreeCellRenderer) { DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer) tcr); if (adapter.isSelected()) { dtcr.setTextSelectionColor(component.getForeground()); dtcr.setBackgroundSelectionColor(component.getBackground()); } else { dtcr.setTextNonSelectionColor(component.getForeground()); dtcr.setBackgroundNonSelectionColor(component.getBackground()); } } } return component; } /** * Sets the specified TreeCellRenderer as the Tree cell renderer. * * @param cellRenderer to use for rendering tree cells. */ public void setTreeCellRenderer(TreeCellRenderer cellRenderer) { if (renderer != null) { renderer.setCellRenderer(cellRenderer); } } public TreeCellRenderer getTreeCellRenderer() { return renderer.getCellRenderer(); } @Override public String getToolTipText(MouseEvent event) { int column = columnAtPoint(event.getPoint()); if (isHierarchical(column)) { int row = rowAtPoint(event.getPoint()); return renderer.getToolTipText(event, row, column); } return super.getToolTipText(event); } /** * Sets the specified icon as the icon to use for rendering collapsed nodes. * * @param icon to use for rendering collapsed nodes */ public void setCollapsedIcon(Icon icon) { renderer.setCollapsedIcon(icon); } /** * Sets the specified icon as the icon to use for rendering expanded nodes. * * @param icon to use for rendering expanded nodes */ public void setExpandedIcon(Icon icon) { renderer.setExpandedIcon(icon); } /** * Sets the specified icon as the icon to use for rendering open container nodes. * * @param icon to use for rendering open nodes */ public void setOpenIcon(Icon icon) { renderer.setOpenIcon(icon); } /** * Sets the specified icon as the icon to use for rendering closed container nodes. * * @param icon to use for rendering closed nodes */ public void setClosedIcon(Icon icon) { renderer.setClosedIcon(icon); } /** * Sets the specified icon as the icon to use for rendering leaf nodes. * * @param icon to use for rendering leaf nodes */ public void setLeafIcon(Icon icon) { renderer.setLeafIcon(icon); } /** * Overridden to ensure that private renderer state is kept in sync with the * state of the component. Calls the inherited version after performing the * necessary synchronization. If you override this method, make sure you call * this version from your version of this method. */ @Override public void clearSelection() { if (renderer != null) { renderer.clearSelection(); } super.clearSelection(); } /** * Collapses all nodes in the treetable. */ public void collapseAll() { renderer.collapseAll(); } /** * Expands all nodes in the treetable. */ public void expandAll() { renderer.expandAll(); } /** * Collapses the node at the specified path in the treetable. * * @param path path of the node to collapse */ public void collapsePath(TreePath path) { renderer.collapsePath(path); } /** * Expands the the node at the specified path in the treetable. * * @param path path of the node to expand */ public void expandPath(TreePath path) { renderer.expandPath(path); } /** * Makes sure all the path components in path are expanded (except * for the last path component) and scrolls so that the * node identified by the path is displayed. Only works when this * <code>JTree</code> is contained in a <code>JScrollPane</code>. * * (doc copied from JTree) * * PENDING: JW - where exactly do we want to scroll? Here: the scroll * is in vertical direction only. Might need to show the tree column? * * @param path the <code>TreePath</code> identifying the node to * bring into view */ public void scrollPathToVisible(TreePath path) { if (path == null) return; renderer.makeVisible(path); int row = getRowForPath(path); scrollRowToVisible(row); } /** * Collapses the row in the treetable. If the specified row index is * not valid, this method will have no effect. */ public void collapseRow(int row) { renderer.collapseRow(row); } /** * Expands the specified row in the treetable. If the specified row index is * not valid, this method will have no effect. */ public void expandRow(int row) { renderer.expandRow(row); } /** * Returns true if the value identified by path is currently viewable, which * means it is either the root or all of its parents are expanded. Otherwise, * this method returns false. * * @return true, if the value identified by path is currently viewable; * false, otherwise */ public boolean isVisible(TreePath path) { return renderer.isVisible(path); } /** * Returns true if the node identified by path is currently expanded. * Otherwise, this method returns false. * * @param path path * @return true, if the value identified by path is currently expanded; * false, otherwise */ public boolean isExpanded(TreePath path) { return renderer.isExpanded(path); } /** * Returns true if the node at the specified display row is currently expanded. * Otherwise, this method returns false. * * @param row row * @return true, if the node at the specified display row is currently expanded. * false, otherwise */ public boolean isExpanded(int row) { return renderer.isExpanded(row); } /** * Returns true if the node identified by path is currently collapsed, * this will return false if any of the values in path are currently not * being displayed. * * @param path path * @return true, if the value identified by path is currently collapsed; * false, otherwise */ public boolean isCollapsed(TreePath path) { return renderer.isCollapsed(path); } /** * Returns true if the node at the specified display row is collapsed. * * @param row row * @return true, if the node at the specified display row is currently collapsed. * false, otherwise */ public boolean isCollapsed(int row) { return renderer.isCollapsed(row); } /** * Returns an <code>Enumeration</code> of the descendants of the * path <code>parent</code> that * are currently expanded. If <code>parent</code> is not currently * expanded, this will return <code>null</code>. * If you expand/collapse nodes while * iterating over the returned <code>Enumeration</code> * this may not return all * the expanded paths, or may return paths that are no longer expanded. * * @param parent the path which is to be examined * @return an <code>Enumeration</code> of the descendents of * <code>parent</code>, or <code>null</code> if * <code>parent</code> is not currently expanded */ public Enumeration getExpandedDescendants(TreePath parent) { return renderer.getExpandedDescendants(parent); } /** * Returns the TreePath for a given x,y location. * * @param x x value * @param y y value * * @return the <code>TreePath</code> for the givern location. */ public TreePath getPathForLocation(int x, int y) { int row = rowAtPoint(new Point(x,y)); if (row == -1) { return null; } return renderer.getPathForRow(row); } /** * Returns the TreePath for a given row. * * @param row * * @return the <code>TreePath</code> for the given row. */ public TreePath getPathForRow(int row) { return renderer.getPathForRow(row); } /** * Returns the row for a given TreePath. * * @param path * @return the row for the given <code>TreePath</code>. */ public int getRowForPath(TreePath path) { return renderer.getRowForPath(path); } /** * Determines whether or not the root node from the TreeModel is visible. * * @param visible true, if the root node is visible; false, otherwise */ public void setRootVisible(boolean visible) { renderer.setRootVisible(visible); // JW: the revalidate forces the root to appear after a // toggling a visible from an initially invisible root. // JTree fires a propertyChange on the ROOT_VISIBLE_PROPERTY // BasicTreeUI reacts by (ultimately) calling JTree.treeDidChange // which revalidate the tree part. // Might consider to listen for the propertyChange (fired only if there // actually was a change) instead of revalidating unconditionally. revalidate(); repaint(); } /** * Returns true if the root node of the tree is displayed. * * @return true if the root node of the tree is displayed */ public boolean isRootVisible() { return renderer.isRootVisible(); } /** * Sets the value of the <code>scrollsOnExpand</code> property for the tree * part. This property specifies whether the expanded paths should be scrolled * into view. In a look and feel in which a tree might not need to scroll * when expanded, this property may be ignored. * * @param scroll true, if expanded paths should be scrolled into view; * false, otherwise */ public void setScrollsOnExpand(boolean scroll) { renderer.setScrollsOnExpand(scroll); } /** * Returns the value of the <code>scrollsOnExpand</code> property. * * @return the value of the <code>scrollsOnExpand</code> property */ public boolean getScrollsOnExpand() { return renderer.getScrollsOnExpand(); } /** * Sets the value of the <code>showsRootHandles</code> property for the tree * part. This property specifies whether the node handles should be displayed. * If handles are not supported by a particular look and feel, this property * may be ignored. * * @param visible true, if root handles should be shown; false, otherwise */ public void setShowsRootHandles(boolean visible) { renderer.setShowsRootHandles(visible); repaint(); } /** * Returns the value of the <code>showsRootHandles</code> property. * * @return the value of the <code>showsRootHandles</code> property */ public boolean getShowsRootHandles() { return renderer.getShowsRootHandles(); } /** * Sets the value of the <code>expandsSelectedPaths</code> property for the tree * part. This property specifies whether the selected paths should be expanded. * * @param expand true, if selected paths should be expanded; false, otherwise */ public void setExpandsSelectedPaths(boolean expand) { renderer.setExpandsSelectedPaths(expand); } /** * Returns the value of the <code>expandsSelectedPaths</code> property. * * @return the value of the <code>expandsSelectedPaths</code> property */ public boolean getExpandsSelectedPaths() { return renderer.getExpandsSelectedPaths(); } /** * Returns the number of mouse clicks needed to expand or close a node. * * @return number of mouse clicks before node is expanded */ public int getToggleClickCount() { return renderer.getToggleClickCount(); } /** * Sets the number of mouse clicks before a node will expand or close. * The default is two. * * @param clickCount the number of clicks required to expand/collapse a node. */ public void setToggleClickCount(int clickCount) { renderer.setToggleClickCount(clickCount); } /** * Returns true if the tree is configured for a large model. * The default value is false. * * @return true if a large model is suggested * @see #setLargeModel */ public boolean isLargeModel() { return renderer.isLargeModel(); } /** * Specifies whether the UI should use a large model. * (Not all UIs will implement this.) <p> * * <strong>NOTE</strong>: this method is exposed for completeness - * currently it's not recommended * to use a large model because there are some issues * (not yet fully understood), namely * issue #25-swingx, and probably #270-swingx. * * @param newValue true to suggest a large model to the UI */ public void setLargeModel(boolean newValue) { renderer.setLargeModel(newValue); // JW: random method calling ... doesn't help // renderer.treeDidChange(); // revalidate(); // repaint(); } /** * Adds a listener for <code>TreeExpansion</code> events. * * TODO (JW): redirect event source to this. * * @param tel a TreeExpansionListener that will be notified * when a tree node is expanded or collapsed */ public void addTreeExpansionListener(TreeExpansionListener tel) { renderer.addTreeExpansionListener(tel); } /** * Removes a listener for <code>TreeExpansion</code> events. * @param tel the <code>TreeExpansionListener</code> to remove */ public void removeTreeExpansionListener(TreeExpansionListener tel) { renderer.removeTreeExpansionListener(tel); } /** * Adds a listener for <code>TreeSelection</code> events. * TODO (JW): redirect event source to this. * * @param tsl a TreeSelectionListener that will be notified * when a tree node is selected or deselected */ public void addTreeSelectionListener(TreeSelectionListener tsl) { renderer.addTreeSelectionListener(tsl); } /** * Removes a listener for <code>TreeSelection</code> events. * @param tsl the <code>TreeSelectionListener</code> to remove */ public void removeTreeSelectionListener(TreeSelectionListener tsl) { renderer.removeTreeSelectionListener(tsl); } /** * Adds a listener for <code>TreeWillExpand</code> events. * TODO (JW): redirect event source to this. * * @param tel a TreeWillExpandListener that will be notified * when a tree node will be expanded or collapsed */ public void addTreeWillExpandListener(TreeWillExpandListener tel) { renderer.addTreeWillExpandListener(tel); } /** * Removes a listener for <code>TreeWillExpand</code> events. * @param tel the <code>TreeWillExpandListener</code> to remove */ public void removeTreeWillExpandListener(TreeWillExpandListener tel) { renderer.removeTreeWillExpandListener(tel); } /** * Returns the selection model for the tree portion of the this treetable. * * @return selection model for the tree portion of the this treetable */ public TreeSelectionModel getTreeSelectionModel() { return renderer.getSelectionModel(); // RG: Fix JDNC issue 41 } /** * Overriden to invoke supers implementation, and then, * if the receiver is editing a Tree column, the editors bounds is * reset. The reason we have to do this is because JTable doesn't * think the table is being edited, as <code>getEditingRow</code> returns * -1, and therefore doesn't automaticly resize the editor for us. */ @Override public void sizeColumnsToFit(int resizingColumn) { /** TODO: Review wrt doLayout() */ super.sizeColumnsToFit(resizingColumn); // rg:changed if (getEditingColumn() != -1 && isHierarchical(editingColumn)) { Rectangle cellRect = getCellRect(realEditingRow(), getEditingColumn(), false); Component component = getEditorComponent(); component.setBounds(cellRect); component.validate(); } } /** * Overridden to message super and forward the method to the tree. * Since the tree is not actually in the component hieachy it will * never receive this unless we forward it in this manner. */ @Override public void updateUI() { super.updateUI(); if (renderer != null) { renderer.updateUI(); // Do this so that the editor is referencing the current renderer // from the tree. The renderer can potentially change each time // laf changes. // JW: Hmm ... really? The renderer is fixed, set once // in creating treetable... // commented to fix #213-jdnc (allow custom editors) // setDefaultEditor(AbstractTreeTableModel.hierarchicalColumnClass, // new TreeTableCellEditor(renderer)); if (getBackground() == null || getBackground() instanceof UIResource) { setBackground(renderer.getBackground()); } } } /** * Determines if the specified column contains hierarchical nodes. * * @param column zero-based index of the column * @return true if the class of objects in the specified column implement * the {@link javax.swing.tree.TreeNode} interface; false otherwise. */ @Override public boolean isHierarchical(int column) { return AbstractTreeTableModel.hierarchicalColumnClass.isAssignableFrom( getColumnClass(column)); } /** * ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel * to listen for changes in the ListSelectionModel it maintains. Once * a change in the ListSelectionModel happens, the paths are updated * in the DefaultTreeSelectionModel. */ class ListToTreeSelectionModelWrapper extends DefaultTreeSelectionModel { /** Set to true when we are updating the ListSelectionModel. */ protected boolean updatingListSelectionModel; public ListToTreeSelectionModelWrapper() { super(); getListSelectionModel().addListSelectionListener (createListSelectionListener()); } /** * Returns the list selection model. ListToTreeSelectionModelWrapper * listens for changes to this model and updates the selected paths * accordingly. */ ListSelectionModel getListSelectionModel() { return listSelectionModel; } /** * This is overridden to set <code>updatingListSelectionModel</code> * and message super. This is the only place DefaultTreeSelectionModel * alters the ListSelectionModel. */ @Override public void resetRowSelection() { if (!updatingListSelectionModel) { updatingListSelectionModel = true; try { super.resetRowSelection(); } finally { updatingListSelectionModel = false; } } // Notice how we don't message super if // updatingListSelectionModel is true. If // updatingListSelectionModel is true, it implies the // ListSelectionModel has already been updated and the // paths are the only thing that needs to be updated. } /** * Creates and returns an instance of ListSelectionHandler. */ protected ListSelectionListener createListSelectionListener() { return new ListSelectionHandler(); } /** * If <code>updatingListSelectionModel</code> is false, this will * reset the selected paths from the selected rows in the list * selection model. */ protected void updateSelectedPathsFromSelectedRows() { if (!updatingListSelectionModel) { updatingListSelectionModel = true; try { if (listSelectionModel.isSelectionEmpty()) { clearSelection(); } else { // This is way expensive, ListSelectionModel needs an // enumerator for iterating. int min = listSelectionModel.getMinSelectionIndex(); int max = listSelectionModel.getMaxSelectionIndex(); List<TreePath> paths = new ArrayList<TreePath>(); for (int counter = min; counter <= max; counter++) { if (listSelectionModel.isSelectedIndex(counter)) { TreePath selPath = renderer.getPathForRow( counter); if (selPath != null) { paths.add(selPath); } } } setSelectionPaths(paths.toArray(new TreePath[paths.size()])); // need to force here: usually the leadRow is adjusted // in resetRowSelection which is disabled during this method leadRow = leadIndex; } } finally { updatingListSelectionModel = false; } } } /** * Class responsible for calling updateSelectedPathsFromSelectedRows * when the selection of the list changse. */ class ListSelectionHandler implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { updateSelectedPathsFromSelectedRows(); } } } } protected static class TreeTableModelAdapter extends AbstractTableModel { private TreeModelListener treeModelListener; TreeTableModelAdapter(TreeTableModel model, JTree tree) { assert model != null; assert tree != null; this.tree = tree; // need tree to implement getRowCount() setTreeTableModel(model); tree.addTreeExpansionListener(new TreeExpansionListener() { // Don't use fireTableRowsInserted() here; the selection model // would get updated twice. public void treeExpanded(TreeExpansionEvent event) { updateAfterExpansionEvent(event); } public void treeCollapsed(TreeExpansionEvent event) { updateAfterExpansionEvent(event); } }); } /** * updates the table after having received an TreeExpansionEvent.<p> * * @param event the TreeExpansionEvent which triggered the method call. */ protected void updateAfterExpansionEvent(TreeExpansionEvent event) { // moved to let the renderer handle directly // treeTable.getTreeTableHacker().setExpansionChangedFlag(); // JW: delayed fire leads to a certain sluggishness occasionally? fireTableDataChanged(); } /** * * @param model must not be null! */ public void setTreeTableModel(TreeTableModel model) { TreeTableModel old = getTreeTableModel(); if (old != null) { old.removeTreeModelListener(getTreeModelListener()); } this.model = model; // Install a TreeModelListener that can update the table when // tree changes. model.addTreeModelListener(getTreeModelListener()); fireTableStructureChanged(); } /** * @return <code>TreeModelListener</code> */ private TreeModelListener getTreeModelListener() { if (treeModelListener == null) { treeModelListener = new TreeModelListener() { // We use delayedFireTableDataChanged as we can // not be guaranteed the tree will have finished processing // the event before us. public void treeNodesChanged(TreeModelEvent e) { delayedFireTableDataChanged(e, 0); } public void treeNodesInserted(TreeModelEvent e) { delayedFireTableDataChanged(e, 1); } public void treeNodesRemoved(TreeModelEvent e) { delayedFireTableDataChanged(e, 2); } public void treeStructureChanged(TreeModelEvent e) { delayedFireTableDataChanged(); } }; } return treeModelListener; } /** * Returns the real TreeTableModel that is wrapped by this TreeTableModelAdapter. * * @return the real TreeTableModel that is wrapped by this TreeTableModelAdapter */ public TreeTableModel getTreeTableModel() { return model; } /** * Returns the JXTreeTable instance to which this TreeTableModelAdapter is * permanently and exclusively bound. For use by * {@link org.jdesktop.swingx.JXTreeTable#setModel(javax.swing.table.TableModel)}. * * @return JXTreeTable to which this TreeTableModelAdapter is permanently bound */ protected JXTreeTable getTreeTable() { return treeTable; } /** * Immutably binds this TreeTableModelAdapter to the specified JXTreeTable. * * @param treeTable the JXTreeTable instance that this adapter is bound to. */ protected final void bind(JXTreeTable treeTable) { // Suppress potentially subversive invocation! // Prevent clearing out the deck for possible hijack attempt later! if (treeTable == null) { throw new IllegalArgumentException("null treeTable"); } if (this.treeTable == null) { this.treeTable = treeTable; } else { throw new IllegalArgumentException("adapter already bound"); } } // Wrappers, implementing TableModel interface. // TableModelListener management provided by AbstractTableModel superclass. @Override public Class getColumnClass(int column) { return model.getColumnClass(column); } public int getColumnCount() { return model.getColumnCount(); } @Override public String getColumnName(int column) { return model.getColumnName(column); } public int getRowCount() { return tree.getRowCount(); } public Object getValueAt(int row, int column) { // Issue #270-swingx: guard against invisible row Object node = nodeForRow(row); return node != null ? model.getValueAt(node, column) : null; } @Override public boolean isCellEditable(int row, int column) { // Issue #270-swingx: guard against invisible row Object node = nodeForRow(row); return node != null ? model.isCellEditable(node, column) : false; } @Override public void setValueAt(Object value, int row, int column) { // Issue #270-swingx: guard against invisible row Object node = nodeForRow(row); if (node != null) { model.setValueAt(value, node, column); } } protected Object nodeForRow(int row) { // Issue #270-swingx: guard against invisible row TreePath path = tree.getPathForRow(row); return path != null ? path.getLastPathComponent() : null; } /** * Invokes fireTableDataChanged after all the pending events have been * processed. SwingUtilities.invokeLater is used to handle this. */ private void delayedFireTableDataChanged() { SwingUtilities.invokeLater(new Runnable() { public void run() { fireTableDataChanged(); } }); } /** * Invokes fireTableDataChanged after all the pending events have been * processed. SwingUtilities.invokeLater is used to handle this. */ private void delayedFireTableDataChanged(final TreeModelEvent tme, final int typeChange) { SwingUtilities.invokeLater(new Runnable() { public void run() { int indices[] = tme.getChildIndices(); TreePath path = tme.getTreePath(); if (indices != null) { if (tree.isExpanded(path)) { // Dont bother to update if the parent // node is collapsed int startingRow = tree.getRowForPath(path)+1; int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int i=0;i<indices.length;i++) { if (indices[i] < min) { min = indices[i]; } if (indices[i] > max) { max = indices[i]; } } switch (typeChange) { case 0 : fireTableRowsUpdated(startingRow + min, startingRow+max); break; case 1: fireTableRowsInserted(startingRow + min, startingRow+max); break; case 2: fireTableRowsDeleted(startingRow + min, startingRow+max); break; } } else { // not expanded - but change might effect appearance of parent // Issue #82-swingx int row = tree.getRowForPath(path); // fix Issue #247-swingx: prevent accidental structureChanged // for collapsed path // in this case row == -1, which == TableEvent.HEADER_ROW if (row >= 0) fireTableRowsUpdated(row, row); } } else { // case where the event is fired to identify root. fireTableDataChanged(); } } }); } private TreeTableModel model; // immutable private final JTree tree; // immutable private JXTreeTable treeTable = null; // logically immutable } static class TreeTableCellRenderer extends JXTree implements TableCellRenderer { // Force user to specify TreeTableModel instead of more general TreeModel public TreeTableCellRenderer(TreeTableModel model) { super(model); putClientProperty("JTree.lineStyle", "None"); setRootVisible(false); // superclass default is "true" setShowsRootHandles(true); // superclass default is "false" /** TODO: Support truncated text directly in DefaultTreeCellRenderer. */ setOverwriteRendererIcons(true); setCellRenderer(new ClippedTreeCellRenderer()); } /** * Hack around #297-swingx: tooltips shown at wrong row. * * The problem is that - due to much tricksery when rendering * the tree - the given coordinates are rather useless. As a * consequence, super maps to wrong coordinates. This takes * over completely. * * PENDING: bidi? * * @param event the mouseEvent in treetable coordinates * @param row the view row index * @param column the view column index * @return the tooltip as appropriate for the given row */ private String getToolTipText(MouseEvent event, int row, int column) { if (row < 0) return null; TreeCellRenderer renderer = getCellRenderer(); TreePath path = getPathForRow(row); Object lastPath = path.getLastPathComponent(); Component rComponent = renderer.getTreeCellRendererComponent (this, lastPath, isRowSelected(row), isExpanded(row), getModel().isLeaf(lastPath), row, true); if(rComponent instanceof JComponent) { Rectangle pathBounds = getPathBounds(path); Rectangle cellRect = treeTable.getCellRect(row, column, false); // JW: what we are after // is the offset into the hierarchical column // then intersect this with the pathbounds Point mousePoint = event.getPoint(); // translate to coordinates relative to cell mousePoint.translate(-cellRect.x, -cellRect.y); // translate horizontally to mousePoint.translate(-pathBounds.x, 0); // show tooltip only if over renderer? // if (mousePoint.x < 0) return null; // p.translate(-pathBounds.x, -pathBounds.y); MouseEvent newEvent = new MouseEvent(rComponent, event.getID(), event.getWhen(), event.getModifiers(), mousePoint.x, mousePoint.y, // p.x, p.y, event.getClickCount(), event.isPopupTrigger()); return ((JComponent)rComponent).getToolTipText(newEvent); } return null; } /** * Immutably binds this TreeTableModelAdapter to the specified JXTreeTable. * For internal use by JXTreeTable only. * * @param treeTable the JXTreeTable instance that this renderer is bound to */ public final void bind(JXTreeTable treeTable) { // Suppress potentially subversive invocation! // Prevent clearing out the deck for possible hijack attempt later! if (treeTable == null) { throw new IllegalArgumentException("null treeTable"); } if (this.treeTable == null) { this.treeTable = treeTable; } else { throw new IllegalArgumentException("renderer already bound"); } } @Override protected void setExpandedState(TreePath path, boolean state) { int count = getRowCount(); super.setExpandedState(path, state); treeTable.getTreeTableHacker().expansionChanged(); treeTable.getTreeTableHacker().completeEditing(); } /** * updateUI is overridden to set the colors of the Tree's renderer * to match that of the table. */ @Override public void updateUI() { super.updateUI(); // Make the tree's cell renderer use the table's cell selection // colors. // TODO JW: need to revisit... // a) the "real" of a JXTree is always wrapped into a DelegatingRenderer // consequently the if-block never executes // b) even if it does it probably (?) should not // unconditionally overwrite custom selection colors. // Check for UIResources instead. TreeCellRenderer tcr = getCellRenderer(); if (tcr instanceof DefaultTreeCellRenderer) { DefaultTreeCellRenderer dtcr = ((DefaultTreeCellRenderer) tcr); // For 1.1 uncomment this, 1.2 has a bug that will cause an // exception to be thrown if the border selection color is null. dtcr.setBorderSelectionColor(null); dtcr.setTextSelectionColor( UIManager.getColor("Table.selectionForeground")); dtcr.setBackgroundSelectionColor( UIManager.getColor("Table.selectionBackground")); } } /** * Sets the row height of the tree, and forwards the row height to * the table. * * */ @Override public void setRowHeight(int rowHeight) { // JW: can't ... updateUI invoked with rowHeight = 0 // hmmm... looks fishy ... // if (rowHeight <= 0) throw super.setRowHeight(rowHeight); if (rowHeight > 0) { if (treeTable != null) { treeTable.adjustTableRowHeight(rowHeight); } } } /** * This is overridden to set the height to match that of the JTable. */ @Override public void setBounds(int x, int y, int w, int h) { if (treeTable != null) { y = 0; // It is not enough to set the height to treeTable.getHeight() h = treeTable.getRowCount() * this.getRowHeight(); } super.setBounds(x, y, w, h); } /** * Sublcassed to translate the graphics such that the last visible row * will be drawn at 0,0. */ @Override public void paint(Graphics g) { Rectangle cellRect = treeTable.getCellRect(visibleRow, 0, false); g.translate(0, -cellRect.y); hierarchicalColumnWidth = getWidth(); super.paint(g); // Draw the Table border if we have focus. if (highlightBorder != null) { // #170: border not drawn correctly // JW: position the border to be drawn in translated area // still not satifying in all cases... // RG: Now it satisfies (at least for the row margins) // Still need to make similar adjustments for column margins... highlightBorder.paintBorder(this, g, 0, cellRect.y, getWidth(), cellRect.height); } } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { assert table == treeTable; if (isSelected) { setBackground(table.getSelectionBackground()); setForeground(table.getSelectionForeground()); } else { setBackground(table.getBackground()); setForeground(table.getForeground()); } highlightBorder = null; if (treeTable != null) { if (treeTable.realEditingRow() == row && treeTable.getEditingColumn() == column) { } else if (hasFocus) { highlightBorder = UIManager.getBorder( "Table.focusCellHighlightBorder"); } } visibleRow = row; return this; } private class ClippedTreeCellRenderer extends DefaultTreeCellRenderer { public void paint(Graphics g) { String fullText = super.getText(); // getText() calls tree.convertValueToText(); // tree.convertValueToText() should call treeModel.convertValueToText(), if possible String shortText = SwingUtilities.layoutCompoundLabel( this, g.getFontMetrics(), fullText, getIcon(), getVerticalAlignment(), getHorizontalAlignment(), getVerticalTextPosition(), getHorizontalTextPosition(), getItemRect(itemRect), iconRect, textRect, getIconTextGap()); /** TODO: setText is more heavyweight than we want in this * situation. Make JLabel.text protected instead of private. */ setText(shortText); // temporarily truncate text super.paint(g); setText(fullText); // restore full text } private Rectangle getItemRect(Rectangle itemRect) { getBounds(itemRect); itemRect.width = hierarchicalColumnWidth - itemRect.x; return itemRect; } // Rectangles filled in by SwingUtilities.layoutCompoundLabel(); private final Rectangle iconRect = new Rectangle(); private final Rectangle textRect = new Rectangle(); // Rectangle filled in by this.getItemRect(); private final Rectangle itemRect = new Rectangle(); } /** Border to draw around the tree, if this is non-null, it will * be painted. */ protected Border highlightBorder = null; protected JXTreeTable treeTable = null; protected int visibleRow = 0; // A JXTreeTable may not have more than one hierarchical column private int hierarchicalColumnWidth = 0; } /** * Returns the adapter that knows how to access the component data model. * The component data adapter is used by filters, sorters, and highlighters. * * @return the adapter that knows how to access the component data model */ @Override protected ComponentAdapter getComponentAdapter() { if (dataAdapter == null) { dataAdapter = new TreeTableDataAdapter(this); } return dataAdapter; } private final static Dimension spacing = new Dimension(0, 2); protected static class TreeTableDataAdapter extends JXTable.TableAdapter { private final JXTreeTable table; /** * Constructs a <code>TreeTableDataAdapter</code> for the specified * target component. * * @param component the target component */ public TreeTableDataAdapter(JXTreeTable component) { super(component); table = component; } public JXTreeTable getTreeTable() { return table; } /** * {@inheritDoc} */ @Override public boolean isExpanded() { return table.isExpanded(row); } /** * {@inheritDoc} */ @Override public boolean isLeaf() { // Issue #270-swingx: guard against invisible row TreePath path = table.getPathForRow(row); if (path != null) { return table.getTreeTableModel().isLeaf(path.getLastPathComponent()); } // JW: this is the same as BasicTreeUI.isLeaf. // Shouldn't happen anyway because must be called for visible rows only. return true; } /** * * @return true if the cell identified by this adapter displays hierarchical * nodes; false otherwise */ @Override public boolean isHierarchical() { return table.isHierarchical(column); } } }
package etomica; import etomica.atom.AtomList; /** * General class for assignment of coordinates to a group of atoms. Puts * a list of atoms in a standard conformation, which then can be manipulated * further by a Configuration class to place the molecules in a phase, or by * a super-conformation class that arranges these atoms with other ones in a * molecule.<br> * This class is used by an AtomFactory to arrange into a standard configuration * each atom group that it builds. */ public abstract class Conformation { public Conformation(Space space) { this.space = space; } /** * Defined by subclass to assign coordinates to the atoms in the given list. */ public abstract void initializePositions(AtomList atomList); protected final Space space; /** * Conformation that does nothing to the atom positions. */ public final static Conformation NULL = new Conformation(null) { public void initializePositions(AtomList list) {} }; }//end of Configuration
package etomica.units; import java.io.*; import java.util.LinkedList; import java.util.Iterator; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; public final class Lister { /* * This method takes the classes form the unitclasses function and removes * any that don't have the Dimension superclass, Null, Undefined, and any * dimensions with "dimension" in the title. */ public static LinkedList listdimensions() { LinkedList dimensionlist = classlist(); for (Iterator e = dimensionlist.iterator(); e.hasNext();) { try { Class c = Class.forName(e.next().toString()); if (c.getSuperclass() != Dimension.class || c.toString().indexOf("Dimension") > -1 || c.toString().indexOf("Null") > -1 || c.toString().indexOf("Undefined") > -1) { e.remove(); } } catch (ClassNotFoundException ee) { System.out.println(ee); } catch (Exception eee) { System.out.println(eee); } } // for (int i = 0; i < dimensionlist.size(); i++) { // System.out.println(dimensionlist.get(i).toString()); // System.out.println(); return dimensionlist; } /* * This method takes the classes form the unitclasses function and removes * any that don't have a SimpleUnit or CompoundUnit superclass, and removes * the pixel class and any containing the word unit. */ public static LinkedList listunits() { LinkedList unitslist = classlist(); for (Iterator e = unitslist.iterator(); e.hasNext();) { try { Class c = Class.forName(e.next().toString()); if ((c.getSuperclass() != SimpleUnit.class && c.getSuperclass() != CompoundUnit.class) || c.toString().indexOf("Unit") > -1 || c.toString().indexOf("Pixel") > -1) { e.remove(); } } catch (ClassNotFoundException ee) { System.out.println(ee); } catch (Exception eee) { System.out.println(eee); } } /* * for (int i = 0; i < unitslist.size(); i++) { * System.out.print(unitslist.get(i).toString() + "\n"); } * System.out.println(); */ return unitslist; } /* * This method finds all the files in the src/etomica/units directory, takes * any with a .java extension, removes the .java, and adds them all to a * linked list of strings. * * Replaced with classlist(); */ public static LinkedList unitsclasses() { File dir = new File("src/etomica/units"); String[] listy = dir.list(); LinkedList clist = new LinkedList(); for (int i = 0; i < listy.length; i++) { String currentitem = listy[i]; int dotspot = currentitem.indexOf("."); String filetype = currentitem.subSequence(dotspot + 1, currentitem.length()).toString(); if (filetype.equals("java")) { currentitem = currentitem.substring(0, dotspot); clist.add(currentitem); // System.out.println(currentitem); } } return clist; } /* * This will replace unitclasses. Make add, processDirectory, and processJar * return */ public static LinkedList classlist() { LinkedList clist = new LinkedList(); ArrayList paths = new ArrayList(); String cpath = System.getProperty("java.class.path"); //System.out.println( "From Etomica plugin: java.class.path = " + cpath ); StringTokenizer tz = new StringTokenizer(cpath, PATHSEP); while(tz.hasMoreTokens()) { paths.add(tz.nextToken()); } for(int i = 0; i < paths.size(); i++) { File file = new File((String) paths.get(i)); if(file.isDirectory()) { if(!processDirectory(file,file.getAbsolutePath()).isEmpty()) clist.addAll(processDirectory(file,file.getAbsolutePath())); } else { if(!processJar(file,file.getAbsolutePath()).isEmpty()) clist.addAll(processJar(file,file.getAbsolutePath())); } } return clist; } /** * Recursively store all class names found in this directory and its * subdirectories */ private static LinkedList processDirectory(File directory, String basepath) { //System.out.println("Processing " + directory.getPath()); LinkedList addlist = new LinkedList(); File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { File currentFile = files[i]; String name = currentFile.getName(); if (currentFile.isDirectory()) { if(!processDirectory(currentFile, basepath).isEmpty()) addlist.addAll(processDirectory(currentFile, basepath)); } else if (name.endsWith(".class")) { if(!add(name, currentFile.getPath(), basepath).isEmpty()) addlist.addAll(add(name, currentFile.getPath(), basepath)); } else if (name.endsWith(".jar")) { if(!processJar(currentFile, basepath).isEmpty()) addlist.addAll(processJar(currentFile, basepath)); } } return addlist; } /** * Store all class names found in this jar file */ private static LinkedList processJar(File jarfile, String basepath) { //System.out.println("Processing JAR " + jarfile.getPath()); LinkedList addlist = new LinkedList(); try { JarInputStream jarIS = new JarInputStream(new FileInputStream( jarfile)); JarEntry entry = null; while ((entry = jarIS.getNextJarEntry()) != null) { String name = entry.getName(); if (name.endsWith(".class")) { //System.out.println( entry.getAttributes().toString() ); if(!add(name, jarfile.getPath(), basepath).isEmpty()) addlist.addAll(add(name, jarfile.getPath(), basepath)); } } } catch (Exception e) { } return addlist; } private static LinkedList add(String origname, String path, String basepath) { LinkedList addlist = new LinkedList(); String name = origname; if (path.startsWith(basepath)) { try { name = path.substring(basepath.length() + 1); } catch (Exception e) { } } if (!name.startsWith("etomica") || name.indexOf('$') >= 0) return addlist; // Get class object name = name.replace('\\', '.'); name = name.replace('/', '.'); if (name.startsWith("etomica.units")){ if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); } Class thisclass = null; try { //System.err.println( "Trying class " + name ); thisclass = Class.forName(name); addlist.add(name); } catch (java.lang.ClassFormatError e) { System.out.println("Could not access class " + name + ": " + e.getLocalizedMessage()); return addlist; } catch (java.lang.VerifyError e) { System.out.println("Could not access class " + name + ": " + e.getLocalizedMessage()); return addlist; } catch (java.lang.NoClassDefFoundError e) { System.out.println("Could not access class " + name + ": " + e.getLocalizedMessage()); return addlist; } catch (Exception e) { System.out.println("Could not access class " + name + ": " + e.getLocalizedMessage()); return addlist; } catch (ExceptionInInitializerError e) { System.out.println("Could not access class " + name + ": " + e.getLocalizedMessage()); return addlist; } if ((thisclass.getModifiers() & java.lang.reflect.Modifier.ABSTRACT) != 0) { return addlist; } } return addlist; } private static String FILESEP = System.getProperty("file.separator"); private static String PATHSEP = System.getProperty("path.separator"); }
package org.batfish.z3; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import org.batfish.collections.EdgeSet; import org.batfish.collections.FibMap; import org.batfish.collections.FibRow; import org.batfish.collections.InterfaceSet; import org.batfish.collections.NodeInterfacePair; import org.batfish.collections.NodeSet; import org.batfish.collections.PolicyRouteFibIpMap; import org.batfish.collections.PolicyRouteFibNodeMap; import org.batfish.collections.RoleSet; import org.batfish.common.BatfishException; import org.batfish.representation.Configuration; import org.batfish.representation.DataPlane; import org.batfish.representation.Edge; import org.batfish.representation.IcmpCode; import org.batfish.representation.IcmpType; import org.batfish.representation.Interface; import org.batfish.representation.Ip; import org.batfish.representation.IpAccessList; import org.batfish.representation.IpAccessListLine; import org.batfish.representation.IpProtocol; import org.batfish.representation.LineAction; import org.batfish.representation.PolicyMap; import org.batfish.representation.PolicyMapAction; import org.batfish.representation.PolicyMapClause; import org.batfish.representation.PolicyMapMatchIpAccessListLine; import org.batfish.representation.PolicyMapMatchLine; import org.batfish.representation.PolicyMapMatchType; import org.batfish.representation.PolicyMapSetLine; import org.batfish.representation.PolicyMapSetNextHopLine; import org.batfish.representation.PolicyMapSetType; import org.batfish.representation.Prefix; import org.batfish.representation.TcpFlags; import org.batfish.representation.Zone; import org.batfish.util.SubRange; import org.batfish.util.Util; import org.batfish.z3.node.AcceptExpr; import org.batfish.z3.node.AclDenyExpr; import org.batfish.z3.node.AclMatchExpr; import org.batfish.z3.node.AclNoMatchExpr; import org.batfish.z3.node.AclPermitExpr; import org.batfish.z3.node.AndExpr; import org.batfish.z3.node.BooleanExpr; import org.batfish.z3.node.Comment; import org.batfish.z3.node.DebugExpr; import org.batfish.z3.node.DeclareRelExpr; import org.batfish.z3.node.DeclareVarExpr; import org.batfish.z3.node.DestinationRouteExpr; import org.batfish.z3.node.DropExpr; import org.batfish.z3.node.EqExpr; import org.batfish.z3.node.ExternalDestinationIpExpr; import org.batfish.z3.node.ExternalSourceIpExpr; import org.batfish.z3.node.ExtractExpr; import org.batfish.z3.node.FalseExpr; import org.batfish.z3.node.InboundInterfaceExpr; import org.batfish.z3.node.IntExpr; import org.batfish.z3.node.LitIntExpr; import org.batfish.z3.node.NodeAcceptExpr; import org.batfish.z3.node.NodeDropExpr; import org.batfish.z3.node.NodeTransitExpr; import org.batfish.z3.node.NonInboundNullSrcZoneExpr; import org.batfish.z3.node.NonInboundSrcInterfaceExpr; import org.batfish.z3.node.NonInboundSrcZoneExpr; import org.batfish.z3.node.NotExpr; import org.batfish.z3.node.OrExpr; import org.batfish.z3.node.OriginateExpr; import org.batfish.z3.node.PacketRelExpr; import org.batfish.z3.node.PolicyDenyExpr; import org.batfish.z3.node.PolicyExpr; import org.batfish.z3.node.PolicyMatchExpr; import org.batfish.z3.node.PolicyNoMatchExpr; import org.batfish.z3.node.PolicyPermitExpr; import org.batfish.z3.node.PostInExpr; import org.batfish.z3.node.PostInInterfaceExpr; import org.batfish.z3.node.PostOutInterfaceExpr; import org.batfish.z3.node.PreInInterfaceExpr; import org.batfish.z3.node.PreOutEdgeExpr; import org.batfish.z3.node.PreOutExpr; import org.batfish.z3.node.PreOutInterfaceExpr; import org.batfish.z3.node.QueryRelationExpr; import org.batfish.z3.node.RangeMatchExpr; import org.batfish.z3.node.RoleAcceptExpr; import org.batfish.z3.node.RoleOriginateExpr; import org.batfish.z3.node.RuleExpr; import org.batfish.z3.node.SaneExpr; import org.batfish.z3.node.Statement; import org.batfish.z3.node.TrueExpr; import org.batfish.z3.node.UnoriginalExpr; import org.batfish.z3.node.VarIntExpr; import com.microsoft.z3.BitVecExpr; import com.microsoft.z3.BoolExpr; import com.microsoft.z3.Context; import com.microsoft.z3.FuncDecl; import com.microsoft.z3.Z3Exception; public class Synthesizer { public static final String DST_IP_VAR = "dst_ip"; public static final String DST_PORT_VAR = "dst_port"; public static final String FLOW_SINK_TERMINATION_NAME = "flow_sink_termination"; public static final int ICMP_CODE_BITS = 8; public static final String ICMP_CODE_VAR = "icmp_code"; public static final int ICMP_TYPE_BITS = 8; public static final String ICMP_TYPE_VAR = "icmp_type"; public static final int IP_BITS = 32; public static final String IP_PROTOCOL_VAR = "ip_prot"; public static final String NODE_NONE_NAME = "(none)"; public static final Map<String, Integer> PACKET_VAR_SIZES = initPacketVarSizes(); public static final List<String> PACKET_VARS = getPacketVars(); public static final int PORT_BITS = 16; public static final int PROTOCOL_BITS = 8; public static final String SRC_IP_VAR = "src_ip"; public static final String SRC_PORT_VAR = "src_port"; public static final int TCP_FLAGS_BITS = 8; public static final String TCP_FLAGS_VAR = "tcp_flags"; @SuppressWarnings("unused") private static void debug(BooleanExpr condition, List<Statement> statements) { RuleExpr rule = new RuleExpr(condition, DebugExpr.INSTANCE); statements.add(rule); } private static List<String> getPacketVars() { List<String> vars = new ArrayList<String>(); vars.add(SRC_IP_VAR); vars.add(DST_IP_VAR); vars.add(SRC_PORT_VAR); vars.add(DST_PORT_VAR); vars.add(IP_PROTOCOL_VAR); vars.add(ICMP_TYPE_VAR); vars.add(ICMP_CODE_VAR); vars.add(TCP_FLAGS_VAR); return vars; } public static Map<String, FuncDecl> getRelDeclFuncDecls( List<Statement> existingStatements, Context ctx) throws Z3Exception { Map<String, FuncDecl> funcDecls = new LinkedHashMap<String, FuncDecl>(); Set<String> relations = new TreeSet<String>(); for (Statement existingStatement : existingStatements) { relations.addAll(existingStatement.getRelations()); } relations.add(QueryRelationExpr.NAME); for (String packetRel : relations) { List<Integer> sizes = new ArrayList<Integer>(); sizes.addAll(PACKET_VAR_SIZES.values()); DeclareRelExpr declaration = new DeclareRelExpr(packetRel, sizes); funcDecls.put(packetRel, declaration.toFuncDecl(ctx)); } return funcDecls; } public static List<Statement> getVarDeclExprs() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment("Variable Declarations")); for (Entry<String, Integer> e : PACKET_VAR_SIZES.entrySet()) { String var = e.getKey(); int size = e.getValue(); statements.add(new DeclareVarExpr(var, size)); } return statements; } public static String indent(int n) { String output = ""; for (int i = 0; i < n; i++) { output += " "; } return output; } private static Map<String, Integer> initPacketVarSizes() { Map<String, Integer> varSizes = new LinkedHashMap<String, Integer>(); varSizes.put(SRC_IP_VAR, IP_BITS); varSizes.put(DST_IP_VAR, IP_BITS); varSizes.put(SRC_PORT_VAR, PORT_BITS); varSizes.put(DST_PORT_VAR, PORT_BITS); varSizes.put(IP_PROTOCOL_VAR, PROTOCOL_BITS); varSizes.put(ICMP_TYPE_VAR, ICMP_TYPE_BITS); varSizes.put(ICMP_CODE_VAR, ICMP_CODE_BITS); varSizes.put(TCP_FLAGS_VAR, TCP_FLAGS_BITS); return varSizes; } private static boolean isLoopbackInterface(String ifaceName) { String lcIfaceName = ifaceName.toLowerCase(); return lcIfaceName.startsWith("lo"); } private static IntExpr newExtractExpr(String var, int low, int high) { int varSize = PACKET_VAR_SIZES.get(var); return newExtractExpr(var, varSize, low, high); } private static IntExpr newExtractExpr(String var, int varSize, int low, int high) { if (low == 0 && high == varSize - 1) { return new VarIntExpr(var); } else { return new ExtractExpr(var, low, high); } } private final Map<String, Configuration> _configurations; private final FibMap _fibs; private InterfaceSet _flowSinks; private final PolicyRouteFibNodeMap _prFibs; private final boolean _simplify; private final EdgeSet _topologyEdges; private final Map<String, Set<Interface>> _topologyInterfaces; private List<String> _warnings; public Synthesizer(Map<String, Configuration> configurations, boolean simplify) { _configurations = configurations; _fibs = null; _prFibs = null; _topologyEdges = null; _flowSinks = null; _simplify = simplify; _topologyInterfaces = null; _warnings = new ArrayList<String>(); } public Synthesizer(Map<String, Configuration> configurations, DataPlane dataPlane, boolean simplify) { _configurations = configurations; _fibs = dataPlane.getFibs(); _prFibs = dataPlane.getPolicyRouteFibNodeMap(); _topologyEdges = dataPlane.getTopologyEdges(); _flowSinks = dataPlane.getFlowSinks(); _simplify = simplify; _topologyInterfaces = new TreeMap<String, Set<Interface>>(); _warnings = new ArrayList<String>(); computeTopologyInterfaces(); pruneInterfaces(); } private void computeTopologyInterfaces() { for (String hostname : _configurations.keySet()) { _topologyInterfaces.put(hostname, new TreeSet<Interface>()); } for (Edge edge : _topologyEdges) { String hostname = edge.getNode1(); if (!_topologyInterfaces.containsKey(hostname)) { _topologyInterfaces.put(hostname, new TreeSet<Interface>()); } Set<Interface> interfaces = _topologyInterfaces.get(hostname); String interfaceName = edge.getInt1(); Interface i = _configurations.get(hostname).getInterfaces() .get(interfaceName); interfaces.add(i); } for (String hostname : _configurations.keySet()) { Configuration c = _configurations.get(hostname); Map<String, Interface> nodeInterfaces = c.getInterfaces(); for (String ifaceName : nodeInterfaces.keySet()) { if (isFlowSink(hostname, ifaceName)) { Interface iface = nodeInterfaces.get(ifaceName); if (iface.getActive()) { Set<Interface> interfaces = _topologyInterfaces.get(hostname); interfaces.add(iface); } } } } } private List<Statement> getAcceptRules() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment("Node accept lead to universal accept")); for (String nodeName : _configurations.keySet()) { NodeAcceptExpr nodeAccept = new NodeAcceptExpr(nodeName); RuleExpr connectAccepts = new RuleExpr(nodeAccept, AcceptExpr.INSTANCE); statements.add(connectAccepts); } return statements; } private List<Statement> getDestRouteToPreOutEdgeRules() { List<Statement> statements = new ArrayList<Statement>(); statements .add(new Comment( "Rules for sending destination routed packets to preoutIface stage")); for (String hostname : _fibs.keySet()) { TreeSet<FibRow> fibSet = _fibs.get(hostname); FibRow firstRow = fibSet.first(); if (!firstRow.getPrefix().equals(Prefix.ZERO)) { // no default route, so add one that drops traffic FibRow dropDefaultRow = new FibRow(Prefix.ZERO, FibRow.DROP_INTERFACE, "", ""); fibSet.add(dropDefaultRow); } FibRow[] fib = fibSet.toArray(new FibRow[] {}); for (int i = 0; i < fib.length; i++) { FibRow currentRow = fib[i]; Set<FibRow> notRows = new TreeSet<FibRow>(); for (int j = i + 1; j < fib.length; j++) { FibRow specificRow = fib[j]; long currentStart = currentRow.getPrefix().getAddress().asLong(); long currentEnd = currentRow.getPrefix().getEndAddress() .asLong(); long specificStart = specificRow.getPrefix().getAddress() .asLong(); long specificEnd = specificRow.getPrefix().getEndAddress() .asLong(); // check whether later prefix is contained in this one if (currentStart <= specificStart && specificEnd <= currentEnd) { if (currentStart == specificStart && currentEnd == specificEnd) { // load balancing continue; } if (currentRow.getInterface().equals( specificRow.getInterface()) && currentRow.getNextHop().equals( specificRow.getNextHop()) && currentRow.getNextHopInterface().equals( specificRow.getNextHopInterface())) { // no need to exclude packets matching the more specific // prefix, // since they would go out same edge continue; } // exclude packets that match a more specific prefix that // would go out a different interface notRows.add(specificRow); } else { break; } } AndExpr conditions = new AndExpr(); DestinationRouteExpr destRoute = new DestinationRouteExpr(hostname); conditions.addConjunct(destRoute); String ifaceOutName = currentRow.getInterface(); PacketRelExpr action; if (ifaceOutName.equals(FibRow.DROP_INTERFACE) || isLoopbackInterface(ifaceOutName) || Util.isNullInterface(ifaceOutName)) { action = new NodeDropExpr(hostname); } else { String nextHop = currentRow.getNextHop(); String ifaceInName = currentRow.getNextHopInterface(); action = new PreOutEdgeExpr(hostname, ifaceOutName, nextHop, ifaceInName); } // must not match more specific routes for (FibRow notRow : notRows) { int prefixLength = notRow.getPrefix().getPrefixLength(); long prefix = notRow.getPrefix().getAddress().asLong(); int first = IP_BITS - prefixLength; if (first >= IP_BITS) { continue; } int last = IP_BITS - 1; LitIntExpr prefixFragmentLit = new LitIntExpr(prefix, first, last); IntExpr prefixFragmentExt = newExtractExpr(DST_IP_VAR, first, last); NotExpr noPrefixMatch = new NotExpr(); EqExpr prefixMatch = new EqExpr(prefixFragmentExt, prefixFragmentLit); noPrefixMatch.SetArgument(prefixMatch); conditions.addConjunct(noPrefixMatch); } // must match route int prefixLength = currentRow.getPrefix().getPrefixLength(); long prefix = currentRow.getPrefix().getAddress().asLong(); int first = IP_BITS - prefixLength; if (first < IP_BITS) { int last = IP_BITS - 1; LitIntExpr prefixFragmentLit = new LitIntExpr(prefix, first, last); IntExpr prefixFragmentExt = newExtractExpr(DST_IP_VAR, first, last); EqExpr prefixMatch = new EqExpr(prefixFragmentExt, prefixFragmentLit); conditions.addConjunct(prefixMatch); } // then we forward out specified interface (or drop) RuleExpr rule = new RuleExpr(conditions, action); statements.add(rule); } } return statements; } private List<Statement> getDropRules() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment("Node drop lead to universal drop")); for (String nodeName : _configurations.keySet()) { NodeDropExpr nodeDrop = new NodeDropExpr(nodeName); RuleExpr connectDrops = new RuleExpr(nodeDrop, DropExpr.INSTANCE); statements.add(connectDrops); } return statements; } private List<Statement> getExternalDstIpRules() { List<Statement> statements = new ArrayList<Statement>(); statements .add(new Comment( "Rule for matching external Source IP - one not assigned to an active interface of any provided node")); Set<Ip> interfaceIps = new TreeSet<Ip>(); for (Entry<String, Configuration> e : _configurations.entrySet()) { Configuration c = e.getValue(); for (Interface i : c.getInterfaces().values()) { if (i.getActive()) { Prefix prefix = i.getPrefix(); if (prefix != null) { Ip ip = prefix.getAddress(); interfaceIps.add(ip); } } } } OrExpr dstIpMatchesSomeInterfaceIp = new OrExpr(); for (Ip ip : interfaceIps) { EqExpr dstIpMatchesSpecificInterfaceIp = new EqExpr(new VarIntExpr( DST_IP_VAR), new LitIntExpr(ip)); dstIpMatchesSomeInterfaceIp .addDisjunct(dstIpMatchesSpecificInterfaceIp); } NotExpr externalDstIp = new NotExpr(dstIpMatchesSomeInterfaceIp); RuleExpr externalDstIpRule = new RuleExpr(externalDstIp, ExternalDestinationIpExpr.INSTANCE); statements.add(externalDstIpRule); return statements; } private List<Statement> getExternalSrcIpRules() { List<Statement> statements = new ArrayList<Statement>(); statements .add(new Comment( "Rule for matching external Source IP - one not assigned to an active interface of any provided node")); Set<Ip> interfaceIps = new TreeSet<Ip>(); for (Entry<String, Configuration> e : _configurations.entrySet()) { Configuration c = e.getValue(); for (Interface i : c.getInterfaces().values()) { if (i.getActive()) { Prefix prefix = i.getPrefix(); if (prefix != null) { Ip ip = prefix.getAddress(); interfaceIps.add(ip); } } } } OrExpr srcIpMatchesSomeInterfaceIp = new OrExpr(); for (Ip ip : interfaceIps) { EqExpr srcIpMatchesSpecificInterfaceIp = new EqExpr(new VarIntExpr( SRC_IP_VAR), new LitIntExpr(ip)); srcIpMatchesSomeInterfaceIp .addDisjunct(srcIpMatchesSpecificInterfaceIp); } NotExpr externalSrcIp = new NotExpr(srcIpMatchesSomeInterfaceIp); RuleExpr externalSrcIpRule = new RuleExpr(externalSrcIp, ExternalSourceIpExpr.INSTANCE); statements.add(externalSrcIpRule); return statements; } private List<Statement> getFlowSinkAcceptRules() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment( "Post out flow sink interface leads to node accept")); for (NodeInterfacePair f : _flowSinks) { String hostname = f.getHostname(); String ifaceName = f.getInterface(); if (isFlowSink(hostname, ifaceName)) { PostOutInterfaceExpr postOutIface = new PostOutInterfaceExpr( hostname, ifaceName); NodeAcceptExpr nodeAccept = new NodeAcceptExpr(hostname); RuleExpr flowSinkAccept = new RuleExpr(postOutIface, nodeAccept); statements.add(flowSinkAccept); } } return statements; } private List<Statement> getInboundInterfaceToNodeAccept() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment( "Rules for connecting inbound_interface to node_accept")); for (Configuration c : _configurations.values()) { String hostname = c.getHostname(); NodeAcceptExpr nodeAccept = new NodeAcceptExpr(hostname); for (Interface i : c.getInterfaces().values()) { String ifaceName = i.getName(); InboundInterfaceExpr inboundInterface = new InboundInterfaceExpr( hostname, ifaceName); // deal with origination totally independently of zone stuff AndExpr originateAcceptConditions = new AndExpr(); OriginateExpr originate = new OriginateExpr(hostname); originateAcceptConditions.addConjunct(inboundInterface); originateAcceptConditions.addConjunct(originate); RuleExpr originateToNodeAccept = new RuleExpr( originateAcceptConditions, nodeAccept); statements.add(originateToNodeAccept); Zone inboundZone = i.getZone(); AndExpr acceptConditions = new AndExpr(); acceptConditions.addConjunct(inboundInterface); if (inboundZone != null) { IpAccessList hostFilter = inboundZone.getToHostFilter(); if (hostFilter != null) { AclPermitExpr hostFilterPermit = new AclPermitExpr(hostname, hostFilter.getName()); acceptConditions.addConjunct(hostFilterPermit); } String inboundFilterName; IpAccessList inboundInterfaceFilter = inboundZone .getInboundInterfaceFilters().get(i); if (inboundInterfaceFilter != null) { inboundFilterName = inboundInterfaceFilter.getName(); } else { IpAccessList inboundFilter = inboundZone.getInboundFilter(); inboundFilterName = inboundFilter.getName(); } AclPermitExpr inboundFilterPermit = new AclPermitExpr(hostname, inboundFilterName); acceptConditions.addConjunct(inboundFilterPermit); } else { // no inbound zone. // accept if packet was orginated at this node and default // inbound action is accept if (c.getDefaultInboundAction() == LineAction.REJECT || c.getDefaultCrossZoneAction() == LineAction.REJECT) { acceptConditions.addConjunct(originate); } } if (inboundZone != null) { OrExpr crossFilterSatisfied = new OrExpr(); // If packet came in on inbound interface, accept. PostInInterfaceExpr postInInboundInterface = new PostInInterfaceExpr( hostname, ifaceName); crossFilterSatisfied.addDisjunct(postInInboundInterface); // Otherwise, the packet must be permitted by the appropriate // cross-zone filter for (Zone srcZone : c.getZones().values()) { AndExpr crossZoneConditions = new AndExpr(); String srcZoneName = srcZone.getName(); IpAccessList crossZoneFilter = srcZone.getToZonePolicies() .get(inboundZone.getName()); NonInboundSrcZoneExpr nonInboundSrcZone = new NonInboundSrcZoneExpr( hostname, srcZoneName); crossZoneConditions.addConjunct(nonInboundSrcZone); if (crossZoneFilter != null) { AclPermitExpr crossZonePermit = new AclPermitExpr( hostname, crossZoneFilter.getName()); crossZoneConditions.addConjunct(crossZonePermit); crossFilterSatisfied.addDisjunct(crossZoneConditions); } else if (c.getDefaultCrossZoneAction() == LineAction.ACCEPT) { crossFilterSatisfied.addDisjunct(crossZoneConditions); } } // handle case where src interface is not in a zone if (c.getDefaultCrossZoneAction() == LineAction.ACCEPT) { NonInboundNullSrcZoneExpr nonInboundNullSrcZone = new NonInboundNullSrcZoneExpr( hostname); crossFilterSatisfied.addDisjunct(nonInboundNullSrcZone); } acceptConditions.addConjunct(crossFilterSatisfied); } RuleExpr inboundInterfaceToNodeAccept = new RuleExpr( acceptConditions, nodeAccept); statements.add(inboundInterfaceToNodeAccept); } } return statements; } private List<Statement> getInboundInterfaceToNodeDrop() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment( "Rules for connecting inbound_interface to node_deny")); for (Configuration c : _configurations.values()) { String hostname = c.getHostname(); NodeDropExpr nodeDrop = new NodeDropExpr(hostname); UnoriginalExpr unoriginal = new UnoriginalExpr(hostname); for (Interface i : c.getInterfaces().values()) { String ifaceName = i.getName(); InboundInterfaceExpr inboundInterface = new InboundInterfaceExpr( hostname, ifaceName); Zone inboundZone = i.getZone(); AndExpr dropConditions = new AndExpr(); dropConditions.addConjunct(unoriginal); dropConditions.addConjunct(inboundInterface); OrExpr failConditions = new OrExpr(); if (inboundZone != null) { IpAccessList hostFilter = inboundZone.getToHostFilter(); if (hostFilter != null) { AclDenyExpr hostFilterDeny = new AclDenyExpr(hostname, hostFilter.getName()); failConditions.addDisjunct(hostFilterDeny); } String inboundFilterName; IpAccessList inboundInterfaceFilter = inboundZone .getInboundInterfaceFilters().get(i); if (inboundInterfaceFilter != null) { inboundFilterName = inboundInterfaceFilter.getName(); } else { IpAccessList inboundFilter = inboundZone.getInboundFilter(); inboundFilterName = inboundFilter.getName(); } AclDenyExpr inboundFilterDeny = new AclDenyExpr(hostname, inboundFilterName); failConditions.addDisjunct(inboundFilterDeny); } else if (c.getDefaultInboundAction() == LineAction.REJECT || c.getDefaultCrossZoneAction() == LineAction.REJECT) { failConditions.addDisjunct(unoriginal); } if (inboundZone != null) { OrExpr crossFilterFailed = new OrExpr(); // If packet didn't come in on inbound interface, drop if denied // by the appropriate cross-zone filter // permitted by the appropriate cross-zone policy for (Zone srcZone : c.getZones().values()) { AndExpr crossZoneConditions = new AndExpr(); String srcZoneName = srcZone.getName(); IpAccessList crossZoneFilter = srcZone.getToZonePolicies() .get(inboundZone.getName()); NonInboundSrcZoneExpr nonInboundSrcZone = new NonInboundSrcZoneExpr( hostname, srcZoneName); crossZoneConditions.addConjunct(nonInboundSrcZone); if (crossZoneFilter != null) { AclDenyExpr crossZoneDeny = new AclDenyExpr(hostname, crossZoneFilter.getName()); crossZoneConditions.addConjunct(crossZoneDeny); crossFilterFailed.addDisjunct(crossZoneConditions); } else if (c.getDefaultCrossZoneAction() == LineAction.REJECT) { crossFilterFailed.addDisjunct(crossZoneConditions); } } // handle case where src interface is not in a zone if (c.getDefaultCrossZoneAction() == LineAction.REJECT) { NonInboundNullSrcZoneExpr nonInboundNullSrcZone = new NonInboundNullSrcZoneExpr( hostname); crossFilterFailed.addDisjunct(nonInboundNullSrcZone); } failConditions.addDisjunct(crossFilterFailed); } dropConditions.addConjunct(failConditions); RuleExpr inboundInterfaceToNodeDrop = new RuleExpr(dropConditions, nodeDrop); statements.add(inboundInterfaceToNodeDrop); } } return statements; } private List<Statement> getMatchAclRules() { List<Statement> statements = new ArrayList<Statement>(); Comment comment = new Comment("Rules for how packets can match acl lines"); statements.add(comment); Map<String, Map<String, IpAccessList>> matchAcls = new TreeMap<String, Map<String, IpAccessList>>(); // first we find out which acls we need to process // if data plane was provided as input, only check acls for topology // nodes/interfaces if (_topologyInterfaces != null) { for (String hostname : _topologyInterfaces.keySet()) { Configuration node = _configurations.get(hostname); Map<String, IpAccessList> aclMap = new TreeMap<String, IpAccessList>(); Set<Interface> interfaces = _topologyInterfaces.get(hostname); for (Interface iface : interfaces) { if (iface.getPrefix() != null) { IpAccessList aclIn = iface.getIncomingFilter(); IpAccessList aclOut = iface.getOutgoingFilter(); PolicyMap routePolicy = iface.getRoutingPolicy(); if (aclIn != null) { String name = aclIn.getName(); aclMap.put(name, aclIn); } if (aclOut != null) { String name = aclOut.getName(); aclMap.put(name, aclOut); } if (routePolicy != null) { for (PolicyMapClause clause : routePolicy.getClauses()) { for (PolicyMapMatchLine matchLine : clause .getMatchLines()) { if (matchLine.getType() == PolicyMapMatchType.IP_ACCESS_LIST) { PolicyMapMatchIpAccessListLine matchAclLine = (PolicyMapMatchIpAccessListLine) matchLine; for (IpAccessList acl : matchAclLine.getLists()) { String name = acl.getName(); aclMap.put(name, acl); } } } } } } } for (Zone zone : node.getZones().values()) { IpAccessList fromHostFilter = zone.getFromHostFilter(); if (fromHostFilter != null) { aclMap.put(fromHostFilter.getName(), fromHostFilter); } IpAccessList toHostFilter = zone.getToHostFilter(); if (toHostFilter != null) { aclMap.put(toHostFilter.getName(), toHostFilter); } IpAccessList inboundFilter = zone.getInboundFilter(); if (inboundFilter != null) { aclMap.put(inboundFilter.getName(), inboundFilter); } for (IpAccessList inboundInterfaceFilter : zone .getInboundInterfaceFilters().values()) { aclMap.put(inboundInterfaceFilter.getName(), inboundInterfaceFilter); } for (IpAccessList toZoneFilter : zone.getToZonePolicies() .values()) { aclMap.put(toZoneFilter.getName(), toZoneFilter); } } if (aclMap.size() > 0) { matchAcls.put(hostname, aclMap); } } } else { // topology is null. just add all acls. for (Entry<String, Configuration> e : _configurations.entrySet()) { String hostname = e.getKey(); Configuration c = e.getValue(); matchAcls.put(hostname, c.getIpAccessLists()); } } for (Entry<String, Map<String, IpAccessList>> e : matchAcls.entrySet()) { String hostname = e.getKey(); Map<String, IpAccessList> aclMap = e.getValue(); for (Entry<String, IpAccessList> e2 : aclMap.entrySet()) { String aclName = e2.getKey(); IpAccessList acl = e2.getValue(); List<IpAccessListLine> lines = acl.getLines(); for (int i = 0; i < lines.size(); i++) { IpAccessListLine line = lines.get(i); // TODO: fix String invalidMessage = line.getInvalidMessage(); boolean valid = invalidMessage == null; if (!valid) { _warnings.add("WARNING: IpAccessList " + aclName + " line " + i + ": disabled: " + invalidMessage + "\n"); } Set<Prefix> srcIpRanges = line.getSourceIpRanges(); Set<Prefix> dstIpRanges = line.getDestinationIpRanges(); Set<IpProtocol> protocols = line.getProtocols(); Set<SubRange> srcPortRanges = new LinkedHashSet<SubRange>(); srcPortRanges.addAll(line.getSrcPortRanges()); Set<SubRange> dstPortRanges = new LinkedHashSet<SubRange>(); dstPortRanges.addAll(line.getDstPortRanges()); int icmpType = line.getIcmpType(); int icmpCode = line.getIcmpCode(); int tcpFlags = line.getTcpFlags(); AndExpr matchConditions = new AndExpr(); // ** must not match previous rule ** BooleanExpr prevNoMatch = (i > 0) ? new AclNoMatchExpr(hostname, aclName, i - 1) : TrueExpr.INSTANCE; AndExpr matchLineCriteria = new AndExpr(); matchConditions.addConjunct(matchLineCriteria); matchConditions.addConjunct(prevNoMatch); // match protocol if (protocols.size() > 0) { OrExpr matchesSomeProtocol = new OrExpr(); for (IpProtocol protocol : protocols) { int protocolNumber = protocol.number(); VarIntExpr protocolVar = new VarIntExpr(IP_PROTOCOL_VAR); LitIntExpr protocolLit = new LitIntExpr(protocolNumber, PROTOCOL_BITS); EqExpr matchProtocol = new EqExpr(protocolVar, protocolLit); matchesSomeProtocol.addDisjunct(matchProtocol); } matchLineCriteria.addConjunct(matchesSomeProtocol); } // match srcIp if (srcIpRanges.size() > 0) { OrExpr matchSomeSrcIpRange = new OrExpr(); for (Prefix srcPrefix : srcIpRanges) { long srcIp = srcPrefix.getAddress().asLong(); int srcIpWildcardBits = IP_BITS - srcPrefix.getPrefixLength(); int srcIpStart = srcIpWildcardBits; int srcIpEnd = IP_BITS - 1; if (srcIpStart < IP_BITS) { IntExpr extractsrcIp = newExtractExpr(SRC_IP_VAR, srcIpStart, srcIpEnd); LitIntExpr srcIpMatchLit = new LitIntExpr(srcIp, srcIpStart, srcIpEnd); EqExpr matchsrcIp = new EqExpr(extractsrcIp, srcIpMatchLit); matchSomeSrcIpRange.addDisjunct(matchsrcIp); } else { matchSomeSrcIpRange.addDisjunct(TrueExpr.INSTANCE); } } matchLineCriteria.addConjunct(matchSomeSrcIpRange); } // match dstIp if (dstIpRanges.size() > 0) { OrExpr matchSomeDstIpRange = new OrExpr(); for (Prefix dstPrefix : dstIpRanges) { long dstIp = dstPrefix.getAddress().asLong(); int dstIpWildcardBits = IP_BITS - dstPrefix.getPrefixLength(); int dstIpStart = dstIpWildcardBits; int dstIpEnd = IP_BITS - 1; if (dstIpStart < IP_BITS) { IntExpr extractDstIp = newExtractExpr(DST_IP_VAR, dstIpStart, dstIpEnd); LitIntExpr dstIpMatchLit = new LitIntExpr(dstIp, dstIpStart, dstIpEnd); EqExpr matchDstIp = new EqExpr(extractDstIp, dstIpMatchLit); matchSomeDstIpRange.addDisjunct(matchDstIp); } else { matchSomeDstIpRange.addDisjunct(TrueExpr.INSTANCE); } } matchLineCriteria.addConjunct(matchSomeDstIpRange); } // match srcport if (srcPortRanges != null && srcPortRanges.size() > 0) { BooleanExpr matchSrcPort = getMatchAclRules_portHelper( srcPortRanges, SRC_PORT_VAR); matchLineCriteria.addConjunct(matchSrcPort); } // matchdstport if (dstPortRanges != null && dstPortRanges.size() > 0) { BooleanExpr matchDstPort = getMatchAclRules_portHelper( dstPortRanges, DST_PORT_VAR); matchLineCriteria.addConjunct(matchDstPort); } AclMatchExpr match = new AclMatchExpr(hostname, aclName, i); RuleExpr matchRule = new RuleExpr(valid ? matchConditions : FalseExpr.INSTANCE, match); statements.add(matchRule); // match icmp-type if (icmpType != IcmpType.UNSET) { EqExpr exactMatch = new EqExpr(new VarIntExpr(ICMP_TYPE_VAR), new LitIntExpr(icmpType, ICMP_TYPE_BITS)); matchLineCriteria.addConjunct(exactMatch); } // match icmp-code if (icmpCode != IcmpCode.UNSET) { EqExpr exactMatch = new EqExpr(new VarIntExpr(ICMP_CODE_VAR), new LitIntExpr(icmpCode, ICMP_CODE_BITS)); matchLineCriteria.addConjunct(exactMatch); } // match tcp-flags if (tcpFlags != TcpFlags.UNSET) { EqExpr exactMatch = new EqExpr(new VarIntExpr(TCP_FLAGS_VAR), new LitIntExpr(tcpFlags, TCP_FLAGS_BITS)); matchLineCriteria.addConjunct(exactMatch); } // no match rule AndExpr noMatchConditions = new AndExpr(); BooleanExpr noMatchLineCriteria = valid ? new NotExpr( matchLineCriteria) : TrueExpr.INSTANCE; noMatchConditions.addConjunct(noMatchLineCriteria); noMatchConditions.addConjunct(prevNoMatch); AclNoMatchExpr noMatch = new AclNoMatchExpr(hostname, aclName, i); RuleExpr noMatchRule = new RuleExpr(noMatchConditions, noMatch); statements.add(noMatchRule); // permit/deny rule for match PolicyExpr aclAction; switch (line.getAction()) { case ACCEPT: aclAction = new AclPermitExpr(hostname, aclName); break; case REJECT: aclAction = new AclDenyExpr(hostname, aclName); break; default: throw new Error("invalid action"); } RuleExpr action = new RuleExpr(match, aclAction); statements.add(action); } // deny rule for not matching last line int lastLineIndex = acl.getLines().size() - 1; AclDenyExpr aclDeny = new AclDenyExpr(hostname, aclName); AclNoMatchExpr noMatchLast = new AclNoMatchExpr(hostname, aclName, lastLineIndex); RuleExpr implicitDeny = new RuleExpr(noMatchLast, aclDeny); statements.add(implicitDeny); } } return statements; } private BooleanExpr getMatchAclRules_portHelper(Set<SubRange> ranges, String portVar) { return new RangeMatchExpr(portVar, PORT_BITS, ranges); } private List<Statement> getNodeAcceptToRoleAcceptRules() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment("Connect node_accept to role_accept")); for (Entry<String, Configuration> e : _configurations.entrySet()) { String hostname = e.getKey(); Configuration c = e.getValue(); NodeAcceptExpr nodeAccept = new NodeAcceptExpr(hostname); RoleSet roles = c.getRoles(); if (roles != null) { for (String role : roles) { RoleAcceptExpr roleAccept = new RoleAcceptExpr(role); RuleExpr rule = new RuleExpr(nodeAccept, roleAccept); statements.add(rule); } } } return statements; } public NodeSet getNodeSet() { NodeSet nodes = new NodeSet(); nodes.addAll(_configurations.keySet()); return nodes; } private List<Statement> getOriginateToPostInRules() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment("Connect originate to post_in")); for (String hostname : _configurations.keySet()) { OriginateExpr originate = new OriginateExpr(hostname); PostInExpr postIn = new PostInExpr(hostname); RuleExpr rule = new RuleExpr(originate, postIn); statements.add(rule); } return statements; } private List<Statement> getPolicyRouteRules() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment("Policy-based routing rules")); for (Entry<String, Set<Interface>> e : _topologyInterfaces.entrySet()) { String hostname = e.getKey(); PreOutExpr preOut = new PreOutExpr(hostname); PolicyRouteFibIpMap ipMap = _prFibs.get(hostname); Set<Interface> interfaces = e.getValue(); for (Interface iface : interfaces) { String ifaceName = iface.getName(); PostInInterfaceExpr postInInterface = new PostInInterfaceExpr( hostname, ifaceName); PolicyMap p = iface.getRoutingPolicy(); if (p != null) { String policyName = p.getMapName(); PolicyPermitExpr permit = new PolicyPermitExpr(hostname, policyName); PolicyDenyExpr deny = new PolicyDenyExpr(hostname, policyName); List<PolicyMapClause> clauses = p.getClauses(); for (int i = 0; i < clauses.size(); i++) { PolicyMapClause clause = clauses.get(i); PolicyMapAction action = clause.getAction(); PolicyMatchExpr match = new PolicyMatchExpr(hostname, policyName, i); PolicyNoMatchExpr noMatch = new PolicyNoMatchExpr(hostname, policyName, i); BooleanExpr prevNoMatch = (i > 0) ? new PolicyNoMatchExpr( hostname, policyName, i - 1) : TrueExpr.INSTANCE; /** * If clause matches, and clause number (matched) is that of a * permit clause, and out interface is among next hops, then * policy permit on out interface */ switch (action) { case PERMIT: for (PolicyMapSetLine setLine : clause.getSetLines()) { if (setLine.getType() == PolicyMapSetType.NEXT_HOP) { PolicyMapSetNextHopLine setNextHopLine = (PolicyMapSetNextHopLine) setLine; for (Ip nextHopIp : setNextHopLine.getNextHops()) { EdgeSet edges = ipMap.get(nextHopIp); /** * If packet reaches postin_interface on inInt, * and preout, and inInt has policy, and policy * matches on out interface, then preout_edge on * out interface and corresponding in interface * */ for (Edge edge : edges) { String outInterface = edge.getInt1(); String nextHop = edge.getNode2(); String inInterface = edge.getInt2(); if (!hostname.equals(edge.getNode1())) { throw new BatfishException("Invalid edge"); } AndExpr forwardConditions = new AndExpr(); forwardConditions.addConjunct(postInInterface); forwardConditions.addConjunct(preOut); forwardConditions.addConjunct(match); if (Util.isNullInterface(outInterface)) { NodeDropExpr nodeDrop = new NodeDropExpr( hostname); RuleExpr dropRule = new RuleExpr( forwardConditions, nodeDrop); statements.add(dropRule); } else { PreOutEdgeExpr preOutEdge = new PreOutEdgeExpr( hostname, outInterface, nextHop, inInterface); RuleExpr preOutEdgeRule = new RuleExpr( forwardConditions, preOutEdge); statements.add(preOutEdgeRule); } } } } } RuleExpr permitRule = new RuleExpr(match, permit); statements.add(permitRule); break; case DENY: /** * If clause matches and clause is deny clause, just deny */ RuleExpr denyRule = new RuleExpr(match, deny); statements.add(denyRule); break; default: throw new Error("bad action"); } /** * For each clause, if we reach that clause, then if any acl * in that clause permits, or there are no acls, clause, if * the packet then the packet is matched by that clause. * * If all (at least one) acls deny, then the packed is not * matched by that clause * * If there are no acls to match, then the packet is matched * by that clause. * */ boolean hasMatchIp = false; AndExpr allAclsDeny = new AndExpr(); OrExpr someAclPermits = new OrExpr(); for (PolicyMapMatchLine matchLine : clause.getMatchLines()) { if (matchLine.getType() == PolicyMapMatchType.IP_ACCESS_LIST) { hasMatchIp = true; PolicyMapMatchIpAccessListLine matchIpLine = (PolicyMapMatchIpAccessListLine) matchLine; for (IpAccessList acl : matchIpLine.getLists()) { String aclName = acl.getName(); AclDenyExpr currentAclDeny = new AclDenyExpr( hostname, aclName); allAclsDeny.addConjunct(currentAclDeny); AclPermitExpr currentAclPermit = new AclPermitExpr( hostname, aclName); someAclPermits.addDisjunct(currentAclPermit); } } } AndExpr matchConditions = new AndExpr(); matchConditions.addConjunct(prevNoMatch); if (hasMatchIp) { /** * no match if all acls deny */ AndExpr noMatchConditions = new AndExpr(); noMatchConditions.addConjunct(prevNoMatch); noMatchConditions.addConjunct(allAclsDeny); RuleExpr noMatchRule = new RuleExpr(noMatchConditions, noMatch); statements.add(noMatchRule); /** * match if some acl permits */ matchConditions.addConjunct(someAclPermits); } RuleExpr matchRule = new RuleExpr(matchConditions, match); statements.add(matchRule); } /** * If the packet reaches the last clause, and is not matched by * that clause, then it is denied by the policy. */ int lastIndex = p.getClauses().size() - 1; PolicyNoMatchExpr noMatchLast = new PolicyNoMatchExpr(hostname, policyName, lastIndex); RuleExpr noMatchDeny = new RuleExpr(noMatchLast, deny); statements.add(noMatchDeny); } } } return statements; } private List<Statement> getPostInInterfaceToNonInboundSrcInterface() { List<Statement> statements = new ArrayList<Statement>(); statements .add(new Comment( "Rules for connecting postin_interface to non_inbound_src_interface")); for (Configuration c : _configurations.values()) { String hostname = c.getHostname(); for (Interface i : c.getInterfaces().values()) { String ifaceName = i.getName(); AndExpr conditions = new AndExpr(); OrExpr dstIpMatchesInterface = new OrExpr(); Prefix prefix = i.getPrefix(); if (prefix != null) { Ip ip = prefix.getAddress(); EqExpr dstIpMatches = new EqExpr(new VarIntExpr(DST_IP_VAR), new LitIntExpr(ip)); dstIpMatchesInterface.addDisjunct(dstIpMatches); } NotExpr dstIpNoMatchSrcInterface = new NotExpr( dstIpMatchesInterface); conditions.addConjunct(dstIpNoMatchSrcInterface); PostInInterfaceExpr postInInterface = new PostInInterfaceExpr( hostname, ifaceName); conditions.addConjunct(postInInterface); NonInboundSrcInterfaceExpr nonInboundSrcInterface = new NonInboundSrcInterfaceExpr( hostname, ifaceName); Zone srcZone = i.getZone(); if (srcZone != null) { NonInboundSrcZoneExpr nonInboundSrcZone = new NonInboundSrcZoneExpr( hostname, srcZone.getName()); RuleExpr nonInboundSrcInterfaceToNonInboundSrcZone = new RuleExpr( nonInboundSrcInterface, nonInboundSrcZone); statements.add(nonInboundSrcInterfaceToNonInboundSrcZone); } else if (c.getDefaultCrossZoneAction() == LineAction.ACCEPT) { NonInboundNullSrcZoneExpr nonInboundNullSrcZone = new NonInboundNullSrcZoneExpr( hostname); RuleExpr nonInboundSrcInterfaceToNonInboundNullSrcZone = new RuleExpr( nonInboundSrcInterface, nonInboundNullSrcZone); statements.add(nonInboundSrcInterfaceToNonInboundNullSrcZone); } RuleExpr postInInterfaceToNonInboundSrcInterface = new RuleExpr( conditions, nonInboundSrcInterface); statements.add(postInInterfaceToNonInboundSrcInterface); } } return statements; } private List<Statement> getPostInInterfaceToPostInRules() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment( "Rules for connecting postInInterface to postIn")); for (Entry<String, Set<Interface>> e : _topologyInterfaces.entrySet()) { String hostname = e.getKey(); Set<Interface> interfaces = e.getValue(); UnoriginalExpr unoriginal = new UnoriginalExpr(hostname); for (Interface i : interfaces) { String ifaceName = i.getName(); PostInInterfaceExpr postInIface = new PostInInterfaceExpr(hostname, ifaceName); PostInExpr postIn = new PostInExpr(hostname); RuleExpr postInInterfaceToPostIn = new RuleExpr(postInIface, postIn); statements.add(postInInterfaceToPostIn); RuleExpr postInInterfaceToUnoriginal = new RuleExpr(postInIface, unoriginal); statements.add(postInInterfaceToUnoriginal); } } return statements; } private List<Statement> getPostInToInboundInterface() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment( "Rules for connecting post_in to inbound_interface")); for (Configuration c : _configurations.values()) { String hostname = c.getHostname(); PostInExpr postIn = new PostInExpr(hostname); for (Interface i : c.getInterfaces().values()) { String ifaceName = i.getName(); OrExpr dstIpMatchesInterface = new OrExpr(); Prefix prefix = i.getPrefix(); if (prefix != null) { Ip ip = prefix.getAddress(); EqExpr dstIpMatches = new EqExpr(new VarIntExpr(DST_IP_VAR), new LitIntExpr(ip)); dstIpMatchesInterface.addDisjunct(dstIpMatches); } AndExpr inboundInterfaceConditions = new AndExpr(); inboundInterfaceConditions.addConjunct(dstIpMatchesInterface); inboundInterfaceConditions.addConjunct(postIn); InboundInterfaceExpr inboundInterface = new InboundInterfaceExpr( hostname, ifaceName); RuleExpr postInToInboundInterface = new RuleExpr( inboundInterfaceConditions, inboundInterface); statements.add(postInToInboundInterface); } } return statements; } /* * private List<Statement> getPostInToNodeAcceptRules() { List<Statement> * statements = new ArrayList<Statement>(); statements .add(new * Comment("Rules for connecting post_in to node_accept")); for * (Configuration c : _configurations.values()) { String hostname = * c.getHostname(); PostInExpr postIn = new PostInExpr(hostname); for * (Interface i : c.getInterfaces().values()) { String ifaceName = * i.getName(); OrExpr someDstIpMatches = new OrExpr(); Prefix prefix = * i.getPrefix(); if (prefix != null) { Ip ip = prefix.getAddress(); EqExpr * dstIpMatches = new EqExpr(new VarIntExpr(DST_IP_VAR), new LitIntExpr(ip)); * someDstIpMatches.addDisjunct(dstIpMatches); } AndExpr * inboundInterfaceConditions = new AndExpr(); * inboundInterfaceConditions.addConjunct(someDstIpMatches); * inboundInterfaceConditions.addConjunct(postIn); InboundInterfaceExpr * inboundInterface = new InboundInterfaceExpr( hostname, ifaceName); * RuleExpr postInToInboundInterface = new RuleExpr( * inboundInterfaceConditions, inboundInterface); AndExpr acceptConditions = * new AndExpr(); PassHostFilterExpr passHostFilter = new * PassHostFilterExpr(hostname); PassInboundFilterExpr passInboundFilter = * new PassInboundFilterExpr( hostname, ifaceName); PostInInterfaceExpr * postInInterface = new PostInInterfaceExpr( hostname, ifaceName); * acceptConditions.addConjunct(postInInterface); * acceptConditions.addConjunct(passHostFilter); * acceptConditions.addConjunct(passInboundFilter); * statements.add(postInToInboundInterface); } NodeAcceptExpr nodeAccept = * new NodeAcceptExpr(hostname); AndExpr conditions = new AndExpr(); * conditions.addConjunct(postIn); conditions.addConjunct(someDstIpMatches); * RuleExpr rule = new RuleExpr(conditions, nodeAccept); * statements.add(rule); } return statements; } */ private List<Statement> getPostInToPreOutRules() { List<Statement> statements = new ArrayList<Statement>(); statements .add(new Comment( "postin ==> preout:", "forward to preout if for each ip address on an interface, destination ip does not match")); for (Configuration c : _configurations.values()) { String hostname = c.getHostname(); OrExpr someDstIpMatch = new OrExpr(); for (Interface i : c.getInterfaces().values()) { Prefix prefix = i.getPrefix(); if (prefix != null) { Ip ip = prefix.getAddress(); EqExpr dstIpMatches = new EqExpr(new VarIntExpr(DST_IP_VAR), new LitIntExpr(ip)); someDstIpMatch.addDisjunct(dstIpMatches); } } NotExpr noDstIpMatch = new NotExpr(someDstIpMatch); PostInExpr postIn = new PostInExpr(hostname); PreOutExpr preOut = new PreOutExpr(hostname); AndExpr conditions = new AndExpr(); conditions.addConjunct(postIn); conditions.addConjunct(noDstIpMatch); RuleExpr rule = new RuleExpr(conditions, preOut); statements.add(rule); } return statements; } private List<Statement> getPostOutIfaceToNodeTransitRules() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment( "Rules connecting postout_iface to node_transit")); for (Entry<String, Set<Interface>> e : _topologyInterfaces.entrySet()) { String hostname = e.getKey(); Set<Interface> interfaces = e.getValue(); NodeTransitExpr nodeTransit = new NodeTransitExpr(hostname); for (Interface iface : interfaces) { String ifaceName = iface.getName(); PostOutInterfaceExpr postOutIface = new PostOutInterfaceExpr( hostname, ifaceName); RuleExpr rule = new RuleExpr(postOutIface, nodeTransit); statements.add(rule); } } return statements; } private List<Statement> getPreInInterfaceToPostInInterfaceRules() { List<Statement> statements = new ArrayList<Statement>(); statements .add(new Comment( "Connect prein_interface to postin_interface, possibly through acl")); for (String hostname : _topologyInterfaces.keySet()) { Set<Interface> interfaces = _topologyInterfaces.get(hostname); for (Interface iface : interfaces) { String ifaceName = iface.getName(); if (isFlowSink(hostname, ifaceName)) { continue; } NodeDropExpr nodeDrop = new NodeDropExpr(hostname); PreInInterfaceExpr preInIface = new PreInInterfaceExpr(hostname, ifaceName); PostInInterfaceExpr postInIface = new PostInInterfaceExpr(hostname, ifaceName); AndExpr conditions = new AndExpr(); conditions.addConjunct(preInIface); IpAccessList inAcl = iface.getIncomingFilter(); if (inAcl != null) { String aclName = inAcl.getName(); AclPermitExpr aclPermit = new AclPermitExpr(hostname, aclName); conditions.addConjunct(aclPermit); AndExpr dropConditions = new AndExpr(); AclDenyExpr aclDeny = new AclDenyExpr(hostname, aclName); dropConditions.addConjunct(preInIface); dropConditions.addConjunct(aclDeny); RuleExpr drop = new RuleExpr(dropConditions, nodeDrop); statements.add(drop); } RuleExpr preInToPostIn = new RuleExpr(conditions, postInIface); statements.add(preInToPostIn); } } return statements; } private List<Statement> getPreOutEdgeToPreOutInterfaceRules() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment("PreOutEdge => PreOutInterface")); for (NodeInterfacePair f : _flowSinks) { String hostnameOut = f.getHostname(); String hostnameIn = NODE_NONE_NAME; String intOut = f.getInterface(); String intIn = FLOW_SINK_TERMINATION_NAME; PreOutEdgeExpr preOutEdge = new PreOutEdgeExpr(hostnameOut, intOut, hostnameIn, intIn); PreOutInterfaceExpr preOutInt = new PreOutInterfaceExpr(hostnameOut, intOut); RuleExpr rule = new RuleExpr(preOutEdge, preOutInt); statements.add(rule); } for (Edge edge : _topologyEdges) { String hostnameOut = edge.getNode1(); String hostnameIn = edge.getNode2(); String intOut = edge.getInt1(); String intIn = edge.getInt2(); PreOutEdgeExpr preOutEdge = new PreOutEdgeExpr(hostnameOut, intOut, hostnameIn, intIn); PreOutInterfaceExpr preOutInt = new PreOutInterfaceExpr(hostnameOut, intOut); RuleExpr rule = new RuleExpr(preOutEdge, preOutInt); statements.add(rule); } return statements; } private List<Statement> getPreOutInterfaceToPostOutInterfaceRules() { List<Statement> statements = new ArrayList<Statement>(); statements .add(new Comment( "Connect preout_interface to postout_interface, possibly through acl")); for (String hostname : _topologyInterfaces.keySet()) { Configuration c = _configurations.get(hostname); Set<Interface> interfaces = _topologyInterfaces.get(hostname); OriginateExpr originate = new OriginateExpr(hostname); UnoriginalExpr unoriginal = new UnoriginalExpr(hostname); for (Interface iface : interfaces) { String ifaceName = iface.getName(); NodeDropExpr nodeDrop = new NodeDropExpr(hostname); PreOutInterfaceExpr preOutIface = new PreOutInterfaceExpr(hostname, ifaceName); PostOutInterfaceExpr postOutIface = new PostOutInterfaceExpr( hostname, ifaceName); AndExpr outConditions = new AndExpr(); AndExpr dropConditions = new AndExpr(); outConditions.addConjunct(preOutIface); dropConditions.addConjunct(preOutIface); OrExpr filterDeny = new OrExpr(); OrExpr crossZonePermit = new OrExpr(); IpAccessList outAcl = iface.getOutgoingFilter(); if (outAcl != null) { String aclName = outAcl.getName(); AclPermitExpr aclPermit = new AclPermitExpr(hostname, aclName); outConditions.addConjunct(aclPermit); AclDenyExpr aclDeny = new AclDenyExpr(hostname, aclName); filterDeny.addDisjunct(aclDeny); } dropConditions.addConjunct(filterDeny); // handle cross-zone filter // first handle case where outgoing interface has no zone Zone outZone = iface.getZone(); if (outZone == null) { if (c.getDefaultCrossZoneAction() == LineAction.REJECT) { filterDeny.addDisjunct(unoriginal); } else { crossZonePermit.addDisjunct(TrueExpr.INSTANCE); } } else { // outgoing interface has zone // now handle case of original packet IpAccessList fromHostFilter = outZone.getFromHostFilter(); if (fromHostFilter != null) { String fromHostFilterName = fromHostFilter.getName(); AclPermitExpr hostFilterPermit = new AclPermitExpr(hostname, fromHostFilterName); AndExpr originateCrossZonePermit = new AndExpr(); originateCrossZonePermit.addConjunct(hostFilterPermit); originateCrossZonePermit.addConjunct(originate); crossZonePermit.addDisjunct(originateCrossZonePermit); AclDenyExpr hostFilterDeny = new AclDenyExpr(hostname, fromHostFilterName); AndExpr originateCrossZoneDeny = new AndExpr(); originateCrossZoneDeny.addConjunct(hostFilterDeny); originateCrossZoneDeny.addConjunct(originate); filterDeny.addDisjunct(originateCrossZoneDeny); } else { crossZonePermit.addDisjunct(originate); } // now handle unoriginal packets // null src zone: NonInboundNullSrcZoneExpr nonInboundNullSrcZone = new NonInboundNullSrcZoneExpr( hostname); if (c.getDefaultCrossZoneAction() == LineAction.REJECT) { filterDeny.addDisjunct(nonInboundNullSrcZone); } else { // default for null src zone is to accept crossZonePermit.addDisjunct(nonInboundNullSrcZone); } // now handle cases of each possible src zone (still unoriginal) for (Zone srcZone : c.getZones().values()) { String srcZoneName = srcZone.getName(); NonInboundSrcZoneExpr nonInboundSrcZone = new NonInboundSrcZoneExpr( hostname, srcZoneName); IpAccessList crossZoneFilter = srcZone.getToZonePolicies() .get(outZone.getName()); // no policy for this pair of zones - use default cross-zone // action if (crossZoneFilter == null) { if (c.getDefaultCrossZoneAction() == LineAction.REJECT) { filterDeny.addDisjunct(nonInboundSrcZone); } else { crossZonePermit.addDisjunct(nonInboundSrcZone); } } else { // there is a cross-zone filter String crossZoneFilterName = crossZoneFilter.getName(); AclPermitExpr crossZoneFilterPermit = new AclPermitExpr( hostname, crossZoneFilterName); AclDenyExpr crossZoneFilterDeny = new AclDenyExpr( hostname, crossZoneFilterName); AndExpr deniedByCrossZoneFilter = new AndExpr(); deniedByCrossZoneFilter.addConjunct(nonInboundSrcZone); deniedByCrossZoneFilter.addConjunct(crossZoneFilterDeny); filterDeny.addDisjunct(deniedByCrossZoneFilter); AndExpr allowedByCrossZoneFilter = new AndExpr(); allowedByCrossZoneFilter.addConjunct(nonInboundSrcZone); allowedByCrossZoneFilter .addConjunct(crossZoneFilterPermit); crossZonePermit.addDisjunct(allowedByCrossZoneFilter); } } } outConditions.addConjunct(crossZonePermit); RuleExpr drop = new RuleExpr(dropConditions, nodeDrop); statements.add(drop); RuleExpr preOutToPostOut = new RuleExpr(outConditions, postOutIface); statements.add(preOutToPostOut); } } return statements; } private List<Statement> getPreOutToDestRouteRules() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment( "Rules for sending packets from preout to destroute stage")); for (String hostname : _configurations.keySet()) { /** * if a packet whose source node is a given node reaches preout on that * node, then it reaches destroute */ PreOutExpr preOut = new PreOutExpr(hostname); OriginateExpr originate = new OriginateExpr(hostname); DestinationRouteExpr destRoute = new DestinationRouteExpr(hostname); AndExpr originConditions = new AndExpr(); originConditions.addConjunct(preOut); originConditions.addConjunct(originate); RuleExpr originDestRoute = new RuleExpr(originConditions, destRoute); statements.add(originDestRoute); } for (Entry<String, Set<Interface>> e : _topologyInterfaces.entrySet()) { String hostname = e.getKey(); PreOutExpr preOut = new PreOutExpr(hostname); DestinationRouteExpr destRoute = new DestinationRouteExpr(hostname); Set<Interface> interfaces = e.getValue(); for (Interface i : interfaces) { String ifaceName = i.getName(); /** * if a packet reaches postin_interface on interface, and interface * is not policy-routed, and it reaches preout, then it reaches * destroute */ /** * if a packet reaches postin_interface on intefrace, and interface * is policy-routed by policy, and policy denies, and it reaches * preout, then it reaches destroute * */ PostInInterfaceExpr postInInterface = new PostInInterfaceExpr( hostname, ifaceName); AndExpr receivedDestRouteConditions = new AndExpr(); receivedDestRouteConditions.addConjunct(postInInterface); receivedDestRouteConditions.addConjunct(preOut); PolicyMap policy = i.getRoutingPolicy(); if (policy != null) { String policyName = policy.getMapName(); PolicyDenyExpr policyDeny = new PolicyDenyExpr(hostname, policyName); receivedDestRouteConditions.addConjunct(policyDeny); } RuleExpr receivedDestRoute = new RuleExpr( receivedDestRouteConditions, destRoute); statements.add(receivedDestRoute); } } return statements; } private List<Statement> getRoleOriginateToNodeOriginateRules() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment( "Rules connecting role_originate to R_originate")); for (Entry<String, Configuration> e : _configurations.entrySet()) { String hostname = e.getKey(); Configuration c = e.getValue(); OriginateExpr nodeOriginate = new OriginateExpr(hostname); RoleSet roles = c.getRoles(); if (roles != null) { for (String role : roles) { RoleOriginateExpr roleOriginate = new RoleOriginateExpr(role); RuleExpr rule = new RuleExpr(roleOriginate, nodeOriginate); statements.add(rule); } } } return statements; } private List<Statement> getSane() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment("Make sure packet fields make sense")); AndExpr noPortNumbers = new AndExpr(); EqExpr noDstPort = new EqExpr(new VarIntExpr(DST_PORT_VAR), new LitIntExpr(0, PORT_BITS)); EqExpr noSrcPort = new EqExpr(new VarIntExpr(SRC_PORT_VAR), new LitIntExpr(0, PORT_BITS)); noPortNumbers.addConjunct(noDstPort); noPortNumbers.addConjunct(noSrcPort); EqExpr noTcpFlags = new EqExpr(new VarIntExpr(TCP_FLAGS_VAR), new LitIntExpr(TcpFlags.UNSET, TCP_FLAGS_BITS)); EqExpr noIcmpCode = new EqExpr(new VarIntExpr(ICMP_CODE_VAR), new LitIntExpr(IcmpCode.UNSET, ICMP_CODE_BITS)); EqExpr noIcmpType = new EqExpr(new VarIntExpr(ICMP_TYPE_VAR), new LitIntExpr(IcmpType.UNSET, ICMP_TYPE_BITS)); AndExpr noIcmp = new AndExpr(); noIcmp.addConjunct(noIcmpType); noIcmp.addConjunct(noIcmpCode); EqExpr icmpProtocol = new EqExpr(new VarIntExpr(IP_PROTOCOL_VAR), new LitIntExpr(IpProtocol.ICMP.number(), PROTOCOL_BITS)); EqExpr tcpProtocol = new EqExpr(new VarIntExpr(IP_PROTOCOL_VAR), new LitIntExpr(IpProtocol.TCP.number(), PROTOCOL_BITS)); EqExpr udpProtocol = new EqExpr(new VarIntExpr(IP_PROTOCOL_VAR), new LitIntExpr(IpProtocol.UDP.number(), PROTOCOL_BITS)); AndExpr tcp = new AndExpr(); tcp.addConjunct(tcpProtocol); tcp.addConjunct(noIcmp); AndExpr udp = new AndExpr(); udp.addConjunct(udpProtocol); udp.addConjunct(noIcmp); udp.addConjunct(noTcpFlags); AndExpr icmp = new AndExpr(); icmp.addConjunct(icmpProtocol); icmp.addConjunct(noTcpFlags); icmp.addConjunct(noPortNumbers); AndExpr otherIp = new AndExpr(); otherIp.addConjunct(noIcmp); otherIp.addConjunct(noTcpFlags); otherIp.addConjunct(noPortNumbers); OrExpr isSane = new OrExpr(); isSane.addDisjunct(icmp); isSane.addDisjunct(tcp); isSane.addDisjunct(udp); isSane.addDisjunct(otherIp); RuleExpr rule = new RuleExpr(isSane, SaneExpr.INSTANCE); statements.add(rule); return statements; } private List<Statement> getToNeighborsRules() { List<Statement> statements = new ArrayList<Statement>(); statements.add(new Comment("Topology edge rules")); for (Edge edge : _topologyEdges) { String hostnameOut = edge.getNode1(); String hostnameIn = edge.getNode2(); String intOut = edge.getInt1(); String intIn = edge.getInt2(); if (isFlowSink(hostnameIn, intIn) || isFlowSink(hostnameOut, intOut)) { continue; } PostOutInterfaceExpr postOutIface = new PostOutInterfaceExpr( hostnameOut, intOut); PreOutEdgeExpr preOutEdge = new PreOutEdgeExpr(hostnameOut, intOut, hostnameIn, intIn); PreInInterfaceExpr preInIface = new PreInInterfaceExpr(hostnameIn, intIn); AndExpr conditions = new AndExpr(); conditions.addConjunct(postOutIface); conditions.addConjunct(preOutEdge); RuleExpr propagateToAdjacent = new RuleExpr(conditions, preInIface); statements.add(propagateToAdjacent); } return statements; } public List<String> getWarnings() { return _warnings; } private boolean isFlowSink(String hostname, String ifaceName) { NodeInterfacePair f = new NodeInterfacePair(hostname, ifaceName); return _flowSinks.contains(f); } private void pruneInterfaces() { for (Configuration c : _configurations.values()) { String hostname = c.getHostname(); Set<String> prunedInterfaces = new HashSet<String>(); Map<String, Interface> interfaces = c.getInterfaces(); Set<Interface> topologyInterfaces = _topologyInterfaces.get(hostname); for (Interface i : interfaces.values()) { String ifaceName = i.getName(); if ((!i.getActive() && !topologyInterfaces.contains(i))) { prunedInterfaces.add(ifaceName); } if (!i.getActive() && topologyInterfaces.contains(i)) { Interface blankInterface = new Interface(ifaceName, c); blankInterface.setActive(false); interfaces.put(ifaceName, blankInterface); } } for (String i : prunedInterfaces) { interfaces.remove(i); } } } public NodProgram synthesizeNodAclProgram(Context ctx) throws Z3Exception { List<Statement> ruleStatements = new ArrayList<Statement>(); List<Statement> sane = getSane(); List<Statement> matchAclRules = getMatchAclRules(); ruleStatements.addAll(sane); ruleStatements.addAll(matchAclRules); return synthesizeNodProgram(ctx, ruleStatements); } public NodProgram synthesizeNodDataPlaneProgram(Context ctx) throws Z3Exception { List<Statement> ruleStatements = new ArrayList<Statement>(); List<Statement> dropRules = getDropRules(); List<Statement> acceptRules = getAcceptRules(); List<Statement> sane = getSane(); List<Statement> flowSinkAcceptRules = getFlowSinkAcceptRules(); List<Statement> originateToPostInRules = getOriginateToPostInRules(); List<Statement> postInInterfaceToPostInRules = getPostInInterfaceToPostInRules(); List<Statement> postInInterfaceToNonInboundSrcInterface = getPostInInterfaceToNonInboundSrcInterface(); List<Statement> postInToInboundInterface = getPostInToInboundInterface(); List<Statement> inboundInterfaceToNodeAccept = getInboundInterfaceToNodeAccept(); List<Statement> inboundInterfaceToNodeDrop = getInboundInterfaceToNodeDrop(); List<Statement> postInToPreOutRules = getPostInToPreOutRules(); List<Statement> preOutToDestRouteRules = getPreOutToDestRouteRules(); List<Statement> destRouteToPreOutEdgeRules = getDestRouteToPreOutEdgeRules(); List<Statement> preOutEdgeToPreOutInterfaceRules = getPreOutEdgeToPreOutInterfaceRules(); List<Statement> policyRouteRules = getPolicyRouteRules(); List<Statement> matchAclRules = getMatchAclRules(); List<Statement> toNeighborsRules = getToNeighborsRules(); List<Statement> preInInterfaceToPostInInterfaceRules = getPreInInterfaceToPostInInterfaceRules(); List<Statement> preOutInterfaceToPostOutInterfaceRules = getPreOutInterfaceToPostOutInterfaceRules(); List<Statement> nodeAcceptToRoleAcceptRules = getNodeAcceptToRoleAcceptRules(); List<Statement> externalSrcIpRules = getExternalSrcIpRules(); List<Statement> externalDstIpRules = getExternalDstIpRules(); List<Statement> postOutIfaceToNodeTransitRules = getPostOutIfaceToNodeTransitRules(); List<Statement> roleOriginateToNodeOriginateRules = getRoleOriginateToNodeOriginateRules(); ruleStatements.addAll(dropRules); ruleStatements.addAll(acceptRules); ruleStatements.addAll(sane); ruleStatements.addAll(flowSinkAcceptRules); ruleStatements.addAll(originateToPostInRules); ruleStatements.addAll(postInInterfaceToPostInRules); ruleStatements.addAll(postInInterfaceToNonInboundSrcInterface); ruleStatements.addAll(postInToInboundInterface); ruleStatements.addAll(inboundInterfaceToNodeAccept); ruleStatements.addAll(inboundInterfaceToNodeDrop); ruleStatements.addAll(postInToPreOutRules); ruleStatements.addAll(preOutToDestRouteRules); ruleStatements.addAll(destRouteToPreOutEdgeRules); ruleStatements.addAll(preOutEdgeToPreOutInterfaceRules); ruleStatements.addAll(policyRouteRules); ruleStatements.addAll(matchAclRules); ruleStatements.addAll(toNeighborsRules); ruleStatements.addAll(preInInterfaceToPostInInterfaceRules); ruleStatements.addAll(preOutInterfaceToPostOutInterfaceRules); ruleStatements.addAll(nodeAcceptToRoleAcceptRules); ruleStatements.addAll(externalSrcIpRules); ruleStatements.addAll(externalDstIpRules); ruleStatements.addAll(postOutIfaceToNodeTransitRules); ruleStatements.addAll(roleOriginateToNodeOriginateRules); return synthesizeNodProgram(ctx, ruleStatements); } private NodProgram synthesizeNodProgram(Context ctx, List<Statement> ruleStatements) { NodProgram nodProgram = new NodProgram(ctx); Map<String, FuncDecl> relDeclFuncDecls = getRelDeclFuncDecls( ruleStatements, ctx); nodProgram.getRelationDeclarations().putAll(relDeclFuncDecls); Map<String, BitVecExpr> variables = nodProgram.getVariables(); Map<String, BitVecExpr> variablesAsConsts = nodProgram .getVariablesAsConsts(); int deBruinIndex = 0; for (Entry<String, Integer> e : PACKET_VAR_SIZES.entrySet()) { String var = e.getKey(); int size = e.getValue(); BitVecExpr varExpr = (BitVecExpr) ctx.mkBound(deBruinIndex, ctx.mkBitVecSort(size)); BitVecExpr varAsConstExpr = (BitVecExpr) ctx.mkConst(var, ctx.mkBitVecSort(size)); variables.put(var, varExpr); variablesAsConsts.put(var, varAsConstExpr); deBruinIndex++; } List<BoolExpr> rules = nodProgram.getRules(); for (Statement rawStatement : ruleStatements) { Statement statement; if (_simplify) { statement = rawStatement.simplify(); } else { statement = rawStatement; } if (statement instanceof RuleExpr) { RuleExpr ruleExpr = (RuleExpr) statement; BoolExpr rule = ruleExpr.toBoolExpr(nodProgram); rules.add(rule); } } return nodProgram; } }
package jolie.lang.parse; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.util.HashMap; import java.util.Map; import jolie.lang.NativeType; /** * Scanner implementation for the Jolie language parser. * * @author Fabrizio Montesi * */ public class Scanner { /** Token types */ public enum TokenType { EOF, ///< End Of File ID, ///< [a-z][a-zA-Z0-9]* COMMA, DOT, INT, TRUE, ///< true FALSE, ///< false LONG, ///< [0-9]+(l|L) DOUBLE, ///< [0-9]*"."[0-9]+(e|E)[0-9]+ LPAREN, RPAREN, LSQUARE, RSQUARE, LCURLY, RCURLY, //DOLLAR, ///< $ STRING, ///< "[[:graph:]]*" INCREMENT, MINUS, ///< The minus sign - ASTERISK, DIVIDE, ASSIGN, PLUS, ADD_ASSIGN, MINUS_ASSIGN, MULTIPLY_ASSIGN, DIVIDE_ASSIGN, SEQUENCE, IF, ELSE, ///< else LANGLE, RANGLE, AT, LINKIN, ///< linkIn LINKOUT, ///< linkOut INSTANCE_OF, ///< instanceof EQUAL, AND, OR, PARALLEL, NOT, CARET, COLON, OP_OW, ///< OneWay OP_RR, ///< RequestResponse DEFINE, ///< define MAJOR_OR_EQUAL, MINOR_OR_EQUAL, NOT_EQUAL, NULL_PROCESS, ///< nullProcess WHILE, ///< while EXECUTION, ///< execution THROW, ///< throw DOCUMENTATION_COMMENT, INSTALL, ///< install SCOPE, ///< scope SPAWN, ///< spawn THIS, ///< this COMPENSATE, ///< comp EXIT, ///< exit INCLUDE, ///< include CONSTANTS, ///< constants POINTS_TO, QUESTION_MARK, ARROW, DEEP_COPY_LEFT, RUN, ///< run UNDEF, ///< undef HASH, ///< PERCENT_SIGN, FOR, ///< for FOREACH, ///< foreach WITH, ///< with DECREMENT, IS_STRING, ///< is_string IS_INT, ///< is_int IS_DOUBLE, ///< is_double IS_BOOL, ///< is_bool IS_LONG, ///< is_long IS_DEFINED, ///< is_defined CAST_INT, ///< int CAST_STRING, ///< string CAST_DOUBLE, ///< double CAST_BOOL, ///< bool CAST_LONG, ///< long SYNCHRONIZED, ///< synchronized THROWS, ///< throws CURRENT_HANDLER, INIT, ///< init PROVIDE, ///< provide ERROR ///< Scanner error } /* * Map of unreserved keywords, * which can be considered as IDs in certain places (e.g. variables). */ private static final Map< String, TokenType > unreservedKeywords = new HashMap<>(); static { // Initialise the unreserved keywords map. unreservedKeywords.put( "OneWay", TokenType.OP_OW ); unreservedKeywords.put( "RequestResponse", TokenType.OP_RR ); unreservedKeywords.put( "linkIn", TokenType.LINKIN ); unreservedKeywords.put( "linkOut", TokenType.LINKOUT ); unreservedKeywords.put( "if", TokenType.IF ); unreservedKeywords.put( "else", TokenType.ELSE ); unreservedKeywords.put( "include", TokenType.INCLUDE ); unreservedKeywords.put( "define", TokenType.DEFINE ); unreservedKeywords.put( "nullProcess", TokenType.NULL_PROCESS ); unreservedKeywords.put( "while", TokenType.WHILE ); unreservedKeywords.put( "execution", TokenType.EXECUTION ); unreservedKeywords.put( "install", TokenType.INSTALL ); unreservedKeywords.put( "this", TokenType.THIS ); unreservedKeywords.put( "synchronized", TokenType.SYNCHRONIZED ); unreservedKeywords.put( "throw", TokenType.THROW ); unreservedKeywords.put( "scope", TokenType.SCOPE ); unreservedKeywords.put( "spawn", TokenType.SPAWN ); unreservedKeywords.put( "comp", TokenType.COMPENSATE ); unreservedKeywords.put( "exit", TokenType.EXIT ); unreservedKeywords.put( "constants", TokenType.CONSTANTS ); unreservedKeywords.put( "undef", TokenType.UNDEF ); unreservedKeywords.put( "for", TokenType.FOR ); unreservedKeywords.put( "foreach", TokenType.FOREACH ); unreservedKeywords.put( "is_defined", TokenType.IS_DEFINED ); unreservedKeywords.put( "is_string", TokenType.IS_STRING ); unreservedKeywords.put( "is_int", TokenType.IS_INT ); unreservedKeywords.put( "is_bool", TokenType.IS_BOOL ); unreservedKeywords.put( "is_long", TokenType.IS_LONG ); unreservedKeywords.put( "is_double", TokenType.IS_DOUBLE ); unreservedKeywords.put( "instanceof", TokenType.INSTANCE_OF ); unreservedKeywords.put( NativeType.INT.id(), TokenType.CAST_INT ); unreservedKeywords.put( NativeType.STRING.id(), TokenType.CAST_STRING ); unreservedKeywords.put( NativeType.BOOL.id(), TokenType.CAST_BOOL ); unreservedKeywords.put( NativeType.DOUBLE.id(), TokenType.CAST_DOUBLE ); unreservedKeywords.put( NativeType.LONG.id(), TokenType.CAST_LONG ); unreservedKeywords.put( "throws", TokenType.THROWS ); unreservedKeywords.put( "cH", TokenType.CURRENT_HANDLER ); unreservedKeywords.put( "init", TokenType.INIT ); unreservedKeywords.put( "with", TokenType.WITH ); unreservedKeywords.put( "true", TokenType.TRUE ); unreservedKeywords.put( "false", TokenType.FALSE ); unreservedKeywords.put( "provide", TokenType.PROVIDE ); } /** * This class represents an input token read by the Scanner class. * * @see Scanner * @author Fabrizio Montesi * @version 1.0 * */ public static class Token { private final TokenType type; private final String content; private final boolean isUnreservedKeyword; /** * Constructor. The content of the token will be set to "". * @param type the type of this token */ public Token( TokenType type ) { this.type = type; this.content = ""; this.isUnreservedKeyword = false; } /** * Constructor. * @param type the type of this token * @param content the content of this token */ public Token( TokenType type, String content ) { this.type = type; this.content = content; this.isUnreservedKeyword = false; } /** * Constructor. * @param type the type of this token * @param content the content of this token * @param isUnreservedKeyword specifies whether this token is an unreserved keyword */ public Token( TokenType type, String content, boolean isUnreservedKeyword ) { this.type = type; this.content = content; this.isUnreservedKeyword = isUnreservedKeyword; } /** * Returns the content of this token. * @return the content of this token */ public String content() { return content; } /** * Returns the type of this token. * @return the type of this token */ public TokenType type() { return type; } /** * Returns <code>true</code> if this token can be considered as a valid * value for a constant, <code>false</code> otherwise. * @return <code>true</code> if this token can be considered as a valid * value for a constant, <code>false</code> otherwise */ public boolean isValidConstant() { return type == TokenType.STRING || type == TokenType.INT || type == TokenType.ID || type == TokenType.LONG || type == TokenType.TRUE || type == TokenType.FALSE || type == TokenType.DOUBLE; } /** * Equivalent to <code>is(TokenType.EOF)</code> * @return <code>true</code> if this token has type <code>TokenType.EOF</code>, false otherwise */ public boolean isEOF() { return ( type == TokenType.EOF ); } /** * Returns <code>true</code> if this token has the passed type, <code>false</code> otherwise. * @param compareType the type to compare the type of this token with * @return <code>true</code> if this token has the passed type, <code>false</code> otherwise */ public boolean is( TokenType compareType ) { return ( type == compareType ); } /** * Returns <code>true</code> if this token has a different type from the passed one, <code>false</code> otherwise. * @param compareType the type to compare the type of this token with * @return <code>true</code> if this token has a different type from the passed one, <code>false</code> otherwise */ public boolean isNot( TokenType compareType ) { return ( type != compareType ); } /** * Returns <code>true</code> if this token has type <code>TokenType.ID</code> * and its content is equal to the passed parameter, <code>false</code> otherwise. * @param keyword the keyword to check the content of this token against * @return <code>true</code> if this token has type <code>TokenType.ID</code> * and its content is equal to the passed parameter, <code>false</code> otherwise */ public boolean isKeyword( String keyword ) { return( type == TokenType.ID && content.equals( keyword ) ); } /** * Returns <code>true</code> if this token has type <code>TokenType.ID</code> * or is a token for an unreserved keyword, <code>false</code> otherwise. * @return <code>true</code> if this token has type <code>TokenType.ID</code> * or is a token for an unreserved keyword, <code>false</code> otherwise. */ public boolean isIdentifier() { return( type == TokenType.ID || isUnreservedKeyword ); } /** * This method behaves as {@link #isKeyword(java.lang.String) isKeyword}, except that * it is case insensitive. * @param keyword the keyword to check the content of this token against * @return */ public boolean isKeywordIgnoreCase( String keyword ) { return( type == TokenType.ID && content.equalsIgnoreCase( keyword ) ); } } private final InputStream stream; // input stream private final InputStreamReader reader; // data input protected char ch; // current character protected int currInt; // current stream int protected int state; // current state private int line; // current line private final URI source; // source name /** * Constructor * @param stream the <code>InputStream</code> to use for input reading * @param source the source URI of the stream * @param charset the character encoding * @throws java.io.IOException if the input reading initialization fails */ public Scanner( InputStream stream, URI source, String charset ) throws IOException { this.stream = stream; this.reader = charset != null ? new InputStreamReader( stream, charset ) : new InputStreamReader( stream ); this.source = source; line = 1; readChar(); } /* public String readWord() throws IOException { return readWord( true ); } public String readWord( boolean readChar ) throws IOException { StringBuilder buffer = new StringBuilder(); if ( readChar ) { readChar(); } do { buffer.append( ch ); readChar(); } while( !isSeparator( ch ) ); return buffer.toString(); } */ private final StringBuilder tokenBuilder = new StringBuilder( 64 ); private void resetTokenBuilder() { tokenBuilder.setLength( 0 ); } public String readLine() throws IOException { resetTokenBuilder(); readChar(); while( !isNewLineChar( ch ) ) { tokenBuilder.append( ch ); readChar(); } return tokenBuilder.toString(); } public InputStream inputStream() { return stream; } /** * Returns character encoding * @return character encoding */ public String charset() { return reader.getEncoding(); } /** * Returns the current line the scanner is reading. * * @return the current line the scanner is reading. */ public int line() { return line; } /** * Returns the source URI the scanner is reading. * * @return the source URI the scanner is reading */ public URI source() { return source; } /** * Eats all separators (whitespace) until the next input. * @throws IOException */ public void eatSeparators() throws IOException { while( isSeparator( ch ) ) { readChar(); } } public void eatSeparatorsUntilEOF() throws IOException { while( isSeparator( ch ) && stream.available() > 0 ) { readChar(); } } /** * Checks whether a character is a separator (whitespace). * @param c the character to check as a whitespace * @return <code>true</code> if <code>c</code> is a separator (whitespace) */ public static boolean isSeparator( char c ) { return isNewLineChar( c ) || c == '\t' || c == ' '; } /** * Checks whether a character is an overflow character. * @param c the character to check * @return <code>true</code> if <code>c</code> is an overflow character */ private static boolean isOverflowChar( char c ) { return ( (int) c >= Character.MAX_VALUE ); } /** * Checks whether a character is a newline character. * @param c the character to check * @return <code>true</code> if <code>c</code> is a newline character */ public static boolean isNewLineChar( char c ) { return ( c == '\n' || c == '\r' ); } /** * Reads the next character and loads it into the scanner local state. * @throws IOException if the source cannot be read */ public final void readChar() throws IOException { currInt = reader.read(); ch = (char) currInt; if ( ch == '\n' ) { line++; } } /** * Returns the current character in the scanner local state. * @return the current character in the scanner local state */ public char currentCharacter() { return ch; } /** * Consumes characters from the source text and returns its corresponding token. * @return the token corresponding to the consumed characters * @throws IOException if not enough characters can be read from the source */ public Token getToken() throws IOException { boolean keepRun = true; state = 1; while ( currInt != -1 && isSeparator( ch ) ) { readChar(); } if ( currInt == -1 ) { return new Token( TokenType.EOF ); } boolean stopOneChar = false; Token retval = null; resetTokenBuilder(); while ( keepRun ) { if ( currInt == -1 && retval == null ) { keepRun = false; // We *need* a token at this point } switch( state ) { /* When considering multi-characters tokens (states > 1), * remember to read another character in case of a * specific character (==) check. */ case 1: // First character if ( Character.isLetter( ch ) || ch == '_' ) { state = 2; } else if ( Character.isDigit( ch ) ) { state = 3; } else if ( ch == '"' ) { state = 4; } else if ( ch == '+' ) { state = 5; } else if ( ch == '*' ) { state = 23; } else if ( ch == '=' ) { state = 6; } else if ( ch == '|' ) { state = 7; } else if ( ch == '&' ) { state = 8; } else if ( ch == '<' ) { state = 9; } else if ( ch == '>' ) { state = 10; } else if ( ch == '!' ) { state = 11; } else if ( ch == '/' ) { state = 12; } else if ( ch == '-' ) { state = 14; } else if ( ch == '.') { // DOT or REAL state = 16; } else { // ONE CHARACTER TOKEN if ( ch == '(' ) { retval = new Token( TokenType.LPAREN ); } else if ( ch == ')' ) { retval = new Token( TokenType.RPAREN ); } else if ( ch == '[' ) { retval = new Token( TokenType.LSQUARE ); } else if ( ch == ']' ) { retval = new Token( TokenType.RSQUARE ); } else if ( ch == '{' ) { retval = new Token( TokenType.LCURLY ); } else if ( ch == '}' ) { retval = new Token( TokenType.RCURLY ); } else if ( ch == '@' ) { retval = new Token( TokenType.AT ); } else if ( ch == ':' ) { retval = new Token( TokenType.COLON ); } else if ( ch == ',' ) { retval = new Token( TokenType.COMMA ); } else if ( ch == ';' ) { retval = new Token( TokenType.SEQUENCE ); } else if ( ch == '%' ) { retval = new Token( TokenType.PERCENT_SIGN ); //else if ( ch == '.' ) //retval = new Token( TokenType.DOT ); } else if ( ch == ' retval = new Token( TokenType.HASH ); } else if ( ch == '^' ) { retval = new Token( TokenType.CARET ); } else if ( ch == '?' ) { retval = new Token( TokenType.QUESTION_MARK ); } /*else if ( ch == '$' ) retval = new Token( TokenType.DOLLAR );*/ readChar(); } break; case 2: // ID (or unreserved keyword) if ( !Character.isLetterOrDigit( ch ) && ch != '_' ) { String str = tokenBuilder.toString(); TokenType tt = unreservedKeywords.get( str ); if ( tt != null ) { // It is an unreserved keyword retval = new Token( tt, str, true ); } else { // It is a normal ID, not corresponding to any keyword retval = new Token( TokenType.ID, str ); } } break; case 3: // INT (or LONG, or DOUBLE) if ( ch == 'e'|| ch == 'E' ){ state = 19; } else if ( !Character.isDigit( ch ) && ch != '.' ) { if ( ch == 'l' || ch == 'L' ) { retval = new Token( TokenType.LONG, tokenBuilder.toString() ); readChar(); } else { retval = new Token( TokenType.INT, tokenBuilder.toString() ); } } else if ( ch == '.' ) { tokenBuilder.append( ch ); readChar(); if ( !Character.isDigit( ch ) ) { retval = new Token( TokenType.ERROR, tokenBuilder.toString() ); } else state = 17; // recognized a DOUBLE } break; case 4: // STRING if ( ch == '"' ) { retval = new Token( TokenType.STRING, tokenBuilder.toString().substring( 1 ) ); readChar(); } else if ( ch == '\\' ) { // Parse special characters readChar(); if ( ch == '\\' ) tokenBuilder.append( '\\' ); else if ( ch == 'n' ) tokenBuilder.append( '\n' ); else if ( ch == 't' ) tokenBuilder.append( '\t' ); else if ( ch == 'r' ) tokenBuilder.append( '\r' ); else if ( ch == '"' ) tokenBuilder.append( '"' ); else if ( ch == 'u' ) tokenBuilder.append( 'u' ); else throw new IOException( "malformed string: bad \\ usage" ); stopOneChar = true; readChar(); } break; case 5: // PLUS OR CHOICE if ( ch == '=' ) { retval = new Token( TokenType.ADD_ASSIGN ); readChar(); } else if ( ch == '+' ) { retval = new Token( TokenType.INCREMENT ); readChar(); } else { retval = new Token( TokenType.PLUS ); } break; case 23: // MULTIPLY or MULTIPLY_ASSIGN if ( ch == '=' ) { retval = new Token( TokenType.MULTIPLY_ASSIGN ); readChar(); } else { retval = new Token( TokenType.ASTERISK, "*" ); } break; case 6: // ASSIGN OR EQUAL if ( ch == '=' ) { retval = new Token( TokenType.EQUAL ); readChar(); } else if ( ch == '>' ) { retval = new Token( TokenType.ARROW ); readChar(); } else retval = new Token( TokenType.ASSIGN ); break; case 7: // PARALLEL OR LOGICAL OR if ( ch == '|' ) { retval = new Token( TokenType.OR ); readChar(); } else retval = new Token( TokenType.PARALLEL ); break; case 8: // LOGICAL AND if ( ch == '&' ) { retval = new Token( TokenType.AND ); readChar(); } break; case 9: // LANGLE OR MINOR_OR_EQUAL OR DEEP_COPY_LEFT if ( ch == '=' ) { retval = new Token( TokenType.MINOR_OR_EQUAL ); readChar(); } else if ( ch == '<' ) { retval = new Token( TokenType.DEEP_COPY_LEFT ); readChar(); } else retval = new Token( TokenType.LANGLE ); break; case 10: // RANGLE OR MINOR_OR_EQUAL if ( ch == '=' ) { retval = new Token( TokenType.MAJOR_OR_EQUAL ); readChar(); } else retval = new Token( TokenType.RANGLE ); break; case 11: // NOT OR NOT_EQUAL if ( ch == '=' ) { retval = new Token( TokenType.NOT_EQUAL ); readChar(); } else retval = new Token( TokenType.NOT ); break; case 12: // DIVIDE OR BEGIN_COMMENT OR LINE_COMMENT if ( ch == '*' ) { state = 13; } else if ( ch == '/' ) { state = 15; } else if( ch == '=' ) { retval = new Token( TokenType.DIVIDE_ASSIGN ); readChar(); } else retval = new Token( TokenType.DIVIDE ); break; case 13: // WAITING FOR END_COMMENT if ( ch == '*' ) { readChar(); stopOneChar = true; if ( ch == '/' ) { readChar(); retval = getToken(); } else if ( ch == '!' ) { resetTokenBuilder(); readChar(); state = 21; } } break; case 14: // MINUS OR (negative) NUMBER OR POINTS_TO if ( Character.isDigit( ch ) ) state = 3; else if ( ch == '-' ) { retval = new Token( TokenType.DECREMENT ); readChar(); } else if ( ch == '>' ) { retval = new Token( TokenType.POINTS_TO ); readChar(); } else if ( ch == '=' ) { retval = new Token( TokenType.MINUS_ASSIGN ); readChar(); } else if ( ch == '.' ) { tokenBuilder.append( ch ); readChar(); if ( !Character.isDigit( ch ) ) retval = new Token( TokenType.ERROR, "-." ); else state = 17; } else retval = new Token( TokenType.MINUS ); break; case 15: // LINE_COMMENT: waiting for end of line if ( isNewLineChar( ch ) || isOverflowChar( ch ) ) { readChar(); retval = getToken(); } break; case 16: // DOT if ( !Character.isDigit( ch ) ) retval = new Token( TokenType.DOT ); else state = 17; // It's a REAL break; case 17: // REAL "."[0-9]+ if ( ch == 'E' || ch == 'e' ) state = 18; else if ( !Character.isDigit( ch ) ) retval = new Token( TokenType.DOUBLE, tokenBuilder.toString() ); break; case 18: // Scientific notation, first char after 'E' if ( ch == '-' || ch == '+' ) state = 19; else if ( Character.isDigit( ch ) ) state = 20; else retval = new Token( TokenType.ERROR ); break; case 19: // Scientific notation, first exp. digit if ( !Character.isDigit( ch ) ) retval = new Token( TokenType.ERROR ); else state = 20; break; case 20: // Scientific notation: from second digit to end if ( !Character.isDigit( ch ) ) retval = new Token( TokenType.DOUBLE, tokenBuilder.toString() ); break; case 21: // Documentation comment if ( ch == '*' ) { readChar(); stopOneChar = true; if ( ch == '/' ) { readChar(); retval = new Token( TokenType.DOCUMENTATION_COMMENT, tokenBuilder.toString() ); } } break; default: retval = new Token( TokenType.ERROR, tokenBuilder.toString() ); break; } if ( retval == null ) { if ( stopOneChar ) stopOneChar = false; else { tokenBuilder.append( ch ); readChar(); } } else { keepRun = false; // Ok, we are done. } } if ( retval == null ) { retval = new Token( TokenType.ERROR ); } return retval; } }
package joshua.decoder.chart_parser; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import joshua.corpus.Vocabulary; import joshua.decoder.ff.tm.Grammar; import joshua.decoder.ff.tm.Rule; import joshua.decoder.ff.tm.RuleCollection; import joshua.decoder.ff.tm.Trie; import joshua.lattice.Arc; import joshua.lattice.Lattice; import joshua.lattice.Node; /** * The DotChart handles Earley-style implicit binarization of translation rules. * * The {@link DotNode} object represents the (possibly partial) application of a synchronous rule. * The implicit binarization is maintained with a pointer to the {@link Trie} node in the grammar, * for easy retrieval of the next symbol to be matched. At every span (i,j) of the input sentence, * every incomplete DotNode is examined to see whether it (a) needs a terminal and matches against * the final terminal of the span or (b) needs a nonterminal and matches against a completed * nonterminal in the main chart at some split point (k,j). * * Once a rule is completed, it is entered into the {@link DotChart}. {@link DotCell} objects are * used to group completed DotNodes over a span. * * There is a separate DotChart for every grammar. * * @author Zhifei Li, <zhifei.work@gmail.com> * @author Matt Post <post@cs.jhu.edu> * @author Kristy Hollingshead Seitz */ class DotChart { // Package-protected instance fields /** * Two-dimensional chart of cells. Some cells might be null. This could definitely be represented * more efficiently, since only the upper half of this triangle is every used. */ private DotCell[][] dotcells; public DotCell getDotCell(int i, int j) { return dotcells[i][j]; } // Private instance fields (maybe could be protected instead) /** * CKY+ style parse chart in which completed span entries are stored. */ private Chart dotChart; /** * Translation grammar which contains the translation rules. */ private Grammar pGrammar; /* Length of input sentence. */ private final int sentLen; /* Represents the input sentence being translated. */ private final Lattice<Integer> input; /* If enabled, rule terminals are treated as regular expressions. */ private boolean regexpMatching = false; // Static fields private static final Logger logger = Logger.getLogger(DotChart.class.getName()); // Constructors // TODO: Maybe this should be a non-static inner class of Chart. That would give us implicit // access to all the arguments of this constructor. Though we would need to take an argument, i, // to know which Chart.this.grammars[i] to use. /** * Constructs a new dot chart from a specified input lattice, a translation grammar, and a parse * chart. * * @param input A lattice which represents an input sentence. * @param grammar A translation grammar. * @param chart A CKY+ style chart in which completed span entries are stored. */ public DotChart(Lattice<Integer> input, Grammar grammar, Chart chart) { this.dotChart = chart; this.pGrammar = grammar; this.input = input; this.sentLen = input.size(); this.dotcells = new DotCell[sentLen][sentLen + 1]; // seeding the dotChart seed(); } public DotChart(Lattice<Integer> input, Grammar grammar, Chart chart, boolean useRegexpMatching) { this.dotChart = chart; this.pGrammar = grammar; this.input = input; this.sentLen = input.size(); this.dotcells = new DotCell[sentLen][sentLen + 1]; // seeding the dotChart seed(); this.regexpMatching = useRegexpMatching; } // Package-protected methods /** * Add initial dot items: dot-items pointer to the root of the grammar trie. */ void seed() { for (int j = 0; j <= sentLen - 1; j++) { if (pGrammar.hasRuleForSpan(j, j, input.distance(j, j))) { if (null == pGrammar.getTrieRoot()) { throw new RuntimeException("trie root is null"); } addDotItem(pGrammar.getTrieRoot(), j, j, null, null, new SourcePath()); } } } /** * This function computes all possible expansions of all rules over the provided span (i,j). By * expansions, we mean the moving of the dot forward (from left to right) over a nonterminal or * terminal symbol on the rule's source side. * * There are two kinds of expansions: * * <ol> * <li>Expansion over a nonterminal symbol. For this kind of expansion, a rule has a dot * immediately prior to a source-side nonterminal. The main Chart is consulted to see whether * there exists a completed nonterminal with the same label. If so, the dot is advanced. * * Discovering nonterminal expansions is a matter of enumerating all split points k such that i < * k and k < j. The nonterminal symbol must exist in the main Chart over (k,j). * * <li>Expansion over a terminal symbol. In this case, expansion is a simple matter of determing * whether the input symbol at position j (the end of the span) matches the next symbol in the * rule. This is equivalent to choosing a split point k = j - 1 and looking for terminal symbols * over (k,j). Note that phrases in the input rule are handled one-by-one as we consider longer * spans. * </ol> */ void expandDotCell(int i, int j) { if (logger.isLoggable(Level.FINEST)) logger.finest("Expanding dot cell (" + i + "," + j + ")"); /* * (1) If the dot is just to the left of a non-terminal variable, we look for theorems or axioms * in the Chart that may apply and extend the dot position. We look for existing axioms over all * spans (k,j), i < k < j. */ for (int k = i + 1; k < j; k++) { extendDotItemsWithProvedItems(i, k, j, false); } /* * (2) If the the dot-item is looking for a source-side terminal symbol, we simply match against * the input sentence and advance the dot. */ Node<Integer> node = input.getNode(j - 1); for (Arc<Integer> arc : node.getOutgoingArcs()) { int last_word = arc.getLabel(); int arc_len = arc.getHead().getNumber() - arc.getTail().getNumber(); // int last_word=foreign_sent[j-1]; // input.getNode(j-1).getNumber(); // if (null != dotcells[i][j - 1]) { // dotitem in dot_bins[i][k]: looking for an item in the right to the dot for (DotNode dotNode : dotcells[i][j - 1].getDotNodes()) { if (this.regexpMatching) { ArrayList<Trie> child_tnodes = matchAll(dotNode, last_word); if (child_tnodes == null || child_tnodes.isEmpty()) continue; for (Trie child_tnode : child_tnodes) { if (null != child_tnode) { addDotItem(child_tnode, i, j - 1 + arc_len, dotNode.antSuperNodes, null, dotNode.srcPath.extend(arc)); } } } else { Trie child_node = dotNode.trieNode.match(last_word); if (null != child_node) { addDotItem(child_node, i, j - 1 + arc_len, dotNode.antSuperNodes, null, dotNode.srcPath.extend(arc)); } } } } } } /** * note: (i,j) is a non-terminal, this cannot be a cn-side terminal, which have been handled in * case2 of dotchart.expand_cell add dotitems that start with the complete super-items in * cell(i,j) */ void startDotItems(int i, int j) { extendDotItemsWithProvedItems(i, i, j, true); } // Private methods /** * Attempt to combine an item in the dot chart with an item in the main chart to create a new item * in the dot chart. The DotChart item is a DotNode begun at position i with the dot currently at * position k. * <p> * In other words, this method looks for (proved) theorems or axioms in the completed chart that * may apply and extend the dot position. * * @param i Start index of a dot chart item * @param k End index of a dot chart item; start index of a completed chart item * @param j End index of a completed chart item * @param startDotItems */ private void extendDotItemsWithProvedItems(int i, int k, int j, boolean startDotItems) { if (this.dotcells[i][k] == null || this.dotChart.getCell(k, j) == null) { return; } // complete super-items (items over the same span with different LHSs) List<SuperNode> superNodes = new ArrayList<SuperNode>(this.dotChart.getCell(k, j) .getSortedSuperItems().values()); /* For every partially complete item over (i,k) */ for (DotNode dotNode : dotcells[i][k].dotNodes) { /* For every completed nonterminal in the main chart */ for (SuperNode superNode : superNodes) { /* * Regular Expression matching allows for a regular-expression style rules in the grammar, * which allows for a very primitive treatment of morphology. This is an advanced, * undocumented feature that introduces a complexity, in that the next "word" in the grammar * rule might match more than one outgoing arc in the grammar trie. */ if (this.regexpMatching) { ArrayList<Trie> child_tnodes = matchAll(dotNode, superNode.lhs); if (child_tnodes.isEmpty()) continue; for (Trie child_tnode : child_tnodes) { if (null == child_tnode) continue; if (true == startDotItems && !child_tnode.hasExtensions()) continue; // TODO addDotItem(child_tnode, i, j, dotNode.getAntSuperNodes(), superNode, dotNode .getSourcePath().extendNonTerminal()); } } else { /* * Standard approach: Check with the item needed by this grammar rule matches the lefthand * side of the rule group under consideration. */ Trie trie = dotNode.trieNode.match(superNode.lhs); if (trie != null) { if (true == startDotItems && !trie.hasExtensions()) continue; addDotItem(trie, i, j, dotNode.getAntSuperNodes(), superNode, dotNode .getSourcePath().extendNonTerminal()); } } } } } /* * We introduced the ability to have regular expressions in rules. When this is enabled for a * grammar, we first check whether there are any children. If there are, we need to try to match * _every rule_ against the symbol we're querying. This is expensive, which is an argument for * keeping your set of regular expression s small and limited to a separate grammar. */ private ArrayList<Trie> matchAll(DotNode dotNode, int wordID) { ArrayList<Trie> trieList = new ArrayList<Trie>(); HashMap<Integer, ? extends Trie> childrenTbl = dotNode.trieNode.getChildren(); if (childrenTbl != null && wordID >= 0) { // get all the extensions, map to string, check for *, build regexp for (Integer arcID : childrenTbl.keySet()) { if (arcID == wordID) { trieList.add(childrenTbl.get(arcID)); } else { String arcWord = Vocabulary.word(arcID); if (Vocabulary.word(wordID).matches(arcWord)) { trieList.add(childrenTbl.get(arcID)); } } } } return trieList; } /** * Creates a dot item and adds it into the cell(i,j) of this dot chart. * * @param tnode * @param i * @param j * @param ant_s_items_in * @param curSuperNode */ private void addDotItem(Trie tnode, int i, int j, List<SuperNode> antSuperNodesIn, SuperNode curSuperNode, SourcePath srcPath) { List<SuperNode> antSuperNodes = new ArrayList<SuperNode>(); if (antSuperNodesIn != null) { antSuperNodes.addAll(antSuperNodesIn); } if (curSuperNode != null) { antSuperNodes.add(curSuperNode); } DotNode item = new DotNode(i, j, tnode, antSuperNodes, srcPath); if (dotcells[i][j] == null) { dotcells[i][j] = new DotCell(); } dotcells[i][j].addDotNode(item); dotChart.nDotitemAdded++; if (logger.isLoggable(Level.FINEST)) { logger.finest(String.format("Add a dotitem in cell (%d, %d), n_dotitem=%d, %s", i, j, dotChart.nDotitemAdded, srcPath)); RuleCollection rules = tnode.getRuleCollection(); if (rules != null) { for (Rule r : rules.getRules()) { // System.out.println("rule: "+r.toString()); logger.finest(r.toString()); } } } } // Package-protected classes /** * A DotCell groups together DotNodes that have been applied over a particular span. A DotNode, in * turn, is a partially-applied grammar rule, represented as a pointer into the grammar trie * structure. */ static class DotCell { // Package-protected fields private List<DotNode> dotNodes = new ArrayList<DotNode>(); public List<DotNode> getDotNodes() { return dotNodes; } private void addDotNode(DotNode dt) { /* * if(l_dot_items==null) l_dot_items= new ArrayList<DotItem>(); */ dotNodes.add(dt); } } /** * A DotNode represents the partial application of a rule rooted to a particular span (i,j). It * maintains a pointer to the trie node in the grammar for efficient mapping. */ static class DotNode { // Package-protected instance fields // int i, j; //start and end position in the chart private Trie trieNode = null; // dot_position, point to grammar trie node, this is the only // place that the DotChart points to the grammar private List<SuperNode> antSuperNodes = null; // pointer to SuperNode in Chart private SourcePath srcPath; public DotNode(int i, int j, Trie trieNode, List<SuperNode> antSuperNodes, SourcePath srcPath) { // i = i_in; // j = j_in; this.trieNode = trieNode; this.antSuperNodes = antSuperNodes; this.srcPath = srcPath; } public boolean equals(Object obj) { if (obj == null) return false; if (!this.getClass().equals(obj.getClass())) return false; DotNode state = (DotNode) obj; /* * Technically, we should be comparing the span inforamtion as well, but that would require us * to store it, increasing memory requirements, and we should be able to guarantee that we * won't be comparing DotNodes across spans. */ // if (this.i != state.i || this.j != state.j) // return false; if (this.trieNode != state.trieNode) return false; return true; } /** * Technically the hash should include the span (i,j), but since DotNodes are grouped by span, * this isn't necessary, and we gain something by not having to store the span. */ public int hashCode() { return this.trieNode.hashCode(); } // convenience function public RuleCollection getApplicableRules() { return getTrieNode().getRuleCollection(); } public Trie getTrieNode() { return trieNode; } public SourcePath getSourcePath() { return srcPath; } public List<SuperNode> getAntSuperNodes() { return antSuperNodes; } } }
package org.luaj.vm2.lua2java; import java.io.CharArrayWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.luaj.vm2.Lua; import org.luaj.vm2.LuaString; import org.luaj.vm2.LuaValue; import org.luaj.vm2.ast.Block; import org.luaj.vm2.ast.Chunk; import org.luaj.vm2.ast.Exp; import org.luaj.vm2.ast.FuncArgs; import org.luaj.vm2.ast.FuncBody; import org.luaj.vm2.ast.Name; import org.luaj.vm2.ast.NameResolver; import org.luaj.vm2.ast.ParList; import org.luaj.vm2.ast.Stat; import org.luaj.vm2.ast.TableConstructor; import org.luaj.vm2.ast.TableField; import org.luaj.vm2.ast.Visitor; import org.luaj.vm2.ast.Exp.AnonFuncDef; import org.luaj.vm2.ast.Exp.BinopExp; import org.luaj.vm2.ast.Exp.Constant; import org.luaj.vm2.ast.Exp.FieldExp; import org.luaj.vm2.ast.Exp.FuncCall; import org.luaj.vm2.ast.Exp.IndexExp; import org.luaj.vm2.ast.Exp.MethodCall; import org.luaj.vm2.ast.Exp.NameExp; import org.luaj.vm2.ast.Exp.ParensExp; import org.luaj.vm2.ast.Exp.UnopExp; import org.luaj.vm2.ast.Exp.VarExp; import org.luaj.vm2.ast.Exp.VarargsExp; import org.luaj.vm2.ast.NameScope.NamedVariable; import org.luaj.vm2.ast.Stat.Assign; import org.luaj.vm2.ast.Stat.Break; import org.luaj.vm2.ast.Stat.FuncCallStat; import org.luaj.vm2.ast.Stat.FuncDef; import org.luaj.vm2.ast.Stat.GenericFor; import org.luaj.vm2.ast.Stat.IfThenElse; import org.luaj.vm2.ast.Stat.LocalAssign; import org.luaj.vm2.ast.Stat.LocalFuncDef; import org.luaj.vm2.ast.Stat.NumericFor; import org.luaj.vm2.ast.Stat.RepeatUntil; import org.luaj.vm2.ast.Stat.Return; import org.luaj.vm2.ast.Stat.WhileDo; public class JavaCodeGen { final Chunk chunk; final String packagename; final String classname; Writer writer; public JavaCodeGen( Chunk chunk, Writer writer,String packagename, String classname) { this.chunk = chunk; this.writer = writer; this.packagename = packagename; this.classname = classname; chunk.accept( new NameResolver() ); chunk.accept( new JavaClassWriterVisitor() ); } class JavaClassWriterVisitor extends Visitor { JavaScope javascope = null; List<String> constantDeclarations = new ArrayList<String>(); Map<LuaString,String> stringConstants = new HashMap<LuaString,String>(); Map<Double,String> numberConstants = new HashMap<Double,String>(); String indent = ""; void addindent() { indent+=" "; } void subindent() { indent = indent.substring(3); } void out(String s) { try { writer.write(s); } catch (IOException e) { throw new RuntimeException("write failed: "+e, e); } } void outi(String s) { out( indent ); out( s ); } void outl(String s) { outi( s ); out( "\n" ); } void outr(String s) { out( s ); out( "\n" ); } void outb(String s) { outl( s ); addindent(); } void oute(String s) { subindent(); outl( s ); } public void visit(Chunk chunk) { if ( packagename != null ) outl("package "+packagename+";"); outl("import org.luaj.vm2.*;"); outl("import org.luaj.vm2.lib.*;"); outb("public class "+classname+" extends VarArgFunction {"); outl("public Varargs onInvoke(Varargs $arg) {"); addindent(); javascope = JavaScope.newJavaScope( chunk ); writeBodyBlock(chunk.block); oute("}"); for ( String s : constantDeclarations ) outl( s ); subindent(); outi("}"); } void writeBodyBlock(Block block) { if ( javascope.needsbinoptmp ) outl( "LuaValue $b;" ); super.visit(block); if ( ! endsInReturn(block) ) outl( "return NONE;" ); } public void visit(Block block) { outb("{"); super.visit(block); oute("}"); } private boolean endsInReturn(Block block) { int n = block.stats.size(); if ( n<=0 ) return false; Stat s = block.stats.get(n-1); if ( s instanceof Return || s instanceof Break ) return true; else if ( s instanceof IfThenElse ) { IfThenElse ite = (IfThenElse) s; if ( ite.elseblock == null || ! endsInReturn(ite.ifblock) || ! endsInReturn(ite.elseblock) ) return false; if ( ite.elseifblocks != null ) for ( Block b : ite.elseifblocks ) if ( ! endsInReturn(b) ) return false; return true; } return false; } public void visit(Stat.Return s) { int n = s.nreturns(); switch ( n ) { case 0: outl( "return NONE;" ); break; case 1: outl( "return "+evalLuaValue(s.values.get(0))+";" ); break; default: if ( s.values.size()==1 && s.values.get(0).isfunccall() ) tailCall( s.values.get(0) ); else outl( "return "+evalListAsVarargs(s.values)+";" ); break; } } public void visit(AnonFuncDef def) { super.visit(def); } public void visit(LocalAssign stat) { int n = stat.names.size(); int m = stat.values!=null? stat.values.size(): 0; if ( n == 1 && m<=1 ) { Name name = stat.names.get(0); String value = m>0? evalLuaValue(stat.values.get(0)): "NIL"; singleLocalDeclareAssign(name,value); } else { for ( Name name : stat.names ) singleLocalDeclareAssign(name,null); multiAssign(stat.names, stat.values); } } public void visit(Assign stat) { multiAssign(stat.vars, stat.exps); } private void multiAssign(List varsOrNames, List<Exp> exps) { int n = varsOrNames.size(); int m = exps != null? exps.size(): 0; boolean vararglist = m>0 && exps.get(m-1).isvarargexp() && n>m; if ( n<=m ) { for ( int i=1; i<=n; i++ ) singleVarOrNameAssign( varsOrNames.get(i-1), evalLuaValue(exps.get(i-1)) ); for ( int i=n+1; i<=m; i++ ) outl( evalLuaValue(exps.get(i-1))+";" ); } else { outb( "{" ); for ( int i=1; i<=m; i++ ) { Exp e = exps.get(i-1); if ( vararglist && (i==m) ) outl( "Varargs $"+i+" = "+evalVarargs(e)+";" ); else outl( "LuaValue $"+i+" = "+evalLuaValue(e)+";" ); } for ( int i=1; i<=n; i++ ) { String valu; if ( i < m ) valu = "$"+i; else if ( i==m ) valu = (vararglist? "$"+i+".arg1()": "$"+i); else if ( vararglist ) valu = "$"+m+".arg("+(i-m+1)+")"; else valu = "NIL"; singleVarOrNameAssign( varsOrNames.get(i-1), valu ); } oute( "}" ); } } private void singleVarOrNameAssign(final Object varOrName, final String valu) { Visitor v = new Visitor() { public void visit(FieldExp exp) { outl(evalLuaValue(exp.lhs)+".set("+evalStringConstant(exp.name.name)+","+valu+");"); } public void visit(IndexExp exp) { outl(evalLuaValue(exp.lhs)+".set("+evalLuaValue(exp.exp)+","+valu+");"); } public void visit(NameExp exp) { singleAssign( exp.name, valu ); } }; if ( varOrName instanceof VarExp ) ((VarExp)varOrName).accept(v); else if ( varOrName instanceof Name ) singleAssign((Name) varOrName, valu); else throw new IllegalStateException("can't assign to "+varOrName.getClass()); } private void singleAssign(Name name, String valu) { if ( name.variable.isLocal() ) { outi( "" ); singleReference( name ); outr( " = "+valu+";" ); } else outl( "env.set("+evalStringConstant(name.name)+","+valu+");"); } private void singleReference(Name name) { if ( name.variable.isLocal() ) { out( javascope.getJavaName(name.variable) ); if ( name.variable.isupvalue && name.variable.hasassignments ) out( "[0]" ); } else { out( "env.get("+evalStringConstant(name.name)+")"); } } private void singleLocalDeclareAssign(Name name, String value) { singleLocalDeclareAssign( name.variable, value ); } private void singleLocalDeclareAssign(NamedVariable variable, String value) { String javaname = javascope.getJavaName(variable); if ( variable.isupvalue && variable.hasassignments ) outl( "final LuaValue[] "+javaname+" = {"+value+"};" ); else if ( variable.isupvalue ) outl( "final LuaValue "+javaname+(value!=null? " = "+value: "")+";" ); else outl( "LuaValue "+javaname+(value!=null? " = "+value: "")+";" ); } public void visit(Break breakstat) { // TODO: wrap in do {} while(false), or add label as nec outl( "break;" ); } private Writer pushWriter() { Writer x = writer; writer = new CharArrayWriter(); return x; } private String popWriter(Writer x) { Writer c = writer; writer = x; return c.toString(); } public String evalListAsVarargs(List<Exp> values) { int n = values!=null? values.size(): 0; switch ( n ) { case 0: return "NONE"; case 1: return evalVarargs(values.get(0)); default: case 2: case 3: Writer x = pushWriter(); out( n>3? "varargsOf(new LuaValue[] {":"varargsOf(" ); for ( int i=1; i<n; i++ ) out( evalLuaValue(values.get(i-1))+"," ); if ( n>3 ) out( "}," ); out( evalVarargs(values.get(n-1))+")" ); return popWriter(x); } } Map<Exp,Integer> callerExpects = new HashMap<Exp,Integer>(); public String evalLuaValue(Exp exp) { Writer x = pushWriter(); callerExpects.put(exp,1); exp.accept(this); return popWriter(x); } public String evalVarargs(Exp exp) { Writer x = pushWriter(); callerExpects.put(exp,-1); exp.accept(this); return popWriter(x); } public String evalBoolean(Exp exp) { Writer x = pushWriter(); callerExpects.put(exp,LuaValue.TBOOLEAN); exp.accept(new Visitor() { public void visit(UnopExp exp) { switch ( exp.op ) { case Lua.OP_NOT: out( "(!"+evalBoolean( exp.rhs )+")"); break; default: out(evalLuaValue(exp)+".toboolean()"); break; } } public void visit(BinopExp exp) { String op; switch ( exp.op ) { case Lua.OP_AND: case Lua.OP_OR: op = (exp.op==Lua.OP_AND? " && ": " || "); out("("+evalBoolean(exp.lhs)+op+evalBoolean(exp.rhs)+")"); break; case Lua.OP_EQ: case Lua.OP_NEQ: op = (exp.op==Lua.OP_EQ? ".eq_b(": ".neq_b("); out("("+evalLuaValue(exp.lhs)+op+evalLuaValue(exp.rhs)+")"); break; case Lua.OP_GT: case Lua.OP_GE: case Lua.OP_LT: case Lua.OP_LE: op = (exp.op==Lua.OP_GT? ">": exp.op==Lua.OP_GE? ">=": exp.op==Lua.OP_LT? "<": "<="); out("("+evalNumber(exp.lhs)+op+evalNumber(exp.rhs)+")"); break; default: out(evalLuaValue(exp)+".toboolean()"); break; } } public void visit(ParensExp exp) { evalBoolean(exp.exp); } public void visit(VarargsExp exp) { out(evalLuaValue(exp)+".toboolean()"); } public void visit(FieldExp exp) { out(evalLuaValue(exp)+".toboolean()"); } public void visit(IndexExp exp) { out(evalLuaValue(exp)+".toboolean()"); } public void visit(NameExp exp) { out(evalLuaValue(exp)+".toboolean()"); } }); return popWriter(x); } public String evalNumber(Exp exp) { Writer x = pushWriter(); callerExpects.put(exp,LuaValue.TBOOLEAN); exp.accept(new Visitor() { public void visit(UnopExp exp) { switch ( exp.op ) { case Lua.OP_LEN: out(evalLuaValue(exp.rhs)+".length()"); break; case Lua.OP_UNM: out("(-"+evalNumber(exp.rhs)+")"); break; default: out(evalLuaValue(exp)+".todouble()"); break; } } public void visit(BinopExp exp) { String op; switch ( exp.op ) { case Lua.OP_ADD: case Lua.OP_SUB: case Lua.OP_MUL: op = (exp.op==Lua.OP_ADD? "+": exp.op==Lua.OP_SUB? "-": "*"); out("("+evalNumber(exp.lhs)+op+evalNumber(exp.rhs)+")"); break; case Lua.OP_POW: out("MathLib.dpow("+evalNumber(exp.lhs)+","+evalNumber(exp.rhs)+")"); break; //case Lua.OP_DIV: out("LuaDouble.ddiv("+evalNumber(exp.lhs)+","+evalNumber(exp.rhs)+")"); break; //case Lua.OP_MOD: out("LuaDouble.dmod("+evalNumber(exp.lhs)+","+evalNumber(exp.rhs)+")"); break; default: out(evalLuaValue(exp)+".todouble()"); break; } } public void visit(ParensExp exp) { evalNumber(exp.exp); } public void visit(VarargsExp exp) { out(evalLuaValue(exp)+".todouble()"); } public void visit(FieldExp exp) { out(evalLuaValue(exp)+".todouble()"); } public void visit(IndexExp exp) { out(evalLuaValue(exp)+".todouble()"); } public void visit(NameExp exp) { out(evalLuaValue(exp)+".todouble()"); } }); return popWriter(x); } public void visit(FuncCallStat stat) { outi(""); stat.funccall.accept(this); outr(";"); } public void visit(BinopExp exp) { switch ( exp.op ) { case Lua.OP_AND: case Lua.OP_OR: String not = (exp.op==Lua.OP_AND? "!": ""); out("("+not+"($b="+evalLuaValue(exp.lhs)+").toboolean()?$b:"+evalLuaValue(exp.rhs)+")"); return; } switch ( exp.op ) { case Lua.OP_ADD: out(evalLuaValue(exp.lhs)+".add("+evalNumber(exp.rhs)+")"); return; case Lua.OP_SUB: out(evalLuaValue(exp.lhs)+".sub("+evalNumber(exp.rhs)+")"); return; case Lua.OP_MUL: out(evalLuaValue(exp.lhs)+".mul("+evalNumber(exp.rhs)+")"); return; case Lua.OP_POW: out(evalLuaValue(exp.lhs)+".pow("+evalNumber(exp.rhs)+")"); return; case Lua.OP_DIV: out("LuaDouble.ddiv("+evalNumber(exp.lhs)+","+evalNumber(exp.rhs)+")"); break; case Lua.OP_MOD: out("LuaDouble.dmod("+evalNumber(exp.lhs)+","+evalNumber(exp.rhs)+")"); break; case Lua.OP_GT: out(evalLuaValue(exp.lhs)+".gt("+evalNumber(exp.rhs)+")"); return; case Lua.OP_GE: out(evalLuaValue(exp.lhs)+".gteq("+evalNumber(exp.rhs)+")"); return; case Lua.OP_LT: out(evalLuaValue(exp.lhs)+".lt("+evalNumber(exp.rhs)+")"); return; case Lua.OP_LE: out(evalLuaValue(exp.lhs)+".lteq("+evalNumber(exp.rhs)+")"); return; case Lua.OP_EQ: out(evalLuaValue(exp.lhs)+".eq("+evalNumber(exp.rhs)+")"); return; case Lua.OP_NEQ: out(evalLuaValue(exp.lhs)+".neq("+evalNumber(exp.rhs)+")"); return; case Lua.OP_CONCAT: out(evalLuaValue(exp.lhs)+".concat("+evalNumber(exp.rhs)+")"); return; default: throw new IllegalStateException("unknown bin op:"+exp.op); } } public void visit(UnopExp exp) { exp.rhs.accept(this); switch ( exp.op ) { case Lua.OP_NOT: out(".not()"); break; case Lua.OP_LEN: out(".len()"); break; case Lua.OP_UNM: out(".neg()"); break; } } public void visit(Constant exp) { switch ( exp.value.type() ) { case LuaValue.TSTRING: { out( evalLuaStringConstant(exp.value.checkstring()) ); break; } case LuaValue.TNIL: out("NIL"); break; case LuaValue.TBOOLEAN: out(exp.value.toboolean()? "TRUE": "FALSE"); break; case LuaValue.TNUMBER: { out( evalNumberConstant(exp.value.todouble()) ); break; } default: throw new IllegalStateException("unknown constant type: "+exp.value.typename()); } } private String evalStringConstant(String str) { return evalLuaStringConstant( LuaValue.valueOf(str) ); } private String evalLuaStringConstant(LuaString str) { if ( stringConstants.containsKey(str) ) return stringConstants.get(str); String declvalue = quotedStringInitializer(str); String javaname = javascope.createConstantName(str.tojstring()); constantDeclarations.add( "static final LuaValue "+javaname+" = valueOf("+declvalue+");" ); stringConstants.put(str,javaname); return javaname; } private String evalNumberConstant(double value) { if ( value == 0 ) return "ZERO"; if ( value == -1 ) return "MINUSONE"; if ( value == 1 ) return "ONE"; if ( numberConstants.containsKey(value) ) return numberConstants.get(value); int ivalue = (int) value; String declvalue = value==ivalue? String.valueOf(ivalue): String.valueOf(value); String javaname = javascope.createConstantName(declvalue); constantDeclarations.add( "static final LuaValue "+javaname+" = valueOf("+declvalue+");" ); numberConstants.put(value,javaname); return javaname; } public void visit(FieldExp exp) { exp.lhs.accept(this); out(".get("+evalStringConstant(exp.name.name)+")"); } public void visit(IndexExp exp) { exp.lhs.accept(this); out(".get("); exp.exp.accept(this); out(")"); } public void visit(NameExp exp) { singleReference( exp.name ); } public void visit(ParensExp exp) { out( evalLuaValue(exp.exp) ); } public void visit(VarargsExp exp) { int c = callerExpects.containsKey(exp)? callerExpects.get(exp): 0; out( c==1? "$arg.arg1()": "$arg" ); } public void visit(MethodCall exp) { List<Exp> e = exp.args.exps; int n = e != null? e.size(): 0; int c = callerExpects.containsKey(exp)? callerExpects.get(exp): 0; if ( c == -1 ) n = -1; out( evalLuaValue(exp.lhs) ); switch ( n ) { case 0: out(".method("+evalStringConstant(exp.name)+")"); break; case 1: case 2: out(".method("+evalStringConstant(exp.name)+","); exp.args.accept(this); out(")"); break; default: out(".invokemethod("+evalStringConstant(exp.name) +((e==null||e.size()==0)? "": ","+evalListAsVarargs(exp.args.exps))+")"); if ( c == 1 ) out(".arg1()"); break; } } public void visit(FuncCall exp) { List<Exp> e = exp.args.exps; int n = e != null? e.size(): 0; if ( n > 0 && e.get(n-1).isvarargexp() ) n = -1; int c = callerExpects.containsKey(exp)? callerExpects.get(exp): 0; if ( c == -1 ) n = -1; out( evalLuaValue(exp.lhs) ); switch ( n ) { case 0: case 1: case 2: case 3: out(".call("); exp.args.accept(this); out(")"); break; default: out(".invoke("+((e==null||e.size()==0)? "": evalListAsVarargs(e))+")"); if ( c == 1 ) out(".arg1()"); break; } } public void tailCall( Exp e ) { if ( e instanceof MethodCall ) { MethodCall mc = (MethodCall) e; outl("return new TailcallVarargs("+evalLuaValue(mc.lhs)+","+evalStringConstant(mc.name)+","+evalListAsVarargs(mc.args.exps)+");"); } else if ( e instanceof FuncCall ) { FuncCall fc = (FuncCall) e; outl("return new TailcallVarargs("+evalLuaValue(fc.lhs)+","+evalListAsVarargs(fc.args.exps)+");"); } else { throw new IllegalArgumentException("can't tail call "+e); } } public void visit(FuncArgs args) { if ( args.exps != null ) { int n = args.exps.size(); if ( n > 0 ) { for ( int i=1; i<n; i++ ) out( evalLuaValue( args.exps.get(i-1) )+"," ); out( evalVarargs( args.exps.get(n-1) ) ); } } } public void visit(FuncBody body) { javascope = javascope.pushJavaScope(body); int n = javascope.nreturns; int m = body.parlist.names!=null? body.parlist.names.size(): 0; if ( n>=0 && n<=1 && m<=3 && ! body.parlist.isvararg ) { switch ( m ) { case 0: outr("new ZeroArgFunction(env) {"); addindent(); outb("public LuaValue call() {"); break; case 1: outr("new OneArgFunction(env) {"); addindent(); outb("public LuaValue call(" +declareArg(body.parlist.names.get(0))+") {"); assignArg(body.parlist.names.get(0)); break; case 2: outr("new TwoArgFunction(env) {"); addindent(); outb("public LuaValue call(" +declareArg(body.parlist.names.get(0))+"," +declareArg(body.parlist.names.get(1))+") {"); assignArg(body.parlist.names.get(0)); assignArg(body.parlist.names.get(1)); break; case 3: outr("new ThreeArgFunction(env) {"); addindent(); outb("public LuaValue call(" +declareArg(body.parlist.names.get(0))+"," +declareArg(body.parlist.names.get(1))+"," +declareArg(body.parlist.names.get(2))+") {"); assignArg(body.parlist.names.get(0)); assignArg(body.parlist.names.get(1)); assignArg(body.parlist.names.get(2)); break; } } else { outr("new VarArgFunction(env) {"); addindent(); outb("public Varargs invoke(Varargs $arg) {"); for ( int i=0; i<m; i++ ) { Name name = body.parlist.names.get(i); String value = i>0? "$arg.arg("+(i+1)+")": "$arg.arg1()"; singleLocalDeclareAssign( name, value ); } if ( body.parlist.isvararg ) { NamedVariable arg = body.scope.find("arg"); javascope.setJavaName(arg,"arg"); if ( m > 0 ) outl( "$arg = $arg.subargs("+(m+1)+");" ); String value = (javascope.usesvarargs? "NIL": "LuaValue.tableOf($arg,1)"); singleLocalDeclareAssign( arg, value ); } } writeBodyBlock(body.block); oute("}"); subindent(); outi("}"); javascope = javascope.popJavaScope(); } private String declareArg(Name name) { String argname = javascope.getJavaName(name.variable); return "LuaValue "+argname+(name.variable.isupvalue? "$0": ""); } private void assignArg(Name name) { if ( name.variable.isupvalue ) { String argname = javascope.getJavaName(name.variable); singleLocalDeclareAssign(name, argname+"$0"); } } public void visit(FuncDef stat) { Writer x = pushWriter(); stat.body.accept(this); String value = popWriter(x); int n = stat.name.dots!=null? stat.name.dots.size(): 0; boolean m = stat.name.method != null; if ( n>0 && !m && stat.name.name.variable.isLocal() ) singleAssign( stat.name.name, value ); else if ( n==0 && !m ) { singleAssign( stat.name.name, value ); } else { singleReference( stat.name.name ); for ( int i=0; i<n-1 || (m&&i<n); i++ ) out( ".get("+evalStringConstant(stat.name.dots.get(i))+")" ); outr( ".set("+evalStringConstant(m? stat.name.method: stat.name.dots.get(n))+", "+value+");" ); } } // functions that use themselves as upvalues require special treatment public void visit(LocalFuncDef stat) { final Name funcname = stat.name; final boolean[] isrecursive = { false }; stat.body.accept( new Visitor() { public void visit(Name name) { if ( name.variable == funcname.variable ) { isrecursive[0] = true; name.variable.hasassignments = true; } } } ); // write body Writer x = pushWriter(); super.visit(stat); String value = popWriter(x); // write declaration if ( isrecursive[0] ) { String javaname = javascope.getJavaName(funcname.variable); outl("final LuaValue[] "+javaname+" = new LuaValue[1];"); outl(javaname+"[0] = "+value+";"); } else { singleLocalDeclareAssign( funcname, value ); } } public void visit(NumericFor stat) { String j = javascope.getJavaName(stat.name.variable); String i = j+"$0"; outi("for ( double " +i+"="+evalLuaValue(stat.initial)+".todouble(), " +j+"$limit="+evalLuaValue(stat.limit)+".todouble()"); if ( stat.step == null ) outr( "; "+i+"<="+j+"$limit; ++"+i+" ) {" ); else { out( ", "+j+"$step="+evalLuaValue(stat.step)+".todouble()"); out( "; "+j+"$step>0? ("+i+"<="+j+"$limit): ("+i+">="+j+"$limit);" ); outr( " "+i+"+="+j+"$step ) {" ); } addindent(); singleLocalDeclareAssign(stat.name, "valueOf("+i+")"); super.visit(stat.block); oute( "}" ); } private Name tmpJavaVar(String s) { Name n = new Name(s); n.variable = javascope.define(s); return n; } public void visit(GenericFor stat) { Name f = tmpJavaVar("f"); Name s = tmpJavaVar("s"); Name var = tmpJavaVar("var"); Name v = tmpJavaVar("v"); String javaf = javascope.getJavaName(f.variable); String javas = javascope.getJavaName(s.variable); String javavar = javascope.getJavaName(var.variable); String javav = javascope.getJavaName(v.variable); outl("LuaValue "+javaf+","+javas+","+javavar+";"); outl("Varargs "+javav+";"); List<Name> fsvar = new ArrayList<Name>(); fsvar.add(f); fsvar.add(s); fsvar.add(var); multiAssign(fsvar, stat.exps); outb("while (true) {"); outl( javav+" = "+javaf+".invoke(varargsOf("+javas+","+javavar+"));"); outl( "if (("+javavar+"="+javav+".arg1()).isnil()) break;"); singleLocalDeclareAssign(stat.names.get(0),javavar); for ( int i=1, n=stat.names.size(); i<n; i++ ) singleLocalDeclareAssign(stat.names.get(i),javav+".arg("+(i+1)+")"); super.visit(stat.block); oute("}"); } public void visit(ParList pars) { super.visit(pars); } public void visit(IfThenElse stat) { outb( "if ( "+evalBoolean(stat.ifexp)+" ) {"); super.visit(stat.ifblock); if ( stat.elseifblocks != null ) for ( int i=0, n=stat.elseifblocks.size(); i<n; i++ ) { subindent(); outl( "} else if ( "+evalBoolean(stat.elseifexps.get(i))+" ) {"); addindent(); super.visit(stat.elseifblocks.get(i)); } if ( stat.elseblock != null ) { subindent(); outl( "} else {"); addindent(); super.visit( stat.elseblock ); } oute( "}" ); } public void visit(RepeatUntil stat) { outb( "do {"); super.visit(stat.block); oute( "} while (!"+evalBoolean(stat.exp)+");" ); } public void visit(TableConstructor table) { int n = table.fields!=null? table.fields.size(): 0; List<TableField> keyed = new ArrayList<TableField>(); List<TableField> list = new ArrayList<TableField>(); for ( int i=0; i<n; i++ ) { TableField f = table.fields.get(i); (( f.name != null || f.index != null )? keyed: list).add(f); } int nk = keyed.size(); int nl = list.size(); out( (nk==0 && nl!=0)? "LuaValue.listOf(": "LuaValue.tableOf(" ); // named elements if ( nk != 0 ) { out( "new LuaValue[]{"); for ( TableField f : keyed ) { if ( f.name != null ) out( evalStringConstant(f.name)+"," ); else out( evalLuaValue(f.index)+"," ); out( evalLuaValue(f.rhs)+"," ); } out( "}" ); } // unnamed elements if ( nl != 0 ) { out( (nk!=0? ",": "") + "new LuaValue[]{" ); Exp last = list.get(nl-1).rhs; boolean vlist = last.isvarargexp(); for ( int i=0, limit=vlist? nl-1: nl; i<limit ; i++ ) out( evalLuaValue( list.get(i).rhs )+"," ); out( vlist? "}, "+evalVarargs(last): "}"); } out( ")" ); } public void visit(WhileDo stat) { outb( "while ("+evalLuaValue(stat.exp)+".toboolean()) {"); super.visit(stat.block); oute( "}" ); } public void visitExps(List<Exp> exps) { super.visitExps(exps); } public void visitNames(List<Name> names) { super.visitNames(names); } public void visitVars(List<VarExp> vars) { super.visitVars(vars); } } private static String quotedStringInitializer(LuaString s) { byte[] bytes = s.m_bytes; int o = s.m_offset; int n = s.m_length; StringBuffer sb = new StringBuffer(n+2); // check for bytes not encodable as utf8 if ( ! s.isValidUtf8() ) { sb.append( "new byte[]{" ); for ( int j=0; j<n; j++ ) { if ( j>0 ) sb.append(","); byte b = bytes[o+j]; switch ( b ) { case '\n': sb.append( "'\\n'" ); break; case '\r': sb.append( "'\\r'" ); break; case '\t': sb.append( "'\\t'" ); break; case '\\': sb.append( "'\\\\'" ); break; default: if ( b >= ' ' ) { sb.append( '\''); sb.append( (char) b ); sb.append( '\''); } else { sb.append( String.valueOf((int)b) ); } break; } } sb.append( "}" ); return sb.toString(); } sb.append('"'); for ( int i=0; i<n; i++ ) { byte b = bytes[o+i]; switch ( b ) { case '\b': sb.append( "\\b" ); break; case '\f': sb.append( "\\f" ); break; case '\n': sb.append( "\\n" ); break; case '\r': sb.append( "\\r" ); break; case '\t': sb.append( "\\t" ); break; case '"': sb.append( "\\\"" ); break; case '\\': sb.append( "\\\\" ); break; default: if ( b >= ' ' ) { sb.append( (char) b ); break; } else { // convert from UTF-8 int u = 0xff & (int) b; if ( u>=0xc0 && i+1<n ) { if ( u>=0xe0 && i+2<n ) { u = ((u & 0xf) << 12) | ((0x3f & bytes[i+1]) << 6) | (0x3f & bytes[i+2]); i+= 2; } else { u = ((u & 0x1f) << 6) | (0x3f & bytes[++i]); } } sb.append( "\\u" ); sb.append( Integer.toHexString(0x10000+u).substring(1) ); } } } sb.append('"'); return sb.toString(); } }
package states; import java.awt.Graphics2D; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.concurrent.ConcurrentLinkedQueue; import data.Level; import data.Room; import data.Square; import data.Text; import entities.Closer; import entities.Corner; import entities.Door; import entities.Enemy; import entities.Entity; import entities.FloorPanel; import entities.Interface; import entities.LooseFloor; import entities.Opener; import entities.Player; import entities.SpikeFloor; import framework.Loader; import framework.Writter; import game.Game; import input.Key; import kuusisto.tinysound.Music; import kuusisto.tinysound.TinySound; public class LevelState extends State{ /* Constants */ private final float INIT_TIME = 3600000; private final int INITIAL_HEALTH = 3; private final int INITIAL_LEVEL = 1; /* Variables */ private boolean start; private float remainingTime; private Level currentLevel; private Room currentRoom; private Interface interfaz; private Player player; private Enemy enemy; private List<LooseFloor> falling_floor; private List<Door> doors; private Music win_song; private Music death_song; private Music credits_song; private Music end_song; private boolean over; private boolean credits; private long counter; private List<Text> texts; public LevelState(GameStateManager gsm, ConcurrentLinkedQueue<Key> keys, Hashtable<String,Integer> keys_mapped, Loader loader, boolean start, Writter writter) { super(gsm, keys, keys_mapped, loader, writter); this.start = start; win_song = TinySound.loadMusic(new File("resources/Music/guard_death_and_obtaining_the_sword.ogg")); death_song = TinySound.loadMusic(new File("resources/Music/fight_death.ogg")); end_song = TinySound.loadMusic(new File("resources/Music/killed_Jaffar.ogg")); credits_song = TinySound.loadMusic(new File("resources/Music/won.ogg")); } @Override public void init() { falling_floor = new LinkedList<LooseFloor>(); interfaz = new Interface(640, 400, 0, 0, loader); over = false; credits = false; texts = new LinkedList<Text>(); counter = 0; // // TESTING ENEMY // currentLevel = loader.loadLevel(INITIAL_LEVEL); // currentRoom = currentLevel.getRoom(1, 9); //// for(String key : loader.getAnimations("wall").keySet()){ //// //System.out.println("key "+ key + " - Animation " + loader.getAnimations("wall").get(key).getId() ); // player = new Player(100,250,loader, 1000, "right"); // Enemy e = (Enemy)currentRoom.getCharacters().get(0); // currentRoom.addCharacter(player); // player.isEnemySaw(true); // e.setPlayer(true, player); if(start){ /* Start game */ remainingTime = INIT_TIME; currentLevel = loader.loadLevel(INITIAL_LEVEL); currentRoom = currentLevel.getRoom(1, 7); doors = currentLevel.getDoors(); // player = new Player(400,110,loader, INITIAL_HEALTH, "left"); // primer piso player = new Player(140,240,loader, INITIAL_HEALTH, "right"); // segundo piso // player = new Player(400,370,loader, INITIAL_HEALTH, "right"); // tercer piso player.setCurrentAnimation("idle_right", 5); // player.setCurrentAnimation("falling_left", 5); player.setySpeed(6); player.setHp(3); currentRoom.addCharacter(player); } else{ /* Load game */ File savegame = new File("savegame/save"); if(savegame.exists() && !savegame.isDirectory()){ /* There is actually a savegame -> resume game */ Scanner save; try { save = new Scanner(new FileReader("savegame/save")); int line = 0; while(save.hasNextLine()){ if(line == 0){ currentLevel = loader.loadLevel(save.nextInt()); } else if(line == 1){ remainingTime = save.nextFloat(); } else if(line == 2){ // player = new Player(save.nextInt()); } line++; save.nextLine(); } save.close(); } catch (FileNotFoundException e) { /* Exception */ e.printStackTrace(); /* There was not any savegame -> Start game */ remainingTime = INIT_TIME; currentLevel = loader.loadLevel(INITIAL_LEVEL); currentRoom = currentLevel.getRoom(1, 7); // player = new Player(INITIAL_HEALTH); } } else{ /* There was not any savegame -> Start game */ remainingTime = INIT_TIME; currentLevel = loader.loadLevel(INITIAL_LEVEL); currentRoom = currentLevel.getRoom(1, 7); // player = new Player(100,300,loader); } } } @Override public void update(long elapsedTime) { remainingTime = remainingTime - elapsedTime; manageKeys(); //currentLevel.update(elapsedTime); currentRoom.update(elapsedTime); if(!over && player.isDead()){ over = true; death_song.play(false); String message = "Press space to restart"; texts.add(Writter.createText(message, (Game.WIDTH/2) - (16* message.length()/2) , Game.HEIGHT - 16)); } if(!over && player.hasFinished()){ over = true; end_song.play(false); } if(!over){ checkPlayerCollisions(elapsedTime); } if(!credits && over && player.hasFinished() && end_song.done() && counter < 1000){ counter = counter + elapsedTime; } if(!credits && over && player.hasFinished() && end_song.done() && counter > 1000){ credits_song.play(false); credits = true; currentRoom = currentLevel.getRoom(1, 8); String message = "To be continued"; texts.add(Writter.createText(message, (Game.WIDTH/2) - (16* message.length()/2) , (Game.HEIGHT/2) - 20)); message = "Press space to return to menu"; texts.add(Writter.createText(message, (Game.WIDTH/2) - (16* message.length()/2) , (Game.HEIGHT) - 16)); } updateFallingFloor(elapsedTime); updateDoors(elapsedTime); checkPlayerSquare(); checkPlayerFinnish(); } @Override public void draw(Graphics2D g) { currentRoom.draw(g); interfaz.drawSelf(g); if(!credits){ player.drawLife(g); } if(enemy!=null){ enemy.drawLife(g); } for(Text t : texts){ t.drawSelf(g); } } @Override public void manageKeys() { Object[] keys_used = keys.toArray(); keys.clear(); Key e; if(keys_used.length!=0){ for (int i = 0; i < keys_used.length; i++) { e = (Key)keys_used[i]; if(e.isPressed()){ /* key pressed */ int key_pressed = e.getKeycode(); if(key_pressed == keys_mapped.get(Key.ESCAPE)){ } else if(key_pressed == keys_mapped.get(Key.SPACE)){ if(over && player.isDead()){ win_song.stop(); death_song.stop(); gsm.setState(GameStateManager.MAINGAMESTATE); } else if(over || credits){ win_song.stop(); death_song.stop(); credits_song.stop(); end_song.stop(); gsm.setState(GameStateManager.MENUSTATE); } } else{ player.manageKeyPressed(key_pressed, keys_mapped); } /* this has to be sent to the player */ if(key_pressed == keys_mapped.get(Key.UP)){ } else if(key_pressed == keys_mapped.get(Key.DOWN)){ } else if(key_pressed == keys_mapped.get(Key.LEFT)){ } else if(key_pressed == keys_mapped.get(Key.RIGHT)){ } else if(key_pressed == keys_mapped.get(Key.ENTER)){ } else if(key_pressed == keys_mapped.get(Key.SHIFT)){ } } else{ /* Key released */ int key_released = e.getKeycode(); if(key_released == keys_mapped.get(Key.ESCAPE)){ } else if(key_released == keys_mapped.get(Key.CONTROL)){ } else{ player.manageKeyReleased(key_released, keys_mapped); } } } } } private void checkPlayerCollisions(long elapsedTime) { Entity floorPanel = null; Entity looseFloor = null; Entity floorBeneath = null; Entity cornerFloor = null; Entity cornerFloorEntity = null; Entity corner = null; Entity cornerJumping = null; Entity wall = null; Entity longLandFloor = null; Entity potion = null; Entity sword = null; Entity door = null; int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // //System.out.println("ps: (" + ps[0] + ", " + ps[1] + "), pc: (" + pc[0] + ", " + pc[1] + ")"); if ( player.isColliding() ) { // resets some climb conditions player.setCanClimb(false); player.setCanClimbDown(false); player.setCornerToClimb(null); player.setCornerToClimbDown(null); } else if ( player.isClimbing() ) { // System.out.println("CLIMBING"); /* Checks if */ corner = checkCorner(); cornerFloor = checkCornerFloor(); cornerFloorEntity = checkCornerFloorEntity(); floorPanel = checkFloorPanel(); looseFloor = checkLooseFloor(); floorBeneath = checkFloorBeneath(); door = checkClimbingDoor(); if (player.startsClimbing() && (corner != null) && !player.isCanClimb() && !player.isCornerPositionFixed() ) { /* Initial climb */ int climbGap = 20; int[] cornerCenter = corner.getCenter(); player.setCornerToClimb(corner); player.setCanClimbDown(false); System.out.println("LO INTENTA: " + Math.abs(cornerCenter[0] - playerCenter[0])); if ( (Math.abs(cornerCenter[0] - playerCenter[0]) < climbGap*4) && corner.getTypeOfEntity().contains("right") && player.getOrientation().equals("left") ) { // left corner System.out.println("LEFT CORNER FIX"); if (cornerFloor != null && cornerFloor.getAnimations() != null){ // player is climbing from the edge player.setX(cornerCenter[0] + (climbGap) ); } else { player.setX(cornerCenter[0] + (2 * climbGap) ); } player.setCornerPositionFixed(true); player.setCanClimb(true); } else if ( (Math.abs(cornerCenter[0] - playerCenter[0]) < climbGap*8) && corner.getTypeOfEntity().contains("left") && player.getOrientation().equals("right") ) { // right corner System.out.println("RIGHT CORNER FIX"); if (cornerFloor != null){ // player is climbing from the edge player.setX(cornerCenter[0] - climbGap/2); } else { player.setX(cornerCenter[0] - climbGap); } player.setCornerPositionFixed(true); player.setCanClimb(true); } } else if ( !player.startsClimbing() && player.isClimbing() && ( (player.isCanClimb() && player.getCornerToClimb() != null) || (player.isCanClimbDown() && player.getCornerToClimbDown() != null) ) ){ /* Normal climbing */ // No need to check for collisions player.setCornerPositionFixed(false); // choses the right corner entity Entity currentCorner = null; Entity cornerToClimb = player.getCornerToClimb(); Entity cornerToClimbDown = player.getCornerToClimbDown(); if (cornerToClimb != null) { currentCorner = cornerToClimb; } else if (cornerToClimbDown != null) { currentCorner = cornerToClimbDown; } // controlls what the player must do while he is interacting // with the current corner if (currentCorner != null) { if (player.getCurrentAnimation().getId().startsWith("scaling down_") && player.isCornerReached()) { int[] cc = currentCorner.getCenter(); if (currentCorner.getTypeOfEntity().contains("right")) { player.setX(cc[0] + 40); player.setY(cc[1] + 125); } else if (currentCorner.getTypeOfEntity().contains("left")) { player.setX(cc[0] - 16); player.setY(cc[1] + 126); } player.setCornerReached(false); if (floorBeneath == null) { player.setCanLandScalingDown(false); System.out.println("Vooooy a caer scaling down " + player.getCenter()[0] + " - " + player.getCenter()[1] + " - " + player.getSquare()[0] + " - " + player.getSquare()[1]); player.setStraightFall(true); player.fall(); } else { player.setCanLandScalingDown(true); // checks if there is floor panels beneath the player to scale down or fall if (cornerFloorEntity != null && cornerFloorEntity.getTypeOfEntity()!= null) { if (currentCorner.getTypeOfEntity().contains("right")) { player.setX(cc[0]); player.setY(cc[1] + 125); } else if (currentCorner.getTypeOfEntity().contains("left")) { player.setX(cc[0] + 10); player.setY(cc[1] + 126); } } } } else if (player.getCurrentAnimation().getId().startsWith("hanging idle_") && !player.isCornerReached()) { int[] cc = currentCorner.getCenter(); if (currentCorner.getTypeOfEntity().contains("right")) { player.setX(cc[0] + 8); player.setY(cc[1] + 103); System.out.println("HANGEADA RIGHT: " + player.getX() + ", " + player.getY()); } else if (currentCorner.getTypeOfEntity().contains("left")) { player.setX(cc[0] + 10); player.setY(cc[1] + 106); System.out.println("HANGEADA LEFT: " + player.getX() + ", " + player.getY()); } player.setCornerReached(true); } else if (player.getCurrentAnimation().getId().startsWith("clipping_")) { player.setCornerReached(false); // player is getting up, have to check if there is a closed door if (door != null && door.getCurrentAnimation().getId().contains("closed")) { int[] cc = currentCorner.getCenter(); if (currentCorner.getTypeOfEntity().contains("right")) { player.setX(cc[0] + 40); player.setY(cc[1] + 125); } else if (currentCorner.getTypeOfEntity().contains("left")) { player.setX(cc[0] - 16); player.setY(cc[1] + 126); } player.scaleDown(); } } else if (!player.getCurrentAnimation().getId().startsWith("hanging idle_")) { player.setCornerReached(false); } } } else if (!player.isClimbing() && corner == null) { player.setCornerToClimb(null); } } else if ( player.isJumping() ) { // System.out.println("JUMPING"); // System.out.println("canLand: " + player.isCanLand()); // System.out.println("canLongLand: " + player.isCanLongLand()); /* Checks if the player can land on the floor */ floorPanel = checkFloorPanel(); looseFloor = checkLooseFloor(); cornerJumping = checkCornerJumping(); wall = checkWall(); door = checkDoor(); if (!player.isLongLand() && player.getCurrentAnimation().getId().contains("jump_") && player.getCurrentAnimation().isLastSprite() && player.getCurrentAnimation().isLastFrame() ){ longLandFloor = checkLongJumpFloor(); } if (player.getCurrentAnimation().getId().contains("landing")) { if (floorPanel != null) { player.setY( (int) floorPanel.getBoundingBox().getMinY()); } player.setCanLongLand(false); player.setLongLand(false); } if (floorPanel != null || looseFloor != null) { // player lands the jump player.setCanLand(true); player.setGrounded(true); } else { // player falls while trying to jump player.setCanLand(false); player.setGrounded(false); } // checks if player can land the starting jump // System.out.println("isLongLand: " + player.isLongLand()); if ( longLandFloor != null && //!player.isLongLand() && player.getCurrentAnimation().getId().contains("jump_") && player.getCurrentAnimation().isLastSprite() && player.getCurrentAnimation().isLastFrame()) { System.out.println("GONNA LAND LIKE A CHARM :D"); // player can land the jump player.setCanLongLand(true); player.setLongLand(true); } else if ( longLandFloor == null && //!player.isLongLand() && player.getCurrentAnimation().getId().contains("jump_") && player.getCurrentAnimation().isLastSprite() && player.getCurrentAnimation().isLastFrame()) { System.out.println("GONNA FALL"); // player cannot land the jump, he will fall player.setCanLongLand(false); player.setLongLand(true); } if (cornerJumping != null) { int[] cornerCenter = cornerJumping.getCenter(); int xReachDistance = 80; int yReachDistance = -10; // player can reach a corner to hang in mid air if ( (Math.abs(playerCenter[0] - cornerCenter[0]) < xReachDistance) && ( (playerCenter[1] - cornerCenter[1]) > yReachDistance) ) { // player is close enough in both axis to reach the corner player.setCanClimb(true); player.setCornerToClimb(cornerJumping); } else { // player is too far to reach the corner in mid air player.setCanClimb(false); player.setCornerToClimb(null); } } if (wall != null) { // player has collided with a wall // player.collide_jump(); System.out.println("Vooooy a caer 2 " + player.getCenter()[0] + " - " + player.getCenter()[1] + " - " + player.getSquare()[0] + " - " + player.getSquare()[1]); player.fall(); // corrects the player position after wall collision int wallxGap = 58; int wallyGap = 36; int[] wallCenter = wall.getCenter(); //DEBUG //System.out.println("TIPO DE MURO: " + wall.getTypeOfEntity()); if (wall.getTypeOfEntity().contains("face")){ //wallCenter[0] < playerCenter[0]) { // left wall //System.out.println("RIGHT WALL FIX"); player.setX(wallCenter[0] + wallxGap); player.setY(wallCenter[1] + wallyGap); } else if (wall.getTypeOfEntity().contains("left") || wall.getTypeOfEntity().contains("single") ){ //wallCenter[0] > playerCenter[0]) { //right wall //System.out.println("LEFT WALL FIX"); player.setX(wallCenter[0] - wallxGap/4); player.setY(wallCenter[1] + wallyGap); } } if (door != null && door.getTypeOfEntity().contains("normal")) { // player has collided with a door player.fall(); // corrects the player position after wall collision int doorxGap = 58; int dooryGap = 36; int[] doorCenter = door.getCenter(); if (doorCenter[0] < playerCenter[0]) { // left wall player.setX(doorCenter[0] + doorxGap); player.setY(doorCenter[1] + dooryGap); } else if (doorCenter[0] > playerCenter[0]) { //right wall player.setX(doorCenter[0] - doorxGap/4); player.setY(doorCenter[1] + dooryGap); } } } else if ( player.isFalling()) { // System.out.println("FALLING"); /* Increases player's fall distance */ int prevFallDistance = player.getFallDistance(); player.setFallDistance(prevFallDistance + player.getFallingSpeed()/4); /* Checks if the player can walk over the floor */ floorPanel = checkFloorPanel(); looseFloor = checkLooseFloor(); cornerJumping = checkCornerJumping(); wall = checkWall(); if ( (floorPanel != null/*|| looseFloor*/) ) { player.setFallingSpeed(0); if( player.isDead()){ // player is dead D: } else if ( player.isSafeFall() ) { // short fall, player lands nicely loader.getSound("landing soft").play(); player.safeLand(); System.out.println("SAFE LAND"); System.out.println(floorPanel.getTypeOfEntity() + ": " + floorPanel.getCenter()[0] + ", " + floorPanel.getCenter()[1]); } else if ( player.isRiskyFall() ) { // long fall, but not dying player.riskyLand(); loader.getSound("landing medium").play(); System.out.println("RISKY LAND"); } else { // free fall, player dies player.die(); loader.getSound("falling").stop(); loader.getSound("landing hard").play(); player.setY((int) floorPanel.getBoundingBox().getMaxY()); System.out.println("DEATH LAND"); } player.setFreeFall(false); player.setFallCollided(false); player.setStraightFall(false); player.setGrounded(true); player.setLandingFall(true); // resets some climb conditions player.setCanClimb(false); player.setCanClimbDown(false); player.setCornerToClimb(null); player.setCornerToClimbDown(null); /* Check loose floors in that row to shake it baby */ checkLoosesToShake(); } else { if(!player.isSafeFall() && !player.isRiskyFall() && !player.isScreaming()) { // player screams when the fall is going to kill him loader.getSound("falling").play(); player.setScreaming(true); } } // Checks for corner to reach in mid air if (cornerJumping != null) { int[] cornerCenter = cornerJumping.getCenter(); int xReachDistance = 80; int yReachDistance = -10; // player can reach a corner to hang in mid air if ( (Math.abs(playerCenter[0] - cornerCenter[0]) < xReachDistance) && ( (playerCenter[1] - cornerCenter[1]) > yReachDistance) ) { // player is close enough in both axis to reach the corner player.setCanClimb(true); player.setCornerToClimb(cornerJumping); System.out.println(cornerJumping.getTypeOfEntity() + ": " + cornerJumping.getCenter()[0] + ", " + cornerJumping.getCenter()[1]); } else { // player is too far to reach the corner in mid air player.setCanClimb(false); player.setCornerToClimb(null); } } if (wall != null) { // player has collided with a wall if ( player.getOrientation().equals("left") && wall.getTypeOfEntity().contains("face") ) { player.setX(wall.getCenter()[0] + 30); } else if (player.getOrientation().equals("left")) { player.setX(wall.getCenter()[0] - 40); } else if ( player.getOrientation().equals("right") && wall.getTypeOfEntity().contains("face") ) { player.setX(wall.getCenter()[0] + 40); } else if (player.getOrientation().equals("right")) { player.setX(wall.getCenter()[0]); } player.setFallCollided(true); } } else { /* Player is grounded */ // System.out.println("GROUNDED"); player.setLongLand(false); /* Checks if the player can stand on the floor */ floorPanel = checkFloorPanel(); looseFloor = checkLooseFloor(); cornerFloor = checkCornerFloor(); cornerFloorEntity = checkCornerFloorEntity(); wall = checkWall(); potion = checkPotion(); sword = checkSword(); door = checkDoor(); /* Check for corners */ corner = checkCorner(); // if (player.getCurrentAnimation().getId().contains("crouching")) { // if (floorPanel != null) { // player.setY( (int) floorPanel.getBoundingBox().getMinY()); // checks if player can drink a nearby potion player.setCanDrink(potion != null); //checks if player can take the sword from floor player.setCanPickSword(sword!=null); if (player.isDrinkingPotion() && potion != null) { deletePotion(potion); } if(player.isPickingSword() && sword != null && player.hasSword()){ win_song.play(false); deleteSword(sword); } if (floorPanel != null) { player.setY((int) floorPanel.getBoundingBox().getMinY()); } /* If there is a corner nearby, the player can climb it */ if (corner != null) { player.setGrounded(true); } // Corner climbing behaviour if (cornerFloor != null && cornerFloor.getAnimations() != null) { player.setGrounded(true); // Checks if player can climb down the corner if (!player.isCornerPositionFixed() ) { int climbDownGap = 35; int safeWalkingGap = 80; player.setCornerToClimbDown(cornerFloor); int[] cornerCenter = cornerFloor.getCenter(); if (Math.abs(cornerCenter[0] - playerCenter[0]) < climbDownGap && player.getCurrentAnimation().getId().equals("idle_left") && cornerFloor.getTypeOfEntity().contains("right")) { // left corner System.out.println("RIGHT CORNER DOWN FIX"); Entity cornerToClimbDown = player.getCornerToClimbDown(); int[] cc = cornerToClimbDown.getCenter(); player.setCanClimbDown(true); player.setCanClimb(false); player.setCornerToClimb(null); } else if (Math.abs(cornerCenter[0] - playerCenter[0]) < climbDownGap && player.getCurrentAnimation().getId().equals("idle_right") && cornerFloor.getTypeOfEntity().contains("left")) { // right corner // player.setX(cornerCenter[0] - climbDownGap); //System.out.println("LEFT CORNER DOWN FIX"); player.setCanClimbDown(true); player.setCanClimb(false); player.setCornerToClimb(null); } else { // player cannot climb down player.setCanClimbDown(false); } // //System.out.println("walking: " + player.isWalkingAStep() + // ", orientation: " + player.getOrientation().equals("left") + // ", corner: " + cornerFloor.getTypeOfEntity().contains("left") + // ", distance: " + (Math.abs(cornerCenter[0] - playerCenter[0]) < safeWalkingGap) ); // controls walking on the edge behaviour if (player.isWalkingAStep() && player.getOrientation().equals("right") && cornerFloor.getTypeOfEntity().contains("right") && Math.abs(cornerCenter[0] - playerCenter[0]) < safeWalkingGap) { // player is walking right, into a right corner if (player.isForcedToStop()) { if ( (playerCenter[0] > cornerCenter[0] - 10) || player.isOnTheEdge()) { //System.out.println("ole: " + safeWalkingGap/8); player.setX(cornerCenter[0] - safeWalkingGap/8 + player.getCurrentAnimation().getImage().getWidth()/2); player.setOnTheEdge(true); } } else { // player hasn't arrived yet to the corner edge player.setForcedToStop(true); } } else if (player.isWalkingAStep() && player.getOrientation().equals("left") && cornerFloor.getTypeOfEntity().contains("left") && Math.abs(cornerCenter[0] - playerCenter[0]) < safeWalkingGap) { // player is walking left, into a left corner if (player.isForcedToStop()) { if ( (playerCenter[0] < cornerCenter[0] + 10) || player.isOnTheEdge()) { // //System.out.println("STOPING PLAYER FROM FALLING OF THE EDGE: " + cornerCenter[0] + " - " + playerCenter[0]); player.setX(cornerCenter[0] + safeWalkingGap/8); player.setOnTheEdge(true); } } else { // player hasn't arrived yet to the corner edge player.setForcedToStop(true); } } } } else if (cornerFloor == null) { // there is no corner near the player that he can climb down // or walk to it's edge player.setCornerToClimbDown(null); // There is nothing beneath the player, it falls if (!player.isFalling() && !player.isOnTheEdge() && !checkFloorSides()) { System.out.println("Vooooy a caer 4 " + player.getCenter()[0] + " - " + player.getCenter()[1] + " - " + player.getSquare()[0] + " - " + player.getSquare()[1]); player.setStraightFall(true); player.fall(); // corrects player position before fall if (cornerFloorEntity != null) { int[] cornerCenter = cornerFloorEntity.getCenter(); int cornerGap = 40; if (cornerFloorEntity.getTypeOfEntity().contains("left")) { player.setX(cornerCenter[0] - cornerGap/4); System.out.println("LEFT CORNER FALL FIX"); } else if (cornerFloorEntity.getTypeOfEntity().contains("right")) { player.setX(cornerCenter[0] + cornerGap); System.out.println("RIGHT CORNER FALL FIX"); } } } } else { player.setCanClimbDown(false); } // Wall collision behaviour if (wall != null) { // player has collided with a wall System.out.println("Wall Collision: " + wall.getTypeOfEntity()); // corrects the player position after wall collision int wallxGap = 40; int[] wallCenter = wall.getCenter(); if (wall.getTypeOfEntity().contains("face")) { // left wall //System.out.println("WALKING RIGHT WALL FIX"); player.setOrientation("left"); player.collide(wall); player.setX(wallCenter[0] + wallxGap); } else if (wall.getTypeOfEntity().contains("left") || wall.getTypeOfEntity().contains("single") ) { //right wall //System.out.println("WALKING LEFT WALL FIX"); player.setOrientation("right"); player.collide(wall); player.setX(wallCenter[0] - (wallxGap/4) ); } } // Door collision behaviour if (door != null && door.getTypeOfEntity().contains("normal")) { if ( (door.getCurrentAnimation().getId().contains("closed")) || (door.getCurrentAnimation().getId().contains("half") && !player.getCurrentAnimation().getId().contains("crouching")) ) { // player has collided with a door // corrects the player position after wall collision int doorxGap = 40; int[] doorCenter = door.getCenter(); if (doorCenter[0] < playerCenter[0]) { // left side door player.setOrientation("left"); player.collide(door); player.setX(doorCenter[0] + doorxGap); } else if (doorCenter[0] > playerCenter[0]) { //right side door player.setOrientation("right"); player.collide(door); player.setX(doorCenter[0] - (doorxGap/2) ); } } else { // door is opened enough to player to go through } } } // END GROUNDED } /** * * @return true if there is any type of floor beneath of player * where it can stand and stay grounded or land */ private Entity checkFloorPanel() { Entity floorPanel = null; Entity finalFloor = null; boolean leftPanel = false; boolean rightPanel = false; boolean leftCorner = false; boolean rightCorner = false; boolean leftFall = false; boolean rightFall = false; int securityGap = 10; /* Obtains the square where the center point of the player is placed */ int playerHeight2 = player.getCurrentAnimation().getImage().getHeight()/2; int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // Checks that the square is within the room if (playerSquare[0] >= 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] <= 9) { /* Checks if there is a panel floor type object in current square */ List<Entity> bEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getBackground(); List<Entity> fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getForeground(); List<Entity> bgEntities = new LinkedList<Entity>(); bgEntities.addAll(bEntities); bgEntities.addAll(fEntities); for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); if ( (name.startsWith("FloorPanel_") && !name.contains("skeleton")) || (name.startsWith("Pillar_") && !name.contains("shadow") && !name.contains("top")) || name.startsWith("Opener") || name.startsWith("Closer") || name.startsWith("SpikeFloor")){ int bgLeft = (int) bgE.getBoundingBox().getMinX(); int bgRight = (int) bgE.getBoundingBox().getMaxX(); int bgTop = (int) bgE.getBoundingBox().getMinY(); int[] ec = bgE.getCenter(); if (name.contains("left") && ((ec[1] - playerCenter[1]) <= playerHeight2 + securityGap) ) { floorPanel = bgE; // player lands on the floor (according to y axis) if ( (playerCenter[0] >= bgLeft) && (playerCenter[0] <= bgRight) ) { // player lands on the floor (according to x axis) // //System.out.println("LEFT LANDING"); leftPanel = true; } else { // player falls, there is no floor beneath him leftFall = true; // newPlayerX = ec[0] - bgWidth / 4; } } else if (name.contains("right") && ((ec[1] - playerCenter[1]) <= playerHeight2 + securityGap) ) { floorPanel = bgE; if ( (playerCenter[0] >= bgLeft) && (playerCenter[0] <= bgRight) ) { // //System.out.println("RIGHT LANDING"); rightPanel = true; } else { rightFall = true; // newPlayerX = ec[0] + bgWidth; } } if(name.startsWith("Opener") && player.isGrounded()){ finalFloor = bgE; if(((Opener) bgE).getDoor() == null){ for(Door d : doors){ if(d.getId() == ((Opener) bgE).getId()){ ((Opener) bgE).setDoor(d); } } } ((Opener) bgE).openDoor(player); } else if(name.startsWith("Closer") && player.isGrounded()){ finalFloor = bgE; if(((Closer) bgE).getDoor() == null){ for(Door d : doors){ if(d.getId() == ((Closer) bgE).getId()){ ((Closer) bgE).setDoor(d); } } } ((Closer) bgE).closeDoor(player); } if(name.startsWith("SpikeFloor")){ finalFloor = bgE; if(!((SpikeFloor) bgE).isActivated()){ ((SpikeFloor) bgE).activate(player); if(player.isFalling() || player.isFreeFall() || (player.getCurrentAnimation().getId().startsWith("running") && !player.isJumping())){ if(player.isFalling() || player.isFreeFall()){ player.setGrounded(true); player.setFreeFall(false); player.setFalling(false); } bgRight = (int) bgE.getBoundingBox().getMaxX(); bgTop = (int) bgE.getBoundingBox().getMaxY(); player.setY(bgTop - 16); player.setSpiked(); if(player.getOrientation().equals("right")){ player.setX(bgRight - 12); } else{ player.setX(bgRight - 30); } } } } } else if (name.startsWith("Corner_")) { if (name.contains("left")) { leftCorner = true; } else if (name.contains("right")) { rightCorner = true; } } } /* Player's behaviour */ if (leftFall && !leftCorner) leftPanel = true; else if (leftFall && leftCorner) { leftPanel = false; } if (rightFall && !rightCorner) rightPanel = true; else if (rightFall && rightCorner) { rightPanel = false; } } if (leftPanel || rightPanel) { finalFloor = floorPanel; } return finalFloor; } /** * * @return false if there the player can stand in a corner, * true if there is corner in the same square as the player, but * the player cant be on it, the player will fall */ private Entity checkCornerFloor() { Entity corner = new Corner(); /* Obtains the square where the center point of the player is placed */ int playerWidth2 = player.getCurrentAnimation().getImage().getWidth()/2; int playerHeight2 = player.getCurrentAnimation().getImage().getHeight()/2; int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // Checks that the square is within the room if (playerSquare[0] >= 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] <= 9) { /* Checks if there is a panel floor type object in current square */ List<Entity> bEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getBackground(); List<Entity> fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getForeground(); List<Entity> bgEntities = new LinkedList<Entity>(); bgEntities.addAll(bEntities); bgEntities.addAll(fEntities); for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("Corner_") ) { int bgLeft = (int) bgE.getBoundingBox().getMinX(); int bgRight = (int) bgE.getBoundingBox().getMaxX(); int bgTop = (int) bgE.getBoundingBox().getMinY(); int bgBottom = (int) bgE.getBoundingBox().getMaxY(); int[] ec = bgE.getCenter(); int[] es = bgE.getSquare(); if (name.contains("left") && (ec[1] > playerCenter[1]) ) { // LEFT CORNER if ( (playerCenter[0] >= bgLeft) && (playerCenter[0] <= bgRight) ) { corner = bgE; } else { // player falls corner = null; } } else if (name.contains("right") && (ec[1] > playerCenter[1]) ) { // RIGHT CORNER if ( (playerCenter[0] >= bgLeft) && (playerCenter[0] <= bgRight) ) { corner = bgE; } else { // player falls corner = null; } } } } } return corner; } /** * * @return a corner located near the player on the floor * beneath him */ private Entity checkCornerFloorEntity() { Entity corner = new Corner(); /* Obtains the square where the center point of the player is placed */ int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // Checks that the square is within the room if (playerSquare[0] >= 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] <= 9) { /* Checks if there is a panel floor type object in current square */ List<Entity> bEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getBackground(); List<Entity> fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getForeground(); List<Entity> bgEntities = new LinkedList<Entity>(); bgEntities.addAll(bEntities); bgEntities.addAll(fEntities); for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("Corner_") ) { int[] ec = bgE.getCenter(); if (ec[1] > playerCenter[1]) { // the corner is beneath the player corner = bgE; } } } } return corner; } /** * * @return true if there is a loose floor panel beneath the player */ private Entity checkLooseFloor() { Entity looseFloor = null; /* Obtains the square where the center point of the player is placed */ int playerWidth2 = player.getCurrentAnimation().getImage().getWidth()/2; int playerHeight2 = player.getCurrentAnimation().getImage().getHeight()/2; int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // Checks that the square is within the room if (playerSquare[0] >= 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] <= 9) { /* Checks if there is a loose floor type object in current square */ List<Entity> bgEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getBackground(); LooseFloor toBeDeleted = null; Entity rightFloor = null; Entity leftFloor = null; for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); if (player.isGrounded() && name.startsWith("LooseFloor") ) { LooseFloor loose = (LooseFloor)bgE; if(!loose.isFalling() && !loose.isActivated()){ System.out.println(playerSquare[0] + " - " + playerSquare[1]); leftFloor = currentRoom.returnNamedEntityBackground("FloorPanel_normal_left", currentRoom.getSquare(playerSquare[0], playerSquare[1])); rightFloor = currentRoom.returnNamedEntityBackground("FloorPanel_normal_right", currentRoom.getSquare(playerSquare[0], playerSquare[1])); loose.setActivated(true); loose.setRoom1(currentRoom.getRow() + 1); loose.setRoom2(currentRoom.getCol() + 1); loose.setRow(playerSquare[0]); loose.setCol(playerSquare[1]); //System.out.println("SQUARE[0] " + playerSquare[0] + " SQUARE[1] " + playerSquare[1]);; toBeDeleted = loose; falling_floor.add(loose); // returns the current loose floor looseFloor = bgE; } } } if(toBeDeleted != null){ currentRoom.deleteEntityBackground(leftFloor, currentRoom.getSquare(playerSquare[0], playerSquare[1])); currentRoom.deleteEntityBackground(rightFloor, currentRoom.getSquare(playerSquare[0], playerSquare[1])); //currentRoom.deleteEntityBackground(toBeDeleted); toBeDeleted = null; } } return looseFloor; } /** * * @return true if there is a corner that the player can reach * doing a vertical jump */ private Entity checkCorner() { Entity corner = null; /* Obtains the square where the center point of the player is placed */ int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // Checks that the square is within the room if (playerSquare[0] > 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] < 9) { /* Checks if there is a corner type object in upleft square */ List<Entity> bEntities = new LinkedList<Entity>(); List<Entity> fEntities = new LinkedList<Entity>(); if (playerSquare[1] > 0) { bEntities = currentRoom.getSquare( playerSquare[0] - 1, playerSquare[1] - 1).getBackground(); fEntities = currentRoom.getSquare( playerSquare[0] - 1, playerSquare[1] - 1).getForeground(); } /* Checks if there is a corner type object in top square */ List<Entity> topBgEntities = currentRoom.getSquare( playerSquare[0] - 1, playerSquare[1]).getBackground(); List<Entity> bgEntities = new LinkedList<Entity>(); bgEntities.addAll(bEntities); bgEntities.addAll(fEntities); bgEntities.addAll(topBgEntities); boolean toBeDeleted = false; Entity leftFloor = null; Entity rightFloor = null; for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("Corner") ) { int[] ec = bgE.getCenter(); // if ( (ec[0] < playerCenter[0]) && if ((ec[1] < playerCenter[1]) && (player.getOrientation().equals("left")) ) { // corner is at player's left side and player is looking left corner = bgE; // //System.out.println("LEFT CORNER DETECTED - (" + ec[0] + ", " + ec[1] + ")"); } } else if( name.startsWith("Loose") && player.isClimbingLastFrame()){ LooseFloor loose = (LooseFloor)bgE; if(loose.getLifes()<1){ if(!loose.isFalling() && !loose.isActivated()){ System.out.println("AHORRRRA " + currentRoom.getRow() + " - " + currentRoom.getCol()); if(playerSquare[0]-1 == 0){ loose.justShakeItBaby(); } else{ leftFloor = currentRoom.returnNamedEntityBackground("FloorPanel_normal_left", currentRoom.getSquare(playerSquare[0]-1, playerSquare[0])); rightFloor = currentRoom.returnNamedEntityBackground("FloorPanel_normal_right", currentRoom.getSquare(playerSquare[0]-1, playerSquare[0])); currentRoom.deleteEntityBackground(leftFloor, currentRoom.getSquare(playerSquare[0]-1, playerSquare[0])); currentRoom.deleteEntityBackground(rightFloor, currentRoom.getSquare(playerSquare[0]-1, playerSquare[0])); loose.setRoom1(currentRoom.getRow() + 1); loose.setRoom2(currentRoom.getCol() + 1); loose.setRow(playerSquare[0]-1); loose.setCol( playerSquare[0]); loose.setActivated(true); //System.out.println("SQUARE[0] " + playerSquare[0] + " SQUARE[1] " + playerSquare[1]);; falling_floor.add(loose); toBeDeleted = true; } } } else{ loose.justShakeItBaby(); } } } if(toBeDeleted){ toBeDeleted = false; currentRoom.deleteEntityBackground(leftFloor, currentRoom.getSquare( playerSquare[0] - 1, playerSquare[0])); currentRoom.deleteEntityBackground(rightFloor, currentRoom.getSquare( playerSquare[0] - 1, playerSquare[0])); } /* Checks if there is a corner type object in upright square */ bEntities = currentRoom.getSquare( playerSquare[0] - 1, playerSquare[1] + 1).getBackground(); fEntities = currentRoom.getSquare( playerSquare[0] - 1, playerSquare[1] + 1).getForeground(); /* Checks if there is a corner type object in top square */ topBgEntities = currentRoom.getSquare( playerSquare[0] - 1, playerSquare[1]).getBackground(); bgEntities = new LinkedList<Entity>(); bgEntities.addAll(bEntities); bgEntities.addAll(fEntities); bgEntities.addAll(topBgEntities); for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("Corner") ) { int[] ec = bgE.getCenter(); // if ( (ec[0] > playerCenter[0]) && if((player.getOrientation().equals("right")) ) { // corner is at player's right side and player is looking right corner = bgE; // //System.out.println("RIGHT CORNER DETECTED"); } } } } return corner; } /** * * @return true if there is a corner that the player can reach * falling or doing a horizontal jump */ private Entity checkCornerJumping() { Entity corner = null; /* Obtains the square where the center point of the player is placed */ int playerWidth2 = player.getCurrentAnimation().getImage().getWidth()/2; int playerHeight2 = player.getCurrentAnimation().getImage().getHeight()/2; int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // Checks that the square is within the room if (playerSquare[0] > 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] < 9) { /* Checks if there is a corner type object in left square */ List<Entity> bEntities = new LinkedList<Entity>(); List<Entity> fEntities = new LinkedList<Entity>(); if (playerSquare[1] > 0) { bEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1] - 1).getBackground(); fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1] - 1).getForeground(); } /* Checks if there is a corner type object in current square */ List<Entity> currBgEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getBackground(); List<Entity> bgEntities = new LinkedList<Entity>(); bgEntities.addAll(bEntities); bgEntities.addAll(fEntities); bgEntities.addAll(currBgEntities); for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("Corner") ) { int[] ec = bgE.getCenter(); int[] es = bgE.getSquare(); if ( (ec[0] < playerCenter[0]) && (bgE.getTypeOfEntity().contains("right")) && (player.getOrientation().equals("left")) ) { // corner is at player's left side and player is looking left corner = bgE; } } } /* Checks if there is a corner type object in right square */ bEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1] + 1).getBackground(); fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1] + 1).getForeground(); bgEntities.addAll(fEntities); /* Checks if there is a corner type object in current square */ currBgEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getBackground(); bgEntities = new LinkedList<Entity>(); bgEntities.addAll(bEntities); bgEntities.addAll(fEntities); bgEntities.addAll(currBgEntities); for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("Corner") ) { int[] ec = bgE.getCenter(); if ( (ec[0] > playerCenter[0]) && bgE.getTypeOfEntity().contains("left") && (player.getOrientation().equals("right")) ) { // corner is at player's right side and player is looking right corner = bgE; } } } } return corner; } /** * * @return true if there is a wall in front of the player * where he will collide */ private Entity checkWall() { Entity wall = null; int wallGap = 20; /* Obtains the square where the center point of the player is placed */ int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // Checks that the square is within the room if (playerSquare[0] >= 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] <= 9) { /* Checks if there is a wall type object in current square */ List<Entity> bgEntities = new LinkedList<Entity>(); List<Entity> bEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getBackground(); List<Entity> fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getForeground(); bgEntities.addAll(bEntities); bgEntities.addAll(fEntities); if (playerSquare[1] > 0) { // Left square List<Entity> bEntitiesLeft = currentRoom.getSquare( playerSquare[0], playerSquare[1] - 1).getBackground(); List<Entity> fEntitiesLeft = currentRoom.getSquare( playerSquare[0], playerSquare[1] - 1).getForeground(); bgEntities.addAll(bEntitiesLeft); bgEntities.addAll(fEntitiesLeft); } if (playerSquare[1] < 9) { // Right square List<Entity> bEntitiesRight = currentRoom.getSquare( playerSquare[0], playerSquare[1] + 1).getBackground(); List<Entity> fEntitiesRight = currentRoom.getSquare( playerSquare[0], playerSquare[1] + 1).getForeground(); bgEntities.addAll(bEntitiesRight); bgEntities.addAll(fEntitiesRight); } // Searches for wall type objects for (Entity bgE : bgEntities) { if (bgE.getBoundingBox() != null) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("Wall_") ) { // wall detected nearby int[] ec = bgE.getCenter(); if ( Math.abs(ec[0] - playerCenter[0]) < wallGap) { // player is close to the wall wall = bgE; } // else if (ec[0] > playerCenter[0] && // (Math.abs(ec[0] - playerCenter[0]) < 2*wallGap) && // name.contains("face") ) { // // player has passed through the wall, must be fixed // wall = bgE; // else if (ec[0] < playerCenter[0] && // (Math.abs(ec[0] - playerCenter[0]) < 2*wallGap) && // name.contains("left")) { // // player has passed through the wall, must be fixed // wall = bgE; } } } } return wall; } /** * * @return true if there is any type of floor in the jump * target square where the player can land */ private Entity checkLongJumpFloor() { Entity floorPanel = null; /* Obtains the square where the center point of the player is placed */ int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // Checks that the square is within the room if (playerSquare[0] >= 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] <= 9) { /* Checks if there is a panel floor type object * in the landing target square (left jump) */ List<Entity> bEntities; List<Entity> fEntities; System.out.println(playerSquare[0] + " - " + playerSquare[1]); if (playerSquare[1] == 0 || playerSquare[1] == 9) { bEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getBackground(); fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getBackground(); } else if (player.getOrientation().equals("left") ) { bEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1] - 1).getBackground(); fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1] - 1).getForeground(); } else if (player.getOrientation().equals("right") ) { bEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1] + 1).getBackground(); fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1] + 1).getForeground(); } else if (playerSquare[1] == 0 || playerSquare[1] == 9) { bEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getBackground(); fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getBackground(); } else { bEntities = null; fEntities = null; } List<Entity> bgEntities = new LinkedList<Entity>(); bgEntities.addAll(bEntities); bgEntities.addAll(fEntities); for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); System.out.println("entities: " + name); if ( name.startsWith("FloorPanel_") || name.startsWith("Loose") || name.startsWith("Corner") || (name.startsWith("Pillar_") && !name.contains("shadow")) || name.startsWith("Opener") || name.startsWith("Closer") || name.startsWith("SpikeFloor")){ floorPanel = bgE; } } } return floorPanel; } /** * * @return true if there is a door in front of the player * where he will collide */ private Entity checkDoor() { Entity door = null; int doorGap = 20; /* Obtains the square where the center point of the player is placed */ int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // Checks that the square is within the room if (playerSquare[0] >= 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] <= 9) { /* Checks if there is a wall type object in current square */ List<Entity> bgEntities = new LinkedList<Entity>(); List<Entity> bEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getBackground(); List<Entity> fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getForeground(); bgEntities.addAll(bEntities); bgEntities.addAll(fEntities); if (playerSquare[1] > 0) { // Left square List<Entity> bEntitiesLeft = currentRoom.getSquare( playerSquare[0], playerSquare[1] - 1).getBackground(); List<Entity> fEntitiesLeft = currentRoom.getSquare( playerSquare[0], playerSquare[1] - 1).getForeground(); bgEntities.addAll(bEntitiesLeft); bgEntities.addAll(fEntitiesLeft); } if (playerSquare[1] < 9) { // Right square List<Entity> bEntitiesRight = currentRoom.getSquare( playerSquare[0], playerSquare[1] + 1).getBackground(); List<Entity> fEntitiesRight = currentRoom.getSquare( playerSquare[0], playerSquare[1] + 1).getForeground(); bgEntities.addAll(bEntitiesRight); bgEntities.addAll(fEntitiesRight); } // Searches for wall type objects for (Entity bgE : bgEntities) { if (bgE.getBoundingBox() != null) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("Door") ) { // wall detected nearby int[] ec = bgE.getCenter(); if ( Math.abs(ec[0] - playerCenter[0]) < doorGap) { // player is close to the door door = bgE; } } } } } return door; } /** * * @return true if there is a door in in the middle * of player's climbing animation */ private Entity checkClimbingDoor() { Entity door = null; int doorGap = 20; /* Obtains the square where the center point of the player is placed */ int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // Checks that the square is within the room if (playerSquare[0] >= 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] <= 9) { /* Checks if there is a wall type object in current square */ List<Entity> bgEntities = new LinkedList<Entity>(); List<Entity> bEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getBackground(); List<Entity> fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getForeground(); bgEntities.addAll(bEntities); bgEntities.addAll(fEntities); if (player.getOrientation().equals("left") && playerSquare[1] > 0 && playerSquare[0] > 0) { // Left square List<Entity> bEntitiesLeft = currentRoom.getSquare( playerSquare[0] - 1, playerSquare[1] - 1).getBackground(); List<Entity> fEntitiesLeft = currentRoom.getSquare( playerSquare[0] - 1, playerSquare[1] - 1).getForeground(); bgEntities.addAll(bEntitiesLeft); bgEntities.addAll(fEntitiesLeft); } if (player.getOrientation().equals("right") && playerSquare[1] < 9 && playerSquare[0] > 0) { // Right square List<Entity> bEntitiesRight = currentRoom.getSquare( playerSquare[0] - 1, playerSquare[1] + 1).getBackground(); List<Entity> fEntitiesRight = currentRoom.getSquare( playerSquare[0] - 1, playerSquare[1] + 1).getForeground(); bgEntities.addAll(bEntitiesRight); bgEntities.addAll(fEntitiesRight); } // Searches for wall type objects for (Entity bgE : bgEntities) { if (bgE.getBoundingBox() != null) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("Door") ) { // wall detected nearby int[] ec = bgE.getCenter(); if (ec[1] < playerCenter[1]) { // player is close to the door door = bgE; } } } } } return door; } /** * * @return true if there is any type of floor beneath the player * so he can scale down from a corner without falling */ private Entity checkFloorBeneath() { Entity floorPanel = null; /* Obtains the square where the center point of the player is placed */ int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // Checks that the square is within the room if (playerSquare[0] >= 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] <= 9) { /* Checks if there is a panel floor type object beneath the player */ List<Entity> bEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getBackground(); List<Entity> fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getForeground(); List<Entity> bgEntities = new LinkedList<Entity>(); bgEntities.addAll(bEntities); bgEntities.addAll(fEntities); for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("FloorPanel_") || name.startsWith("Corner") || name.startsWith("Loose") || (name.startsWith("Pillar_") && !name.contains("shadow") && !name.contains("top")) || name.startsWith("Opener") || name.startsWith("Closer") || name.startsWith("SpikeFloor")){ floorPanel = bgE; } } } return floorPanel; } public int[] getSquareCenter(int i, int j) { /* Calculates the center of the square */ int px = 64 + j * 64; int py = (int)(6 + 63 + (i-1) * 126); return new int[]{px, py}; } public void updateFallingFloor(long elapsedTime){ List<LooseFloor> toBeDeleted = new LinkedList<LooseFloor>(); for(LooseFloor loose: falling_floor){ if(!loose.isBroken()){ loose.updateReal(elapsedTime); if(checkLooseCollision(loose)){ /* Check collision */ loose.setBroken(); toBeDeleted.add(loose); Room looseRoom = currentLevel.getRoom(loose.getRoom1(), loose.getRoom2()); looseRoom.deleteEntityBackground(loose); List<Entity> newEntities = new LinkedList<Entity>(); /* Put broken */ int[] looseCenter = loose.getCenter(); int[] looseSquare = loose.getSquare(looseCenter[0], looseCenter[1]); System.out.println("SE VA A ROMPEEEER " + looseSquare[0] + " - " + looseSquare[1]); int px = 64 + looseSquare[1] * 64; int py = (int)(6 + looseSquare[0] * 126); newEntities.add(new FloorPanel(px,py,0,-6,loader,"broken_left")); px = 64 + (looseSquare[1]+1) * 64; py = (int)(6 + looseSquare[0] * 126); System.out.println("ROTIIIISIMA " + px + " - " + py); newEntities.add(new FloorPanel(px,py,-12,-2,loader,"broken_right")); currentLevel.getRoom(loose.getRoom1(), loose.getRoom2()).addBackground(newEntities); } else{ /* Didnt collided */ if(loose.isLastFrameMoving()){ //System.out.println("AHORA CREARIAMOS ESQUINA"); /* Create corners */ Room roomToOperate = currentLevel.getRoom(loose.getRoom1(), loose.getRoom2()); Entity newCorner = returnCorner(roomToOperate.getSquare(loose.getRow(), loose.getCol())); Entity newCornerRight = returnCorner(roomToOperate.getSquare(loose.getRow(), loose.getCol() + 1)); if(newCorner == null && newCornerRight == null){ //Si no hay ninguna esquina -> mirar que haya pared //Pared izquierda newCorner = roomToOperate.returnNamedEntityBackground("Wall_face_stack_main", currentRoom.getSquare(loose.getRow(), loose.getCol())); //Pared derecha newCornerRight = roomToOperate.returnNamedEntityForeground("Wall_left_stack_main", currentRoom.getSquare(loose.getRow(), loose.getCol()+1)); if(newCorner == null && newCornerRight == null){ System.out.println("CASO 1 - NO ESQUINAS NO PARED"); //No hay pared newCorner = new Corner(getPX(loose.getCol()),getPY(loose.getRow()),-12,-2,loader,"normal_right"); roomToOperate.addToBackground(newCorner, roomToOperate.getSquare(loose.getRow(), loose.getCol())); newCorner = new Corner(getPX(loose.getCol()+1),getPY(loose.getRow()),0,-6,loader,"normal_left"); roomToOperate.addToBackground(newCorner, roomToOperate.getSquare(loose.getRow(), loose.getCol()+1)); /* Comprobar si es en la ultima fila => eliminar base y crear corners en el piso de abajo tambien */ if(loose.getRow() == 3){ Room newRoom = currentLevel.getRoom(loose.getRoom1() + 1, loose.getRoom2()); Square underSquare = newRoom.getSquare(0, loose.getCol()); Entity looseUnder = newRoom.returnNamedEntityBackground("LooseFloor", underSquare); newRoom.deleteEntityBackground(looseUnder, underSquare); looseUnder = newRoom.returnNamedEntityBackground("FloorPanel_normal_left", underSquare); newRoom.deleteEntityBackground(looseUnder, underSquare); newCorner = new Corner(getPX(loose.getCol()),getPY(0),-12,-2,loader,"normal_right"); newRoom.addToBackground(newCorner, underSquare); newCorner = new Corner(getPX(loose.getCol()+1),getPY(0),0,-6,loader,"normal_left"); newRoom.addToBackground(newCorner, newRoom.getSquare(0,loose.getCol()+1)); } } else if(newCorner != null && newCornerRight == null){ System.out.println("CASO 2 - NO ESQUINAS PARED IZQUIERDA"); //Hay pared izquierda y no derecha -> Crear solo esquina a la derecha newCorner = new Corner(getPX(loose.getCol()+1),getPY(loose.getRow()),0,-6,loader,"normal_left"); roomToOperate.addToBackground(newCorner, roomToOperate.getSquare(loose.getRow(), loose.getCol()+1)); /* Comprobar si es en la ultima fila => eliminar base y crear corners en el piso de abajo tambien */ if(loose.getRow() == 3){ Room newRoom = currentLevel.getRoom(roomToOperate.getRow() + 2, roomToOperate.getCol() + 1); Square underSquare = newRoom.getSquare(0, loose.getCol()); Entity looseUnder = newRoom.returnNamedEntityBackground("LooseFloor", underSquare); newRoom.deleteEntityBackground(looseUnder, underSquare); looseUnder = newRoom.returnNamedEntityBackground("FloorPanel_normal_left", underSquare); newRoom.deleteEntityBackground(looseUnder, underSquare); newCorner = new Corner(getPX(loose.getCol()+1),getPY(0),0,-6,loader,"normal_left"); newRoom.addToBackground(newCorner, newRoom.getSquare(0,loose.getCol()+1)); } // Makes the player fall correctly player.setStraightFall(true); player.fall(); int[] cornerCenter = newCorner.getCenter(); int cornerGap = 0; int cornerYGap = 10; int newPlayerX = cornerCenter[0] - cornerGap; if (player.getX() > newPlayerX) { player.setX(newPlayerX); System.out.println("Caso 2 - FALL FIX"); } else { System.out.println("Caso 2 - NO NEED FOR FIX"); } // player.setY(cornerCenter[1] + cornerYGap); } else if(newCorner == null && newCornerRight != null){ System.out.println("CASO 3 - NO ESQUINAS PARED DERECHA"); //Hay pared en la derecha y no en la izquierda -> crear solo esquina a la izquierda newCorner = new Corner(getPX(loose.getCol()),getPY(loose.getRow()),-12,-2,loader,"normal_right"); roomToOperate.addToBackground(newCorner, roomToOperate.getSquare(loose.getRow(), loose.getCol())); if(loose.getRow() == 3){ Room newRoom = currentLevel.getRoom(roomToOperate.getRow() + 2, roomToOperate.getCol() + 1); Square underSquare = newRoom.getSquare(0, loose.getCol()); Entity looseUnder = newRoom.returnNamedEntityBackground("LooseFloor", underSquare); newRoom.deleteEntityBackground(looseUnder, underSquare); looseUnder = newRoom.returnNamedEntityBackground("FloorPanel_normal_left", underSquare); newRoom.deleteEntityBackground(looseUnder, underSquare); newCorner = new Corner(getPX(loose.getCol()),getPY(0),-12,-2,loader,"normal_right"); newRoom.addToBackground(newCorner, underSquare); } // Makes the player fall correctly player.setStraightFall(true); player.fall(); int[] cornerCenter = newCornerRight.getCenter(); int cornerGap = 60; int cornerYGap = 10; int newPlayerX = cornerCenter[0] - cornerGap; if (player.getX() < newPlayerX) { player.setX(newPlayerX); System.out.println("Caso 3 - FALL FIX"); } else { System.out.println("Caso 3 - NO NEED FOR FIX"); } // player.setY(cornerCenter[1] + cornerYGap); } //Si no hay ninguna esquina -> se aade una derecha en la casilla actual y una izquierda en la casilla de la derecha } else if(newCorner != null && newCorner.getTypeOfEntity().contains("left")){ //Si hay esquina con nombre left -> se quita de la casilla actual y se mete una left en la casilla derecha salvo que haya pared roomToOperate.deleteEntityBackground(newCorner, roomToOperate.getSquare(loose.getRow(), loose.getCol())); //Pared derecha newCornerRight = roomToOperate.returnNamedEntityForeground("Wall_left_stack_main", currentRoom.getSquare(loose.getRow(), loose.getCol()+1)); if(newCornerRight == null){ System.out.println("CASO 4 - ESQUINA IZQUIERDA NO PARED DERECHA"); newCorner = new Corner(getPX(loose.getCol()+1),getPY(loose.getRow()),0,-6,loader,"normal_left"); roomToOperate.addToBackground(newCorner, roomToOperate.getSquare(loose.getRow(), loose.getCol()+1)); // Makes the player fall correctly player.setStraightFall(true); player.fall(); int[] cornerCenter = newCorner.getCenter(); int cornerGap = 0; int cornerYGap = 10; int newPlayerX = cornerCenter[0] - cornerGap; if (player.getX() > newPlayerX) { player.setX(newPlayerX); System.out.println("Caso 4 - FALL FIX"); } else { System.out.println("Caso 4 - NO NEED FOR FIX"); } player.setY(cornerCenter[1] + cornerYGap); } else{ System.out.println("CASO 5 - ESQUINA IZQUIERDA PARED DERECHA"); // makes the player fall if he is in the same square as the falling loose floor int looseSquareX = loose.getRow(); int looseSquareY = loose.getCol(); int[] newPlayerCenter = player.getCenter(); int[] newPlayerSquare = player.getSquare(newPlayerCenter[0], newPlayerCenter[1]); if (newPlayerSquare[0] == looseSquareX && newPlayerSquare[1] == looseSquareY) { player.setStraightFall(true); player.fall(); // int[] cornerCenter = newCornerRight.getCenter(); // int cornerGap = 40; // if (newCornerRight.getTypeOfEntity().contains("left")) { // player.setX(cornerCenter[0] - cornerGap/4); // System.out.println("LEFT CORNER FALL FIX"); // else if (newCornerRight.getTypeOfEntity().contains("right")) { // player.setX(cornerCenter[0] + cornerGap); // System.out.println("RIGHT CORNER FALL FIX"); } } /* Comprobar si es en la ultima fila => eliminar base y esquina izquierda, y colocar esquina izquierda en la siguiente */ if(loose.getRow() == 3){ Room newRoom = currentLevel.getRoom(roomToOperate.getRow() + 2, roomToOperate.getCol() + 1); Square underSquare = newRoom.getSquare(0, loose.getCol()); Entity looseUnder = newRoom.returnNamedEntityBackground("Loose", underSquare); newRoom.deleteEntityBackground(looseUnder, underSquare); looseUnder = newRoom.returnNamedEntityBackground("FloorPanel_normal_left", underSquare); newRoom.deleteEntityBackground(looseUnder, underSquare); looseUnder = newRoom.returnNamedEntityBackground("Corner", underSquare); newRoom.deleteEntityBackground(looseUnder, underSquare); if(newCornerRight == null){ newCorner = new Corner(getPX(loose.getCol()+1),getPY(0),0,-6,loader,"normal_left"); newRoom.addToBackground(newCorner, newRoom.getSquare(0,loose.getCol()+1)); } } } else if(newCornerRight.getTypeOfEntity().contains("right")){ //Si hay una esquina con nombre right -> se quita de la casilla actual, y se mete una right en la casilla de la izq salvo que haya pared roomToOperate.deleteEntityBackground(newCornerRight, roomToOperate.getSquare(loose.getRow(), loose.getCol()+1)); //Pared izquierda newCorner = roomToOperate.returnNamedEntityBackground("Wall_face_stack_main", currentRoom.getSquare(loose.getRow(), loose.getCol())); if(newCorner == null){ System.out.println("CASO 6 - ESQUINA DERECHA NO PARED IZQUIERDA"); newCornerRight = new Corner(getPX(loose.getCol()),getPY(loose.getRow()),-12,-2,loader,"normal_right"); roomToOperate.addToBackground(newCornerRight, roomToOperate.getSquare(loose.getRow(), loose.getCol())); // Makes the player fall correctly player.setStraightFall(true); player.fall(); int[] cornerCenter = newCornerRight.getCenter(); int cornerGap = 60; int cornerYGap = 10; int newPlayerX = cornerCenter[0] - cornerGap; if (player.getX() < newPlayerX) { player.setX(newPlayerX); System.out.println("Caso 6 - FALL FIX"); } else { System.out.println("Caso 6 - NO NEED FOR FIX"); } player.setY(cornerCenter[1] + cornerYGap); } else{ System.out.println("CASO 7 - ESQUINA DERECHA PARED IZQUIERDA"); // makes the player fall if he is in the same square as the falling loose floor int looseSquareX = loose.getRow(); int looseSquareY = loose.getCol(); int[] newPlayerCenter = player.getCenter(); int[] newPlayerSquare = player.getSquare(newPlayerCenter[0], newPlayerCenter[1]); if (newPlayerSquare[0] == looseSquareX && newPlayerSquare[1] == looseSquareY) { player.setStraightFall(true); player.fall(); } } /* Comprobar si es en la ultima fila => eliminar base y crear corners en el piso de abajo tambien */ if(loose.getRow() == 3){ Room newRoom = currentLevel.getRoom(roomToOperate.getRow() + 2, roomToOperate.getCol() + 1); Square underSquare = newRoom.getSquare(0, loose.getCol()); Entity looseUnder = newRoom.returnNamedEntityBackground("Loose", underSquare); newRoom.deleteEntityBackground(looseUnder, underSquare); looseUnder = newRoom.returnNamedEntityBackground("FloorPanel_normal_left", underSquare); newRoom.deleteEntityBackground(looseUnder, underSquare); if(newCorner == null){ newCornerRight = new Corner(getPX(loose.getCol()),getPY(0),-12,-2,loader,"normal_right"); newRoom.addToBackground(newCornerRight, underSquare); } } } } if(loose.getY() > (400 + loose.getCurrentAnimation().getImage().getHeight())){ System.out.println("CAMBIO DE ROOOOOM"); /* Changed room */ Room looseRoom = currentLevel.getRoom(loose.getRoom1(), loose.getRoom2()); looseRoom.deleteEntityBackground(loose); loose.setY(0); loose.increaseRoom1(); looseRoom = currentLevel.getRoom(loose.getRoom1(), loose.getRoom2()); looseRoom.addToBackground(loose); } } } } for(LooseFloor b : toBeDeleted){ falling_floor.remove(b); } toBeDeleted = new LinkedList<LooseFloor>(); } private boolean checkLooseCollision(LooseFloor loose){ /* Obtains the square where the center point of the loose is placed */ int looseWidth2 = loose.getCurrentAnimation().getImage().getWidth()/2; int looseHeight2 = loose.getCurrentAnimation().getImage().getHeight()/2; int[] looseCenter = loose.getCenter(); int[] looseSquare = loose.getSquare(looseCenter[0], looseCenter[1]); Room looseRoom = currentLevel.getRoom(loose.getRoom1(), loose.getRoom2()); boolean collision = false; if(looseSquare[0] != 4){ List<Entity> bEntities = looseRoom.getSquare( looseSquare[0], looseSquare[1]).getBackground(); for (Entity bgE : bEntities) { String name = bgE.getTypeOfEntity(); if(name.startsWith("FloorPanel_normal_left") || name.startsWith("FloorPanel_broken_right")){ int[] ec = bgE.getCenter(); if(loose.getCenter()[1] - ec[1] > -10 && loose.getCenter()[1] - ec[1] <= 10){ collision = true; } } } } return collision; } private void updateDoors(long elapsedTime){ for(Door d : doors){ d.updateReal(elapsedTime); } } private Corner returnCorner(Square looseSquare){ Corner toBeReturned = null; List<Entity> bg = looseSquare.getBackground(); for (Entity bgE : bg) { if(bgE.getTypeOfEntity().startsWith("Corner")){ toBeReturned = (Corner)bgE; } } return toBeReturned; } private int getPX(int col){ return 64 + col * 64; } private int getPY(int row){ return (int)(6 + row * 126); } public void checkPlayerSquare(){ int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); //System.out.println("Casilla " + playerSquare[0] + " - " + playerSquare[1]); if (!(playerSquare[0] > 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] <= 9)) { if(playerSquare[0] <= 0){ /* Arriba */ if(player.isClimbing()){ System.out.println("arriba"); System.out.println("NEW ROOM : " + currentRoom.getRow() + " - " + (currentRoom.getCol() + 1)); Room newRoom = currentLevel.getRoom(currentRoom.getRow(), currentRoom.getCol() + 1); Entity actualCorner = player.getCornerToClimb(); if(actualCorner == null){ actualCorner = player.getCornerToClimbDown(); } int yDistanceCorner = actualCorner.getCenter()[1] - player.getY(); List<Entity> entities = newRoom.getSquare(3, playerSquare[1]).getBackground(); for(Entity e : entities){ if(e.getTypeOfEntity().startsWith("Corner")){ System.out.println("found corner arriba"); player.setY(e.getCenter()[1] - yDistanceCorner); player.setCornerToClimbDown(null); player.setCornerToClimb(e); } } if(enemy != null){ enemy.setPlayer(false, player); } currentRoom.deleteCharacter(player); enemy = (Enemy)newRoom.getGuard(); newRoom.addCharacter(player); if(enemy != null){ if(!enemy.isDead()){ enemy.setPlayer(true, player); if(player.hasSword()){ player.isEnemySaw(true); } } } currentRoom = newRoom; } } else if(playerSquare[0] > 3){ /* Abajo */ Room newRoom = currentLevel.getRoom(currentRoom.getRow() + 2, currentRoom.getCol() + 1); if(player.isClimbing()){ System.out.println("abajo"); Entity actualCorner = player.getCornerToClimbDown(); if(actualCorner == null){ actualCorner = player.getCornerToClimb(); } int yDistanceCorner = actualCorner.getCenter()[1] - player.getY(); List<Entity> entities = newRoom.getSquare(0, playerSquare[1]).getBackground(); for(Entity e : entities){ if(e.getTypeOfEntity().startsWith("Corner")){ System.out.println("found corner abajo"); player.setY(e.getCenter()[1] - yDistanceCorner); player.setCornerToClimb(null); player.setCanClimb(false); player.setCornerToClimbDown(e); player.setCanClimbDown(true); } } currentRoom.deleteCharacter(player); if(enemy != null){ enemy.setPlayer(false, player); } enemy = (Enemy)newRoom.getGuard(); newRoom.addCharacter(player); if(enemy != null){ if(!enemy.isDead()){ enemy.setPlayer(true, player); if(player.hasSword()){ player.isEnemySaw(true); } } } currentRoom = newRoom; } else{ currentRoom.deleteCharacter(player); newRoom.addCharacter(player); player.setY(40); currentRoom = newRoom; } } else if(playerSquare[1] < 0){ /* Izquierda */ currentRoom.deleteCharacter(player); Room newRoom = currentLevel.getRoom(currentRoom.getRow() + 1, currentRoom.getCol()); if(enemy != null){ enemy.setPlayer(false, player); } enemy = (Enemy)newRoom.getGuard(); newRoom.addCharacter(player); if(enemy != null){ if(!enemy.isDead()){ enemy.setPlayer(true, player); if(player.hasSword()){ player.isEnemySaw(true); } } } player.setX(620); currentRoom = newRoom; } else if(playerSquare[1] > 9){ /* Derecha */ currentRoom.deleteCharacter(player); Room newRoom = currentLevel.getRoom(currentRoom.getRow() + 1, currentRoom.getCol() + 2); if(enemy != null){ enemy.setPlayer(false, player); } enemy = (Enemy)newRoom.getGuard(); newRoom.addCharacter(player); if(enemy != null){ if(!enemy.isDead()){ enemy.setPlayer(true, player); if(player.hasSword()){ player.isEnemySaw(true); } } } player.setX(20); currentRoom = newRoom; } } } public void checkLoosesToShake(){ int row = player.getSquare()[0]; if(row < 4){ for(int i = 0; i < 10; i++){ List<Entity> bg = currentRoom.getSquare(row, i).getBackground(); for(Entity e : bg){ if(e.getTypeOfEntity().startsWith("LooseFloor")){ ((LooseFloor)e).justShakeItBaby(); } } } } } public boolean checkFloorSides(){ boolean isFloor = false; /* Comprobar que la ultima casilla de la hab izquierda tiene un suelo si estamos en la primera */ if(player.getSquare()[1] == 0 && player.getOrientation().equals("left")){ Room leftRoom = currentLevel.getRoom(currentRoom.getRow() + 1, currentRoom.getCol()); List<Entity> bg = leftRoom.getSquare(player.getSquare()[0],9).getBackground(); for(Entity e : bg){ System.out.println("BORDES"); String name = e.getTypeOfEntity(); if ( name.startsWith("FloorPanel_") || (name.startsWith("Pillar_") && !name.contains("shadow") && !name.contains("top")) || name.startsWith("Opener") || name.startsWith("Closer") || name.startsWith("SpikeFloor")){ isFloor = true; } } } else if(player.getSquare()[1] == 0 && player.getOrientation().equals("right")){ Room leftRoom = currentLevel.getRoom(currentRoom.getRow() + 1, currentRoom.getCol()); List<Entity> bg = leftRoom.getSquare(player.getSquare()[0],9).getBackground(); for(Entity e : bg){ System.out.println("BORDES"); String name = e.getTypeOfEntity(); if ( name.startsWith("FloorPanel_") || (name.startsWith("Pillar_") && !name.contains("shadow") && !name.contains("top")) || name.startsWith("Opener") || name.startsWith("Closer") || name.startsWith("SpikeFloor")){ isFloor = true; } } } else if(player.getSquare()[1] == 9 && player.getOrientation().equals("right")){ Room leftRoom = currentLevel.getRoom(currentRoom.getRow() + 1, currentRoom.getCol() + 2); List<Entity> bg = leftRoom.getSquare(player.getSquare()[0],9).getBackground(); for(Entity e : bg){ System.out.println("BORDES"); String name = e.getTypeOfEntity(); if ( name.startsWith("FloorPanel_") || (name.startsWith("Pillar_") && !name.contains("shadow") && !name.contains("top")) || name.startsWith("Opener") || name.startsWith("Closer") || name.startsWith("SpikeFloor")){ isFloor = true; } } } return isFloor; } /** * * @return true if there is a sword in front of the player * that he can pick */ private Entity checkSword() { Entity sword = null; int swordGap = 50; /* Obtains the square where the center point of the player is placed */ int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // Checks that the square is within the room if (playerSquare[0] >= 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] <= 9) { if (player.getOrientation().equals("left")) { /* Checks if there is a potion type object in current square */ List<Entity> bgEntities = new LinkedList<Entity>(); List<Entity> fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getForeground(); List<Entity> fEntities2; if (playerSquare[1] > 0) { fEntities2 = currentRoom.getSquare( playerSquare[0], playerSquare[1] - 1).getForeground(); bgEntities.addAll(fEntities2); } bgEntities.addAll(fEntities); // Searches for potion type objects for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); int[] ec = bgE.getCenter(); if ( name.startsWith("SwordFloor") && ec[0] < playerCenter[0] && (Math.abs(ec[0] - playerCenter[0]) < swordGap) ) { // player is close to the potion sword = bgE; } } } else if (player.getOrientation().equals("right")) { /* Checks if there is a potion type object in current square */ List<Entity> bgEntities = new LinkedList<Entity>(); List<Entity> fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getForeground(); List<Entity> fEntities2; if (playerSquare[1] < 9) { fEntities2 = currentRoom.getSquare( playerSquare[0], playerSquare[1] + 1).getForeground(); bgEntities.addAll(fEntities2); } bgEntities.addAll(fEntities); // Searches for potion type objects for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); int[] ec = bgE.getCenter(); if ( name.startsWith("Sword") && ec[0] > playerCenter[0] && (Math.abs(ec[0] - playerCenter[0]) < swordGap) ) { // player is close to the potion sword = bgE; } } } } return sword; } /** * * @return deletes the potion that the player is drinking */ private Entity deleteSword(Entity sword) { /* Obtains the square where the center point of the player is placed */ int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // Checks that the square is within the room if (playerSquare[0] >= 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] <= 9) { /* Checks if there is a potion type object in current square */ List<Entity> bgEntities = new LinkedList<Entity>(); Square currentSquare = currentRoom.getSquare( playerSquare[0], playerSquare[1]); List<Entity> fEntities = currentSquare.getForeground(); bgEntities.addAll(fEntities); /* Checks if there is a potion type object in left square */ List<Entity> bgEntitiesLeft = new LinkedList<Entity>(); Square currentSquareLeft = currentRoom.getSquare( playerSquare[0], playerSquare[1] - 1); List<Entity> fEntitiesLeft = currentSquareLeft.getForeground(); bgEntitiesLeft.addAll(fEntitiesLeft); /* Checks if there is a potion type object in right square */ List<Entity> bgEntitiesRight = new LinkedList<Entity>(); Square currentSquareRight = currentRoom.getSquare( playerSquare[0], playerSquare[1] + 1); List<Entity> fEntitiesRight = currentSquareRight.getForeground(); bgEntitiesRight.addAll(fEntitiesRight); if (player.getOrientation().equals("left")) { // Searches for potion type objects for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("SwordFloor")) { // player is close to the potion currentRoom.deleteEntityForeground(bgE, currentSquare); } } // Searches for potion type objects for (Entity bgE : bgEntitiesLeft) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("SwordFloor")) { // player is close to the potion currentRoom.deleteEntityForeground(bgE, currentSquareLeft); } } } else if (player.getOrientation().equals("right")) { // Searches for potion type objects for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("SwordFloor")) { // player is close to the potion currentRoom.deleteEntityForeground(sword, currentSquare); } } // Searches for potion type objects for (Entity bgE : bgEntitiesRight) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("SwordFloor")) { // player is close to the potion currentRoom.deleteEntityForeground(sword, currentSquareRight); } } } } return sword; } /** * * @return true if there is a potion in front of the player * that he can drink */ private Entity checkPotion() { Entity potion = null; int potionGap = 50; /* Obtains the square where the center point of the player is placed */ int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // Checks that the square is within the room if (playerSquare[0] >= 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] <= 9) { if (player.getOrientation().equals("left")) { /* Checks if there is a potion type object in current square */ List<Entity> bgEntities = new LinkedList<Entity>(); List<Entity> fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getForeground(); List<Entity> fEntities2; if (playerSquare[1] > 0) { fEntities2 = currentRoom.getSquare( playerSquare[0], playerSquare[1] - 1).getForeground(); bgEntities.addAll(fEntities2); } bgEntities.addAll(fEntities); // Searches for potion type objects for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); int[] ec = bgE.getCenter(); if ( name.startsWith("Potion_") && ec[0] < playerCenter[0] && (Math.abs(ec[0] - playerCenter[0]) < potionGap) ) { // player is close to the potion potion = bgE; } } } else if (player.getOrientation().equals("right")) { /* Checks if there is a potion type object in current square */ List<Entity> bgEntities = new LinkedList<Entity>(); List<Entity> fEntities = currentRoom.getSquare( playerSquare[0], playerSquare[1]).getForeground(); List<Entity> fEntities2; if (playerSquare[1] < 9) { fEntities2 = currentRoom.getSquare( playerSquare[0], playerSquare[1] + 1).getForeground(); bgEntities.addAll(fEntities2); } bgEntities.addAll(fEntities); // Searches for potion type objects for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); int[] ec = bgE.getCenter(); if ( name.startsWith("Potion_") && ec[0] > playerCenter[0] && (Math.abs(ec[0] - playerCenter[0]) < potionGap) ) { // player is close to the potion potion = bgE; } } } } return potion; } /** * * @return deletes the potion that the player is drinking */ private Entity deletePotion(Entity potion) { /* Obtains the square where the center point of the player is placed */ int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // Checks that the square is within the room if (playerSquare[0] >= 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] <= 9) { /* Checks if there is a potion type object in current square */ List<Entity> bgEntities = new LinkedList<Entity>(); Square currentSquare = currentRoom.getSquare( playerSquare[0], playerSquare[1]); List<Entity> fEntities = currentSquare.getForeground(); bgEntities.addAll(fEntities); /* Checks if there is a potion type object in left square */ List<Entity> bgEntitiesLeft = new LinkedList<Entity>(); Square currentSquareLeft = currentRoom.getSquare( playerSquare[0], playerSquare[1] - 1); List<Entity> fEntitiesLeft = currentSquareLeft.getForeground(); bgEntitiesLeft.addAll(fEntitiesLeft); /* Checks if there is a potion type object in right square */ List<Entity> bgEntitiesRight = new LinkedList<Entity>(); Square currentSquareRight = currentRoom.getSquare( playerSquare[0], playerSquare[1] + 1); List<Entity> fEntitiesRight = currentSquareRight.getForeground(); bgEntitiesRight.addAll(fEntitiesRight); if (player.getOrientation().equals("left")) { // Searches for potion type objects for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("Potion_")) { // player is close to the potion currentRoom.deleteEntityForeground(bgE, currentSquare); } } // Searches for potion type objects for (Entity bgE : bgEntitiesLeft) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("Potion_")) { // player is close to the potion currentRoom.deleteEntityForeground(bgE, currentSquareLeft); } } } else if (player.getOrientation().equals("right")) { // Searches for potion type objects for (Entity bgE : bgEntities) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("Potion_")) { // player is close to the potion currentRoom.deleteEntityForeground(potion, currentSquare); } } // Searches for potion type objects for (Entity bgE : bgEntitiesRight) { String name = bgE.getTypeOfEntity(); if ( name.startsWith("Potion_")) { // player is close to the potion currentRoom.deleteEntityForeground(potion, currentSquareRight); } } } } return potion; } public void checkPlayerFinnish(){ /* Obtains the square where the center point of the player is placed */ int[] playerCenter = player.getCenter(); int[] playerSquare = player.getSquare(playerCenter[0], playerCenter[1]); // Checks that the square is within the room if (playerSquare[0] >= 0 && playerSquare[1] >= 0 && playerSquare[0] <= 3 && playerSquare[1] <= 9) { /* Checks if there is a panel floor type object beneath the player */ Entity door = currentRoom.returnNamedEntityBackground("Door_final", currentRoom.getSquare(playerSquare[0], playerSquare[1])); if(door != null && ((Door)door).isOpenedFinal()){ player.finalDoorOpened(true, door.getXCentre() - 29, door.getY() + 30); } else{ player.finalDoorOpened(false, 0,0); } } } }
package Parser; import commandFactory.CommandType; import commonClasses.Constants; import commonClasses.SummaryReport; public class Parser { private ParsedResult result; private MainCommandInterpreter mainHandler; private OptionalCommandInterpreter optionHandler; public Parser() { mainHandler = new MainCommandInterpreter(); optionHandler = new OptionalCommandInterpreter(); } public ParsedResult parseString(String input) { result = new ParsedResult(); // Processing first command and getting command param try { String[] seperatedInput = input.split("-"); String commandWord = getCommandWord(seperatedInput[0]); mainHandler.identifyAndSetCommand(commandWord.toLowerCase()); if (commandDoesNotRequireParam(mainHandler.getCommand())) { result.setCommandType(mainHandler.getCommand()); return result; } String remainingInput = mainHandler.removeCommandWord(seperatedInput[0]); result = mainHandler.updateResults(result, remainingInput.trim()); // Processing optional commands processOptionalCommand(seperatedInput); if (result.getTaskDetails().getDueDate() == null) { result.getTaskDetails().setDueDate(Constants.SOMEDAY); } } catch (Exception e) { result.setValidationResult(false); } return result; } private void processOptionalCommand(String[] remainingInput) { String commandWord; for(int i=1; i<remainingInput.length;i++) { commandWord = getCommandWord(remainingInput[i]); optionHandler.identifyAndSetCommand(commandWord.toLowerCase()); remainingInput[i] = optionHandler.removeCommandWord(remainingInput[i]); result = optionHandler.updateResults(result, remainingInput[i].trim()); } } private static boolean commandDoesNotRequireParam(CommandType command) { if (command == CommandType.UNDO) return true; return false; } private static String getCommandWord(String input) { String[] splittedCommand = input.split(" "); return splittedCommand[0]; } }
package DisorientedArt.SlackBot; import java.io.IOException; import java.net.UnknownHostException; import java.time.LocalTime; import Slack.Messages; import Ulitity.APICalls; public class App { public static void main( String[] args ) throws IOException, InterruptedException { String userInput = args[1]; //Sets the token from external file of userToken.txt SlackInfo.setToken(SlackInfo.externalToken()); printTime(); switch(userInput) { case "active": System.out.println("Active settings started"); break; case "inactive": System.out.println("Deactivating the Raspberry Pi"); break; } APICalls.apiTest(); APICalls.authTest(); do{ try { APICalls.channelHistory(); } catch (UnknownHostException LostConection){ System.out.println("Connection was lost from the Pi"); } catch (Exception e) { //TODO Auto-generated catch block e.printStackTrace(); break; } Thread.sleep(2000); }while(LocalTime.now().isBefore(LocalTime.of(18, 00))); // switch (args[0].toString()) // case "active": // try { // APICalls.channelHistory(); // } catch (Exception e) { // //TODO Auto-generated catch block // e.printStackTrace(); // break; // Thread.sleep(2000); // }while(LocalTime.now().isBefore(LocalTime.of(23, 50))); // break; // case "delete": // SlackInfo.setDeleteMessage(""); // APICalls.removeMessage(); // break; // case "test": // //Runs the code throughout a typical work day // APICalls.apiTest(); // APICalls.authTest(); // APICalls.setActiveUser(); // APICalls.giphyMessage(Messages.randomAdjective()); // break; // default: // try { // APICalls.channelHistory(); // } catch (Exception e) { // //TODO Auto-generated catch block // e.printStackTrace(); // break; // Thread.sleep(2000); // }while(LocalTime.now().isBefore(LocalTime.of(18, 00))); // break; // printTime(); } public static void printTime(){ System.out.println(LocalTime.now()); } }
package HxCKDMS.HxCConfig; import HxCKDMS.HxCConfig.Exceptions.InvalidConfigClassException; import HxCKDMS.HxCConfig.Handlers.AdvancedHandlers; import HxCKDMS.HxCConfig.Handlers.BasicHandlers; import HxCKDMS.HxCUtils.LogHelper; import HxCKDMS.HxCUtils.StringHelper; import java.io.*; import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; @SuppressWarnings({"WeakerAccess", "unused"}) public class HxCConfig { private Class<?> configClass; private HashMap<String, HashMap<String, HashMap<String, String>>> configDataWatcherTest = new HashMap<>(); private File configFile, dataWatcherFile, configDirectory, dataWatcherDirectory; private LinkedHashMap<String, LinkedHashMap<String, Object>> configWritingData = new LinkedHashMap<>(); private static HashMap<Class<?>, AbstractTypeHandler> TypeHandlers = new HashMap<>(); private HashMap<String, String> CategoryComments = new HashMap<>(); private HashMap<String, HashMap<String, String>> valueComments = new HashMap<>(); private String app_name; static { //Basic types registerTypeHandler(new BasicHandlers.StringHandler()); registerTypeHandler(new BasicHandlers.IntegerHandler()); registerTypeHandler(new BasicHandlers.DoubleHandler()); registerTypeHandler(new BasicHandlers.CharacterHandler()); registerTypeHandler(new BasicHandlers.FloatHandler()); registerTypeHandler(new BasicHandlers.LongHandler()); registerTypeHandler(new BasicHandlers.ShortHandler()); registerTypeHandler(new BasicHandlers.ByteHandler()); registerTypeHandler(new BasicHandlers.BooleanHandler()); //Lists registerTypeHandler(new AdvancedHandlers.ListHandler()); registerTypeHandler(new AdvancedHandlers.ArrayListHandler()); registerTypeHandler(new AdvancedHandlers.LinkedListHandler()); //Maps registerTypeHandler(new AdvancedHandlers.MapHandler()); registerTypeHandler(new AdvancedHandlers.HashMapHandler()); registerTypeHandler(new AdvancedHandlers.LinkedHashMapHandler()); } public static void registerTypeHandler(AbstractTypeHandler typeHandler) { Arrays.stream(typeHandler.getTypes()).forEach(clazz -> TypeHandlers.putIfAbsent(clazz, typeHandler)); } public void setCategoryComment(String category, String comment) { CategoryComments.put(category, comment); } public HxCConfig(Class<?> clazz, String configName, File configDirectory, String extension, String app_name) { this.configClass = clazz; this.configFile = new File(configDirectory, configName + "." + extension); this.configDirectory = configDirectory; this.dataWatcherDirectory = new File(configDirectory + "/.datawatcher/"); this.dataWatcherFile = new File(dataWatcherDirectory, configName + ".dat"); this.app_name = app_name; setCategoryComment("Default", "This is the default category."); } @SuppressWarnings("ResultOfMethodCallIgnored") public void initConfiguration() { configWritingData.clear(); try { configDirectory.mkdirs(); if(!configFile.exists()) configFile.createNewFile(); dataWatcherDirectory.mkdirs(); if(!dataWatcherFile.exists()) dataWatcherFile.createNewFile(); Path path = dataWatcherDirectory.toPath(); Files.setAttribute(path, "dos:hidden", true); deSerialize(); read(); write(); } catch (Exception e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") public void deSerialize() { try { ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(dataWatcherFile)); configDataWatcherTest = (HashMap<String, HashMap<String, HashMap<String, String>>>) inputStream.readObject(); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } private void read() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(configFile), "UTF-8")); String line; String category = ""; while ((line = reader.readLine()) != null) { if (line.trim().startsWith("#")) continue; boolean firstIteration = true; line = line.replaceFirst(" ", "\t"); char[] characters = line.toCharArray(); StringBuilder nameBuilder = new StringBuilder(); if (line.endsWith("{")) { StringBuilder categoryBuilder = new StringBuilder(); for (int i = 0; i < characters.length; i++) { if (i == 0) continue; if (characters[i] == '{' && characters[i-1] == ' ') break; categoryBuilder.append(characters[i-1]); } if (categoryBuilder.length() != 0) category = categoryBuilder.toString(); } for (char character : characters) { if (firstIteration && character == '\t') { firstIteration = false; continue; } else if (firstIteration) break; if (character == '\t' || character == '=' || character == ']') break; nameBuilder.append(character); firstIteration = false; } if (nameBuilder.length() == 0) continue; String variableName = nameBuilder.toString(); try { Class<?> type = Class.forName(configDataWatcherTest.get(category).get(variableName).get("Type")); TypeHandlers.get(type).read(variableName, configDataWatcherTest.get(category).get(variableName), line, reader, configClass); } catch (ClassNotFoundException | IllegalAccessException | NoSuchFieldException e) { e.printStackTrace(); } } reader.close(); } private void serialize() { try { ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(dataWatcherFile)); outputStream.writeObject(configDataWatcherTest); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } private void write() throws IOException { if (!configClass.isAnnotationPresent(Config.class)) throw new InvalidConfigClassException(configClass.getCanonicalName(), "Class doesn't have @Config annotation."); Arrays.stream(configClass.getDeclaredFields()).filter(field -> !field.isAnnotationPresent(Config.ignore.class)).forEachOrdered(this::handleFieldWriting); Arrays.stream(configClass.getDeclaredClasses()).filter(clazz -> !clazz.isAnnotationPresent(Config.ignore.class)).forEachOrdered(this::handleClass); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(configFile), "UTF-8")); StringBuilder stringBuilder = new StringBuilder(); for (Map.Entry<String, LinkedHashMap<String, Object>> entry : configWritingData.entrySet()) { stringBuilder.append(StringHelper.repeat('#', 106)).append('\n'); stringBuilder.append('#').append(' ').append(entry.getKey()).append('\n'); stringBuilder.append(StringHelper.repeat('#', 106)).append('\n'); if (CategoryComments.containsKey(entry.getKey())) { stringBuilder.append('#').append(' ').append(CategoryComments.get(entry.getKey())).append('\n'); stringBuilder.append(StringHelper.repeat('#', 106)).append("\n"); } stringBuilder.append('\n'); stringBuilder.append(entry.getKey()).append(" {\n"); for (Map.Entry<String, Object> entry2 : entry.getValue().entrySet()) { if (valueComments.containsKey(entry.getKey()) && valueComments.get(entry.getKey()).containsKey(entry2.getKey())) stringBuilder.append('\t').append('#').append(' ').append(valueComments.get(entry.getKey()).get(entry2.getKey())).append('\n'); stringBuilder.append('\t').append(entry2.getKey()).append('=').append(entry2.getValue()).append("\n\n"); } stringBuilder.deleteCharAt(stringBuilder.length() - 1); stringBuilder.append("}\n\n"); } writer.write(stringBuilder.toString().trim()); writer.close(); serialize(); } private void handleClass(Class clazz) { } private void handleFieldWriting(Field field) { if (TypeHandlers.containsKey(field.getType())) try { HashMap<String, String> data = new HashMap<>(); String categoryName = field.isAnnotationPresent(Config.category.class) ? field.getAnnotation(Config.category.class).value() : "General"; HashMap<String, HashMap<String, String>> category = configDataWatcherTest.getOrDefault(categoryName, new HashMap<>()); TypeHandlers.get(field.getType()).write(field, configWritingData, data); category.put(field.getName(), data); configDataWatcherTest.put(categoryName, category); HashMap<String, String> comment = valueComments.getOrDefault(categoryName, new HashMap<>()); if(field.isAnnotationPresent(Config.comment.class)) comment.put(field.getName(), field.getAnnotation(Config.comment.class).value()); valueComments.put(categoryName, comment); } catch (IllegalAccessException e) { e.printStackTrace(); } else LogHelper.severe(String.format("Configuration type: %1$s is unsupported!", field.getType().getCanonicalName()), app_name); } }
package VASSAL.launch; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.RandomAccessFile; import java.lang.reflect.InvocationTargetException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import javax.swing.JFrame; import javax.swing.JMenuBar; import javax.swing.SwingUtilities; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.SystemUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import VASSAL.Info; import VASSAL.build.module.metadata.AbstractMetaData; import VASSAL.build.module.metadata.MetaDataFactory; import VASSAL.build.module.metadata.SaveMetaData; import VASSAL.configure.IntConfigurer; import VASSAL.configure.LongConfigurer; import VASSAL.i18n.Resources; import VASSAL.i18n.TranslateVassalWindow; import VASSAL.preferences.Prefs; import VASSAL.tools.ErrorDialog; import VASSAL.tools.ThrowableUtils; import VASSAL.tools.io.IOUtils; import VASSAL.tools.io.ZipArchive; import VASSAL.tools.logging.LoggedOutputStream; import VASSAL.tools.menu.MacOSXMenuManager; import VASSAL.tools.menu.MenuBarProxy; import VASSAL.tools.menu.MenuManager; /** * Tracks recently-used modules and builds the main GUI window for * interacting with modules. * * @author rodneykinney * @since 3.1.0 */ public class ModuleManager { private static final Logger logger = LoggerFactory.getLogger(ModuleManager.class); private static final String NEXT_VERSION_CHECK = "nextVersionCheck"; public static final String MAXIMUM_HEAP = "maximumHeap"; //$NON-NLS-1$ public static final String INITIAL_HEAP = "initialHeap"; //$NON-NLS-1$ public static void main(String[] args) { // FIXME: We need to catch more exceptions in main() and then exit in // order to avoid situations where the main thread ends due to an uncaught // exception, but there are other threads still running, and so VASSAL // is thrown here... // parse command-line arguments LaunchRequest lr = null; try { lr = LaunchRequest.parseArgs(args); } catch (LaunchRequestException e) { // FIXME: should be a dialog... System.err.println("VASSAL: " + e.getMessage()); System.exit(1); } // do this before the graphics subsystem fires up or it won't stick System.setProperty("swing.boldMetal", "false"); if (lr.mode == LaunchRequest.Mode.TRANSLATE) { // show the translation window in translation mode SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // FIXME: does this window exit on close? new TranslateVassalWindow(null).setVisible(true); } }); return; } // How we start exactly one request server: // To ensure that exactly one process acts as the request server, we // acquire a lock on the ~/VASSAL/key file, and then attempt to acquire // a lock on the ~/VASSAL/lock file. If we cannot lock ~/VASSAL/lock, // then there is already a server running; in that case, we read the // port number and security key from ~/VASSAL/key. If we can lock // ~/VASSAL/lock, then we start the server, write the port number and // key to ~/VASSAL/key, and continue to hold the lock on ~/VASSAL/lock. // Finally, we unlock ~/VASSAL/key and proceed to act as a client, // sending requests over localhost:port using the security key. // The advantages of this method are: // (1) No race conditions between processes started at the same time. // (2) No port collisions, because we don't use a predetermined port. final File keyfile = new File(Info.getConfDir(), "key"); final File lockfile = new File(Info.getConfDir(), "lock"); int port = 0; long key = 0; FileLock klock = null; try (RandomAccessFile kraf = new RandomAccessFile(keyfile, "rw")) { // acquire an exclusive lock on the key file try { klock = kraf.getChannel().lock(); } catch (OverlappingFileLockException e) { throw new IOException(e); } // determine whether we are the server or a client // Note: We purposely keep lout open in the case where we are the // server, because closing lout will release the lock. FileLock lock = null; final FileOutputStream lout = new FileOutputStream(lockfile); try { lock = lout.getChannel().tryLock(); } catch (OverlappingFileLockException e) { throw new IOException(e); } if (lock != null) { // we have the lock, so we will be the request server // bind to an available port on the loopback device final ServerSocket serverSocket = new ServerSocket(0, 0, InetAddress.getByName(null)); // write the port number where we listen to the key file port = serverSocket.getLocalPort(); kraf.writeInt(port); // create new security key and write it to the key file key = (long) (Math.random() * Long.MAX_VALUE); kraf.writeLong(key); // create a new Module Manager new ModuleManager(serverSocket, key, lout, lock); } else { // we do not have the lock, so we will be a request client lout.close(); // read the port number we will connect to from the key file port = kraf.readInt(); // read the security key from the key file key = kraf.readLong(); } } catch (IOException e) { // FIXME: should be a dialog... System.err.println("VASSAL: IO error"); e.printStackTrace(); System.exit(1); } // lock on the key file is released lr.key = key; // pass launch parameters on to the ModuleManager via the socket try (Socket clientSocket = new Socket((String) null, port); ObjectOutputStream out = new ObjectOutputStream( new BufferedOutputStream(clientSocket.getOutputStream()))) { out.writeObject(lr); out.flush(); try (InputStream in = clientSocket.getInputStream()) { IOUtils.copy(in, System.err); } } catch (UnknownHostException e) { logger.error("Unable to open socket for loopback device", e); System.exit(1); } catch (IOException e) { // FIXME: should be a dialog... logger.error("VASSAL: Problem with socket on port {}", port, e); System.exit(1); } } private static ModuleManager instance = null; public static ModuleManager getInstance() { return instance; } private final long key; private FileOutputStream lout; private FileLock lock; private final ServerSocket serverSocket; public ModuleManager(ServerSocket serverSocket, long key, FileOutputStream lout, FileLock lock) throws IOException { if (instance != null) throw new IllegalStateException(); instance = this; this.serverSocket = serverSocket; this.key = key; // we hang on to these to prevent the lock from being lost this.lout = lout; this.lock = lock; // truncate the errorLog final File errorLog = new File(Info.getHomeDir(), "errorLog"); new FileOutputStream(errorLog).close(); final StartUp start = SystemUtils.IS_OS_MAC_OSX ? new ModuleManagerMacOSXStartUp() : new StartUp(); start.startErrorLog(); // log everything which comes across our stderr System.setErr(new PrintStream(new LoggedOutputStream(), true)); Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler()); start.initSystemProperties(); // try to migrate old preferences if there are no current ones final File pdir = Info.getPrefsDir(); if (!pdir.exists()) { // Check the 3.2.0 through 3.2.7 location File pzip = new File(Info.getHomeDir(), "Preferences"); if (!pzip.exists()) { // Check the pre-3.2 location. pzip = new File(System.getProperty("user.home"), "VASSAL/Preferences"); } if (pzip.exists()) { FileUtils.forceMkdir(pdir); final byte[] buf = new byte[4096]; try { try (ZipArchive za = new ZipArchive(pzip)) { for (String f : za.getFiles()) { final File ofile = new File( pdir, "VASSAL".equals(f) ? "V_Global" : Prefs.sanitize(f) ); try (InputStream in = za.getInputStream(f); OutputStream out = new FileOutputStream(ofile)) { IOUtils.copy(in, out, buf); } } } } catch (IOException e) { logger.error("Failed to convert legacy preferences file.", e); } } } if (SystemUtils.IS_OS_MAC_OSX) new MacOSXMenuManager(); else new ModuleManagerMenuManager(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { launch(); } }); // ModuleManagerWindow.getInstance() != null now, so listen on the socket final Thread socketListener = new Thread( new SocketListener(serverSocket), "socket listener"); socketListener.setDaemon(true); socketListener.start(); final Prefs globalPrefs = Prefs.getGlobalPrefs(); // determine when we should next check on the current version of VASSAL final LongConfigurer nextVersionCheckConfig = new LongConfigurer(NEXT_VERSION_CHECK, null, -1L); globalPrefs.addOption(null, nextVersionCheckConfig); long nextVersionCheck = nextVersionCheckConfig.getLongValue(-1L); if (nextVersionCheck < System.currentTimeMillis()) { new UpdateCheckRequest().execute(); } // set the time for the next version check if (nextVersionCheck == -1L) { // this was our first check; randomly check after 0-10 days to // to spread version checks evenly over a 10-day period nextVersionCheck = System.currentTimeMillis() + (long) (Math.random() * 10 * 86400000); } else { // check again in 10 days nextVersionCheck += 10 * 86400000; } nextVersionCheckConfig.setValue(nextVersionCheck); // FIXME: the importer heap size configurers don't belong here // the initial heap size for the module importer final IntConfigurer initHeapConf = new IntConfigurer( INITIAL_HEAP, Resources.getString("GlobalOptions.initial_heap"), //$NON-NLS-1$ 256 ); globalPrefs.addOption("Importer", initHeapConf); // the maximum heap size for the module importer final IntConfigurer maxHeapConf = new IntConfigurer( MAXIMUM_HEAP, Resources.getString("GlobalOptions.maximum_heap"), //$NON-NLS-1$ 512 ); globalPrefs.addOption("Importer", maxHeapConf); } public void shutDown() throws IOException { lock.release(); lout.close(); } private class SocketListener implements Runnable { private final ServerSocket serverSocket; public SocketListener(ServerSocket serverSocket) { this.serverSocket = serverSocket; } @Override public void run() { try { Socket clientSocket = null; // TODO while can only complete by throwing, do not use exceptions for ordinary control flow while (true) { try { clientSocket = serverSocket.accept(); final String message; try (ObjectInputStream in = new ObjectInputStream( new BufferedInputStream(clientSocket.getInputStream()))) { message = execute(in.readObject()); } clientSocket.close(); if (message == null || clientSocket.isClosed()) continue; try (PrintStream out = new PrintStream( new BufferedOutputStream(clientSocket.getOutputStream()))) { out.println(message); } } catch (IOException e) { ErrorDialog.showDetails( e, ThrowableUtils.getStackTrace(e), "Error.socket_error" ); } catch (ClassNotFoundException e) { ErrorDialog.bug(e); } finally { if (clientSocket != null) { try { clientSocket.close(); } catch (IOException e) { logger.error("Error while closing client socket", e); } } } } } finally { if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { logger.error("Error while closing server socket", e); } } } } } protected void launch() { logger.info("Manager"); final ModuleManagerWindow window = ModuleManagerWindow.getInstance(); window.setVisible(true); final boolean isFirstTime = !Info.getPrefsDir().exists(); if (isFirstTime) new FirstTimeDialog(window).setVisible(true); } protected String execute(Object req) { if (req instanceof LaunchRequest) { final LaunchRequest lr = (LaunchRequest) req; if (lr.key != key) { // FIXME: translate return "incorrect key"; } final LaunchRequestHandler handler = new LaunchRequestHandler(lr); try { SwingUtilities.invokeAndWait(handler); } catch (InterruptedException e) { return "interrupted"; // FIXME } catch (InvocationTargetException e) { ErrorDialog.bug(e); return null; } return handler.getResult(); } else { return "unrecognized command"; // FIXME } } private static class LaunchRequestHandler implements Runnable { private final LaunchRequest lr; private String result; public LaunchRequestHandler(LaunchRequest lr) { this.lr = lr; } @Override public void run() { result = handle(); } public String getResult() { return result; } private String handle() { final ModuleManagerWindow window = ModuleManagerWindow.getInstance(); switch (lr.mode) { case MANAGE: window.toFront(); break; case LOAD: if (Player.LaunchAction.isEditing(lr.module)) return "module open for editing"; // FIXME if (lr.module == null && lr.game != null) { // attempt to find the module for the saved game or log final AbstractMetaData data = MetaDataFactory.buildMetaData(lr.game); if (data instanceof SaveMetaData) { // we found save metadata final String moduleName = ((SaveMetaData) data).getModuleName(); if (moduleName != null && moduleName.length() > 0) { // get the module file by module name lr.module = window.getModuleByName(moduleName); } else { // this is a pre 3.1 save file, can't tell the module name // FIXME: show some error here return "cannot find module"; } } } if (lr.module == null) { return "cannot find module"; // FIXME: show some error here } else if (lr.game == null) { new Player.LaunchAction(window, lr.module).actionPerformed(null); } else { new Player.LaunchAction( window, lr.module, lr.game).actionPerformed(null); } break; case EDIT: if (Editor.LaunchAction.isInUse(lr.module)) return "module open for play"; // FIXME if (Editor.LaunchAction.isEditing(lr.module)) return "module open for editing"; // FIXME new Editor.LaunchAction(window, lr.module).actionPerformed(null); break; case IMPORT: new Editor.ImportLaunchAction( window, lr.importFile).actionPerformed(null); break; case NEW: new Editor.NewModuleLaunchAction(window).actionPerformed(null); break; case EDIT_EXT: return "not yet implemented"; // FIXME case NEW_EXT: return "not yet implemented"; // FIXME default: return "unrecognized mode"; // FIXME } return null; } } private static class ModuleManagerMenuManager extends MenuManager { private final MenuBarProxy menuBar = new MenuBarProxy(); @Override public JMenuBar getMenuBarFor(JFrame fc) { return (fc instanceof ModuleManagerWindow) ? menuBar.createPeer() : null; } @Override public MenuBarProxy getMenuBarProxyFor(JFrame fc) { return (fc instanceof ModuleManagerWindow) ? menuBar : null; } } }
package cloud.swiftnode.kspam; import cloud.swiftnode.kspam.abstraction.processor.CacheInitProcessor; import cloud.swiftnode.kspam.abstraction.processor.CacheSaveProcessor; import cloud.swiftnode.kspam.abstraction.processor.InjectionProcessor; import cloud.swiftnode.kspam.abstraction.processor.MetricsInitProcessor; import cloud.swiftnode.kspam.abstraction.processor.UpdateCheckProcessor; import cloud.swiftnode.kspam.abstraction.processor.VirusScanProcessor; import cloud.swiftnode.kspam.command.Commands; import cloud.swiftnode.kspam.listener.PlayerListener; import cloud.swiftnode.kspam.listener.ServerListener; import cloud.swiftnode.kspam.util.Config; import cloud.swiftnode.kspam.util.Lang; import cloud.swiftnode.kspam.util.Static; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; public class KSpam extends JavaPlugin { public static Plugin INSTANCE; @Override public void onLoad() { new InjectionProcessor().process(); } @Override public void onEnable() { INSTANCE = this; Bukkit.getPluginManager().registerEvents(new PlayerListener(), this); Bukkit.getPluginManager().registerEvents(new ServerListener(), this); saveDefaultConfig(); new CacheInitProcessor().process(); new MetricsInitProcessor().process(); Static.runTaskTimerAsync(() -> new UpdateCheckProcessor().process(),0, Config.updateCheckPeriod() * 3600 * 20); getCommand("kspam").setExecutor(new Commands()); Static.runTaskLaterAsync(() -> new VirusScanProcessor().process(), 20); Static.consoleMsg(Lang.INTRO.builder() .single(Lang.Key.KSPAM_VERSION, Static.getVersion()).build(false)); } @Override public void onDisable() { saveConfig(); new CacheSaveProcessor().process(); } }
package com.cqs.nio; import com.google.common.base.Stopwatch; import org.apache.commons.io.IOUtils; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.concurrent.TimeUnit; public class FileChannelDemo { public static void sendFile(OutputStream os, RandomAccessFile raFile) throws IOException { FileChannel channel = raFile.getChannel(); final int SIZE = 1024 * 1024; ByteBuffer buffer = ByteBuffer.allocate(SIZE); byte[] bytes = new byte[SIZE]; int length; while ((length = channel.read(buffer)) != -1) { buffer.flip(); while (buffer.hasRemaining()) { buffer.get(bytes, 0, length); os.write(bytes); } buffer.clear(); } os.flush(); IOUtils.closeQuietly(channel); } public static void main(String[] args) throws IOException { Stopwatch stopwatch = Stopwatch.createStarted();ffff RandomAccessFile source = new RandomAccessFile("/home/cqs/Documents//[].01...avi", "r"); OutputStream os = new FileOutputStream(new File("01...avi")); sendFile(os, source); stopwatch.stop(); System.out.println(stopwatch.elapsed(TimeUnit.MILLISECONDS)); } }
package com.box.sdk; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.box.sdk.http.HttpMethod; import com.eclipsesource.json.JsonObject; /** * Utility class for uploading large files. */ public final class LargeFileUpload { private static final String DIGEST_HEADER_PREFIX_SHA = "sha="; private static final String DIGEST_ALGORITHM_SHA1 = "SHA1"; private static final String MARKER_QUERY_STRING = "marker"; private static final String LIMIT_QUERY_STRING = "limit"; private static final int DEFAULT_CONNECTIONS = 3; private static final int DEFAULT_TIMEOUT = 1; private static final TimeUnit DEFAULT_TIMEUNIT = TimeUnit.HOURS; private ThreadPoolExecutor executorService; private long timeout; private TimeUnit timeUnit; private int connections; /** * Creates a LargeFileUpload object. * @param nParallelConnections number of parallel http connections to use * @param timeOut time to wait before killing the job * @param unit time unit for the time wait value */ public LargeFileUpload(int nParallelConnections, long timeOut, TimeUnit unit) { this.executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(nParallelConnections); this.timeout = timeOut; this.timeUnit = unit; } /** * Creates a LargeFileUpload object with a default number of parallel conections and timeout. */ public LargeFileUpload() { this.executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(this.DEFAULT_CONNECTIONS); this.timeout = this.DEFAULT_TIMEOUT; this.timeUnit = this.DEFAULT_TIMEUNIT; } private BoxFileUploadSession.Info createUploadSession(BoxAPIConnection boxApi, String folderId, URL url, String fileName, long fileSize) { BoxJSONRequest request = new BoxJSONRequest(boxApi, url, HttpMethod.POST); //Create the JSON body of the request JsonObject body = new JsonObject(); body.add("folder_id", folderId); body.add("file_name", fileName); body.add("file_size", fileSize); request.setBody(body.toString()); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); String sessionId = jsonObject.get("id").asString(); BoxFileUploadSession session = new BoxFileUploadSession(boxApi, sessionId); return session.new Info(jsonObject); } /** * Uploads a new large file. * @param boxApi the API connection to be used by the upload session. * @param folderId the id of the folder in which the file will be uploaded. * @param stream the input stream that feeds the content of the file. * @param url the upload session URL. * @param fileName the name of the file to be created. * @param fileSize the total size of the file. * @return the created file instance. * @throws InterruptedException when a thread gets interupted. * @throws IOException when reading a stream throws exception. */ public BoxFile.Info upload(BoxAPIConnection boxApi, String folderId, InputStream stream, URL url, String fileName, long fileSize) throws InterruptedException, IOException { //Create a upload session BoxFileUploadSession.Info session = this.createUploadSession(boxApi, folderId, url, fileName, fileSize); return this.uploadHelper(session, stream, fileSize); } /** * Creates a new version of a large file. * @param boxApi the API connection to be used by the upload session. * @param stream the input stream that feeds the content of the file. * @param url the upload session URL. * @param fileSize the total size of the file. * @return the file instance that also contains the version information. * @throws InterruptedException when a thread gets interupted. * @throws IOException when reading a stream throws exception. */ public BoxFile.Info upload(BoxAPIConnection boxApi, InputStream stream, URL url, long fileSize) throws InterruptedException, IOException { //creates a upload session BoxFileUploadSession.Info session = this.createUploadSession(boxApi, url, fileSize); return this.uploadHelper(session, stream, fileSize); } private BoxFile.Info uploadHelper(BoxFileUploadSession.Info session, InputStream stream, long fileSize) throws InterruptedException, IOException { //Upload parts using the upload session MessageDigest digest = null; try { digest = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1); } catch (NoSuchAlgorithmException ae) { throw new BoxAPIException("Digest algorithm not found", ae); } DigestInputStream dis = new DigestInputStream(stream, digest); List<BoxFileUploadSessionPart> parts = this.uploadParts(session, dis, fileSize); //Creates the file hash byte[] digestBytes = digest.digest(); String digestStr = Base64.encode(digestBytes); //Commit the upload session. If there is a failure, abort the commit. try { return session.getResource().commit(digestStr, parts, null, null, null); } catch (Exception e) { session.getResource().abort(); throw new BoxAPIException("Unable to commit the upload session", e); } } private BoxFileUploadSession.Info createUploadSession(BoxAPIConnection boxApi, URL url, long fileSize) { BoxJSONRequest request = new BoxJSONRequest(boxApi, url, HttpMethod.POST); //Creates the body of the request JsonObject body = new JsonObject(); body.add("file_size", fileSize); request.setBody(body.toString()); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); String sessionId = jsonObject.get("id").asString(); BoxFileUploadSession session = new BoxFileUploadSession(boxApi, sessionId); return session.new Info(jsonObject); } /* * Upload parts of the file. The part size is retrieved from the upload session. */ private List<BoxFileUploadSessionPart> uploadParts(BoxFileUploadSession.Info session, InputStream stream, long fileSize) throws InterruptedException { List<BoxFileUploadSessionPart> parts = new ArrayList<BoxFileUploadSessionPart>(); int partSize = session.getPartSize(); long offset = 0; int processed = 0; int partPostion = 0; while (processed < fileSize) { //Waiting for any thread to finish before long timeoutForWaitingInMillis = TimeUnit.MILLISECONDS.convert(this.timeout, this.timeUnit); if (this.executorService.getCorePoolSize() == this.executorService.getActiveCount()) { if (timeoutForWaitingInMillis > 0) { Thread.sleep(1000); timeoutForWaitingInMillis -= 1000; } else { throw new BoxAPIException("Upload parts timedout"); } } long diff = fileSize - (long) processed; //The size last part of the file can be lesser than the part size. if (diff < (long) partSize) { partSize = (int) diff; } parts.add(null); byte[] bytes = new byte[partSize]; try { int readStatus = stream.read(bytes); if (readStatus == -1) { throw new BoxAPIException("Stream ended while upload was progressing"); } } catch (IOException ioe) { throw new BoxAPIException("Reading data from stream failed.", ioe); } this.executorService.execute( new LargeFileUploadTask(session.getResource(), bytes, offset, partSize, fileSize, parts, partPostion) ); //Increase the offset and proceesed bytes to calculate the Content-Range header. processed += partSize; offset += partSize; partPostion++; } this.executorService.shutdown(); this.executorService.awaitTermination(this.timeout, this.timeUnit); return parts; } /** * Generates the Base64 encoded SHA-1 hash for content available in the stream. * It can be used to calculate the hash of a file. * @param stream the input stream of the file or data. * @return the Base64 encoded hash string. */ public String generateDigest(InputStream stream) { MessageDigest digest = null; try { digest = MessageDigest.getInstance(DIGEST_ALGORITHM_SHA1); } catch (NoSuchAlgorithmException ae) { throw new BoxAPIException("Digest algorithm not found", ae); } //Calcuate the digest using the stream. DigestInputStream dis = new DigestInputStream(stream, digest); try { int value = dis.read(); while (value != -1) { value = dis.read(); } } catch (IOException ioe) { throw new BoxAPIException("Reading the stream failed.", ioe); } //Get the calculated digest for the stream byte[] digestBytes = digest.digest(); return Base64.encode(digestBytes); } }
package com.conveyal.gtfs; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.S3Object; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.io.ByteStreams; import com.google.common.io.Files; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.NoSuchElementException; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.function.Function; import java.util.zip.ZipFile; /** * Fast cache for GTFS feeds stored on S3. */ public class GTFSCache { private static final Logger LOG = LoggerFactory.getLogger(GTFSCache.class); public final String bucket; public final String bucketFolder; public final File cacheDir; private static final AmazonS3 s3 = new AmazonS3Client(); private LoadingCache<String, GTFSFeed> cache = CacheBuilder.newBuilder() .maximumSize(10) .build(new CacheLoader<String, GTFSFeed>() { @Override public GTFSFeed load(String s) throws Exception { return retrieveFeed(s); } }); /** If bucket is null, work offline and do not use S3 */ public GTFSCache(String bucket, File cacheDir) { if (bucket == null) LOG.info("No bucket specified; GTFS Cache will run locally"); else LOG.info("Using bucket {} for GTFS Cache", bucket); this.bucket = bucket; this.bucketFolder = null; this.cacheDir = cacheDir; } public GTFSCache(String bucket, String bucketFolder, File cacheDir) { if (bucket == null) LOG.info("No bucket specified; GTFS Cache will run locally"); else LOG.info("Using bucket {} for GTFS Cache", bucket); this.bucket = bucket; this.bucketFolder = bucketFolder != null ? bucketFolder.replaceAll("\\/","") : null; this.cacheDir = cacheDir; } /** * Add a GTFS feed to this cache with the given ID. NB this is not the feed ID, because feed IDs are not * unique when you load multiple versions of the same feed. */ public GTFSFeed put (String id, File feedFile) throws Exception { return put(id, feedFile, null); } /** Add a GTFS feed to this cache where the ID is calculated from the feed itself */ public GTFSFeed put (Function<GTFSFeed, String> idGenerator, File feedFile) throws Exception { return put(null, feedFile, idGenerator); } private GTFSFeed put (String id, File feedFile, Function<GTFSFeed, String> idGenerator) throws Exception { // generate temporary ID to name files String tempId = id != null ? id : UUID.randomUUID().toString(); // read the feed String cleanTempId = cleanId(tempId); File dbFile = new File(cacheDir, cleanTempId + ".db"); File movedFeedFile = new File(cacheDir, cleanTempId + ".zip"); // don't copy if we're loading from a locally-cached feed if (!feedFile.equals(movedFeedFile)) Files.copy(feedFile, movedFeedFile); GTFSFeed feed = new GTFSFeed(dbFile.getAbsolutePath()); feed.loadFromFile(new ZipFile(movedFeedFile)); feed.findPatterns(); if (idGenerator != null) id = idGenerator.apply(feed); String cleanId = cleanId(id); feed.close(); // make sure everything is written to disk if (idGenerator != null) { new File(cacheDir, cleanTempId + ".zip").renameTo(new File(cacheDir, cleanId + ".zip")); new File(cacheDir, cleanTempId + ".db").renameTo(new File(cacheDir, cleanId + ".db")); new File(cacheDir, cleanTempId + ".db.p").renameTo(new File(cacheDir, cleanId + ".db.p")); } // upload feed // TODO best way to do this? Should we zip the files together? if (bucket != null) { LOG.info("Writing feed to s3 cache"); String key = bucketFolder != null ? String.join("/", bucketFolder, cleanId) : cleanId; s3.putObject(bucket, key + ".zip", feedFile); LOG.info("Zip file written."); s3.putObject(bucket, key + ".db", new File(cacheDir, cleanId + ".db")); s3.putObject(bucket, key + ".db.p", new File(cacheDir, cleanId + ".db.p")); LOG.info("db files written."); } // reconnect to feed database feed = new GTFSFeed(new File(cacheDir, cleanId + ".db").getAbsolutePath()); cache.put(id, feed); return feed; } public GTFSFeed get (String id) { try { return cache.get(id); } catch (ExecutionException e) { throw new RuntimeException(e); } } public boolean containsId (String id) { GTFSFeed feed = null; try { feed = cache.get(id); } catch (Exception e) { return false; } return feed != null; } /** retrieve a feed from local cache or S3 */ private GTFSFeed retrieveFeed (String originalId) { // see if we have it cached locally String id = cleanId(originalId); String key = bucketFolder != null ? String.join("/", bucketFolder, id) : id; File dbFile = new File(cacheDir, id + ".db"); if (dbFile.exists()) { LOG.info("Processed GTFS was found cached locally"); try { return new GTFSFeed(dbFile.getAbsolutePath()); } catch (Exception e) { LOG.info("Error loading local MapDB.", e); } } if (bucket != null) { try { LOG.info("Attempting to download cached GTFS MapDB."); S3Object db = s3.getObject(bucket, key + ".db"); InputStream is = db.getObjectContent(); FileOutputStream fos = new FileOutputStream(dbFile); ByteStreams.copy(is, fos); is.close(); fos.close(); S3Object dbp = s3.getObject(bucket, key + ".db.p"); InputStream isp = dbp.getObjectContent(); FileOutputStream fosp = new FileOutputStream(new File(cacheDir, id + ".db.p")); ByteStreams.copy(isp, fosp); isp.close(); fosp.close(); LOG.info("Returning processed GTFS from S3"); return new GTFSFeed(dbFile.getAbsolutePath()); } catch (AmazonServiceException | IOException e) { LOG.info("Error retrieving MapDB from S3, will load from original GTFS.", e); } } // see if the // if we fell through to here, getting the mapdb was unsuccessful // grab GTFS from S3 if it is not found locally LOG.info("Loading feed from local cache directory..."); File feedFile = new File(cacheDir, id + ".zip"); if (!feedFile.exists() && bucket != null) { LOG.info("Feed not found locally, downloading from S3."); try { S3Object gtfs = s3.getObject(bucket, key + ".zip"); InputStream is = gtfs.getObjectContent(); FileOutputStream fos = new FileOutputStream(feedFile); ByteStreams.copy(is, fos); is.close(); fos.close(); } catch (Exception e) { LOG.warn("Could not download feed at s3://{}/{}.", bucket, key); throw new RuntimeException(e); } } if (feedFile.exists()) { // TODO this will also re-upload the original feed ZIP to S3. try { return put(originalId, feedFile); } catch (Exception e) { throw new RuntimeException(e); } } else { throw new NoSuchElementException(originalId); } } public static String cleanId(String id) { return id.replaceAll("[^A-Za-z0-9]", "-"); } }
package ui; import com.jme3.light.DirectionalLight; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.FastMath; import com.jme3.math.Quaternion; import com.jme3.math.Vector3f; import com.jme3.post.FilterPostProcessor; import com.jme3.renderer.queue.RenderQueue; import com.jme3.scene.Geometry; import com.jme3.scene.Mesh; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.scene.shape.Box; import com.jme3.scene.shape.Quad; import com.jme3.shadow.DirectionalLightShadowFilter; import com.jme3.shadow.DirectionalLightShadowRenderer; import com.jme3.util.SkyFactory; import model.Cell; import model.MaterialManager; import model.Position; import model.World; import java.util.*; class Environment implements Observer { public static final float SCALE = 0.2f; private static final Mesh BOX = new Box(SCALE/2, SCALE/2, SCALE/2); private static final float FLOOR_SIZE = 5000; private final VisualGUI visualGUI; private Node cellsNode; private Map<Position, Spatial> voxelMap; private Queue<Cell> toAdd; private Queue<Position> toRemove; private boolean updatingCells; private Node getCellsNode() { return cellsNode; } private Geometry floor; private Geometry getFloor() { return floor; } Environment(VisualGUI visualGUI) { this.visualGUI = visualGUI; voxelMap = new HashMap<>(); toAdd = new LinkedList<>(); toRemove = new LinkedList<>(); updatingCells = false; World.getInstance().addObserver(this); } void initializeEnvironment() { addSkySphere(); addCells(); addFloor(); addShadows(); } private void addSkySphere() { visualGUI.getRootNode().attachChild(SkyFactory.createSky(visualGUI.getAssetManager(), "Textures/Skysphere.jpg", SkyFactory.EnvMapType.SphereMap)); } private void addCells() { cellsNode = new Node(); cellsNode.setShadowMode(RenderQueue.ShadowMode.CastAndReceive); visualGUI.getRootNode().setShadowMode(RenderQueue.ShadowMode.Off); visualGUI.getRootNode().attachChild(cellsNode); updateCells(); } private void addShadows() { DirectionalLight sun = new DirectionalLight(); sun.setColor(ColorRGBA.White); sun.setDirection(new Vector3f(-.5f, -.5f, -.5f).normalizeLocal()); visualGUI.getRootNode().addLight(sun); /* Drop shadows */ final int SHADOWMAP_SIZE = 1024; DirectionalLightShadowRenderer dlsr = new DirectionalLightShadowRenderer(visualGUI.getAssetManager(), SHADOWMAP_SIZE, 3); dlsr.setLight(sun); visualGUI.getViewPort().addProcessor(dlsr); DirectionalLightShadowFilter dlsf = new DirectionalLightShadowFilter(visualGUI.getAssetManager(), SHADOWMAP_SIZE, 3); dlsf.setLight(sun); dlsf.setEnabled(true); FilterPostProcessor fpp = new FilterPostProcessor(visualGUI.getAssetManager()); fpp.addFilter(dlsf); visualGUI.getViewPort().addProcessor(fpp); } private void addFloor() { floor = new Geometry("Box", new Quad(FLOOR_SIZE, FLOOR_SIZE)); Material unshaded = new Material(visualGUI.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); unshaded.setColor("Color", ColorRGBA.White); floor.setMaterial(unshaded); floor.setShadowMode(RenderQueue.ShadowMode.Receive); Quaternion q = new Quaternion(); floor.setLocalRotation(q.fromAngleAxis(-FastMath.PI / 2, new Vector3f(1, 0, 0))); floor.setLocalTranslation(-FLOOR_SIZE / 2, -SCALE / 2, FLOOR_SIZE / 2); visualGUI.getRootNode().attachChild(floor); updateFloor(); } void update(float tpf) { updateCells(); updateFloor(); } private void updateFloor() { float minimumY = 0; // should be at least at the sea level for (Cell cell : World.getInstance().getCells()) { minimumY = Math.min(minimumY, cell.getPosition().getComponent(1) * SCALE); } Vector3f floorTranslation = getFloor().getLocalTranslation(); Vector3f nextFloorTranslation = floorTranslation.setY(minimumY - SCALE/2); getFloor().setLocalTranslation(nextFloorTranslation); } private void updateCells() { while (!toAdd.isEmpty()) { if (toAdd.peek() != null) { Cell cell = toAdd.remove(); removeSpatial(cell.getPosition()); addSpatial(cell); } } while (!toRemove.isEmpty()) { if (toRemove.peek() != null) { Position position = toRemove.remove(); removeSpatial(position); } } } private void addSpatial(Cell cell) { Spatial node = new Geometry("Box", BOX); node.setShadowMode(RenderQueue.ShadowMode.CastAndReceive); Material material = MaterialManager.getInstance() .getColoredMaterial(visualGUI.getAssetManager(), cell.getColor()); node.setMaterial(material); node.setLocalTranslation( cell.getPosition().getComponent(0) * SCALE, cell.getPosition().getComponent(1) * SCALE, cell.getPosition().getComponent(2) * SCALE); cellsNode.attachChild(node); voxelMap.put(cell.getPosition(), node); } private void removeSpatial(Position position) { if (voxelMap.containsKey(position)) { cellsNode.detachChild(voxelMap.get(position)); } } @Override public void update(Observable o, Object arg) { // NOTE: addAll won't work here for (Cell cell : World.getInstance().getToAdd()) { toAdd.add(cell); } for (Position position : World.getInstance().getToRemove()) { toRemove.add(position); } } }
package com.devsmart.ubjson; import java.util.Comparator; public abstract class UBValue implements Comparable<UBValue> { public static final byte MARKER_NULL = 'Z'; public static final byte MARKER_TRUE = 'T'; public static final byte MARKER_FALSE = 'F'; public static final byte MARKER_CHAR = 'C'; public static final byte MARKER_INT8 = 'i'; public static final byte MARKER_UINT8 = 'U'; public static final byte MARKER_INT16 = 'I'; public static final byte MARKER_INT32 = 'l'; public static final byte MARKER_INT64 = 'L'; public static final byte MARKER_FLOAT32 = 'd'; public static final byte MARKER_FLOAT64 = 'D'; public static final byte MARKER_STRING = 'S'; public static final byte MARKER_ARRAY_START = '['; public static final byte MARKER_ARRAY_END = ']'; public static final byte MARKER_OBJ_START = '{'; public static final byte MARKER_OBJ_END = '}'; public static final byte MARKER_OPTIMIZED_TYPE = '$'; public static final byte MARKER_OPTIMIZED_SIZE = ' public enum Type { Null, Char, Bool, Int8, Uint8, Int16, Int32, Int64, Float32, Float64, String, Array, Object } public abstract Type getType(); //public abstract void write(OutputStream out) throws IOException; public boolean isNull() { return getType() == Type.Null; } public boolean isBool() { return getType() == Type.Bool; } public boolean asBool() { return ((UBBool)this).getBool(); } public boolean isChar() { return getType() == Type.Char; } public char asChar() { return ((UBChar)this).getChar(); } public boolean isNumber() { switch (getType()){ case Int8: case Uint8: case Int16: case Int32: case Int64: case Float32: case Float64: return true; default: return false; } } public boolean isInteger() { switch (getType()){ case Int8: case Uint8: case Int16: case Int32: case Int64: return true; default: return false; } } public boolean isString() { return getType() == Type.String; } public String asString() { if(this.isNull()) { return null; } else { UBString thiz = (UBString) this; return thiz.getString(); } } public byte[] asByteArray() { return ((UBString)this).asByteArray(); } public byte asByte() { return (byte)asInt(); } public short asShort() { return (short)asInt(); } public int asInt() { switch (getType()){ case Int8: return ((UBInt8)this).getInt(); case Uint8: return ((UBUInt8)this).getInt(); case Int16: return ((UBInt16)this).getInt(); case Int32: return ((UBInt32)this).getInt(); case Int64: return (int)((UBInt64)this).getInt(); case Float32: return (int)((UBFloat32)this).getFloat(); case Float64: return (int)((UBFloat64)this).getDouble(); default: throw new RuntimeException("not a number type"); } } public long asLong() { switch (getType()){ case Bool: return asBool() ? 1 : 0; case Char: return asChar(); case Int8: return ((UBInt8)this).getInt(); case Uint8: return ((UBUInt8)this).getInt(); case Int16: return ((UBInt16)this).getInt(); case Int32: return ((UBInt32)this).getInt(); case Int64: return (long)((UBInt64)this).getInt(); case Float32: return (long)((UBFloat32)this).getFloat(); case Float64: return (long)((UBFloat64)this).getDouble(); default: throw new RuntimeException("not a number type"); } } public float asFloat32() { float retval; switch (getType()) { case Float32: retval = ((UBFloat32)this).getFloat(); break; case Float64: retval = (float)((UBFloat64)this).getDouble(); break; case String: retval = Float.parseFloat(asString()); default: throw new RuntimeException("not a float type"); } return retval; } public double asFloat64() { double retval; switch (getType()) { case Float32: retval = ((UBFloat32)this).getFloat(); break; case Float64: retval = ((UBFloat64)this).getDouble(); break; case String: retval = Double.parseDouble(asString()); default: throw new RuntimeException("not a float type"); } return retval; } public boolean isArray() { return getType() == Type.Array; } public UBArray asArray() { return ((UBArray)this); } public int size() { int retval; switch (getType()) { case Array: retval = asArray().size(); break; case String: retval = ((UBString)this).length(); break; default: retval = -1; } return retval; } /** * Interprets a strongly-typed number array to array of booleans. * If a value found in the array is > 0 return true, false otherwise. * @return */ public boolean[] asBoolArray() { boolean[] retval; UBArray array = asArray(); switch(array.getStrongType()){ case Int8: { byte[] data = ((UBInt8Array) array).getValues(); retval = new boolean[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i] > 0; } break; } case Int16: { short[] data = ((UBInt16Array) array).getValues(); retval = new boolean[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i] > 0; } break; } case Int32: { int[] data = ((UBInt32Array)array).getValues(); retval = new boolean[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i] > 0; } break; } case Float32: { float[] data = ((UBFloat32Array) array).getValues(); retval = new boolean[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i] > 0; } break; } case Float64: { double[] data = ((UBFloat64Array) array).getValues(); retval = new boolean[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i] > 0; } break; } default: throw new RuntimeException("not an int32[] type"); } return retval; } public short[] asShortArray() { short[] retval; UBArray array = asArray(); switch(array.getStrongType()){ case Int8: { byte[] data = ((UBInt8Array) array).getValues(); retval = new short[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i]; } break; } case Int16: { retval = ((UBInt16Array) array).getValues(); break; } case Int32: { int[] data = ((UBInt32Array) array).getValues(); retval = new short[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = (short) data[i]; } break; } case Float32: { float[] data = ((UBFloat32Array) array).getValues(); retval = new short[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = (short) data[i]; } break; } case Float64: { double[] data = ((UBFloat64Array) array).getValues(); retval = new short[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = (short) data[i]; } break; } default: throw new RuntimeException("not an int32[] type"); } return retval; } public int[] asInt32Array() { int[] retval; UBArray array = asArray(); switch(array.getStrongType()){ case Int8: { byte[] data = ((UBInt8Array) array).getValues(); retval = new int[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i]; } break; } case Int16: { short[] data = ((UBInt16Array) array).getValues(); retval = new int[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i]; } break; } case Int32: { retval = ((UBInt32Array)array).getValues(); break; } case Float32: { float[] data = ((UBFloat32Array) array).getValues(); retval = new int[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = (int) data[i]; } break; } case Float64: { double[] data = ((UBFloat64Array) array).getValues(); retval = new int[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = (int) data[i]; } break; } default: throw new RuntimeException("not an int32[] type"); } return retval; } public float[] asFloat32Array() { float[] retval; UBArray array = asArray(); switch(array.getStrongType()){ case Int8: { byte[] data = ((UBInt8Array) array).getValues(); retval = new float[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i]; } break; } case Int16: { short[] data = ((UBInt16Array) array).getValues(); retval = new float[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i]; } break; } case Int32: { int[] data = ((UBInt32Array) array).getValues(); retval = new float[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i]; } break; } case Float32: retval = ((UBFloat32Array)array).getValues(); break; case Float64: { double[] data = ((UBFloat64Array) array).getValues(); retval = new float[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = (float) data[i]; } break; } default: throw new RuntimeException("not an float32[] type"); } return retval; } public double[] asFloat64Array() { double[] retval; UBArray array = asArray(); switch(array.getStrongType()){ case Int8: { byte[] data = ((UBInt8Array) array).getValues(); retval = new double[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i]; } break; } case Int16: { short[] data = ((UBInt16Array) array).getValues(); retval = new double[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i]; } break; } case Int32: { int[] data = ((UBInt32Array) array).getValues(); retval = new double[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i]; } break; } case Float32: { float[] data = ((UBFloat32Array) array).getValues(); retval = new double[data.length]; for (int i = 0; i < data.length; i++) { retval[i] = data[i]; } break; } case Float64: { retval = ((UBFloat64Array)array).getValues(); break; } default: throw new RuntimeException("not an float32[] type"); } return retval; } public boolean isObject() { return getType() == Type.Object; } public UBObject asObject() { return ((UBObject)this); } @Override public int hashCode() { int retval = 0; switch (getType()) { case Null: retval = 0; break; case Bool: retval = asBool() ? 1 : 0; break; case Char: retval = asChar(); break; case Int8: case Uint8: case Int16: case Int32: retval = asInt(); break; case Int64: { long value = asLong(); retval = (int) (value ^ (value >>> 32)); break; } case Float32: retval = Float.floatToIntBits(asFloat32()); break; case Float64: { long value = Double.doubleToLongBits(asFloat64()); retval = (int) (value ^ (value >>> 32)); break; } case String: retval = asString().hashCode(); break; } return retval; } @Override public boolean equals(Object obj) { if(obj == null) { return false; } if(!(obj instanceof UBValue)) { return false; } return COMPARATOR.compare(this, (UBValue)obj) == 0; } @Override public int compareTo(UBValue value) { return COMPARATOR.compare(this, value); } private static int getCompareType(UBValue value) { int retval = 0; switch(value.getType()) { case Null: retval = 0; break; case Bool: retval = 1; break; case Char: retval = 2; break; case Int8: case Uint8: case Int16: case Int32: case Int64: retval = 3; break; case Float32: case Float64: retval = 4; break; case String: retval = 5; break; case Array: retval = 6; break; case Object: retval = 7; break; } return retval; } private static int compareBool(boolean a, boolean b){ return (a == b) ? 0 : (a ? 1 : -1); } private static int compareChar(char a, char b) { return (a == b) ? 0 : (a < b ? -1 : 1); } private static int compareLong(long a, long b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } public static final Comparator<UBValue> COMPARATOR = new Comparator<UBValue>() { @Override public int compare(UBValue a, UBValue b) { int retval = getCompareType(a) - getCompareType(b); if(retval == 0) { switch (getCompareType(a)) { case 1: retval = compareBool(a.asBool(), b.asBool()); break; case 2: retval = compareChar(a.asChar(), b.asChar()); break; case 3: retval = compareLong(a.asLong(), b.asLong()); break; case 4: retval = Double.compare(a.asFloat64(), b.asFloat64()); break; case 5: retval = a.asString().compareTo(b.asString()); break; case 6: retval = a.asArray().compareTo(b.asArray()); break; case 7: retval = a.asObject().compareTo(b.asObject()); break; } } return retval; } }; }
package ui; import java.io.IOException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.concurrent.Task; import javafx.geometry.Orientation; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.ScrollBar; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextInputDialog; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import javafx.stage.Modality; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import service.ServiceManager; import storage.DataManager; import ui.issuecolumn.ColumnControl; import ui.issuecolumn.IssueColumn; import util.DialogMessage; import util.events.IssueCreatedEvent; import util.events.LabelCreatedEvent; import util.events.MilestoneCreatedEvent; import util.events.PanelSavedEvent; import util.events.PanelSavedEventHandler; public class MenuControl extends MenuBar { private static final Logger logger = LogManager.getLogger(MenuControl.class.getName()); private final ColumnControl columns; private final ScrollPane columnsScrollPane; private final UI ui; public MenuControl(UI ui, ColumnControl columns, ScrollPane columnsScrollPane) { this.columns = columns; this.columnsScrollPane = columnsScrollPane; this.ui = ui; createMenuItems(); } private void createMenuItems() { Menu newMenu = new Menu("New"); newMenu.getItems().addAll(createNewMenuItems()); Menu panels = createPanelsMenu(); Menu view = new Menu("View"); view.getItems().addAll(createRefreshMenuItem(), createForceRefreshMenuItem(), createDocumentationMenuItem()); getMenus().addAll(newMenu, panels, view); } private Menu createPanelsMenu() { Menu cols = new Menu("Panels"); MenuItem createLeft = new MenuItem("Create (Left)"); createLeft.setOnAction(e -> { logger.info("Menu: Panels > Create (Left)"); columns.createNewPanelAtStart(); columnsScrollPane.setHvalue(columnsScrollPane.getHmin()); }); createLeft.setAccelerator(new KeyCodeCombination(KeyCode.N, KeyCombination.CONTROL_DOWN, KeyCombination.SHIFT_DOWN)); MenuItem createRight = new MenuItem("Create"); createRight.setOnAction(e -> { logger.info("Menu: Panels > Create"); columns.createNewPanelAtEnd(); // listener is used as columnsScroll's Hmax property doesn't update // synchronously ChangeListener<Number> listener = new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> arg0, Number arg1, Number arg2) { for (Node child : columnsScrollPane.getChildrenUnmodifiable()) { if (child instanceof ScrollBar) { ScrollBar scrollBar = (ScrollBar) child; if (scrollBar.getOrientation() == Orientation.HORIZONTAL && scrollBar.visibleProperty().get()) { columnsScrollPane.setHvalue(columnsScrollPane.getHmax()); break; } } } columns.widthProperty().removeListener(this); } }; columns.widthProperty().addListener(listener); }); createRight.setAccelerator(new KeyCodeCombination(KeyCode.N, KeyCombination.CONTROL_DOWN)); MenuItem closeColumn = new MenuItem("Close"); closeColumn.setOnAction(e -> { logger.info("Menu: Panels > Close"); columns.closeCurrentColumn(); }); closeColumn.setAccelerator(new KeyCodeCombination(KeyCode.W, KeyCombination.CONTROL_DOWN)); Menu sets = new Menu("Sets"); sets.getItems().addAll(createPanelsSetsMenu()); cols.getItems().addAll(createRight, createLeft, closeColumn, sets); return cols; } /** * Called upon the Panels > Sets > Save being clicked */ private void onPanelSetSave() { logger.info("Menu: Panels > Sets > Save"); List<String> filterStrings = getCurrentFilterExprs(); if (!filterStrings.isEmpty()) { TextInputDialog dlg = new TextInputDialog(""); dlg.setTitle("Panel Set Name"); dlg.getDialogPane().setContentText("What should this panel set be called?"); dlg.getDialogPane().setHeaderText("Please name this panel set"); Optional<String> response = dlg.showAndWait(); if (response.isPresent()) { DataManager.getInstance().addPanelSet(response.get(), filterStrings); ui.triggerEvent(new PanelSavedEvent()); logger.info("New panel set " + response.get() + " saved, containing " + filterStrings); return; } } logger.info("Did not save new panel set"); } /** * Called upon the Panels > Sets > Open being clicked */ private void onPanelSetOpen(String panelSetName, List<String> filterSet) { logger.info("Menu: Panels > Sets > Open > " + panelSetName); columns.closeAllColumns(); columns.openColumnsWithFilters(filterSet); } /** * Called upon the Panels > Sets > Delete being clicked */ private void onPanelSetDelete(String panelSetName) { logger.info("Menu: Panels > Sets > Delete > " + panelSetName); Alert dlg = new Alert(AlertType.CONFIRMATION, ""); dlg.initModality(Modality.APPLICATION_MODAL); dlg.setTitle("Confirmation"); dlg.getDialogPane().setHeaderText("Delete panel set '" + panelSetName + "'?"); dlg.getDialogPane().setContentText("Are you sure you want to delete this panelSet?"); Optional<ButtonType> response = dlg.showAndWait(); if (response.isPresent() && response.get().getButtonData() == ButtonData.OK_DONE) { DataManager.getInstance().removePanelSet(panelSetName); ui.triggerEvent(new PanelSavedEvent()); logger.info(panelSetName + " was deleted"); } else { logger.info(panelSetName + " was not deleted"); } } private MenuItem[] createPanelsSetsMenu() { MenuItem save = new MenuItem("Save"); save.setOnAction(e -> onPanelSetSave()); Menu open = new Menu("Open"); Menu delete = new Menu("Delete"); ui.registerEvent(new PanelSavedEventHandler() { @Override public void handle(PanelSavedEvent e) { open.getItems().clear(); delete.getItems().clear(); Map<String, List<String>> panelSets = DataManager.getInstance().getAllPanelSets(); for (final String panelSetName : panelSets.keySet()) { final List<String> filterSet = panelSets.get(panelSetName); MenuItem openItem = new MenuItem(panelSetName); openItem.setOnAction(e1 -> onPanelSetOpen(panelSetName, filterSet)); open.getItems().add(openItem); MenuItem deleteItem = new MenuItem(panelSetName); deleteItem.setOnAction(e1 -> onPanelSetDelete(panelSetName)); delete.getItems().add(deleteItem); } } }); return new MenuItem[] {save, open, delete}; } /** * Returns the list of filter strings currently showing the user interface * @return */ private List<String> getCurrentFilterExprs() { return columns.getChildren().stream().flatMap(c -> { if (c instanceof IssueColumn) { return Stream.of(((IssueColumn) c).getCurrentFilterString()); } else { return Stream.of(); } }).collect(Collectors.toList()); } private MenuItem createDocumentationMenuItem() { MenuItem documentationMenuItem = new MenuItem("Documentation"); documentationMenuItem.setOnAction((e) -> { logger.info("Menu: View > Documentation"); ui.getBrowserComponent().showDocs(); }); documentationMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.F1)); return documentationMenuItem; } private MenuItem createRefreshMenuItem() { MenuItem refreshMenuItem = new MenuItem("Refresh"); refreshMenuItem.setOnAction((e) -> { logger.info("Menu: View > Refresh"); ServiceManager.getInstance().updateModelNowAndPeriodically(); columns.refresh(); }); refreshMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.F5)); return refreshMenuItem; } private MenuItem createForceRefreshMenuItem() { MenuItem forceRefreshMenuItem = new MenuItem("Force Refresh"); forceRefreshMenuItem.setOnAction((e) -> { triggerForceRefreshProgressDialog(); }); forceRefreshMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.F5, KeyCombination.CONTROL_DOWN)); return forceRefreshMenuItem; } private void triggerForceRefreshProgressDialog() { Task<Boolean> task = new Task<Boolean>() { @Override protected Boolean call() throws IOException { try { logger.info("Menu: View > Force Refresh"); ServiceManager.getInstance().stopModelUpdate(); ServiceManager.getInstance().getModel().forceReloadComponents(); ServiceManager.getInstance().updateModelNowAndPeriodically(); } catch (SocketTimeoutException e) { handleSocketTimeoutException(e); return false; } catch (UnknownHostException e) { handleUnknownHostException(e); return false; } catch (Exception e) { logger.error(e.getMessage(), e); e.printStackTrace(); return false; } logger.info("Menu: View > Force Refresh completed"); return true; } private void handleSocketTimeoutException(Exception e) { Platform.runLater(() -> { logger.error(e.getMessage(), e); DialogMessage.showWarningDialog("Internet Connection is down", "Timeout while loading items from github. Please check your internet connection."); }); } private void handleUnknownHostException(Exception e) { Platform.runLater(() -> { logger.error(e.getMessage(), e); DialogMessage.showWarningDialog("No Internet Connection", "Please check your internet connection and try again"); }); } }; DialogMessage.showProgressDialog(task, "Reloading issues for current repo... This may take awhile, please wait."); Thread thread = new Thread(task); thread.setDaemon(true); thread.start(); } private MenuItem[] createNewMenuItems() { MenuItem newIssueMenuItem = new MenuItem("Issue"); newIssueMenuItem.setOnAction(e -> { logger.info("Menu: New > Issue"); ui.triggerEvent(new IssueCreatedEvent()); }); newIssueMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.I, KeyCombination.CONTROL_DOWN)); MenuItem newLabelMenuItem = new MenuItem("Label"); newLabelMenuItem.setOnAction(e -> { logger.info("Menu: New > Label"); ui.triggerEvent(new LabelCreatedEvent()); }); newLabelMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.L, KeyCombination.CONTROL_DOWN)); MenuItem newMilestoneMenuItem = new MenuItem("Milestone"); newMilestoneMenuItem.setOnAction(e -> { logger.info("Menu: New > Milestone"); ui.triggerEvent(new MilestoneCreatedEvent()); }); newMilestoneMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.M, KeyCombination.CONTROL_DOWN)); return new MenuItem[] { newIssueMenuItem, newLabelMenuItem, newMilestoneMenuItem }; } }
package com.github.jkutner; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.filefilter.TrueFileFilter; import org.xembly.Directives; import org.xembly.ImpossibleModificationException; import org.xembly.Xembler; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class BoincApp { public static final String DEFAULT_WRAPPER_VERSION="26016"; private static String[] defaultPlatforms = new String[] { "x86_64-apple-darwin", "i686-apple-darwin", "windows_intelx86", "windows_x86_64", "i686-pc-linux-gnu", "x86_64-pc-linux-gnu" }; private Set<String> platforms; private File boincDir = new File(System.getProperty("user.dir"), "boinc"); private File srcUberjar; private File srcJobXml; private File srcTemplatesDir; private String versionKey; public BoincApp( File uberjar, Map<String,Boolean> altPlatforms, File jobXml, File templatesDir, String versionKey ) { platforms = new HashSet<String>(); for (String p : altPlatforms.keySet()) if (altPlatforms.get(p)) platforms.add(p); for (String p : defaultPlatforms) if (!altPlatforms.containsKey(p) || altPlatforms.get(p)) platforms.add(p); this.srcUberjar = uberjar; this.srcJobXml = jobXml; this.srcTemplatesDir = templatesDir; this.versionKey = versionKey; } public void cleanBoincDir(Boolean keepWrapper) throws IOException { if (this.boincDir.exists()) { if (keepWrapper) { for (File f : FileUtils.listFiles(this.boincDir, new WrapperFilter(), TrueFileFilter.INSTANCE)) { if (!f.isDirectory()) { FileUtils.forceDelete(f); } } } else { FileUtils.deleteDirectory(this.boincDir); } } } private static class WrapperFilter implements IOFileFilter { public boolean accept(File file) { return !"zip".equals(FilenameUtils.getExtension(file.getName())); } public boolean accept(File file, String s) { return !"zip".equals(FilenameUtils.getExtension(s)); } } public void packageIntoBoincDir() throws IOException, ImpossibleModificationException, ZipException { cleanBoincDir(true); FileUtils.forceMkdir(boincDir); File appDir = new File(boincDir, "app"); FileUtils.forceMkdir(appDir); File templatesDir = new File(boincDir, "templates"); FileUtils.copyDirectory(this.srcTemplatesDir, templatesDir); File downloadsDir = new File(boincDir, "downloads"); FileUtils.forceMkdir(downloadsDir); File uberjar = new File(downloadsDir, this.srcUberjar.getName()); FileUtils.copyFile(this.srcUberjar, uberjar); for (String p : platforms) { Map<String,File> files = new HashMap<String, File>(); File platformDir = new File(appDir, p); FileUtils.forceMkdir(platformDir); files.put(uberjar.getName(), uberjar); files.put("job.xml", copyJobXml(platformDir, p)); files.put("wrapper", installWrapper(platformDir, p)); createVersionFile(platformDir, files); createComposerJson(); } } protected File copyJobXml(File platformDir, String platform) throws IOException { String jobFilename = "job_"+platform+"_"+this.versionKey+".xml"; File jobFile = new File(platformDir, jobFilename); FileUtils.copyFile(this.srcJobXml, jobFile); return jobFile; } protected File installWrapper(File platformDir, String platform) throws IOException, ZipException { String wrapperZipFilename = wrapperName(platform)+".zip"; File wrapperZipFile = new File(platformDir, wrapperZipFilename); if (wrapperZipFile.exists()) { // TODO check md5 // FileUtils.forceDelete(wrapperZipFile); System.out.println("Using existing " + wrapperZipFile + "..."); } else { System.out.println("Downloading " + wrapperZipFilename + "..."); String urlString = System.getProperty( "boinc.wrapper." + platform + ".url", "http://boinc.berkeley.edu/dl/" + wrapperZipFilename); URL wrapperUrl = new URL(urlString); // TODO make better FileUtils.copyURLToFile(wrapperUrl, wrapperZipFile); } System.out.println("Extracting " + wrapperZipFilename + "..."); ZipFile zipFile = new ZipFile(wrapperZipFile); zipFile.extractAll(platformDir.toString()); return new File(platformDir, wrapperName(platform)+wrapperExtension(platform)); } protected void createVersionFile(File platformDir, Map<String,File> files) throws ImpossibleModificationException, IOException { Directives version = new Directives().add("version"); for (String logicalName : files.keySet()) { File physicalFile = files.get(logicalName); Directives fileXml = version.add("file") .add("physical_name").set(physicalFile.getName()).up() .add("copy_file").set("true").up(); if (logicalName.equals("wrapper")) { fileXml.add("main_program").set("true").up(); } else { fileXml.add("logical_name").set(logicalName).up(); } fileXml.up(); } String xml = new Xembler(version).xml(); File versionFile = new File(platformDir, "version.xml"); FileUtils.writeStringToFile(versionFile, xml); } protected void createComposerJson() throws IOException { File composerJson = new File(System.getProperty("usr.dir"), "composer.json"); if (!composerJson.exists()) FileUtils.writeStringToFile(composerJson, "{}"); } protected String wrapperName(String platform) { String wrapperVersion = System.getProperty("boinc.wrapper.version", wrapperVersion(platform)); return "wrapper_"+wrapperVersion+"_"+platform; } protected String wrapperVersion(String platform) { if (platform.startsWith("windows_")) return "26016"; return "26014"; } protected String wrapperExtension(String platform) { if (platform.startsWith("windows_")) return ".exe"; return ""; } }
package com.github.jkutner; import com.github.jkutner.boinc.BoincAssimilator; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.filefilter.IOFileFilter; import org.apache.commons.io.filefilter.TrueFileFilter; import org.xembly.Directives; import org.xembly.ImpossibleModificationException; import org.xembly.Xembler; import java.io.*; import java.net.URL; import java.util.*; public class BoincApp { public static final String DEFAULT_WRAPPER_VERSION="26016"; private static String[] defaultPlatforms = new String[] { "x86_64-apple-darwin", "i686-apple-darwin", "windows_intelx86", "windows_x86_64", "i686-pc-linux-gnu", "x86_64-pc-linux-gnu" }; private Set<String> platforms; private File boincDir = new File(System.getProperty("user.dir"), "boinc"); private File srcUberjar; private File srcJobXml; private File srcTemplatesDir; private String versionKey; private File targetDir; private String assimilatorClass; public BoincApp( File uberjar, Map<String,Boolean> altPlatforms, File jobXml, File templatesDir, String versionKey, File targetDir, String assimilatorClass ) { platforms = new HashSet<String>(); for (String p : altPlatforms.keySet()) if (altPlatforms.get(p)) platforms.add(p); for (String p : defaultPlatforms) if (!altPlatforms.containsKey(p) || altPlatforms.get(p)) platforms.add(p); this.srcUberjar = uberjar; this.srcJobXml = jobXml; this.srcTemplatesDir = templatesDir; this.versionKey = versionKey == null ? UUID.randomUUID().toString() : versionKey; this.targetDir = targetDir; this.assimilatorClass = assimilatorClass; } public void cleanBoincDir(Boolean keepWrapper) throws IOException { if (this.boincDir.exists()) { if (keepWrapper) { for (File f : FileUtils.listFiles(this.boincDir, new WrapperFilter(), TrueFileFilter.INSTANCE)) { if (!f.isDirectory()) { FileUtils.forceDelete(f); } } } else { FileUtils.deleteDirectory(this.boincDir); } } } private static class WrapperFilter implements IOFileFilter { public boolean accept(File file) { return !"zip".equals(FilenameUtils.getExtension(file.getName())); } public boolean accept(File file, String s) { return !"zip".equals(FilenameUtils.getExtension(s)); } } public void packageIntoBoincDir() throws IOException, ImpossibleModificationException, ZipException { cleanBoincDir(true); FileUtils.forceMkdir(boincDir); File appDir = new File(boincDir, "app"); FileUtils.forceMkdir(appDir); File binDir = new File(boincDir, "bin"); FileUtils.forceMkdir(binDir); if (this.srcTemplatesDir.exists()) { File templatesDir = new File(boincDir, "templates"); FileUtils.copyDirectory(this.srcTemplatesDir, templatesDir); } //File downloadsDir = new File(boincDir, "download"); //FileUtils.forceMkdir(downloadsDir); String uberjarName = this.srcUberjar.getName(); String uberjarPhysicalName = FilenameUtils.getBaseName(this.srcUberjar.getName())+"_"+this.versionKey+".jar"; writeDaemonsXml(binDir, uberjarPhysicalName); for (String p : platforms) { Map<String,File> files = new HashMap<String, File>(); File platformDir = new File(appDir, p); FileUtils.forceMkdir(platformDir); File uberjar = new File(platformDir, uberjarPhysicalName); FileUtils.copyFile(this.srcUberjar, uberjar); files.put(uberjarName, uberjar); files.put("job.xml", copyJobXml(platformDir, p, uberjarName)); files.put("wrapper", installWrapper(platformDir, p)); createVersionFile(platformDir, files); createComposerJson(); } } protected void createAssimilatorScript(File binDir, String uberjarPhysicalName) throws IOException { File scriptFile = new File(binDir, "java_assimilator"); try ( InputStream is = getClass().getResourceAsStream("/java_assimilator.sh"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); FileWriter fw = new FileWriter(scriptFile); BufferedWriter out = new BufferedWriter(fw); ) { String line; while ((line = br.readLine()) != null) { line = line.replace("%uberjar_name%", uberjarPhysicalName); line = line.replace("%java_opts%", BoincAssimilator.buildJavaOpts(this.assimilatorClass)); line = line.replace("%assimilator_class%", this.assimilatorClass); out.write(line); out.write("\n"); } } } protected void writeDaemonsXml(File binDir, String uberjarPhysicalName) throws ImpossibleModificationException, IOException { File daemonsFile = new File(boincDir, "daemons.xml"); Directives directives = new Directives().add("daemons") .add("daemon").add("cmd").set("feeder -d 3").up().up() .add("daemon").add("cmd").set("transitioner -d 3").up().up() .add("daemon").add("cmd").set("file_deleter -d 2 --preserve_wu_files --preserve_result_files").up().up(); directives.add("daemon").add("cmd").set("sample_trivial_validator -d 2 --app ${HEROKU_APP_NAME}").up().up(); if (this.assimilatorClass != null) { directives.add("daemon").add("cmd").set("script_assimilator --script java_assimilator -d 2 --app ${HEROKU_APP_NAME}").up().up(); createAssimilatorScript(binDir, uberjarPhysicalName); } else { directives.add("daemon").add("cmd").set("sample_assimilator -d 2 --app ${HEROKU_APP_NAME}").up().up(); } String xml = new Xembler(directives).xml(); String xmlWithoutHeader = xml.substring(xml.indexOf('\n')+1); FileUtils.writeStringToFile(daemonsFile, xmlWithoutHeader); } protected File copyJobXml(File platformDir, String platform, String uberjarName) throws ImpossibleModificationException, IOException { String xml = new Xembler(new Directives().add("job_desc") .add("task") .add("application").set(getJavaCmd(platform)).up() .add("command_line").set("-jar " + uberjarName).up() .add("append_cmdline_args") ).xml(); String jobFilename = "job_"+platform+"_"+this.versionKey+".xml"; File jobFile = new File(platformDir, jobFilename); FileUtils.writeStringToFile(jobFile, xml); return jobFile; } protected File installWrapper(File platformDir, String platform) throws IOException, ZipException { String wrapperZipFilename = wrapperName(platform) + ".zip"; File wrapperZipFile = new File(this.targetDir, wrapperZipFilename); if (wrapperZipFile.exists()) { System.out.println("Using cached " + wrapperZipFilename + "..."); } else { System.out.println("Downloading " + wrapperZipFilename + "..."); String urlString = System.getProperty( "boinc.wrapper." + platform + ".url", "http://boinc.berkeley.edu/dl/" + wrapperZipFilename); URL wrapperUrl = new URL(urlString); FileUtils.copyURLToFile(wrapperUrl, wrapperZipFile); } System.out.println("Extracting " + wrapperZipFilename + "..."); ZipFile zipFile = new ZipFile(wrapperZipFile); zipFile.extractAll(platformDir.toString()); return new File(platformDir, wrapperName(platform)+wrapperExtension(platform)); } protected void createVersionFile(File platformDir, Map<String,File> files) throws ImpossibleModificationException, IOException { Directives version = new Directives().add("version"); for (String logicalName : files.keySet()) { File physicalFile = files.get(logicalName); Directives fileXml = version.add("file") .add("physical_name").set(physicalFile.getName()).up() .add("copy_file").up(); if (logicalName.equals("wrapper")) { fileXml.add("main_program").up(); } else { fileXml.add("logical_name").set(logicalName).up(); } fileXml.up(); } String xml = new Xembler(version).xml(); File versionFile = new File(platformDir, "version.xml"); FileUtils.writeStringToFile(versionFile, xml); } protected void createComposerJson() throws IOException { File composerJson = new File(System.getProperty("usr.dir"), "composer.json"); if (!composerJson.exists()) FileUtils.writeStringToFile(composerJson, "{}"); } protected String wrapperName(String platform) { String wrapperVersion = System.getProperty("boinc.wrapper.version", wrapperVersion(platform)); return "wrapper_"+wrapperVersion+"_"+platform; } protected String wrapperVersion(String platform) { if (platform.startsWith("windows_")) return "26016"; return "26014"; } protected String wrapperExtension(String platform) { if (platform.startsWith("windows_")) return ".exe"; return ""; } protected String getJavaCmd(String platform) { return "/usr/bin/java"; } }
package com.jaamsim.input; import java.util.ArrayList; import com.jaamsim.basicsim.ObjectType; import com.jaamsim.units.DimensionlessUnit; import com.jaamsim.units.Unit; public class ExpParser { public interface UnOpFunc { public ExpResult apply(ParseContext context, ExpResult val) throws Error; } public interface BinOpFunc { public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, int pos) throws Error; } public interface CallableFunc { public ExpResult call(ParseContext context, ExpResult[] args, int pos) throws Error; } public static class UnitData { double scaleFactor; Class<? extends Unit> unitType; } public interface ParseContext { public UnitData getUnitByName(String name); public Class<? extends Unit> multUnitTypes(Class<? extends Unit> a, Class<? extends Unit> b); public Class<? extends Unit> divUnitTypes(Class<? extends Unit> num, Class<? extends Unit> denom); } public interface EvalContext { public ExpResult getVariableValue(String[] names) throws Error; } private interface ExpressionWalker { public void visit(Expression exp) throws Error; public Expression updateRef(Expression exp) throws Error; } // Expression types public abstract static class Expression { public ParseContext context; public int tokenPos; public abstract ExpResult evaluate(EvalContext ec) throws Error; public Expression(ParseContext context, int pos) { this.context = context; this.tokenPos = pos; } abstract void walk(ExpressionWalker w) throws Error; } private static class Constant extends Expression { public ExpResult val; public Constant(ParseContext context, ExpResult val, int pos) { super(context, pos); this.val = val; } @Override public ExpResult evaluate(EvalContext ec) { return val; } @Override void walk(ExpressionWalker w) throws Error { w.visit(this); } } public static class Variable extends Expression { private String[] vals; public Variable(ParseContext context, String[] vals, int pos) { super(context, pos); this.vals = vals; } @Override public ExpResult evaluate(EvalContext ec) throws Error { return ec.getVariableValue(vals); } @Override void walk(ExpressionWalker w) throws Error { w.visit(this); } } private static class UnaryOp extends Expression { public Expression subExp; private UnOpFunc func; UnaryOp(ParseContext context, Expression subExp, UnOpFunc func, int pos) { super(context, pos); this.subExp = subExp; this.func = func; } @Override public ExpResult evaluate(EvalContext ec) throws Error { return func.apply(context, subExp.evaluate(ec)); } @Override void walk(ExpressionWalker w) throws Error { subExp.walk(w); subExp = w.updateRef(subExp); w.visit(this); } } private static class BinaryOp extends Expression { public Expression lSubExp; public Expression rSubExp; public ExpResult lConstVal; public ExpResult rConstVal; private final BinOpFunc func; BinaryOp(ParseContext context, Expression lSubExp, Expression rSubExp, BinOpFunc func, int pos) { super(context, pos); this.lSubExp = lSubExp; this.rSubExp = rSubExp; this.func = func; } @Override public ExpResult evaluate(EvalContext ec) throws Error { ExpResult lRes = lConstVal != null ? lConstVal : lSubExp.evaluate(ec); ExpResult rRes = rConstVal != null ? rConstVal : rSubExp.evaluate(ec); return func.apply(context, lRes, rRes, tokenPos); } @Override void walk(ExpressionWalker w) throws Error { lSubExp.walk(w); rSubExp.walk(w); lSubExp = w.updateRef(lSubExp); rSubExp = w.updateRef(rSubExp); w.visit(this); } } public static class Conditional extends Expression { private Expression condExp; private Expression trueExp; private Expression falseExp; private ExpResult constCondRes; private ExpResult constTrueRes; private ExpResult constFalseRes; public Conditional(ParseContext context, Expression c, Expression t, Expression f, int pos) { super(context, pos); condExp = c; trueExp = t; falseExp =f; } @Override public ExpResult evaluate(EvalContext ec) throws Error { ExpResult condRes = constCondRes != null ? constCondRes : condExp.evaluate(ec); if (condRes.value == 0) return constFalseRes != null ? constFalseRes : falseExp.evaluate(ec); else return constTrueRes != null ? constTrueRes : trueExp.evaluate(ec); } @Override void walk(ExpressionWalker w) throws Error { condExp.walk(w); trueExp.walk(w); falseExp.walk(w); condExp = w.updateRef(condExp); trueExp = w.updateRef(trueExp); falseExp = w.updateRef(falseExp); w.visit(this); } } public static class FuncCall extends Expression { private ArrayList<Expression> args; private ArrayList<ExpResult> constResults; private CallableFunc function; public FuncCall(ParseContext context, CallableFunc function, ArrayList<Expression> args, int pos) { super(context, pos); this.function = function; this.args = args; constResults = new ArrayList<>(args.size()); for (int i = 0; i < args.size(); ++i) { constResults.add(null); } } @Override public ExpResult evaluate(EvalContext ec) throws Error { ExpResult[] argVals = new ExpResult[args.size()]; for (int i = 0; i < args.size(); ++i) { ExpResult constArg = constResults.get(i); argVals[i] = constArg != null ? constArg : args.get(i).evaluate(ec); } return function.call(context, argVals, tokenPos); } @Override void walk(ExpressionWalker w) throws Error { for (int i = 0; i < args.size(); ++i) { args.get(i).walk(w); } for (int i = 0; i < args.size(); ++i) { args.set(i, w.updateRef(args.get(i))); } w.visit(this); } } public static class Assignment { public String[] destination; public Expression value; } // Entries for user definable operators and functions private static class UnaryOpEntry { public String symbol; public UnOpFunc function; public double bindingPower; } private static class BinaryOpEntry { public String symbol; public BinOpFunc function; public double bindingPower; public boolean rAssoc; } private static class FunctionEntry { public String name; public CallableFunc function; public int numMinArgs; public int numMaxArgs; } private static ArrayList<UnaryOpEntry> unaryOps = new ArrayList<>(); private static ArrayList<BinaryOpEntry> binaryOps = new ArrayList<>(); private static ArrayList<FunctionEntry> functions = new ArrayList<>(); private static void addUnaryOp(String symbol, double bindPower, UnOpFunc func) { UnaryOpEntry oe = new UnaryOpEntry(); oe.symbol = symbol; oe.function = func; oe.bindingPower = bindPower; unaryOps.add(oe); } private static void addBinaryOp(String symbol, double bindPower, boolean rAssoc, BinOpFunc func) { BinaryOpEntry oe = new BinaryOpEntry(); oe.symbol = symbol; oe.function = func; oe.bindingPower = bindPower; oe.rAssoc = rAssoc; binaryOps.add(oe); } private static void addFunction(String name, int numMinArgs, int numMaxArgs, CallableFunc func) { FunctionEntry fe = new FunctionEntry(); fe.name = name; fe.function = func; fe.numMinArgs = numMinArgs; fe.numMaxArgs = numMaxArgs; functions.add(fe); } private static UnaryOpEntry getUnaryOp(String symbol) { for (UnaryOpEntry oe: unaryOps) { if (oe.symbol.equals(symbol)) return oe; } return null; } private static BinaryOpEntry getBinaryOp(String symbol) { for (BinaryOpEntry oe: binaryOps) { if (oe.symbol.equals(symbol)) return oe; } return null; } private static FunctionEntry getFunctionEntry(String funcName) { for (FunctionEntry fe : functions) { if (fe.name.equals(funcName)){ return fe; } } return null; } // Statically initialize the operators and functions static { // Unary Operators addUnaryOp("-", 50, new UnOpFunc() { @Override public ExpResult apply(ParseContext context, ExpResult val){ return new ExpResult(-val.value, val.unitType); } }); addUnaryOp("+", 50, new UnOpFunc() { @Override public ExpResult apply(ParseContext context, ExpResult val){ return new ExpResult(val.value, val.unitType); } }); addUnaryOp("!", 50, new UnOpFunc() { @Override public ExpResult apply(ParseContext context, ExpResult val){ return new ExpResult(val.value == 0 ? 1 : 0, DimensionlessUnit.class); } }); // Binary operators addBinaryOp("+", 20, false, new BinOpFunc() { @Override public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, int pos) throws Error { if (lval.unitType != rval.unitType) { throw new Error(getUnitMismatchString(lval.unitType, rval.unitType, pos)); } return new ExpResult(lval.value + rval.value, lval.unitType); } }); addBinaryOp("-", 20, false, new BinOpFunc() { @Override public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, int pos) throws Error { if (lval.unitType != rval.unitType) { throw new Error(getUnitMismatchString(lval.unitType, rval.unitType, pos)); } return new ExpResult(lval.value - rval.value, lval.unitType); } }); addBinaryOp("*", 30, false, new BinOpFunc() { @Override public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, int pos) throws Error { Class<? extends Unit> newType = context.multUnitTypes(lval.unitType, rval.unitType); if (newType == null) { throw new Error(getUnitMismatchString(lval.unitType, rval.unitType, pos)); } return new ExpResult(lval.value * rval.value, newType); } }); addBinaryOp("/", 30, false, new BinOpFunc() { @Override public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, int pos) throws Error { Class<? extends Unit> newType = context.divUnitTypes(lval.unitType, rval.unitType); if (newType == null) { throw new Error(getUnitMismatchString(lval.unitType, rval.unitType, pos)); } return new ExpResult(lval.value / rval.value, newType); } }); addBinaryOp("^", 40, true, new BinOpFunc() { @Override public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, int pos) throws Error { if (lval.unitType != DimensionlessUnit.class || rval.unitType != DimensionlessUnit.class) { throw new Error(getUnitMismatchString(lval.unitType, rval.unitType, pos)); } return new ExpResult(Math.pow(lval.value, rval.value), DimensionlessUnit.class); } }); addBinaryOp("==", 10, false, new BinOpFunc() { @Override public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, int pos) throws Error { if (lval.unitType != rval.unitType) { throw new Error(getUnitMismatchString(lval.unitType, rval.unitType, pos)); } return new ExpResult(lval.value == rval.value ? 1 : 0, DimensionlessUnit.class); } }); addBinaryOp("!=", 10, false, new BinOpFunc() { @Override public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, int pos) throws Error { if (lval.unitType != rval.unitType) { throw new Error(getUnitMismatchString(lval.unitType, rval.unitType, pos)); } return new ExpResult(lval.value != rval.value ? 1 : 0, DimensionlessUnit.class); } }); addBinaryOp("&&", 8, false, new BinOpFunc() { @Override public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, int pos){ return new ExpResult((lval.value!=0) && (rval.value!=0) ? 1 : 0, DimensionlessUnit.class); } }); addBinaryOp("||", 6, false, new BinOpFunc() { @Override public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, int pos){ return new ExpResult((lval.value!=0) || (rval.value!=0) ? 1 : 0, DimensionlessUnit.class); } }); addBinaryOp("<", 12, false, new BinOpFunc() { @Override public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, int pos) throws Error { if (lval.unitType != rval.unitType) { throw new Error(getUnitMismatchString(lval.unitType, rval.unitType, pos)); } return new ExpResult(lval.value < rval.value ? 1 : 0, DimensionlessUnit.class); } }); addBinaryOp("<=", 12, false, new BinOpFunc() { @Override public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, int pos) throws Error { if (lval.unitType != rval.unitType) { throw new Error(getUnitMismatchString(lval.unitType, rval.unitType, pos)); } return new ExpResult(lval.value <= rval.value ? 1 : 0, DimensionlessUnit.class); } }); addBinaryOp(">", 12, false, new BinOpFunc() { @Override public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, int pos) throws Error { if (lval.unitType != rval.unitType) { throw new Error(getUnitMismatchString(lval.unitType, rval.unitType, pos)); } return new ExpResult(lval.value > rval.value ? 1 : 0, DimensionlessUnit.class); } }); addBinaryOp(">=", 12, false, new BinOpFunc() { @Override public ExpResult apply(ParseContext context, ExpResult lval, ExpResult rval, int pos) throws Error { if (lval.unitType != rval.unitType) { throw new Error(getUnitMismatchString(lval.unitType, rval.unitType, pos)); } return new ExpResult(lval.value >= rval.value ? 1 : 0, DimensionlessUnit.class); } }); // Functions addFunction("max", 2, -1, new CallableFunc() { @Override public ExpResult call(ParseContext context, ExpResult[] args, int pos) throws Error { for (int i = 1; i < args.length; ++ i) { if (args[0].unitType != args[i].unitType) throw new Error(getUnitMismatchString(args[0].unitType, args[i].unitType, pos)); } ExpResult res = args[0]; for (int i = 1; i < args.length; ++ i) { if (args[i].value > res.value) res = args[i]; } return res; } }); addFunction("min", 2, -1, new CallableFunc() { @Override public ExpResult call(ParseContext context, ExpResult[] args, int pos) throws Error { for (int i = 1; i < args.length; ++ i) { if (args[0].unitType != args[i].unitType) throw new Error(getUnitMismatchString(args[0].unitType, args[i].unitType, pos)); } ExpResult res = args[0]; for (int i = 1; i < args.length; ++ i) { if (args[i].value < res.value) res = args[i]; } return res; } }); addFunction("abs", 1, 1, new CallableFunc() { @Override public ExpResult call(ParseContext context, ExpResult[] args, int pos) { return new ExpResult(Math.abs(args[0].value), args[0].unitType); } }); addFunction("indexOfMin", 2, -1, new CallableFunc() { @Override public ExpResult call(ParseContext context, ExpResult[] args, int pos) throws Error { for (int i = 1; i < args.length; ++ i) { if (args[0].unitType != args[i].unitType) throw new Error(getUnitMismatchString(args[0].unitType, args[i].unitType, pos)); } ExpResult res = args[0]; int index = 0; for (int i = 1; i < args.length; ++ i) { if (args[i].value < res.value) { res = args[i]; index = i; } } return new ExpResult(index + 1, DimensionlessUnit.class); } }); addFunction("indexOfMax", 2, -1, new CallableFunc() { @Override public ExpResult call(ParseContext context, ExpResult[] args, int pos) throws Error { for (int i = 1; i < args.length; ++ i) { if (args[0].unitType != args[i].unitType) throw new Error(getUnitMismatchString(args[0].unitType, args[i].unitType, pos)); } ExpResult res = args[0]; int index = 0; for (int i = 1; i < args.length; ++ i) { if (args[i].value > res.value) { res = args[i]; index = i; } } return new ExpResult(index + 1, DimensionlessUnit.class); } }); } public static class Error extends Exception { Error(String err) { super(err); } Error(Throwable cause) { super(cause); } } private static String unitToString(Class<? extends Unit> unit) { for (ObjectType type : ObjectType.getAll()) { if (type.getJavaClass() == unit) { return type.getName(); } } return "Unknown Unit"; } private static String getUnitMismatchString(Class<? extends Unit> u0, Class<? extends Unit> u1, int pos) { String s0 = unitToString(u0); String s1 = unitToString(u1); return String.format("Unit mismatch: '%s' and '%s' are not compatible at position: %d", s0, s1, pos); } /** * A utility class to make dealing with a list of tokens easier * */ private static class TokenList { ArrayList<ExpTokenizer.Token> tokens; int pos; TokenList(ArrayList<ExpTokenizer.Token> tokens) { this.tokens = tokens; this.pos = 0; } public void expect(int type, String val) throws Error { if (pos == tokens.size()) { throw new Error(String.format("Expected \"%s\", past the end of input", val)); } ExpTokenizer.Token nextTok = tokens.get(pos); if (nextTok.type != type || !nextTok.value.equals(val)) { throw new Error(String.format("Expected \"%s\", got \"%s\" at position %d", val, nextTok.value, nextTok.pos)); } pos++; } public ExpTokenizer.Token next() { if (pos >= tokens.size()) { return null; } return tokens.get(pos++); } public ExpTokenizer.Token peek() { if (pos >= tokens.size()) { return null; } return tokens.get(pos); } } private static class ConstOptimizer implements ExpressionWalker { @Override public void visit(Expression exp) throws Error { // Note: Below we are passing 'null' as an EvalContext, this is not typically // acceptable, but is 'safe enough' when we know the expression is a constant if (exp instanceof BinaryOp) { BinaryOp bo = (BinaryOp)exp; if (bo.lSubExp instanceof Constant) { // Just the left is a constant, store it in the binop bo.lConstVal = bo.lSubExp.evaluate(null); } if (bo.rSubExp instanceof Constant) { // Just the right is a constant, store it in the binop bo.rConstVal = bo.rSubExp.evaluate(null); } } if (exp instanceof Conditional) { Conditional cond = (Conditional)exp; if (cond.condExp instanceof Constant) { cond.constCondRes = cond.condExp.evaluate(null); } if (cond.trueExp instanceof Constant) { cond.constTrueRes = cond.trueExp.evaluate(null); } if (cond.falseExp instanceof Constant) { cond.constFalseRes = cond.falseExp.evaluate(null); } } if (exp instanceof FuncCall) { FuncCall fc = (FuncCall)exp; for (int i = 0; i < fc.args.size(); ++i) { if (fc.args.get(i) instanceof Constant) { fc.constResults.set(i, fc.args.get(i).evaluate(null)); } } } } /** * Give a node a chance to swap itself out with a different subtree. */ @Override public Expression updateRef(Expression exp) throws Error { if (exp instanceof UnaryOp) { UnaryOp uo = (UnaryOp)exp; if (uo.subExp instanceof Constant) { // This is an unary operation on a constant, we can replace it with a constant ExpResult val = uo.evaluate(null); return new Constant(uo.context, val, uo.tokenPos); } } if (exp instanceof BinaryOp) { BinaryOp bo = (BinaryOp)exp; if ((bo.lSubExp instanceof Constant) && (bo.rSubExp instanceof Constant)) { // both sub expressions are constants, so replace the binop with a constant ExpResult val = bo.evaluate(null); return new Constant(bo.context, val, bo.tokenPos); } } return exp; } } private static ConstOptimizer CONST_OP = new ConstOptimizer(); /** * The main entry point to the expression parsing system, will either return a valid * expression that can be evaluated, or throw an error. */ public static Expression parseExpression(ParseContext context, String input) throws Error { ArrayList<ExpTokenizer.Token> ts; try { ts = ExpTokenizer.tokenize(input); } catch (ExpTokenizer.Error ex){ throw new Error(ex.getMessage()); } TokenList tokens = new TokenList(ts); Expression exp = parseExp(context, tokens, 0); // Make sure we've parsed all the tokens ExpTokenizer.Token peeked = tokens.peek(); if (peeked != null) { throw new Error(String.format("Unexpected additional values at position: %d", peeked.pos)); } exp.walk(CONST_OP); exp = CONST_OP.updateRef(exp); // Finally, give the entire expression a chance to optimize itself into a constant return exp; } private static Expression parseExp(ParseContext context, TokenList tokens, double bindPower) throws Error { Expression lhs = parseOpeningExp(context, tokens, bindPower); // Now peek for a binary op to modify this expression while (true) { ExpTokenizer.Token peeked = tokens.peek(); if (peeked == null || peeked.type != ExpTokenizer.SYM_TYPE) { break; } BinaryOpEntry binOp = getBinaryOp(peeked.value); if (binOp != null && binOp.bindingPower > bindPower) { // The next token is a binary op and powerful enough to bind us lhs = handleBinOp(context, tokens, lhs, binOp, peeked.pos); continue; } // Specific check for binding the conditional (?:) operator if (peeked.value.equals("?") && bindPower == 0) { lhs = handleConditional(context, tokens, lhs, peeked.pos); continue; } break; } // We have bound as many operators as we can, return it return lhs; } private static Expression handleBinOp(ParseContext context, TokenList tokens, Expression lhs, BinaryOpEntry binOp, int pos) throws Error { tokens.next(); // Consume the operator // For right associative operators, we weaken the binding power a bit at application time (but not testing time) double assocMod = binOp.rAssoc ? -0.5 : 0; Expression rhs = parseExp(context, tokens, binOp.bindingPower + assocMod); //currentPower = oe.bindingPower; return new BinaryOp(context, lhs, rhs, binOp.function, pos); } private static Expression handleConditional(ParseContext context, TokenList tokens, Expression lhs, int pos) throws Error { tokens.next(); // Consume the '?' Expression trueExp = parseExp(context, tokens, 0); tokens.expect(ExpTokenizer.SYM_TYPE, ":"); Expression falseExp = parseExp(context, tokens , 0); return new Conditional(context, lhs, trueExp, falseExp, pos); } public static Assignment parseAssignment(ParseContext context, String input) throws Error { ArrayList<ExpTokenizer.Token> ts; try { ts = ExpTokenizer.tokenize(input); } catch (ExpTokenizer.Error ex){ throw new Error(ex.getMessage()); } TokenList tokens = new TokenList(ts); ExpTokenizer.Token nextTok = tokens.next(); if (nextTok == null || (nextTok.type != ExpTokenizer.SQ_TYPE && !nextTok.value.equals("this") && !nextTok.value.equals("obj"))) { throw new Error("Assignments must start with an identifier"); } ArrayList<String> destination = parseIdentifier(nextTok, tokens); nextTok = tokens.next(); if (nextTok == null || nextTok.type != ExpTokenizer.SYM_TYPE || !nextTok.value.equals("=")) { throw new Error("Expected '=' in assignment"); } Expression exp = parseExp(context, tokens, 0); Assignment ret = new Assignment(); ret.destination = destination.toArray(STRING_ARRAY_TYPE); ret.value = exp; return ret; } // Static array to make ArrayList.toArray work private static final String[] STRING_ARRAY_TYPE = new String[0]; // The first half of expression parsing, parse a simple expression based on the next token private static Expression parseOpeningExp(ParseContext context, TokenList tokens, double bindPower) throws Error{ ExpTokenizer.Token nextTok = tokens.next(); // consume the first token if (nextTok == null) { throw new Error("Unexpected end of string"); } if (nextTok.type == ExpTokenizer.NUM_TYPE) { return parseConstant(context, nextTok.value, tokens, nextTok.pos); } if (nextTok.type == ExpTokenizer.VAR_TYPE && !nextTok.value.equals("this") && !nextTok.value.equals("obj")) { return parseFuncCall(context, nextTok.value, tokens, nextTok.pos); } if (nextTok.type == ExpTokenizer.SQ_TYPE || nextTok.value.equals("this") || nextTok.value.equals("obj")) { ArrayList<String> vals = parseIdentifier(nextTok, tokens); return new Variable(context, vals.toArray(STRING_ARRAY_TYPE), nextTok.pos); } // The next token must be a symbol // handle parenthesis if (nextTok.value.equals("(")) { Expression exp = parseExp(context, tokens, 0); tokens.expect(ExpTokenizer.SYM_TYPE, ")"); // Expect the closing paren return exp; } UnaryOpEntry oe = getUnaryOp(nextTok.value); if (oe != null) { Expression exp = parseExp(context, tokens, oe.bindingPower); return new UnaryOp(context, exp, oe.function, nextTok.pos); } // We're all out of tricks here, this is an unknown expression throw new Error(String.format("Can not parse expression at %d", nextTok.pos)); } private static Expression parseConstant(ParseContext context, String constant, TokenList tokens, int pos) throws Error { double mult = 1; Class<? extends Unit> ut = DimensionlessUnit.class; ExpTokenizer.Token peeked = tokens.peek(); if (peeked != null && peeked.type == ExpTokenizer.SQ_TYPE) { // This constant is followed by a square quoted token, it must be the unit tokens.next(); // Consume unit token UnitData unit = context.getUnitByName(peeked.value); if (unit == null) { throw new Error(String.format("Unknown unit: %s", peeked.value)); } mult = unit.scaleFactor; ut = unit.unitType; } return new Constant(context, new ExpResult(Double.parseDouble(constant)*mult, ut), pos); } private static Expression parseFuncCall(ParseContext context, String funcName, TokenList tokens, int pos) throws Error { tokens.expect(ExpTokenizer.SYM_TYPE, "("); ArrayList<Expression> arguments = new ArrayList<>(); ExpTokenizer.Token peeked = tokens.peek(); if (peeked == null) { throw new Error("Unexpected end of input in argument list"); } boolean isEmpty = false; if (peeked.value.equals(")")) { // Special case with empty argument list isEmpty = true; tokens.next(); // Consume closing parens } while (!isEmpty) { Expression nextArg = parseExp(context, tokens, 0); arguments.add(nextArg); ExpTokenizer.Token nextTok = tokens.next(); if (nextTok == null) { throw new Error("Unexpected end of input in argument list."); } if (nextTok.value.equals(")")) { break; } if (nextTok.value.equals(",")) { continue; } // Unexpected token throw new Error(String.format("Unexpected token in arguement list at: %d", nextTok.pos)); } FunctionEntry fe = getFunctionEntry(funcName); if (fe == null) { throw new Error(String.format("Uknown function: \"%s\"", funcName)); } if (fe.numMinArgs > 0 && arguments.size() < fe.numMinArgs){ throw new Error(String.format("Function \"%s\" expects at least %d arguments. %d provided.", funcName, fe.numMinArgs, arguments.size())); } if (fe.numMaxArgs > 0 && arguments.size() > fe.numMaxArgs){ throw new Error(String.format("Function \"%s\" expects at most %d arguments. %d provided.", funcName, fe.numMaxArgs, arguments.size())); } return new FuncCall(context, fe.function, arguments, pos); } private static ArrayList<String> parseIdentifier(ExpTokenizer.Token firstName, TokenList tokens) throws Error { ArrayList<String> vals = new ArrayList<>(); vals.add(firstName.value.intern()); while (true) { ExpTokenizer.Token peeked = tokens.peek(); if (peeked == null || peeked.type != ExpTokenizer.SYM_TYPE || !peeked.value.equals(".")) { break; } // Next token is a '.' so parse another name tokens.next(); // consume ExpTokenizer.Token nextName = tokens.next(); if (nextName == null || nextName.type != ExpTokenizer.VAR_TYPE) { throw new Error(String.format("Expected Identifier after '.' at pos: %d", peeked.pos)); } vals.add(nextName.value.intern()); } return vals; } }
package com.metaco.api; import com.metaco.api.contracts.*; import com.metaco.api.exceptions.MetacoClientException; import java.util.List; public interface MetacoClient { AccountRegistrationResult registerAccount(RegisterAccountRequest request) throws MetacoClientException; AccountStatus getAccountStatus() throws MetacoClientException; void confirmPhoneNumber(ValidateAccountRequest request) throws MetacoClientException; Asset[] getAssets() throws MetacoClientException; Asset getAsset(String ticker) throws MetacoClientException; AssetsHistoryResult getAssetsHistory(HistoryCriteria criteria) throws MetacoClientException; AssetsHistoryResult getAssetsHistory(HistoryCriteria criteria, List<String> tickers) throws MetacoClientException; Order createOrder(NewOrder createOrder) throws MetacoClientException; OrderResultPage getOrders() throws MetacoClientException; Order getOrder(String id) throws MetacoClientException; Order submitSignedOrder(String id, RawTransaction rawTransaction) throws MetacoClientException; void cancelOrder(String id) throws MetacoClientException; TransactionToSign createTransaction(NewTransaction newTransaction) throws MetacoClientException; TransactionBroadcastResult broadcastTransaction(RawTransaction rawTransaction) throws MetacoClientException; WalletDetails getWalletDetails(String address) throws MetacoClientException; /** * For testing purposes only * On some requests, when you use the TestingMode of the client, you will get a DebugData, which will simplify the testing of the API and the client * As an example, a debugData could be the fake validationCode when your register an account. */ String getLatestDebugData(); }
package com.wix.mysql; import com.google.common.collect.Sets; import com.google.common.io.CharStreams; import com.wix.mysql.config.MysqldConfig; import com.wix.mysql.input.LogFileProcessor; import com.wix.mysql.input.OutputWatchStreamProcessor; import de.flapdoodle.embed.process.collections.Collections; import de.flapdoodle.embed.process.config.IRuntimeConfig; import de.flapdoodle.embed.process.distribution.Distribution; import de.flapdoodle.embed.process.distribution.Platform; import de.flapdoodle.embed.process.extract.IExtractedFileSet; import de.flapdoodle.embed.process.io.StreamToLineProcessor; import de.flapdoodle.embed.process.runtime.AbstractProcess; import de.flapdoodle.embed.process.runtime.ProcessControl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.lang.reflect.Field; import java.nio.file.Paths; import java.util.List; import java.util.Set; import static com.wix.mysql.utils.Utils.closeCloseables; import static de.flapdoodle.embed.process.distribution.Platform.Windows; /** * @author viliusl * @since 27/09/14 */ public class MysqldProcess extends AbstractProcess<MysqldConfig, MysqldExecutable, MysqldProcess> { private final static Logger logger = LoggerFactory.getLogger(MysqldProcess.class); private OutputWatchStreamProcessor logWatch = null; private LogFileProcessor logFile = null; public MysqldProcess( final Distribution distribution, final MysqldConfig config, final IRuntimeConfig runtimeConfig, final MysqldExecutable executable) throws IOException { super(distribution, config, runtimeConfig, executable); } @Override protected void onBeforeProcessStart(ProcessBuilder processBuilder, MysqldConfig config, IRuntimeConfig runtimeConfig) { super.onBeforeProcessStart(processBuilder, config, runtimeConfig); logWatch = new OutputWatchStreamProcessor( Sets.newHashSet("ready for connections"), Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(runtimeConfig.getProcessOutput().getOutput())); logFile = new LogFileProcessor( new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), logWatch); } @Override public void onAfterProcessStart(final ProcessControl process, final IRuntimeConfig runtimeConfig) throws IOException { try { logWatch.waitForResult(getConfig().getTimeout()); if (!logWatch.isInitWithSuccess()) { throw new RuntimeException("mysql start failed with error: " + logWatch.getFailureFound()); } new MysqlConfigurer(getConfig(), runtimeConfig, getExecutable().executable.generatedBaseDir()).configure(); } catch (Exception e) { // emit IO exception for {@link AbstractProcess} would try to stop running process gracefully throw new IOException(e); } finally { if (logFile != null) logFile.shutdown(); } } @Override protected List<String> getCommandLine(Distribution distribution, MysqldConfig config, IExtractedFileSet exe) throws IOException { final String baseDir = exe.generatedBaseDir().getAbsolutePath(); return Collections.newArrayList( exe.executable().getAbsolutePath(), "--no-defaults", "--log-output=NONE", String.format("--basedir=%s", baseDir), String.format("--datadir=%s/data", baseDir), String.format("--plugin-dir=%s/lib/plugin", baseDir), String.format("--pid-file=%s.pid", pidFile(exe.executable())), String.format("--lc-messages-dir=%s/share", baseDir), String.format("--port=%s", config.getPort()), String.format("--log-error=%s/data/error.log", baseDir)); } @Override protected void stopInternal() { synchronized (this) { logger.info("try to stop mysqld"); if (!stopUsingMysqldadmin()) { logger.warn("could not stop mysqld via mysqladmin, try next"); if (!sendKillToProcess()) { logger.warn("could not stop mysqld, try next"); if (!sendTermToProcess()) { logger.warn("could not stop mysqld, try next"); if (!tryKillToProcess()) { logger.warn("could not stop mysqld the second time, try one last thing"); try { stopProcess(); } catch (IllegalStateException e) { logger.error("error while trying to stop mysql process", e); } } } } } } } @Override protected void cleanupInternal() {} private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet( "'Can't connect to MySQL server on 'localhost'", Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete"); try { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), String.format("--port=%s", getConfig().getPort()), "shutdown"}); retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { String errOutput = CharStreams.toString(stdErr); if (errOutput.contains("Can't connect to MySQL server on")) { logger.warn("mysql was already shutdown - no need to add extra shutdown hook - process does it out of the box."); retValue = true; } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdOut, stdErr); if (processor != null) processor.shutdown(); } return retValue; } /** * Work-around to get Executable in hooks where it's not provided and as * all init is done in base class constructor, local vars are still not * initialized:/ */ private MysqldExecutable getExecutable() { try { Field f = AbstractProcess.class.getDeclaredField("executable"); f.setAccessible(true); return (MysqldExecutable)f.get(this); } catch (Exception e) { throw new RuntimeException(e); } } /** * Work-around to get IRuntimeConfig in hooks where it's not provided and as * all init is done in base class constructor, local vars are still not * initialized:/ */ private IRuntimeConfig getRuntimeConfig() { try { Field f = AbstractProcess.class.getDeclaredField("runtimeConfig"); f.setAccessible(true); return (IRuntimeConfig)f.get(this); } catch (Exception e) { throw new RuntimeException(e); } } /** * Helper for getting stable sock file. Saving to local instance variable on service start does not work due * to the way flapdoodle process library works - it does all init in {@link AbstractProcess} and instance of * {@link MysqldProcess} is not yet present, so vars are not initialized. * This algo gives stable sock file based on single run profile, but can leave trash sock files in tmp dir. * * Notes: * .sock file needs to be in system temp dir and not in ex. target/... * This is due to possible problems with existing mysql installation and apparmor profiles * in linuxes. */ private String sockFile(IExtractedFileSet exe) throws IOException { String sysTempDir = System.getProperty("java.io.tmpdir"); String sockFile = String.format("%s.sock", exe.generatedBaseDir().getName()); return new File(sysTempDir, sockFile).getAbsolutePath(); } }
package jade.core; import jade.util.leap.LinkedList; import jade.util.Logger; public class Runtime { // JADE runtime execution modes: // MULTIPLE --> Several containers can be activated in a JVM private static final int MULTIPLE_MODE = 0; // SINGLE --> Only one container can be activated in a JVM private static final int SINGLE_MODE = 1; // UNKNOWN --> Mode not yet set private static final int UNKNOWN_MODE = 2; private static Runtime theInstance; static { theInstance = new Runtime(); } //#MIDP_EXCLUDE_BEGIN private ThreadGroup criticalThreads; //#MIDP_EXCLUDE_END private int activeContainers = 0; private LinkedList terminators = new LinkedList(); private AgentContainerImpl theContainer = null; private int mode = UNKNOWN_MODE; // Private constructor to forbid instantiation outside the class. private Runtime() { // Do nothing } /** * This method returns the singleton instance of this class * that should be then used to create agent containers. **/ public static Runtime instance() { return theInstance; } //#MIDP_EXCLUDE_BEGIN public jade.wrapper.AgentContainer createAgentContainer(Profile p) { if (mode == UNKNOWN_MODE || mode == MULTIPLE_MODE) { mode = MULTIPLE_MODE; p.setParameter(Profile.MAIN, "false"); // set to an agent container AgentContainerImpl impl = new AgentContainerImpl(p); beginContainer(); if (impl.joinPlatform()) { return impl.getContainerController(); } else { return null; } } else { throw new IllegalStateException("Single-container modality already activated"); } } public jade.wrapper.AgentContainer createMainContainer(Profile p) { if (mode == UNKNOWN_MODE || mode == MULTIPLE_MODE) { mode = MULTIPLE_MODE; p.setParameter(Profile.MAIN, "true"); // set to a main container AgentContainerImpl impl = new AgentContainerImpl(p); beginContainer(); if (impl.joinPlatform()) { return impl.getContainerController(); } else { return null; } } else { throw new IllegalStateException("Single-container modality already activated"); } } /** Causes the local JVM to be closed when the last container in this JVM terminates. <br> <b>NOT available in MIDP</b> <br> */ public void setCloseVM(boolean flag) { if (flag) { terminators.addLast(new Runnable() { public void run() { // Give one more chance to other threads to complete Thread.yield(); System.out.println("JADE is closing down now."); System.exit(0); } } ); } } //#MIDP_EXCLUDE_END public void startUp(Profile p) { if (mode == MULTIPLE_MODE) { throw new IllegalStateException("Multiple-container modality already activated"); } if (mode == UNKNOWN_MODE) { mode = SINGLE_MODE; theContainer = new AgentContainerImpl(p); beginContainer(); theContainer.joinPlatform(); } } /** Stops the JADE container running in the Single-container modality. */ public void shutDown() { if (theContainer != null) { theContainer.shutDown(); } } /** Allows setting a <code>Runnable</code> that is executed when the last container in this JVM terminates. */ public void invokeOnTermination(Runnable r) { terminators.addFirst(r); } // Called by a starting up container. void beginContainer() { Logger.println(getCopyrightNotice()); if(activeContainers == 0) { // Initialize and start up the timer dispatcher TimerDispatcher theDispatcher = new TimerDispatcher(); //#MIDP_EXCLUDE_BEGIN // Set up group and attributes for time critical threads criticalThreads = new ThreadGroup("JADE time-critical threads"); criticalThreads.setMaxPriority(Thread.MAX_PRIORITY); Thread t = new Thread(criticalThreads, theDispatcher); t.setPriority(criticalThreads.getMaxPriority()); t.setName("JADE Timer dispatcher"); //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN Thread t = new Thread(theDispatcher); #MIDP_INCLUDE_END*/ theDispatcher.setThread(t); TimerDispatcher.setTimerDispatcher(theDispatcher); theDispatcher.start(); } ++activeContainers; } // Called by a terminating container. void endContainer() { --activeContainers; if(activeContainers == 0) { // Start a new Thread that calls all terminators one after // the other Thread t = new Thread(new Runnable() { public void run() { for (int i = 0; i < terminators.size(); ++i) { Runnable r = (Runnable) terminators.get(i); r.run(); } } } ); //#MIDP_EXCLUDE_BEGIN t.setDaemon(false); //#MIDP_EXCLUDE_END // Terminate the TimerDispatcher and release its resources TimerDispatcher.getTimerDispatcher().stop(); // Reset mode mode = UNKNOWN_MODE; theContainer = null; //#MIDP_EXCLUDE_BEGIN try { criticalThreads.destroy(); } catch(IllegalThreadStateException itse) { System.out.println("Time-critical threads still active: "); criticalThreads.list(); } finally { criticalThreads = null; } //#MIDP_EXCLUDE_END t.start(); } } //#APIDOC_EXCLUDE_BEGIN public TimerDispatcher getTimerDispatcher() { return TimerDispatcher.getTimerDispatcher(); } //#APIDOC_EXCLUDE_END //#APIDOC_EXCLUDE_BEGIN public static String getCopyrightNotice() { String CVSname = "$Name$"; String CVSdate = "$Date$"; int colonPos = CVSname.indexOf(":"); int dollarPos = CVSname.lastIndexOf('$'); String name = CVSname.substring(colonPos + 1, dollarPos); if(name.indexOf("JADE") == -1) name = "JADE snapshot"; else { name = name.replace('-', ' '); name = name.replace('_', '.'); name = name.trim(); } colonPos = CVSdate.indexOf(':'); dollarPos = CVSdate.lastIndexOf('$'); String date = CVSdate.substring(colonPos + 1, dollarPos); date = date.trim(); return(" This is "+name + " - " + date+"\n downloaded in Open Source, under LGPL restrictions,\n at http://jade.cselt.it/\n"); } //#APIDOC_EXCLUDE_END }
package dbpedia; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import edu.stanford.nlp.ling.CoreLabel; import edu.stanford.nlp.process.CoreLabelTokenFactory; import edu.stanford.nlp.process.PTBTokenizer; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.jena.riot.RDFDataMgr; import org.rdfhdt.hdt.hdt.HDT; import org.rdfhdt.hdt.hdt.HDTManager; import org.rdfhdt.hdtjena.HDTGraph; public class PairCountsProcessor { public void process(String dataLoc) { PrintWriter out = null; try { // String dir = "/Users/Milan/Downloads/db-abstracts-en/"; out = new PrintWriter(new BufferedWriter(new FileWriter(dataLoc+"train-data-pair-counts/pairCounts", true))); HashMap<String,Occurrence> hm = new HashMap(); File folder = new File(dataLoc+"dbpedia-abstracts/"); File[] listOfFiles = folder.listFiles(); System.out.println(dataLoc); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { if(listOfFiles[i].getName().endsWith(".ttl")) { System.out.println("File " + dataLoc+"dbpedia-abstracts/"+listOfFiles[i].getName()); convertOneFile(dataLoc+"dbpedia-abstracts/"+listOfFiles[i].getName(), dataLoc, hm); } } } Iterator it = hm.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); // System.out.println(pair.getKey() + " = " + pair.getValue()); Occurrence occ = (Occurrence)pair.getValue(); out.write(occ.getLabel()+"\t"+URLDecoder.decode(occ.getLink(), "UTF-8")+"\t"+occ.getCount()+"\n"); it.remove(); // avoids a ConcurrentModificationException } } catch (IOException ex) { Logger.getLogger(PairCountsProcessor.class.getName()).log(Level.SEVERE, null, ex); } finally { out.close(); } } public void convertOneFile(String fileLoc, String dataLoc, HashMap<String,Occurrence> hm) { Model model = RDFDataMgr.loadModel(fileLoc); System.out.println(fileLoc); StmtIterator ctxtIter = model.listStatements(null, RDF.type, model.getProperty("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#Context")); while(ctxtIter.hasNext()) { PrintWriter out = null; Statement ctxtStm = ctxtIter.nextStatement(); Resource ctxtRes = ctxtStm.getSubject(); try { // String docId = ctxtRes.getURI().split("/")[ctxtRes.getURI().split("/").length-2]; // String[] splitParts = ctxtRes.getURI().split("dbpedia.org/resource/"); // String[] secondParts = splitParts[1].split("/abstract"); // String docId = secondParts[0]; // docId = docId.replaceAll("/", "_"); // System.out.println(docId); // out = new PrintWriter(new BufferedWriter(new FileWriter(dataLoc+"train-data/"+docId, true))); StmtIterator entityIter = model.listStatements(null, model.getProperty("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#referenceContext"), ctxtRes); while(entityIter.hasNext()) { Statement entityStm = entityIter.nextStatement(); Resource entityRes = entityStm.getSubject(); String anchor = entityRes.getProperty(model.getProperty("http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#anchorOf")).getString(); String link = null; Statement linkStm = entityRes.getProperty(model.getProperty("http://www.w3.org/2005/11/its/rdf#taIdentRef")); if(linkStm != null) { link = linkStm.getObject().asResource().getURI(); if(hm.containsKey(anchor+":"+link)) { Occurrence occ = hm.get(anchor+":"+link); int counter = occ.getCount(); counter++; occ.setCount(counter); // System.out.println(occ.getLabel()+":"+ occ.getLink()+":"+occ.getCount()); hm.put(anchor+":"+link, occ); } else { // first occurrence Occurrence occ = new Occurrence(); occ.setLabel(anchor); occ.setLink(link); occ.setCount(1); hm.put(anchor+":"+link, occ); } } } } catch (Exception ex) { System.out.println("problem:" + ex.getMessage()); System.out.println("problem:" + ex.fillInStackTrace()); } finally { try { // out.close(); } catch (Exception ex) { System.out.println("problem2:" + ex.getMessage()); System.out.println("problem2:" + ex.fillInStackTrace()); } } } } public class Occurrence { private int count; private String label; private String link; /** * @return the count */ public int getCount() { return count; } /** * @param count the count to set */ public void setCount(int count) { this.count = count; } /** * @return the label */ public String getLabel() { return label; } /** * @param label the label to set */ public void setLabel(String label) { this.label = label; } /** * @return the link */ public String getLink() { return link; } /** * @param link the link to set */ public void setLink(String link) { this.link = link; } } }
package jade.core; import java.net.MalformedURLException; import java.rmi.*; // FIXME: This will go away... import java.rmi.registry.*; // FIXME: This will go away... import java.util.LinkedList; /** This class is a Singleton class, allowing intial access to the JADE runtime system. Invoking methods on the shared instance of this class, it is possible to create <it>in-process</it> agent containers. @author Giovanni Rimassa - Universita` di Parma */ public class Runtime { private static Runtime theInstance; static { theInstance = new Runtime(); } // Private constructor to forbid instantiation outside the class. private Runtime() { // Do nothing } public static Runtime instance() { return theInstance; } /** Creates a new agent container in the current JVM, providing access through a proxy object. @return A proxy object, through which services can be requested from the real JADE container. */ public jade.wrapper.AgentContainer createAgentContainer(Profile p) { try { String host = p.getParameter(Profile.MAIN_HOST); String port = p.getParameter(Profile.MAIN_PORT); String platformRMI = "rmi://" + host + ":" + port + "/JADE"; String[] empty = new String[] { }; AgentContainerImpl impl = new AgentContainerImpl(p); // Look the remote Main Container up into the // RMI Registry, then create a Smart Proxy for it. MainContainer remoteMC = (MainContainer)Naming.lookup(platformRMI); MainContainer mc = new MainContainerProxy(remoteMC); impl.joinPlatform(mc, new LinkedList().iterator(), empty, empty); beginContainer(); return new jade.wrapper.AgentContainer(impl); } catch(RemoteException re) { throw new InternalError("Remote exception in a local call."); } catch(NotBoundException nbe) { throw new InternalError("The platform was not found in the RMI Registry"); } catch(MalformedURLException murle) { throw new InternalError("Malformed URL exception"); // FIXME: Need to throw a suitable exception } catch(ProfileException pe) { throw new InternalError("Can't read configuration from Profile."); } } /** Creates a new main container in the current JVM, providing access through a proxy object. @return A proxy object, through which services can be requested from the real JADE main container. */ public jade.wrapper.MainContainer createMainContainer(Profile p) { try { String host = p.getParameter(Profile.MAIN_HOST); String port = p.getParameter(Profile.MAIN_PORT); String platformRMI = "rmi://" + host + ":" + port + "/JADE"; AgentContainerImpl impl = new AgentContainerImpl(p); MainContainerImpl mc = new MainContainerImpl(p); // Create an embedded RMI Registry within the platform and // bind the Agent Platform to it int portNumber = Integer.parseInt(port); Registry theRegistry = LocateRegistry.createRegistry(portNumber); Naming.bind(platformRMI, mc); String[] empty = new String[] { }; impl.joinPlatform(mc, new LinkedList().iterator(), empty, empty); beginContainer(); return new jade.wrapper.MainContainer(impl); } catch(RemoteException re) { throw new InternalError("Remote Exception"); // FIXME: Need to throw a suitable exception } catch(MalformedURLException murle) { throw new InternalError("Malformed URL exception"); // FIXME: Need to throw a suitable exception } catch(AlreadyBoundException abe) { throw new InternalError("Already Bound Exception"); // FIXME: Need to throw a suitable exception } catch(ProfileException pe) { throw new InternalError("Can't read configuration from Profile."); } } // Called by jade.core.Starter to make the VM terminate when all the // containers are closed. void setCloseVM(boolean flag) { closeVM = flag; } // Called by a starting up container. void beginContainer() { if(activeContainers == 0) { // Set up group and attributes for time critical threads criticalThreads = new ThreadGroup("JADE time-critical threads"); criticalThreads.setMaxPriority(Thread.MAX_PRIORITY); // Initialize and start up the timer dispatcher theDispatcher = new TimerDispatcher(); Thread t = new Thread(criticalThreads, theDispatcher); t.setPriority(criticalThreads.getMaxPriority()); theDispatcher.setThread(t); theDispatcher.start(); } ++activeContainers; } // Called by a terminating container. void endContainer() { --activeContainers; if(activeContainers == 0) { theDispatcher.stop(); try { criticalThreads.destroy(); } catch(IllegalThreadStateException itse) { System.out.println("Time-critical threads still active: "); criticalThreads.list(); } finally { criticalThreads = null; } if(closeVM) System.exit(0); } } TimerDispatcher getTimerDispatcher() { return theDispatcher; } private ThreadGroup criticalThreads; private TimerDispatcher theDispatcher; private int activeContainers = 0; private boolean closeVM = false; private AgentToolkit defaultToolkit; void setDefaultToolkit(AgentToolkit tk) { defaultToolkit = tk; } AgentToolkit getDefaultToolkit() { return defaultToolkit; } }
package de.skuzzle.semantic; import java.io.Serializable; import java.util.Comparator; public final class Version implements Comparable<Version>, Serializable { /** Conforms to all Version implementations since 0.6.0 */ private static final long serialVersionUID = 6034927062401119911L; private static final String[] EMPTY_ARRAY = new String[0]; /** * Semantic Version Specification to which this class complies * * @since 0.2.0 */ public static final Version COMPLIANCE = Version.create(2, 0, 0); /** * This exception indicates that a version- or a part of a version string could not be * parsed according to the semantic version specification. * * @author Simon Taddiken */ public static class VersionFormatException extends RuntimeException { private static final long serialVersionUID = 1L; /** * Creates a new VersionFormatException with the given message. * * @param message The exception message. */ private VersionFormatException(String message) { super(message); } } /** * Comparator for natural version ordering. See {@link #compare(Version, Version)} for * more information. * * @since 0.2.0 */ public static final Comparator<Version> NATURAL_ORDER = new Comparator<Version>() { @Override public int compare(Version o1, Version o2) { return Version.compare(o1, o2); } }; /** * Comparator for ordering versions with additionally considering the build meta data * field when comparing versions. * * <p> * Note: this comparator imposes orderings that are inconsistent with equals. * </p> * * @since 0.3.0 */ public static final Comparator<Version> WITH_BUILD_META_DATA_ORDER = new Comparator<Version>() { @Override public int compare(Version o1, Version o2) { return compareWithBuildMetaData(o1, o2); } }; private static final int TO_STRING_ESTIMATE = 12; private static final int HASH_PRIME = 31; // state machine states for parsing a version string private static final int STATE_MAJOR = 0; private static final int STATE_MINOR = 1; private static final int STATE_PATCH = 2; private static final int STATE_PRE_RELEASE = 3; private static final int STATE_PRE_RELEASE_ID = 4; private static final int STATE_BUILD_MD = 5; private static final int EOS = -1; private static final int FAILURE = -2; private final int major; private final int minor; private final int patch; private final String preRelease; private final String buildMetaData; // store hash code once it has been calculated private volatile int hash; private Version(int major, int minor, int patch, String preRelease, String buildMd) { this.major = major; this.minor = minor; this.patch = patch; this.preRelease = preRelease; this.buildMetaData = buildMd; } private Version(String v) { int i = 0; int stateBefore = STATE_MAJOR; int state = stateBefore; final char[] chars = v.toCharArray(); int majorPart = 0; int minorPart = 0; int patchpart = 0; StringBuilder preReleasePart = null; StringBuilder buildMDPart = null; while (i <= chars.length) { final boolean stateSwitched = i == 0 || state != stateBefore; stateBefore = state; final int c = i == chars.length ? -1 : chars[i]; switch (state) { case STATE_MAJOR: if (c != '.' && majorPart == 0 && !stateSwitched) { throw illegalLeadingChar(v, c, "major"); } else if (c >= '0' && c <= '9') { majorPart = Character.digit(c, 10) + majorPart * 10; } else if (c == '.') { state = STATE_MINOR; } else { throw unexpectedChar(v, c); } break; case STATE_MINOR: if (c != '.' && minorPart == 0 && !stateSwitched) { throw illegalLeadingChar(v, c, "minor"); } else if (c >= '0' && c <= '9') { minorPart = Character.digit(c, 10) + minorPart * 10; } else if (c == '.') { state = STATE_PATCH; } else { throw unexpectedChar(v, c); } break; case STATE_PATCH: if (c != EOS && c != '-' && c != '+' && patchpart == 0 && !stateSwitched) { throw illegalLeadingChar(v, c, "patch"); } else if (c >= '0' && c <= '9') { patchpart = Character.digit(c, 10) + patchpart * 10; } else if (c == '-') { state = STATE_PRE_RELEASE; } else if (c == '+') { state = STATE_BUILD_MD; } else if (c != EOS) { throw unexpectedChar(v, c); } break; case STATE_PRE_RELEASE: preReleasePart = new StringBuilder(); state = parseIdentifiers(chars, i, preReleasePart, false, true, false, "pre-release"); i += preReleasePart.length(); break; case STATE_BUILD_MD: buildMDPart = new StringBuilder(); state = parseIdentifiers(chars, i, buildMDPart, true, true, false, "build-meta-data"); break; case EOS: break; default: throw new IllegalStateException("Illegal state " + state); } ++i; } this.major = majorPart; this.minor = minorPart; this.patch = patchpart; checkParams(majorPart, minorPart, patchpart); this.preRelease = preReleasePart == null ? "" : preReleasePart.toString(); this.buildMetaData = buildMDPart == null ? "" : buildMDPart.toString(); } private static int parseIdentifiers(char[] chars, int start, StringBuilder b, boolean allowLeading0, boolean allowTransition, boolean checkOnly, String partName) { int state = STATE_PRE_RELEASE; int partStart = -1; int i = start; while (i <= chars.length) { final int c = i == chars.length ? -1 : chars[i]; switch (state) { case STATE_PRE_RELEASE: if ((c == '.' || c == EOS) && partStart == -1) { // empty part if (checkOnly) { return FAILURE; } throw unexpectedChar(new String(chars), c); } else if (c == '.') { // start of new part if (!allowLeading0 && chars[partStart] == '0' && i - partStart > 1) { if (checkOnly) { return FAILURE; } throw illegalLeadingChar(new String(chars), c, partName); } partStart = -1; b.appendCodePoint(c); i++; continue; } if (partStart == -1) { partStart = i; } if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '-') { b.appendCodePoint(c); state = STATE_PRE_RELEASE_ID; } else if (c >= '0' && c <= '9') { b.appendCodePoint(c); } else if (c == '+') { if (!allowLeading0 && chars[partStart] == '0' && i - partStart > 1) { if (checkOnly) { return FAILURE; } throw illegalLeadingChar(new String(chars), c, partName); } else if (!allowTransition) { if (checkOnly) { return FAILURE; } throw unexpectedChar(new String(chars), c); } return STATE_BUILD_MD; } else if (c == EOS) { if (!allowLeading0 && chars[partStart] == '0' && i - partStart > 1) { if (checkOnly) { return FAILURE; } throw illegalLeadingChar(new String(chars), partStart, partName); } } else { if (checkOnly) { return FAILURE; } throw unexpectedChar(new String(chars), c); } break; case STATE_PRE_RELEASE_ID: if (c == '.') { b.appendCodePoint(c); partStart = -1; state = STATE_PRE_RELEASE; } else if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '-') { b.appendCodePoint(c); } else if (c >= '0' && c <= '9') { b.appendCodePoint(c); } else if (c == '+') { if (!allowTransition) { if (checkOnly) { return FAILURE; } throw unexpectedChar(new String(chars), c); } return STATE_BUILD_MD; } else if (c != EOS) { if (checkOnly) { return FAILURE; } throw unexpectedChar(new String(chars), c); } break; default: throw new IllegalStateException("Illegal state" + start); } ++i; } return EOS; } private static VersionFormatException illegalLeadingChar(String v, int c, String part) { if (c == -1) { return new VersionFormatException(String.format( "Incomplete version part in %s", v)); } return new VersionFormatException( String.format("Illegal leading char '%c' in %s part of %s", c, part, v)); } private static VersionFormatException unexpectedChar(String v, int c) { if (c == -1) { return new VersionFormatException(String.format( "Incomplete version part in %s", v)); } return new VersionFormatException( String.format("Unexpected char in %s: %c", v, c)); } /** * Tries to parse the given String as a semantic version and returns whether the * String is properly formatted according to the semantic version specification. * * <p> * Note: this method does not throw an exception upon <code>null</code> input, but * returns <code>false</code> instead. * </p> * * @param version The String to check. * @return Whether the given String is formatted as a semantic version. * @since 0.5.0 */ public static boolean isValidVersion(String version) { if (version == null || version.isEmpty()) { return false; } try { new Version(version); return true; } catch (final VersionFormatException e) { return false; } } /** * Returns whether the given String is a valid pre-release identifier. That is, this * method returns <code>true</code> if, and only if the {@code preRelease} parameter * is either the empty string or properly formatted as a pre-release identifier * according to the semantic version specification. * * <p> * Note: this method does not throw an exception upon <code>null</code> input, but * returns <code>false</code> instead. * </p> * * @param preRelease The String to check. * @return Whether the given String is a valid pre-release identifier. * @since 0.5.0 */ public static boolean isValidPreRelease(String preRelease) { if (preRelease == null) { return false; } else if (preRelease.isEmpty()) { return true; } return parseIdentifiers(preRelease.toCharArray(), 0, new StringBuilder(), false, false, true, "") != FAILURE; } /** * Returns whether the given String is a valid build meta data identifier. That is, * this method returns <code>true</code> if, and only if the {@code buildMetaData} * parameter is either the empty string or properly formatted as a build meta data * identifier according to the semantic version specification. * * <p> * Note: this method does not throw an exception upon <code>null</code> input, but * returns <code>false</code> instead. * </p> * * @param buildMetaData The String to check. * @return Whether the given String is a valid build meta data identifier. * @since 0.5.0 */ public static boolean isValidBuildMetaData(String buildMetaData) { if (buildMetaData == null) { return false; } else if (buildMetaData.isEmpty()) { return true; } return parseIdentifiers(buildMetaData.toCharArray(), 0, new StringBuilder(), true, false, true, "") != FAILURE; } public static Version max(Version v1, Version v2) { require(v1 != null, "v1 is null"); require(v2 != null, "v2 is null"); return compare(v1, v2, false) < 0 ? v2 : v1; } public static Version min(Version v1, Version v2) { require(v1 != null, "v1 is null"); require(v2 != null, "v2 is null"); return compare(v1, v2, false) <= 0 ? v1 : v2; } public static int compare(Version v1, Version v2) { // throw NPE to comply with Comparable specification if (v1 == null) { throw new NullPointerException("v1 is null"); } else if (v2 == null) { throw new NullPointerException("v2 is null"); } return compare(v1, v2, false); } /** * Compares two Versions with additionally considering the build meta data field if * all other parts are equal. Note: This is <em>not</em> part of the semantic version * specification. * * <p> * Comparison of the build meta data parts happens exactly as for pre release * identifiers. Considering of build meta data first kicks in if both versions are * equal when using their natural order. * </p> * * <p> * This method fulfills the general contract for Java's {@link Comparator Comparators} * and {@link Comparable Comparables}. * </p> * * @param v1 The first version for comparison. * @param v2 The second version for comparison. * @return A value below 0 iff {@code v1 &lt; v2}, a value above 0 iff * {@code v1 &gt; v2</tt> and 0 iff <tt>v1 = v2}. * @throws NullPointerException If either parameter is null. * @since 0.3.0 */ public static int compareWithBuildMetaData(Version v1, Version v2) { // throw NPE to comply with Comparable specification if (v1 == null) { throw new NullPointerException("v1 is null"); } else if (v2 == null) { throw new NullPointerException("v2 is null"); } return compare(v1, v2, true); } private static int compare(Version v1, Version v2, boolean withBuildMetaData) { int result = 0; if (v1 != v2) { final int mc, mm, mp, pr, md; if ((mc = compareInt(v1.major, v2.major)) != 0) { result = mc; } else if ((mm = compareInt(v1.minor, v2.minor)) != 0) { result = mm; } else if ((mp = compareInt(v1.patch, v2.patch)) != 0) { result = mp; } else if ((pr = comparePreRelease(v1, v2)) != 0) { result = pr; } else if (withBuildMetaData && ((md = compareBuildMetaData(v1, v2)) != 0)) { result = md; } } return result; } private static int compareInt(int a, int b) { return a - b; } private static int comparePreRelease(Version v1, Version v2) { return compareLiterals(v1.getPreRelease(), v2.getPreRelease()); } private static int compareBuildMetaData(Version v1, Version v2) { return compareLiterals(v1.getBuildMetaData(), v2.getBuildMetaData()); } private static int compareLiterals(String v1Literal, String v2Literal) { int result = 0; if (!v1Literal.isEmpty() && !v2Literal.isEmpty()) { // compare pre release parts result = compareIdentifiers(v1Literal.split("\\."), v2Literal.split("\\.")); } else if (!v1Literal.isEmpty()) { // other is greater, because it is no pre release result = -1; } else if (!v2Literal.isEmpty()) { // this is greater because other is no pre release result = 1; } return result; } private static int compareIdentifiers(String[] parts1, String[] parts2) { final int min = Math.min(parts1.length, parts2.length); for (int i = 0; i < min; ++i) { final int r = compareIdentifierParts(parts1[i], parts2[i]); if (r != 0) { // versions differ in part i return r; } } // all id's are equal, so compare amount of id's return compareInt(parts1.length, parts2.length); } private static int compareIdentifierParts(String p1, String p2) { final int num1 = isNumeric(p1); final int num2 = isNumeric(p2); final int result; if (num1 < 0 && num2 < 0) { // both are not numerical -> compare lexically result = p1.compareTo(p2); } else if (num1 >= 0 && num2 >= 0) { // both are numerical result = compareInt(num1, num2); } else if (num1 >= 0) { // only part1 is numerical -> p2 is greater result = -1; } else { // only part2 is numerical -> p1 is greater result = 1; } return result; } /** * Determines whether s is a positive number. If it is, the number is returned, * otherwise the result is -1. * * @param s The String to check. * @return The positive number (incl. 0) if s a number, or -1 if it is not. */ private static int isNumeric(String s) { try { return Integer.parseInt(s); } catch (final NumberFormatException e) { return -1; } } /** * Creates a new Version from the provided components. Neither value of * {@code major, minor} or {@code patch} must be lower than 0 and at least one must be * greater than zero. {@code preRelease} or {@code buildMetaData} may be the empty * String. In this case, the created {@code Version} will have no pre release resp. * build meta data field. If those parameters are not empty, they must conform to the * semantic version specification. * * @param major The major version. * @param minor The minor version. * @param patch The patch version. * @param preRelease The pre release version or the empty string. * @param buildMetaData The build meta data field or the empty string. * @return The version instance. * @throws VersionFormatException If {@code preRelease} or {@code buildMetaData} does * not conform to the semantic version specification. */ public static final Version create(int major, int minor, int patch, String preRelease, String buildMetaData) { checkParams(major, minor, patch); require(preRelease != null, "preRelease is null"); require(buildMetaData != null, "buildMetaData is null"); if (!isValidPreRelease(preRelease)) { throw new VersionFormatException( String.format("Illegal pre-release part: %s", preRelease)); } else if (!isValidBuildMetaData(buildMetaData)) { throw new VersionFormatException( String.format("Illegal build-meta-data part: %s", buildMetaData)); } return new Version(major, minor, patch, preRelease, buildMetaData); } /** * Creates a new Version from the provided components. The version's build meta data * field will be empty. Neither value of {@code major, minor} or {@code patch} must be * lower than 0 and at least one must be greater than zero. {@code preRelease} may be * the empty String. In this case, the created version will have no pre release field. * If it is not empty, it must conform to the specifications of the semantic version. * * @param major The major version. * @param minor The minor version. * @param patch The patch version. * @param preRelease The pre release version or the empty string. * @return The version instance. * @throws VersionFormatException If {@code preRelease} is not empty and does not * conform to the semantic versioning specification */ public static final Version create(int major, int minor, int patch, String preRelease) { checkParams(major, minor, patch); require(preRelease != null, "preRelease is null"); if (!isValidPreRelease(preRelease)) { throw new VersionFormatException(preRelease); } return new Version(major, minor, patch, preRelease, ""); } /** * Creates a new Version from the three provided components. The version's pre release * and build meta data fields will be empty. Neither value must be lower than 0 and at * least one must be greater than zero * * @param major The major version. * @param minor The minor version. * @param patch The patch version. * @return The version instance. */ public static final Version create(int major, int minor, int patch) { checkParams(major, minor, patch); return new Version(major, minor, patch, "", ""); } private static void checkParams(int major, int minor, int patch) { require(major >= 0, "major < 0"); require(minor >= 0, "minor < 0"); require(patch >= 0, "patch < 0"); require(major != 0 || minor != 0 || patch != 0, "all parts are 0"); } private static void require(boolean condition, String message) { if (!condition) { throw new IllegalArgumentException(message); } } public static final Version parseVersion(String versionString) { require(versionString != null, "versionString is null"); return new Version(versionString); } /** * Tries to parse the provided String as a semantic version. If * {@code allowPreRelease} is <code>false</code>, the String must have neither a * pre-release nor a build meta data part. Thus the given String must have the format * {@code X.Y.Z} where at least one part must be greater than zero. * * <p> * If {@code allowPreRelease} is <code>true</code>, the String is parsed according to * the normal semantic version specification. * </p> * * @param versionString The String to parse. * @param allowPreRelease Whether pre-release and build meta data field are allowed. * @return The parsed version. * @throws VersionFormatException If the String is no valid version * @since 0.4.0 */ public static Version parseVersion(String versionString, boolean allowPreRelease) { final Version version = parseVersion(versionString); if (!allowPreRelease && (version.isPreRelease() || version.hasBuildMetaData())) { throw new VersionFormatException(String.format( "Version string '%s' is expected to have no pre-release or " + "build meta data part", versionString)); } return version; } public Version min(Version other) { return min(this, other); } public Version max(Version other) { return max(this, other); } /** * Gets this version's major number. * * @return The major version. */ public int getMajor() { return this.major; } /** * Gets this version's minor number. * * @return The minor version. */ public int getMinor() { return this.minor; } /** * Gets this version's path number. * * @return The patch number. */ public int getPatch() { return this.patch; } /** * Gets the pre release parts of this version as array by splitting the pre result * version string at the dots. * * @return Pre release version as array. Array is empty if this version has no pre * release part. */ public String[] getPreReleaseParts() { return this.preRelease.isEmpty() ? EMPTY_ARRAY : this.preRelease.split("\\."); } /** * Gets the pre release identifier of this version. If this version has no such * identifier, an empty string is returned. * * @return This version's pre release identifier or an empty String if this version * has no such identifier. */ public String getPreRelease() { return this.preRelease; } /** * Gets this version's build meta data. If this version has no build meta data, the * returned string is empty. * * @return The build meta data or an empty String if this version has no build meta * data. */ public String getBuildMetaData() { return this.buildMetaData; } /** * Gets this version's build meta data as array by splitting the meta data at dots. If * this version has no build meta data, the result is an empty array. * * @return The build meta data as array. */ public String[] getBuildMetaDataParts() { return this.buildMetaData.isEmpty() ? EMPTY_ARRAY : this.buildMetaData.split("\\."); } /** * Determines whether this version is still under initial development. * * @return <code>true</code> iff this version's major part is zero. */ public boolean isInitialDevelopment() { return this.major == 0; } /** * Determines whether this is a pre release version. * * @return <code>true</code> iff {@link #getPreRelease()} is not empty. */ public boolean isPreRelease() { return !this.preRelease.isEmpty(); } /** * Determines whether this version has a build meta data field. * * @return <code>true</code> iff {@link #getBuildMetaData()} is not empty. */ public boolean hasBuildMetaData() { return !this.buildMetaData.isEmpty(); } /** * Creates a String representation of this version by joining its parts together as by * the semantic version specification. * * @return The version as a String. */ @Override public String toString() { final StringBuilder b = new StringBuilder(this.preRelease.length() + this.buildMetaData.length() + TO_STRING_ESTIMATE); b.append(this.major).append(".").append(this.minor).append(".") .append(this.patch); if (!this.preRelease.isEmpty()) { b.append("-").append(this.preRelease); } if (!this.buildMetaData.isEmpty()) { b.append("+").append(this.buildMetaData); } return b.toString(); } /** * The hash code for a version instance is computed from the fields {@link #getMajor() * major}, {@link #getMinor() minor}, {@link #getPatch() patch} and * {@link #getPreRelease() pre-release}. * * @return A hash code for this object. */ @Override public int hashCode() { int h = this.hash; if (h == 0) { h = HASH_PRIME + this.major; h = HASH_PRIME * h + this.minor; h = HASH_PRIME * h + this.patch; h = HASH_PRIME * h + this.preRelease.hashCode(); this.hash = h; } return this.hash; } /** * Determines whether this version is equal to the passed object. This is the case if * the passed object is an instance of Version and this version * {@link #compareTo(Version) compared} to the provided one yields 0. Thus, this * method ignores the {@link #getBuildMetaData()} field. * * @param obj the object to compare with. * @return <code>true</code> iff {@code obj} is an instance of {@code Version} and * {@code this.compareTo((Version) obj) == 0} * @see #compareTo(Version) */ @Override public boolean equals(Object obj) { return testEquality(obj, false); } /** * Determines whether this version is equal to the passed object (as determined by * {@link #equals(Object)} and additionally considers the build meta data part of both * versions for equality. * * @param obj The object to compare with. * @return <code>true</code> iff {@code this.equals(obj)} and * {@code this.getBuildMetaData().equals(((Version) obj).getBuildMetaData())} * @since 0.4.0 */ public boolean equalsWithBuildMetaData(Object obj) { return testEquality(obj, true); } private boolean testEquality(Object obj, boolean includeBuildMd) { return obj == this || obj instanceof Version && compare(this, (Version) obj, includeBuildMd) == 0; } /** * Compares this version to the provided one, following the <em>semantic * versioning</em> specification. See {@link #compare(Version, Version)} for more * information. * * @param other The version to compare to. * @return A value lower than 0 if this &lt; other, a value greater than 0 if this * &gt; other and 0 if this == other. The absolute value of the result has no * semantical interpretation. */ @Override public int compareTo(Version other) { return compare(this, other); } /** * Compares this version to the provided one. Unlike the {@link #compareTo(Version)} * method, this one additionally considers the build meta data field of both versions, * if all other parts are equal. Note: This is <em>not</em> part of the semantic * version specification. * * <p> * Comparison of the build meta data parts happens exactly as for pre release * identifiers. Considering of build meta data first kicks in if both versions are * equal when using their natural order. * </p> * * @param other The version to compare to. * @return A value lower than 0 if this &lt; other, a value greater than 0 if this * &gt; other and 0 if this == other. The absolute value of the result has no * semantical interpretation. * @since 0.3.0 */ public int compareToWithBuildMetaData(Version other) { return compareWithBuildMetaData(this, other); } /** * Returns a new Version where all identifiers are converted to upper case letters. * * @return A new version with upper case identifiers. * @since 1.1.0 */ public Version toUpperCase() { return new Version(this.major, this.minor, this.patch, this.preRelease.toUpperCase(), this.buildMetaData.toUpperCase()); } /** * Returns a new Version where all identifiers are converted to lower case letters. * * @return A new version with lower case identifiers. * @since 1.1.0 */ public Version toLowerCase() { return new Version(this.major, this.minor, this.patch, this.preRelease.toLowerCase(), this.buildMetaData.toLowerCase()); } }
import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class InsertFlight extends HttpServlet { private String formatTime(String time) { return "TO_DATE('" + time.trim() + ":00'" + ", 'hh24:mi:ss')"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String airline = request.getParameter("airline"); String plane = request.getParameter("plane"); String source = request.getParameter("source"); String destination = request.getParameter("destination"); String origin = request.getParameter("origin"); String time = request.getParameter("time"); String num = request.getParameter("num"); String flights = "INSERT INTO Flight(num, src, destination) " + "VALUES ( '" + num + "'," + "'" + source + "'," + "'" + destination + "')"; String incoming = "INSERT INTO IncomingFlight (num, plannedarrival) " + "VALUES ( '" + num + "'," + "" + formatTime(time) + ")"; String outgoing = "INSERT INTO OutgoingFlight (num, planneddeparture) " + "VALUES ( '" + num + "'," + "" + formatTime(time) + ")"; String operates = "INSERT INTO Operates (airlinecode, planemodelcode, flightnumber) " + "VALUES ('" + airline +"'," + "'" + plane + "',"+ "'" + num + "')"; Connection conn = ConnectionManager.getInstance().getConnection(); String resp = ""; try { Statement st = conn.createStatement(); st.executeUpdate(flights); st.executeUpdate(operates); if (origin.equals("incoming")) { st.executeUpdate(incoming); } if (origin.equals("outgoing")) { st.executeUpdate(outgoing); } st.close(); } catch (SQLException e) { resp = "Encountered error: " + e; } resp += "<html><head><title>Successfully inserted</title></head>" + "<body><p>Successfully inserted new flight <b>" + airline + num + "</b>. <a href='/servlet/InsertFlightForm'>Go Back</a>.</p></body></html>"; String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; out.println(docType + resp); } }
package ee.sk.smartid; import ee.sk.smartid.rest.SessionStatusPoller; import ee.sk.smartid.rest.SmartIdConnector; import ee.sk.smartid.rest.SmartIdRestConnector; import org.glassfish.jersey.client.ClientConfig; import java.util.concurrent.TimeUnit; public class SmartIdClient { private String relyingPartyUUID; private String relyingPartyName; private String hostUrl; private ClientConfig networkConnectionConfig; private TimeUnit pollingSleepTimeUnit = TimeUnit.SECONDS; private long pollingSleepTimeout = 1L; private TimeUnit sessionStatusResponseSocketOpenTimeUnit; private long sessionStatusResponseSocketOpenTimeValue; private SmartIdConnector connector; /** * Gets an instance of the certificate request builder * * @return certificate request builder instance */ public CertificateRequestBuilder getCertificate() { SessionStatusPoller sessionStatusPoller = createSessionStatusPoller(getSmartIdConnector()); CertificateRequestBuilder builder = new CertificateRequestBuilder(getSmartIdConnector(), sessionStatusPoller); populateBuilderFields(builder); return builder; } /** * Gets an instance of the signature request builder * * @return signature request builder instance */ public SignatureRequestBuilder createSignature() { SessionStatusPoller sessionStatusPoller = createSessionStatusPoller(getSmartIdConnector()); SignatureRequestBuilder builder = new SignatureRequestBuilder(getSmartIdConnector(), sessionStatusPoller); populateBuilderFields(builder); return builder; } /** * Gets an instance of the authentication request builder * * @return authentication request builder instance */ public AuthenticationRequestBuilder createAuthentication() { SessionStatusPoller sessionStatusPoller = createSessionStatusPoller(getSmartIdConnector()); AuthenticationRequestBuilder builder = new AuthenticationRequestBuilder(getSmartIdConnector(), sessionStatusPoller); populateBuilderFields(builder); return builder; } /** * Sets the UUID of the relying party * <p> * Can be set also on the builder level, * but in that case it has to be set explicitly * every time when building a new request. * * @param relyingPartyUUID UUID of the relying party */ public void setRelyingPartyUUID(String relyingPartyUUID) { this.relyingPartyUUID = relyingPartyUUID; } /** * Gets the UUID of the relying party * * @return UUID of the relying party */ public String getRelyingPartyUUID() { return relyingPartyUUID; } /** * Sets the name of the relying party * <p> * Can be set also on the builder level, * but in that case it has to be set * every time when building a new request. * * @param relyingPartyName name of the relying party */ public void setRelyingPartyName(String relyingPartyName) { this.relyingPartyName = relyingPartyName; } /** * Gets the name of the relying party * * @return name of the relying party */ public String getRelyingPartyName() { return relyingPartyName; } /** * Sets the base URL of the Smart-ID backend environment * <p> * It defines the endpoint which the client communicates to. * * @param hostUrl base URL of the Smart-ID backend environment */ public void setHostUrl(String hostUrl) { this.hostUrl = hostUrl; } /** * Sets the network connection configuration * <p> * Useful for configuring network connection * timeouts, proxy settings, request headers etc. * * @param networkConnectionConfig Jersey's network connection configuration instance */ public void setNetworkConnectionConfig(ClientConfig networkConnectionConfig) { this.networkConnectionConfig = networkConnectionConfig; } /** * Sets the timeout for each session status poll * <p> * Under the hood each operation (authentication, signing, choosing * certificate) consists of 2 request steps: * <p> * 1. Initiation request * <p> * 2. Session status request * <p> * Session status request is a long poll method, meaning * the request method might not return until a timeout expires * set by this parameter. * <p> * Caller can tune the request parameters inside the bounds * set by service operator. * <p> * If not provided, a default is used. * * @param timeUnit time unit of the {@code timeValue} argument * @param timeValue time value of each status poll's timeout. */ public void setSessionStatusResponseSocketOpenTime(TimeUnit timeUnit, long timeValue) { sessionStatusResponseSocketOpenTimeUnit = timeUnit; sessionStatusResponseSocketOpenTimeValue = timeValue; } /** * Sets the timeout/pause between each session status poll * * @param unit time unit of the {@code timeout} argument * @param timeout timeout value in the given {@code unit} */ public void setPollingSleepTimeout(TimeUnit unit, long timeout) { pollingSleepTimeUnit = unit; pollingSleepTimeout = timeout; } private void populateBuilderFields(SmartIdRequestBuilder builder) { builder.withRelyingPartyUUID(relyingPartyUUID); builder.withRelyingPartyName(relyingPartyName); } private SessionStatusPoller createSessionStatusPoller(SmartIdConnector connector) { SessionStatusPoller sessionStatusPoller = new SessionStatusPoller(connector); sessionStatusPoller.setPollingSleepTime(pollingSleepTimeUnit, pollingSleepTimeout); sessionStatusPoller.setResponseSocketOpenTime(sessionStatusResponseSocketOpenTimeUnit, sessionStatusResponseSocketOpenTimeValue); return sessionStatusPoller; } public SmartIdConnector getSmartIdConnector() { if (null == connector) { // Fallback to REST connector when not initialised setSmartIdConnector(new SmartIdRestConnector(hostUrl, networkConnectionConfig)); } return connector; } public void setSmartIdConnector(SmartIdConnector smartIdConnector) { this.connector = smartIdConnector; } }
package filter.expression; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.function.BiConsumer; import java.util.function.Predicate; import java.util.stream.Collectors; import backend.interfaces.IModel; import backend.resource.TurboIssue; import backend.resource.TurboLabel; import backend.resource.TurboMilestone; import backend.resource.TurboUser; import filter.MetaQualifierInfo; import filter.QualifierApplicationException; import util.Utility; public class Qualifier implements FilterExpression { public static final String UPDATED = "updated"; public static final String REPO = "repo"; public static final String SORT = "sort"; public static final Qualifier EMPTY = new Qualifier("", ""); public static final String[] KEYWORDS = new String[] { "assignees", "author", "body", "closed", "comments", "created", "creator", "date", "nonSelfUpdate", "desc", "description", "has", "id", "in", "involves", "is", "issue", "keyword", "label", "labels", "merged", "milestone", "milestones", "no", "open", "pr", "pullrequest", "read", "repo", "sort", "state", "status", "title", "type", "unmerged", "unread", "updated", "user" }; private final String name; // Only one of these will be present at a time private Optional<DateRange> dateRange = Optional.empty(); private Optional<String> content = Optional.empty(); private Optional<LocalDate> date = Optional.empty(); private Optional<NumberRange> numberRange = Optional.empty(); private Optional<Integer> number = Optional.empty(); private List<SortKey> sortKeys = new ArrayList<>(); // Copy constructor public Qualifier(Qualifier other) { this.name = other.getName(); if (other.getDateRange().isPresent()) { this.dateRange = other.getDateRange(); } else if (other.getDate().isPresent()) { this.date = other.getDate(); } else if (other.getContent().isPresent()) { this.content = other.getContent(); } else if (other.getNumberRange().isPresent()) { this.numberRange = other.getNumberRange(); } else if (other.getNumber().isPresent()) { this.number = other.getNumber(); } else if (!other.sortKeys.isEmpty()) { this.sortKeys = new ArrayList<>(other.sortKeys); } else { assert false : "Unrecognised content type! You may have forgotten to add it above"; } } public Qualifier(String name, String content) { this.name = name; this.content = Optional.of(content); } public Qualifier(String name, NumberRange numberRange) { this.name = name; this.numberRange = Optional.of(numberRange); } public Qualifier(String name, DateRange dateRange) { this.name = name; this.dateRange = Optional.of(dateRange); } public Qualifier(String name, LocalDate date) { this.name = name; this.date = Optional.of(date); } public Qualifier(String name, int number) { this.name = name; this.number = Optional.of(number); } public Qualifier(String name, List<SortKey> keys) { this.name = name; this.sortKeys = new ArrayList<>(keys); } /** * Helper function for testing a filter expression against an issue. * Ensures that meta-qualifiers are taken care of. * Should always be used over isSatisfiedBy. */ public static boolean process(IModel model, FilterExpression expr, TurboIssue issue, String currentUser) { FilterExpression exprWithNormalQualifiers = expr.filter(Qualifier::shouldNotBeStripped); List<Qualifier> metaQualifiers = expr.find(Qualifier::isMetaQualifier); // Preprocessing for repo qualifier boolean containsRepoQualifier = metaQualifiers.stream() .map(Qualifier::getName) .collect(Collectors.toList()) .contains("repo"); if (!containsRepoQualifier) { exprWithNormalQualifiers = new Conjunction( new Qualifier("repo", model.getDefaultRepo()), exprWithNormalQualifiers); } return exprWithNormalQualifiers.isSatisfiedBy(model, issue, new MetaQualifierInfo(metaQualifiers), currentUser); } public static void processMetaQualifierEffects(FilterExpression expr, BiConsumer<Qualifier, MetaQualifierInfo> callback) { List<Qualifier> qualifiers = expr.find(Qualifier::isMetaQualifier); MetaQualifierInfo info = new MetaQualifierInfo(qualifiers); qualifiers.forEach(q -> callback.accept(q, info)); } private static LocalDateTime currentTime = null; private static LocalDateTime getCurrentTime() { if (currentTime == null) { return LocalDateTime.now(); } else { return currentTime; } } /** * For testing. Stubs the current time so time-related qualifiers work properly. */ public static void setCurrentTime(LocalDateTime dateTime) { currentTime = dateTime; } public boolean isEmptyQualifier() { return name.isEmpty() && content.isPresent() && content.get().isEmpty(); } @Override public boolean isSatisfiedBy(IModel model, TurboIssue issue, MetaQualifierInfo info, String currentUser) { assert name != null; // The empty qualifier is satisfied by anything if (isEmptyQualifier()) return true; switch (name) { case "id": return idSatisfies(issue); case "keyword": return keywordSatisfies(issue, info); case "title": return titleSatisfies(issue); case "body": case "desc": case "description": return bodySatisfies(issue); case "milestone": return milestoneSatisfies(model, issue); case "label": return labelsSatisfy(model, issue); case "author": case "creator": return authorSatisfies(issue); case "assignee": return assigneeSatisfies(model, issue); case "involves": case "user": return involvesSatisfies(model, issue); case "type": return typeSatisfies(issue); case "state": case "status": return stateSatisfies(issue); case "has": return satisfiesHasConditions(issue); case "no": return satisfiesNoConditions(issue); case "is": return satisfiesIsConditions(issue); case "created": return satisfiesCreationDate(issue); case "updated": return satisfiesUpdatedHours(issue, currentUser); case "repo": return satisfiesRepo(issue); default: return false; } } @Override public void applyTo(TurboIssue issue, IModel model) throws QualifierApplicationException { assert name != null && content != null; // The empty qualifier should not be applied to anything assert !isEmptyQualifier(); switch (name) { case "title": case "desc": case "description": case "body": case "keyword": throw new QualifierApplicationException("Unnecessary filter: issue text cannot be changed by dragging"); case "id": throw new QualifierApplicationException("Unnecessary filter: id is immutable"); case "created": throw new QualifierApplicationException("Unnecessary filter: cannot change issue creation date"); case "has": case "no": case "is": throw new QualifierApplicationException("Ambiguous filter: " + name); case "milestone": applyMilestone(issue, model); break; case "label": applyLabel(issue, model); break; case "assignee": applyAssignee(issue, model); break; case "author": case "creator": throw new QualifierApplicationException("Unnecessary filter: cannot change author of issue"); case "involves": case "user": throw new QualifierApplicationException("Ambiguous filter: cannot change users involved with issue"); case "state": case "status": applyState(issue); break; default: break; } } @Override public boolean canBeAppliedToIssue() { return true; } @Override public List<String> getQualifierNames() { return new ArrayList<>(Arrays.asList(name)); } @Override public FilterExpression filter(Predicate<Qualifier> pred) { if (pred.test(this)) { return new Qualifier(this); } else { return EMPTY; } } @Override public List<Qualifier> find(Predicate<Qualifier> pred) { if (pred.test(this)) { ArrayList<Qualifier> result = new ArrayList<>(); result.add(this); return result; } else { return new ArrayList<>(); } } /** * This method is used to serialise qualifiers. Thus whatever form returned * should be syntactically valid. */ @Override public String toString() { if (this == EMPTY) { return ""; } else if (content.isPresent()) { String quotedContent = content.get(); if (quotedContent.contains(" ")) { quotedContent = "\"" + quotedContent + "\""; } if (name.equals("keyword")) { return quotedContent; } else { return name + ":" + quotedContent; } } else if (date.isPresent()) { return name + ":" + date.get().toString(); } else if (dateRange.isPresent()) { return name + ":" + dateRange.get().toString(); } else if (!sortKeys.isEmpty()) { return name + ":" + sortKeys.stream().map(SortKey::toString).collect(Collectors.joining(",")); } else if (numberRange.isPresent()) { return name + ":" + numberRange.get().toString(); } else if (number.isPresent()) { return name + ":" + number.get().toString(); } else { assert false : "Should not happen"; return ""; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((content == null) ? 0 : content.hashCode()); result = prime * result + ((date == null) ? 0 : date.hashCode()); result = prime * result + ((dateRange == null) ? 0 : dateRange.hashCode()); result = prime * result + ((number == null) ? 0 : number.hashCode()); result = prime * result + ((numberRange == null) ? 0 : numberRange.hashCode()); result = prime * result + ((sortKeys == null) ? 0 : sortKeys.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Qualifier other = (Qualifier) obj; return content.equals(other.content) && date.equals(other.date) && dateRange.equals(other.dateRange) && number.equals(other.number) && numberRange.equals(other.numberRange) && sortKeys.equals(other.sortKeys) && name.equals(other.name); } private static boolean shouldNotBeStripped(Qualifier q) { return !shouldBeStripped(q); } private static boolean shouldBeStripped(Qualifier q) { switch (q.getName()) { case "in": case "sort": return true; default: return false; } } private static boolean isMetaQualifier(Qualifier q) { switch (q.getName()) { case "sort": case "in": case "repo": return true; default: return false; } } public Comparator<TurboIssue> getCompoundSortComparator(IModel model, boolean metadataRefresh) { if (sortKeys.isEmpty()) { return (a, b) -> 0; } return (a, b) -> { for (SortKey key : sortKeys) { Comparator<TurboIssue> comparator = getSortComparator(model, key.key, key.inverted, metadataRefresh); int result = comparator.compare(a, b); if (result != 0) { return result; } } return 0; }; } public static Comparator<TurboIssue> getSortComparator(IModel model, String key, boolean inverted, boolean metadataRefresh) { Comparator<TurboIssue> comparator = (a, b) -> 0; boolean isLabelGroup = false; switch (key) { case "comments": comparator = (a, b) -> a.getCommentCount() - b.getCommentCount(); break; case "repo": comparator = (a, b) -> a.getRepoId().compareTo(b.getRepoId()); break; case "updated": case "date": comparator = (a, b) -> a.getUpdatedAt().compareTo(b.getUpdatedAt()); break; case "nonSelfUpdate": if (metadataRefresh) { comparator = (a, b) -> a.getMetadata().getNonSelfUpdatedAt().compareTo(b.getMetadata().getNonSelfUpdatedAt()); } else { comparator = (a, b) -> a.getUpdatedAt().compareTo(b.getUpdatedAt()); } break; case "id": comparator = (a, b) -> a.getId() - b.getId(); break; default: // Doesn't match anything; assume it's a label group isLabelGroup = true; break; } if (isLabelGroup) { // Has a different notion of inversion return getLabelGroupComparator(model, key, inverted); } else { // Use default behaviour for inverting if (!inverted) { return comparator; } else { final Comparator<TurboIssue> finalComparator = comparator; return (a, b) -> -finalComparator.compare(a, b); } } } public static Comparator<TurboIssue> getLabelGroupComparator(IModel model, String key, boolean inverted) { // Strip trailing ., if any final String group = key.replaceAll("\\.$", ""); return (a, b) -> { // Matches labels belong to the given group Predicate<TurboLabel> sameGroup = l -> l.getGroup().isPresent() && l.getGroup().get().equals(group); Comparator<TurboLabel> labelComparator = (x, y) -> x.getName().compareTo(y.getName()); List<TurboLabel> aLabels = model.getLabelsOfIssue(a, sameGroup); List<TurboLabel> bLabels = model.getLabelsOfIssue(b, sameGroup); Collections.sort(aLabels, labelComparator); Collections.sort(bLabels, labelComparator); // Put empty lists at the back if (aLabels.size() == 0 && bLabels.size() == 0) { return 0; } else if (aLabels.size() == 0) { // a is larger return 1; } else if (bLabels.size() == 0) { // b is larger return -1; } // Compare lengths int result = !inverted ? aLabels.size() - bLabels.size() : bLabels.size() - aLabels.size(); if (result != 0) { return result; } // Lexicographic label comparison assert aLabels.size() == bLabels.size(); for (int i = 0; i < aLabels.size(); i++) { result = !inverted ? labelComparator.compare(aLabels.get(i), bLabels.get(i)) : labelComparator.compare(bLabels.get(i), aLabels.get(i)); if (result != 0) { return result; } } return 0; }; } private boolean idSatisfies(TurboIssue issue) { if (number.isPresent()) { return issue.getId() == number.get(); } else if (numberRange.isPresent()) { return numberRange.get().encloses(issue.getId()); } return false; } private boolean satisfiesUpdatedHours(TurboIssue issue, String currentUser) { NumberRange updatedRange; if (numberRange.isPresent()) { updatedRange = numberRange.get(); } else if (number.isPresent()) { updatedRange = new NumberRange(null, number.get(), true); } else { return false; } int hoursSinceUpdate; if (issue.getMetadata().isUpdated()) { // Second time being filtered, we now have metadata from source, so we can use getNonSelfUpdatedAt. hoursSinceUpdate = Utility.safeLongToInt(issue.getMetadata().getNonSelfUpdatedAt() .until(getCurrentTime(), ChronoUnit.HOURS)); } else { // First time being filtered (haven't gotten metadata from source yet). hoursSinceUpdate = Utility.safeLongToInt(issue.getUpdatedAt().until(getCurrentTime(), ChronoUnit.HOURS)); } if (updatedRange.encloses(hoursSinceUpdate)) return true; // If it doesn't enclose, we also consider creation as an update event. int hoursSinceCreation = Utility.safeLongToInt(issue.getCreatedAt() .until(getCurrentTime(), ChronoUnit.HOURS)); if (!issue.getCreator().equalsIgnoreCase(currentUser)) { // But on the second time being filtered, we consider only if creator is different if (updatedRange.encloses(hoursSinceCreation)) return true; } // Creation time is also outside of range, we do not need to show this issue at all. return false; } private boolean satisfiesRepo(TurboIssue issue) { if (!content.isPresent()) return false; return issue.getRepoId().equals(content.get()); } private boolean satisfiesCreationDate(TurboIssue issue) { LocalDate creationDate = issue.getCreatedAt().toLocalDate(); if (date.isPresent()) { return creationDate.isEqual(date.get()); } else if (dateRange.isPresent()) { return dateRange.get().encloses(creationDate); } else { return false; } } private boolean satisfiesHasConditions(TurboIssue issue) { if (!content.isPresent()) return false; switch (content.get()) { case "label": case "labels": return issue.getLabels().size() > 0; case "milestone": case "milestones": assert issue.getMilestone() != null; return issue.getMilestone().isPresent(); case "assignee": case "assignees": assert issue.getMilestone() != null; return issue.getAssignee().isPresent(); default: return false; } } private boolean satisfiesNoConditions(TurboIssue issue) { return content.isPresent() && !satisfiesHasConditions(issue); } private boolean satisfiesIsConditions(TurboIssue issue) { if (!content.isPresent()) return false; switch (content.get()) { case "open": case "closed": return stateSatisfies(issue); case "pr": case "issue": return typeSatisfies(issue); case "merged": return issue.isPullRequest() && !issue.isOpen(); case "unmerged": return issue.isPullRequest() && issue.isOpen(); case "read": return issue.isCurrentlyRead(); case "unread": return !issue.isCurrentlyRead(); default: return false; } } private boolean stateSatisfies(TurboIssue issue) { if (!content.isPresent()) return false; String content = this.content.get().toLowerCase(); if (content.contains("open")) { return issue.isOpen(); } else if (content.contains("closed")) { return !issue.isOpen(); } else { return false; } } private boolean assigneeSatisfies(IModel model, TurboIssue issue) { if (!content.isPresent()) return false; Optional<TurboUser> assignee = model.getAssigneeOfIssue(issue); if (!assignee.isPresent()) return false; String content = this.content.get().toLowerCase(); String login = assignee.get().getLoginName() == null ? "" : assignee.get().getLoginName().toLowerCase(); String name = assignee.get().getRealName() == null ? "" : assignee.get().getRealName().toLowerCase(); return login.contains(content) || name.contains(content); } private boolean authorSatisfies(TurboIssue issue) { if (!content.isPresent()) return false; String creator = issue.getCreator(); return creator.toLowerCase().contains(content.get().toLowerCase()); } private boolean involvesSatisfies(IModel model, TurboIssue issue) { return authorSatisfies(issue) || assigneeSatisfies(model, issue); } private boolean labelsSatisfy(IModel model, TurboIssue issue) { if (!content.isPresent()) return false; // Make use of TurboLabel constructor to parse the string, to avoid duplication TurboLabel tokens = new TurboLabel("", content.get().toLowerCase()); String group = ""; if (tokens.getGroup().isPresent()) { group = tokens.getGroup().get().toLowerCase(); } String labelName = tokens.getName().toLowerCase(); for (TurboLabel label : model.getLabelsOfIssue(issue)) { if (label.getGroup().isPresent()) { if (labelName.isEmpty()) { // Check the group if (label.getGroup().get().toLowerCase().contains(group)) { return true; } } else { if (label.getGroup().get().toLowerCase().contains(group) && label.getName().toLowerCase().contains(labelName)) { return true; } } } else { // Check only the label name if (!group.isEmpty()) { return false; } else if (!labelName.isEmpty() && label.getName().toLowerCase().contains(labelName)) { return true; } } } return false; } private boolean milestoneSatisfies(IModel model, TurboIssue issue) { if (!content.isPresent()) return false; Optional<TurboMilestone> milestone = model.getMilestoneOfIssue(issue); if (!milestone.isPresent()) return false; String contents = content.get().toLowerCase(); String title = milestone.get().getTitle().toLowerCase(); return title.contains(contents); } private boolean keywordSatisfies(TurboIssue issue, MetaQualifierInfo info) { if (info.getIn().isPresent()) { switch (info.getIn().get()) { case "title": return titleSatisfies(issue); case "body": case "desc": case "description": return bodySatisfies(issue); default: return false; } } else { return titleSatisfies(issue) || bodySatisfies(issue); } } private boolean bodySatisfies(TurboIssue issue) { if (!content.isPresent()) return false; return issue.getDescription().toLowerCase().contains(content.get().toLowerCase()); } private boolean titleSatisfies(TurboIssue issue) { if (!content.isPresent()) return false; return issue.getTitle().toLowerCase().contains(content.get().toLowerCase()); } private boolean typeSatisfies(TurboIssue issue) { if (!content.isPresent()) return false; String content = this.content.get().toLowerCase(); switch (content) { case "issue": return !issue.isPullRequest(); case "pr": case "pullrequest": return issue.isPullRequest(); default: return false; } } private void applyMilestone(TurboIssue issue, IModel model) throws QualifierApplicationException { if (!content.isPresent()) { throw new QualifierApplicationException("Name of milestone to apply required"); } // Find milestones containing partial title List<TurboMilestone> milestones = model.getMilestones().stream() .filter(m -> m.getTitle().toLowerCase().contains(content.get().toLowerCase())) .collect(Collectors.toList()); if (milestones.isEmpty()) { throw new QualifierApplicationException("Invalid milestone " + content.get()); } else if (milestones.size() == 1) { issue.setMilestone(milestones.get(0)); return; } // Find milestones containing exact title milestones = model.getMilestones().stream() .filter(m -> m.getTitle().toLowerCase().equals(content.get().toLowerCase())) .collect(Collectors.toList()); if (milestones.isEmpty()) { throw new QualifierApplicationException("Invalid milestone " + content.get()); } else if (milestones.size() == 1) { issue.setMilestone(milestones.get(0)); return; } throw new QualifierApplicationException( "Ambiguous filter: can apply any of the following milestones: " + milestones.toString()); } private void applyLabel(TurboIssue issue, IModel model) throws QualifierApplicationException { if (!content.isPresent()) { throw new QualifierApplicationException("Name of label to apply required"); } // Find labels containing the label name List<TurboLabel> labels = model.getLabels().stream() .filter(l -> l.getActualName().toLowerCase().contains(content.get().toLowerCase())) .collect(Collectors.toList()); if (labels.isEmpty()) { throw new QualifierApplicationException("Invalid label " + content.get()); } else if (labels.size() == 1) { issue.addLabel(labels.get(0)); return; } // Find labels with the exact label name labels = model.getLabels().stream() .filter(l -> l.getActualName().toLowerCase().equals(content.get().toLowerCase())) .collect(Collectors.toList()); if (labels.isEmpty()) { throw new QualifierApplicationException("Invalid label " + content.get()); } else if (labels.size() == 1) { issue.addLabel(labels.get(0)); return; } throw new QualifierApplicationException( "Ambiguous filter: can apply any of the following labels: " + labels.toString()); } private void applyAssignee(TurboIssue issue, IModel model) throws QualifierApplicationException { if (!content.isPresent()) { throw new QualifierApplicationException("Name of assignee to apply required"); } // Find assignees containing partial name List<TurboUser> assignees = model.getUsers().stream() .filter(c -> c.getLoginName().toLowerCase().contains(content.get().toLowerCase())) .collect(Collectors.toList()); if (assignees.isEmpty()) { throw new QualifierApplicationException("Invalid user " + content.get()); } else if (assignees.size() == 1) { issue.setAssignee(assignees.get(0)); return; } // Find assignees containing partial name assignees = model.getUsers().stream() .filter(c -> c.getLoginName().toLowerCase().equals(content.get().toLowerCase())) .collect(Collectors.toList()); if (assignees.isEmpty()) { throw new QualifierApplicationException("Invalid user " + content.get()); } else if (assignees.size() == 1) { issue.setAssignee(assignees.get(0)); return; } throw new QualifierApplicationException( "Ambiguous filter: can apply any of the following assignees: " + assignees.toString()); } private void applyState(TurboIssue issue) throws QualifierApplicationException { if (!content.isPresent()) { throw new QualifierApplicationException("State to apply required"); } if (content.get().toLowerCase().contains("open")) { issue.setOpen(true); } else if (content.get().toLowerCase().contains("closed")) { issue.setOpen(false); } else { throw new QualifierApplicationException("Invalid state " + content.get()); } } public Optional<Integer> getNumber() { return number; } public Optional<NumberRange> getNumberRange() { return numberRange; } public Optional<DateRange> getDateRange() { return dateRange; } public Optional<String> getContent() { return content; } public Optional<LocalDate> getDate() { return date; } public String getName() { return name; } }
package graphql.util; import graphql.Internal; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; import static graphql.Assert.assertNotNull; @Internal abstract class RecursionState<T> { private final Deque<TraverserContext<?>> delegate; private final Map<T, Object> visitedMap = new ConcurrentHashMap<>(); public RecursionState() { this(new ArrayDeque<>(32)); } public RecursionState(Deque<? super TraverserContext<T>> delegate) { this.delegate = (Deque<TraverserContext<?>>) assertNotNull(delegate); } public TraverserContext<T> peek() { return (TraverserContext<T>) delegate.peek(); } public abstract TraverserContext<T> pop(); public abstract void pushAll(TraverserContext<T> o, Function<? super T, ? extends List<T>> getChildren); public void addAll(Collection<? extends T> col) { assertNotNull(col).stream().map((x) -> newContext(x, null)).collect(Collectors.toCollection(() -> delegate)); } public boolean isEmpty() { return delegate.isEmpty(); } public void clear() { delegate.clear(); visitedMap.clear(); } public TraverserContext<T> newContext(final T o, final TraverserContext<T> parent) { return new TraverserContext<T>() { @Override public T thisNode() { return o; } @Override public TraverserContext<T> parentContext() { return parent; } @Override public boolean isVisited(Object data) { return visitedMap.putIfAbsent(o, Optional.ofNullable(data).orElse(TraverserMarkers.NULL)) != null; } @Override public Map<T, Object> visitedNodes() { return visitedMap; } @Override public <S> S getVar(Class<? super S> key) { return (S) key.cast(vars.get(key)); } @Override public <S> TraverserContext<T> setVar(Class<? super S> key, S value) { vars.put(key, value); return this; } final Map<Class<?>, Object> vars = new HashMap<>(); }; } protected Deque<TraverserContext<?>> getDelegate() { return delegate; } }
package hr.fer.zemris.java.vhdl; import hr.fer.zemris.java.vhdl.models.components.Component; import hr.fer.zemris.java.vhdl.models.components.IModelListener; import hr.fer.zemris.java.vhdl.models.components.Model; import hr.fer.zemris.java.vhdl.models.declarable.Signal; import hr.fer.zemris.java.vhdl.models.values.LogicValue; import hr.fer.zemris.java.vhdl.models.values.Value; import hr.fer.zemris.java.vhdl.models.values.Vector; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLayer; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.plaf.LayerUI; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.util.Optional; public class GUI extends JFrame implements IModelListener { private Model model; private VHDLComponent blackBox; private JLayer<JComponent> layer; public GUI(Model model) { this.model = model; model.addListener(this); setDefaultCloseOperation(DISPOSE_ON_CLOSE); initGUI(model.getTable().getTestedComponent()); pack(); } private void initGUI(Component component) { Container cp = getContentPane(); cp.setLayout(new BorderLayout()); blackBox = new VHDLComponent(component); JPanel panel = new JPanel(new BorderLayout()); ZoomUI zoomUI = new ZoomUI(); layer = new JLayer<>(blackBox, zoomUI); panel.add(new JScrollPane(layer), BorderLayout.CENTER); cp.add(panel); addMouseListener(zoomUI); } private void addMouseListener(ZoomUI zoomUI) { layer.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { Point p = layer.getMousePosition(); double zoom = zoomUI.zoom; System.out.println(zoom * p.getX() + ", " + zoom * p.getY()); Optional<VHDLComponent.Input> input = blackBox.getInputForPoint(p.getX() / zoom, p.getY() / zoom); if (input.isPresent()) { VHDLComponent.Input i = input.get(); LogicValue value; if (i.getSignal().getDeclaration().getTypeOf() == Value.TypeOf.STD_LOGIC_VECTOR) { value = ((Vector) i.getSignal().getValue()) .getLogicValue(i.getPosition()); } else { value = (LogicValue) i.getSignal().getValue(); } if (value != LogicValue.ZERO) { model.signalChange(i.getSignal(), LogicValue.ZERO, i.getPosition(), System.currentTimeMillis()); } else { model.signalChange(i.getSignal(), LogicValue.ONE, i.getPosition(), System.currentTimeMillis()); } } layer.repaint(); } }); layer.addMouseWheelListener(new MouseAdapter() { @Override public void mouseWheelMoved(MouseWheelEvent e) { if (e.getWheelRotation() == 1) { zoomUI.zoomIn(); } else { zoomUI.zoomOut(); } layer.setPreferredSize(new Dimension((int) (zoomUI.zoom * blackBox.getWidth()), (int) (zoomUI.zoom * blackBox.getHeight()))); layer.revalidate(); layer.repaint(); } }); } @Override public void signalChanged(Signal signal, long time) { blackBox.repaint(); } private static class ZoomUI extends LayerUI<JComponent> { private double zoom = 1; public static final double INCREMENT = 0.1; public void installUI(JComponent c) { super.installUI(c); JLayer jlayer = (JLayer) c; jlayer.setLayerEventMask( AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_WHEEL_EVENT_MASK); } @Override public void uninstallUI(JComponent c) { JLayer jlayer = (JLayer) c; jlayer.setLayerEventMask(0); super.uninstallUI(c); } @Override public void paint(Graphics g, JComponent c) { Graphics2D g2 = (Graphics2D) g.create(); g2.scale(zoom, zoom); super.paint(g2, c); g2.dispose(); } @Override protected void processMouseWheelEvent( MouseWheelEvent e, JLayer<? extends JComponent> l) { super.processMouseWheelEvent(e, l); } public void zoomIn() { if (5 - Math.abs(zoom) < 10e-5) { return; } zoom += INCREMENT; } public void zoomOut() { if (Math.abs(zoom) - 0.25 < 10e-5) { return; } zoom -= INCREMENT; } public double getZoom() { return zoom; } } }
package io.elssa.nn; import java.net.InetSocketAddress; import java.net.SocketAddress; /** * Represents a TCP network endpoint; a host/port pair. * * @author malensek */ public class NetworkEndpoint { protected String hostname; protected int port; public NetworkEndpoint(String hostname, int port) { this.hostname = hostname; this.port = port; } public NetworkEndpoint(SocketAddress address) { if (address instanceof InetSocketAddress) { InetSocketAddress iAddress = (InetSocketAddress) address; this.hostname = iAddress.getHostName(); this.port = iAddress.getPort(); } } public String hostname() { return hostname; } public int port() { return port; } private String stringRepresentation() { return hostname + ":" + port; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((hostname == null) ? 0 : hostname.hashCode()); result = prime * result + port; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } NetworkEndpoint other = (NetworkEndpoint) obj; return this.stringRepresentation().equals(other.stringRepresentation()); } @Override public String toString() { return stringRepresentation(); } }
package io.scif.formats; import java.io.IOException; import java.util.Arrays; import java.util.Hashtable; import java.util.Vector; import net.imagej.axis.Axes; import net.imglib2.display.ColorTable; import net.imglib2.display.ColorTable16; import net.imglib2.display.ColorTable8; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import io.scif.AbstractChecker; import io.scif.AbstractFormat; import io.scif.AbstractMetadata; import io.scif.AbstractParser; import io.scif.ByteArrayPlane; import io.scif.ByteArrayReader; import io.scif.FilePattern; import io.scif.Format; import io.scif.FormatException; import io.scif.HasColorTable; import io.scif.ImageMetadata; import io.scif.MetadataLevel; import io.scif.UnsupportedCompressionException; import io.scif.codec.Codec; import io.scif.codec.CodecOptions; import io.scif.codec.CodecService; import io.scif.codec.JPEG2000Codec; import io.scif.codec.JPEGCodec; import io.scif.codec.PackbitsCodec; import io.scif.common.DataTools; import io.scif.config.SCIFIOConfig; import io.scif.io.Location; import io.scif.io.RandomAccessInputStream; import io.scif.services.InitializeService; import io.scif.util.FormatTools; @Plugin(type = Format.class, name = "DICOM") public class DICOMFormat extends AbstractFormat { // -- Constants -- public static final String DICOM_MAGIC_STRING = "DICM"; private static final Hashtable<Integer, String> TYPES = buildTypes(); // -- AbstractFormat Methods -- @Override protected String[] makeSuffixArray() { return new String[] { "dic", "dcm", "dicom", "jp2", "j2ki", "j2kr", "raw", "ima" }; } // -- Static Helper methods -- /** * Assemble the data dictionary. This is incomplete at best, since there are * literally thousands of fields defined by the DICOM specifications. */ private static Hashtable<Integer, String> buildTypes() { final Hashtable<Integer, String> dict = new Hashtable<Integer, String>(); dict.put(0x00020002, "Media Storage SOP Class UID"); dict.put(0x00020003, "Media Storage SOP Instance UID"); dict.put(0x00020010, "Transfer Syntax UID"); dict.put(0x00020012, "Implementation Class UID"); dict.put(0x00020013, "Implementation Version Name"); dict.put(0x00020016, "Source Application Entity Title"); dict.put(0x00080005, "Specific Character Set"); dict.put(0x00080008, "Image Type"); dict.put(0x00080010, "Recognition Code"); dict.put(0x00080012, "Instance Creation Date"); dict.put(0x00080013, "Instance Creation Time"); dict.put(0x00080014, "Instance Creator UID"); dict.put(0x00080016, "SOP Class UID"); dict.put(0x00080018, "SOP Instance UID"); dict.put(0x0008001a, "Related General SOP Class UID"); dict.put(0x0008001b, "Original Specialized SOP Class UID"); dict.put(0x00080020, "Study Date"); dict.put(0x00080021, "Series Date"); dict.put(0x00080022, "Acquisition Date"); dict.put(0x00080023, "Content Date"); dict.put(0x00080024, "Overlay Date"); dict.put(0x00080025, "Curve Date"); dict.put(0x0008002a, "Acquisition Date/Time"); dict.put(0x00080030, "Study Time"); dict.put(0x00080031, "Series Time"); dict.put(0x00080032, "Acquisition Time"); dict.put(0x00080033, "Content Time"); dict.put(0x00080034, "Overlay Time"); dict.put(0x00080035, "Curve Time"); dict.put(0x00080041, "Data Set Subtype"); dict.put(0x00080050, "Accession Number"); dict.put(0x00080052, "Query/Retrieve Level"); dict.put(0x00080054, "Retrieve AE Title"); dict.put(0x00080056, "Instance Availability"); dict.put(0x00080058, "Failed SOP Instance UID List"); dict.put(0x00080060, "Modality"); dict.put(0x00080061, "Modalities in Study"); dict.put(0x00080062, "SOP Classes in Study"); dict.put(0x00080064, "Conversion Type"); dict.put(0x00080068, "Presentation Intent Type"); dict.put(0x00080070, "Manufacturer"); dict.put(0x00080080, "Institution Name"); dict.put(0x00080081, "Institution Address"); dict.put(0x00080082, "Institution Code Sequence"); dict.put(0x00080090, "Referring Physician's Name"); dict.put(0x00080092, "Referring Physician's Address"); dict.put(0x00080094, "Referring Physician's Telephone"); dict.put(0x00080096, "Referring Physician ID"); dict.put(0x00080100, "Code Value"); dict.put(0x00080102, "Coding Scheme Designator"); dict.put(0x00080103, "Coding Scheme Version"); dict.put(0x00080104, "Code Meaning"); dict.put(0x00080105, "Mapping Resource"); dict.put(0x00080106, "Context Group Version"); dict.put(0x00080107, "Context Group Local Version"); dict.put(0x0008010b, "Context Group Extension Flag"); dict.put(0x0008010c, "Coding Scheme UID"); dict.put(0x0008010d, "Context Group Extension Creator UID"); dict.put(0x0008010f, "Context ID"); dict.put(0x00080110, "Coding Scheme ID"); dict.put(0x00080112, "Coding Scheme Registry"); dict.put(0x00080114, "Coding Scheme External ID"); dict.put(0x00080115, "Coding Scheme Name"); dict.put(0x00080116, "Responsible Organization"); dict.put(0x00080201, "Timezone Offset from UTC"); dict.put(0x00081010, "Station Name"); dict.put(0x00081030, "Study Description"); dict.put(0x00081032, "Procedure Code Sequence"); dict.put(0x0008103e, "Series Description"); dict.put(0x00081040, "Institutional Department Name"); dict.put(0x00081048, "Physician(s) of Record"); dict.put(0x00081049, "Physician(s) of Record ID"); dict.put(0x00081050, "Performing Physician's Name"); dict.put(0x00081052, "Performing Physican ID"); dict.put(0x00081060, "Name of Physician(s) Reading Study"); dict.put(0x00081062, "Physician(s) Reading Study ID"); dict.put(0x00081070, "Operator's Name"); dict.put(0x00081072, "Operator ID"); dict.put(0x00081080, "Admitting Diagnoses Description"); dict.put(0x00081084, "Admitting Diagnoses Code Sequence"); dict.put(0x00081090, "Manufacturer's Model Name"); dict.put(0x00081100, "Referenced Results Sequence"); dict.put(0x00081110, "Referenced Study Sequence"); dict.put(0x00081111, "Referenced Performed Procedure Step"); dict.put(0x00081115, "Referenced Series Sequence"); dict.put(0x00081120, "Referenced Patient Sequence"); dict.put(0x00081125, "Referenced Visit Sequence"); dict.put(0x00081130, "Referenced Overlay Sequence"); dict.put(0x0008113a, "Referenced Waveform Sequence"); dict.put(0x00081140, "Referenced Image Sequence"); dict.put(0x00081145, "Referenced Curve Sequence"); dict.put(0x0008114a, "Referenced Instance Sequence"); dict.put(0x00081150, "Referenced SOP Class UID"); dict.put(0x00081155, "Referenced SOP Instance UID"); dict.put(0x0008115a, "SOP Classes Supported"); dict.put(0x00081160, "Referenced Frame Number"); dict.put(0x00081195, "Transaction UID"); dict.put(0x00081197, "Failure Reason"); dict.put(0x00081198, "Failed SOP Sequence"); dict.put(0x00081199, "Referenced SOP Sequence"); dict.put(0x00081200, "Studies Containing Other Referenced Instances Sequence"); dict.put(0x00081250, "Related Series Sequence"); dict.put(0x00082111, "Derivation Description"); dict.put(0x00082112, "Source Image Sequence"); dict.put(0x00082120, "Stage Name"); dict.put(0x00082122, "Stage Number"); dict.put(0x00082124, "Number of Stages"); dict.put(0x00082127, "View Name"); dict.put(0x00082128, "View Number"); dict.put(0x00082129, "Number of Event Timers"); dict.put(0x0008212a, "Number of Views in Stage"); dict.put(0x00082130, "Event Elapsed Time(s)"); dict.put(0x00082132, "Event Timer Name(s)"); dict.put(0x00082142, "Start Trim"); dict.put(0x00082143, "Stop Trim"); dict.put(0x00082144, "Recommended Display Frame Rate"); dict.put(0x00082218, "Anatomic Region Sequence"); dict.put(0x00082220, "Anatomic Region Modifier Sequence"); dict.put(0x00082228, "Primary Anatomic Structure Sequence"); dict.put(0x00082229, "Anatomic Structure Sequence"); dict.put(0x00082230, "Primary Anatomic Structure Modifier"); dict.put(0x00082240, "Transducer Position Sequence"); dict.put(0x00082242, "Transducer Position Modifier Sequence"); dict.put(0x00082244, "Transducer Orientation Sequence"); dict.put(0x00082246, "Transducer Orientation Modifier"); dict.put(0x00083001, "Alternate Representation Sequence"); dict.put(0x00089007, "Frame Type"); dict.put(0x00089092, "Referenced Image Evidence Sequence"); dict.put(0x00089121, "Referenced Raw Data Sequence"); dict.put(0x00089123, "Creator-Version UID"); dict.put(0x00089124, "Derivation Image Sequence"); dict.put(0x00089154, "Source Image Evidence Sequence"); dict.put(0x00089205, "Pixel Representation"); dict.put(0x00089206, "Volumetric Properties"); dict.put(0x00089207, "Volume Based Calculation Technique"); dict.put(0x00089208, "Complex Image Component"); dict.put(0x00089209, "Acquisition Contrast"); dict.put(0x00089215, "Derivation Code Sequence"); dict.put(0x00089237, "Reference Grayscale Presentation State"); dict.put(0x00100010, "Patient's Name"); dict.put(0x00100020, "Patient ID"); dict.put(0x00100021, "Issuer of Patient ID"); dict.put(0x00100030, "Patient's Birth Date"); dict.put(0x00100032, "Patient's Birth Time"); dict.put(0x00100040, "Patient's Sex"); dict.put(0x00100050, "Patient's Insurance Plane Code"); dict.put(0x00100101, "Patient's Primary Language Code"); dict.put(0x00100102, "Patient's Primary Language Modifier"); dict.put(0x00101000, "Other Patient IDs"); dict.put(0x00101001, "Other Patient Names"); dict.put(0x00101005, "Patient's Birth Name"); dict.put(0x00101010, "Patient's Age"); dict.put(0x00101020, "Patient's Size"); dict.put(0x00101030, "Patient's Weight"); dict.put(0x00101040, "Patient's Address"); dict.put(0x00101060, "Patient's Mother's Birth Name"); dict.put(0x00101080, "Military Rank"); dict.put(0x00101081, "Branch of Service"); dict.put(0x00101090, "Medical Record Locator"); dict.put(0x00102000, "Medical Alerts"); dict.put(0x00102110, "Contrast Allergies"); dict.put(0x00102150, "Country of Residence"); dict.put(0x00102152, "Region of Residence"); dict.put(0x00102154, "Patient's Telephone Numbers"); dict.put(0x00102160, "Ethnic Group"); dict.put(0x00102180, "Occupation"); dict.put(0x001021a0, "Smoking Status"); dict.put(0x001021b0, "Additional Patient History"); dict.put(0x001021c0, "Pregnancy Status"); dict.put(0x001021d0, "Last Menstrual Date"); dict.put(0x001021f0, "Patient's Religious Preference"); dict.put(0x00104000, "Patient Comments"); dict.put(0x00120010, "Clinical Trial Sponsor Name"); dict.put(0x00120020, "Clinical Trial Protocol ID"); dict.put(0x00120021, "Clinical Trial Protocol Name"); dict.put(0x00120030, "Clinical Trial Site ID"); dict.put(0x00120031, "Clinical Trial Site Name"); dict.put(0x00120040, "Clinical Trial Subject ID"); dict.put(0x00120042, "Clinical Trial Subject Reading ID"); dict.put(0x00120050, "Clinical Trial Time Point ID"); dict.put(0x00120051, "Clinical Trial Time Point Description"); dict.put(0x00120060, "Clinical Trial Coordinating Center"); dict.put(0x00180010, "Contrast/Bolus Agent"); dict.put(0x00180012, "Contrast/Bolus Agent Sequence"); dict.put(0x00180014, "Contrast/Bolus Admin. Route Sequence"); dict.put(0x00180015, "Body Part Examined"); dict.put(0x00180020, "Scanning Sequence"); dict.put(0x00180021, "Sequence Variant"); dict.put(0x00180022, "Scan Options"); dict.put(0x00180023, "MR Acquisition Type"); dict.put(0x00180024, "Sequence Name"); dict.put(0x00180025, "Angio Flag"); dict.put(0x00180026, "Intervention Drug Information Sequence"); dict.put(0x00180027, "Intervention Drug Stop Time"); dict.put(0x00180028, "Intervention Drug Dose"); dict.put(0x00180029, "Intervention Drug Sequence"); dict.put(0x0018002a, "Additional Drug Sequence"); dict.put(0x00180031, "Radiopharmaceutical"); dict.put(0x00180034, "Intervention Drug Name"); dict.put(0x00180035, "Intervention Drug Start Time"); dict.put(0x00180036, "Intervention Sequence"); dict.put(0x00180038, "Intervention Status"); dict.put(0x0018003a, "Intervention Description"); dict.put(0x00180040, "Cine Rate"); dict.put(0x00180050, "Slice Thickness"); dict.put(0x00180060, "KVP"); dict.put(0x00180070, "Counts Accumulated"); dict.put(0x00180071, "Acquisition Termination Condition"); dict.put(0x00180072, "Effective Duration"); dict.put(0x00180073, "Acquisition Start Condition"); dict.put(0x00180074, "Acquisition Start Condition Data"); dict.put(0x00180075, "Acquisition Termination Condition Data"); dict.put(0x00180080, "Repetition Time"); dict.put(0x00180081, "Echo Time"); dict.put(0x00180082, "Inversion Time"); dict.put(0x00180083, "Number of Averages"); dict.put(0x00180084, "Imaging Frequency"); dict.put(0x00180085, "Imaged Nucleus"); dict.put(0x00180086, "Echo Number(s)"); dict.put(0x00180087, "Magnetic Field Strength"); dict.put(0x00180088, "Spacing Between Slices"); dict.put(0x00180089, "Number of Phase Encoding Steps"); dict.put(0x00180090, "Data Collection Diameter"); dict.put(0x00180091, "Echo Train Length"); dict.put(0x00180093, "Percent Sampling"); dict.put(0x00180094, "Percent Phase Field of View"); dict.put(0x00180095, "Pixel Bandwidth"); dict.put(0x00181000, "Device Serial Number"); dict.put(0x00181004, "Plate ID"); dict.put(0x00181010, "Secondary Capture Device ID"); dict.put(0x00181011, "Hardcopy Creation Device ID"); dict.put(0x00181012, "Date of Secondary Capture"); dict.put(0x00181014, "Time of Secondary Capture"); dict.put(0x00181016, "Secondary Capture Device Manufacturer"); dict.put(0x00181017, "Hardcopy Device Manufacturer"); dict.put(0x00181018, "Secondary Capture Device Model Name"); dict.put(0x00181019, "Secondary Capture Device Software Version"); dict.put(0x0018101a, "Hardcopy Device Software Version"); dict.put(0x0018101b, "Hardcopy Device Model Name"); dict.put(0x00181020, "Software Version(s)"); dict.put(0x00181022, "Video Image Format Acquired"); dict.put(0x00181023, "Digital Image Format Acquired"); dict.put(0x00181030, "Protocol Name"); dict.put(0x00181040, "Contrast/Bolus Route"); dict.put(0x00181041, "Contrast/Bolus Volume"); dict.put(0x00181042, "Contrast/Bolus Start Time"); dict.put(0x00181043, "Contrast/Bolus Stop Time"); dict.put(0x00181044, "Contrast/Bolus Total Dose"); dict.put(0x00181045, "Syringe Counts"); dict.put(0x00181046, "Contrast Flow Rate"); dict.put(0x00181047, "Contrast Flow Duration"); dict.put(0x00181048, "Contrast/Bolus Ingredient"); dict.put(0x00181049, "Contrast Ingredient Concentration"); dict.put(0x00181050, "Spatial Resolution"); dict.put(0x00181060, "Trigger Time"); dict.put(0x00181061, "Trigger Source or Type"); dict.put(0x00181062, "Nominal Interval"); dict.put(0x00181063, "Frame Time"); dict.put(0x00181064, "Framing Type"); dict.put(0x00181065, "Frame Time Vector"); dict.put(0x00181066, "Frame Delay"); dict.put(0x00181067, "Image Trigger Delay"); dict.put(0x00181068, "Multiplex Group Time Offset"); dict.put(0x00181069, "Trigger Time Offset"); dict.put(0x0018106a, "Synchronization Trigger"); dict.put(0x0018106c, "Synchronization Channel"); dict.put(0x0018106e, "Trigger Sample Position"); dict.put(0x00181070, "Radiopharmaceutical Route"); dict.put(0x00181071, "Radiopharmaceutical Volume"); dict.put(0x00181072, "Radiopharmaceutical Start Time"); dict.put(0x00181073, "Radiopharmaceutical Stop Time"); dict.put(0x00181074, "Radionuclide Total Dose"); dict.put(0x00181075, "Radionuclide Half Life"); dict.put(0x00181076, "Radionuclide Positron Fraction"); dict.put(0x00181077, "Radiopharmaceutical Specific Activity"); dict.put(0x00181080, "Beat Rejection Flag"); dict.put(0x00181081, "Low R-R Value"); dict.put(0x00181082, "High R-R Value"); dict.put(0x00181083, "Intervals Acquired"); dict.put(0x00181084, "Intervals Rejected"); dict.put(0x00181085, "PVC Rejection"); dict.put(0x00181086, "Skip Beats"); dict.put(0x00181088, "Heart Rate"); dict.put(0x00181090, "Cardiac Number of Images"); dict.put(0x00181094, "Trigger Window"); dict.put(0x00181100, "Reconstruction Diameter"); dict.put(0x00181110, "Distance Source to Detector"); dict.put(0x00181111, "Distance Source to Patient"); dict.put(0x00181114, "Estimated Radiographic Mag. Factor"); dict.put(0x00181120, "Gantry/Detector Tilt"); dict.put(0x00181121, "Gantry/Detector Skew"); dict.put(0x00181130, "Table Height"); dict.put(0x00181131, "Table Traverse"); dict.put(0x00181134, "Table Motion"); dict.put(0x00181135, "Table Vertical Increment"); dict.put(0x00181136, "Table Lateral Increment"); dict.put(0x00181137, "Table Longitudinal Increment"); dict.put(0x00181138, "Table Angle"); dict.put(0x0018113a, "Table Type"); dict.put(0x00181140, "Rotation Direction"); dict.put(0x00181141, "Angular Position"); dict.put(0x00181142, "Radial Position"); dict.put(0x00181143, "Scan Arc"); dict.put(0x00181144, "Angular Step"); dict.put(0x00181145, "Center of Rotation Offset"); dict.put(0x00181147, "Field of View Shape"); dict.put(0x00181149, "Field of View Dimension(s)"); dict.put(0x00181150, "Exposure Time"); dict.put(0x00181151, "X-ray Tube Current"); dict.put(0x00181152, "Exposure"); dict.put(0x00181153, "Exposure in uAs"); dict.put(0x00181154, "Average Pulse Width"); dict.put(0x00181155, "Radiation Setting"); dict.put(0x00181156, "Rectification Type"); dict.put(0x0018115a, "Radiation Mode"); dict.put(0x0018115e, "Image Area Dose Product"); dict.put(0x00181160, "Filter Type"); dict.put(0x00181161, "Type of Filters"); dict.put(0x00181162, "Intensifier Size"); dict.put(0x00181164, "Imager Pixel Spacing"); dict.put(0x00181166, "Grid"); dict.put(0x00181170, "Generator Power"); dict.put(0x00181180, "Collimator/Grid Name"); dict.put(0x00181181, "Collimator Type"); dict.put(0x00181182, "Focal Distance"); dict.put(0x00181183, "X Focus Center"); dict.put(0x00181184, "Y Focus Center"); dict.put(0x00181190, "Focal Spot(s)"); dict.put(0x00181191, "Anode Target Material"); dict.put(0x001811a0, "Body Part Thickness"); dict.put(0x001811a2, "Compression Force"); dict.put(0x00181200, "Date of Last Calibration"); dict.put(0x00181201, "Time of Last Calibration"); dict.put(0x00181210, "Convolution Kernel"); dict.put(0x00181242, "Actual Frame Duration"); dict.put(0x00181243, "Count Rate"); dict.put(0x00181244, "Preferred Playback Sequencing"); dict.put(0x00181250, "Receive Coil Name"); dict.put(0x00181251, "Transmit Coil Name"); dict.put(0x00181260, "Plate Type"); dict.put(0x00181261, "Phosphor Type"); dict.put(0x00181300, "Scan Velocity"); dict.put(0x00181301, "Whole Body Technique"); dict.put(0x00181302, "Scan Length"); dict.put(0x00181310, "Acquisition Matrix"); dict.put(0x00181312, "In-plane Phase Encoding Direction"); dict.put(0x00181314, "Flip Angle"); dict.put(0x00181315, "Variable Flip Angle Flag"); dict.put(0x00181316, "SAR"); dict.put(0x00181318, "dB/dt"); dict.put(0x00181400, "Acquisition Device Processing Descr."); dict.put(0x00181401, "Acquisition Device Processing Code"); dict.put(0x00181402, "Cassette Orientation"); dict.put(0x00181403, "Cassette Size"); dict.put(0x00181404, "Exposures on Plate"); dict.put(0x00181405, "Relative X-ray Exposure"); dict.put(0x00181450, "Column Angulation"); dict.put(0x00181460, "Tomo Layer Height"); dict.put(0x00181470, "Tomo Angle"); dict.put(0x00181480, "Tomo Time"); dict.put(0x00181490, "Tomo Type"); dict.put(0x00181491, "Tomo Class"); dict.put(0x00181495, "Number of Tomosynthesis Source Images"); dict.put(0x00181500, "Positioner Motion"); dict.put(0x00181508, "Positioner Type"); dict.put(0x00181510, "Positioner Primary Angle"); dict.put(0x00181511, "Positioner Secondary Angle"); dict.put(0x00181520, "Positioner Primary Angle Increment"); dict.put(0x00181521, "Positioner Secondary Angle Increment"); dict.put(0x00181530, "Detector Primary Angle"); dict.put(0x00181531, "Detector Secondary Angle"); dict.put(0x00181600, "Shutter Shape"); dict.put(0x00181602, "Shutter Left Vertical Edge"); dict.put(0x00181604, "Shutter Right Vertical Edge"); dict.put(0x00181606, "Shutter Upper Horizontal Edge"); dict.put(0x00181608, "Shutter Lower Horizontal Edge"); dict.put(0x00181610, "Center of Circular Shutter"); dict.put(0x00181612, "Radius of Circular Shutter"); dict.put(0x00181620, "Vertices of the Polygonal Shutter"); dict.put(0x00181622, "Shutter Presentation Value"); dict.put(0x00181623, "Shutter Overlay Group"); dict.put(0x00181700, "Collimator Shape"); dict.put(0x00181702, "Collimator Left Vertical Edge"); dict.put(0x00181704, "Collimator Right Vertical Edge"); dict.put(0x00181706, "Collimator Upper Horizontal Edge"); dict.put(0x00181708, "Collimator Lower Horizontal Edge"); dict.put(0x00181710, "Center of Circular Collimator"); dict.put(0x00181712, "Radius of Circular Collimator"); dict.put(0x00181720, "Vertices of the polygonal Collimator"); dict.put(0x00181800, "Acquisition Time Synchronized"); dict.put(0x00181801, "Time Source"); dict.put(0x00181802, "Time Distribution Protocol"); dict.put(0x00181803, "NTP Source Address"); dict.put(0x00182001, "Page Number Vector"); dict.put(0x00182002, "Frame Label Vector"); dict.put(0x00182003, "Frame Primary Angle Vector"); dict.put(0x00182004, "Frame Secondary Angle Vector"); dict.put(0x00182005, "Slice Location Vector"); dict.put(0x00182006, "Display Window Label Vector"); dict.put(0x00182010, "Nominal Scanned Pixel Spacing"); dict.put(0x00182020, "Digitizing Device Transport Direction"); dict.put(0x00182030, "Rotation of Scanned Film"); dict.put(0x00183100, "IVUS Acquisition"); dict.put(0x00183101, "IVUS Pullback Rate"); dict.put(0x00183102, "IVUS Gated Rate"); dict.put(0x00183103, "IVUS Pullback Start Frame Number"); dict.put(0x00183104, "IVUS Pullback Stop Frame Number"); dict.put(0x00183105, "Lesion Number"); dict.put(0x00185000, "Output Power"); dict.put(0x00185010, "Transducer Data"); dict.put(0x00185012, "Focus Depth"); dict.put(0x00185020, "Processing Function"); dict.put(0x00185021, "Postprocessing Fuction"); dict.put(0x00185022, "Mechanical Index"); dict.put(0x00185024, "Bone Thermal Index"); dict.put(0x00185026, "Cranial Thermal Index"); dict.put(0x00185027, "Soft Tissue Thermal Index"); dict.put(0x00185028, "Soft Tissue-focus Thermal Index"); dict.put(0x00185029, "Soft Tissue-surface Thermal Index"); dict.put(0x00185050, "Depth of scan field"); dict.put(0x00185100, "Patient Position"); dict.put(0x00185101, "View Position"); dict.put(0x00185104, "Projection Eponymous Name Code"); dict.put(0x00186000, "Sensitivity"); dict.put(0x00186011, "Sequence of Ultrasound Regions"); dict.put(0x00186012, "Region Spatial Format"); dict.put(0x00186014, "Region Data Type"); dict.put(0x00186016, "Region Flags"); dict.put(0x00186018, "Region Location Min X0"); dict.put(0x0018601a, "Region Location Min Y0"); dict.put(0x0018601c, "Region Location Max X1"); dict.put(0x0018601e, "Region Location Max Y1"); dict.put(0x00186020, "Reference Pixel X0"); dict.put(0x00186022, "Reference Pixel Y0"); dict.put(0x00186024, "Physical Units X Direction"); dict.put(0x00186026, "Physical Units Y Direction"); dict.put(0x00186028, "Reference Pixel Physical Value X"); dict.put(0x0018602a, "Reference Pixel Physical Value Y"); dict.put(0x0018602c, "Physical Delta X"); dict.put(0x0018602e, "Physical Delta Y"); dict.put(0x00186030, "Transducer Frequency"); dict.put(0x00186031, "Transducer Type"); dict.put(0x00186032, "Pulse Repetition Frequency"); dict.put(0x00186034, "Doppler Correction Angle"); dict.put(0x00186036, "Steering Angle"); dict.put(0x00186039, "Doppler Sample Volume X Position"); dict.put(0x0018603b, "Doppler Sample Volume Y Position"); dict.put(0x0018603d, "TM-Line Position X0"); dict.put(0x0018603f, "TM-Line Position Y0"); dict.put(0x00186041, "TM-Line Position X1"); dict.put(0x00186043, "TM-Line Position Y1"); dict.put(0x00186044, "Pixel Component Organization"); dict.put(0x00186046, "Pixel Component Mask"); dict.put(0x00186048, "Pixel Component Range Start"); dict.put(0x0018604a, "Pixel Component Range Stop"); dict.put(0x0018604c, "Pixel Component Physical Units"); dict.put(0x0018604e, "Pixel Component Data Type"); dict.put(0x00186050, "Number of Table Break Points"); dict.put(0x00186052, "Table of X Break Points"); dict.put(0x00186054, "Table of Y Break Points"); dict.put(0x00186056, "Number of Table Entries"); dict.put(0x00186058, "Table of Pixel Values"); dict.put(0x0018605a, "Table of Parameter Values"); dict.put(0x00186060, "R Wave Time Vector"); dict.put(0x00187000, "Detector Conditions Nominal Flag"); dict.put(0x00187001, "Detector Temperature"); dict.put(0x00187004, "Detector Type"); dict.put(0x00187005, "Detector Configuration"); dict.put(0x00187006, "Detector Description"); dict.put(0x00187008, "Detector Mode"); dict.put(0x0018700a, "Detector ID"); dict.put(0x0018700c, "Date of Last Detector Calibration"); dict.put(0x0018700e, "Time of Last Detector Calibration"); dict.put(0x00187012, "Detector Time Since Last Exposure"); dict.put(0x00187014, "Detector Active Time"); dict.put(0x00187016, "Detector Activation Offset"); dict.put(0x0018701a, "Detector Binning"); dict.put(0x00187020, "Detector Element Physical Size"); dict.put(0x00187022, "Detector Element Spacing"); dict.put(0x00187024, "Detector Active Shape"); dict.put(0x00187026, "Detector Active Dimension(s)"); dict.put(0x00187028, "Detector Active Origin"); dict.put(0x0018702a, "Detector Manufacturer Name"); dict.put(0x0018702b, "Detector Model Name"); dict.put(0x00187030, "Field of View Origin"); dict.put(0x00187032, "Field of View Rotation"); dict.put(0x00187034, "Field of View Horizontal Flip"); dict.put(0x00187040, "Grid Absorbing Material"); dict.put(0x00187041, "Grid Spacing Material"); dict.put(0x00187042, "Grid Thickness"); dict.put(0x00187044, "Grid Pitch"); dict.put(0x00187046, "Grid Aspect Ratio"); dict.put(0x00187048, "Grid Period"); dict.put(0x0018704c, "Grid Focal Distance"); dict.put(0x00187050, "Filter Material"); dict.put(0x00187052, "Filter Thickness Min"); dict.put(0x00187054, "Filter Thickness Max"); dict.put(0x00187060, "Exposure Control Mode"); dict.put(0x0020000d, "Study Instance UID"); dict.put(0x0020000e, "Series Instance UID"); dict.put(0x00200011, "Series Number"); dict.put(0x00200012, "Acquisition Number"); dict.put(0x00200013, "Instance Number"); dict.put(0x00200020, "Patient Orientation"); dict.put(0x00200030, "Image Position"); dict.put(0x00200032, "Image Position (Patient)"); dict.put(0x00200037, "Image Orientation (Patient)"); dict.put(0x00200050, "Location"); dict.put(0x00200052, "Frame of Reference UID"); dict.put(0x00200070, "Image Geometry Type"); dict.put(0x00201001, "Acquisitions in Series"); dict.put(0x00201020, "Reference"); dict.put(0x00201041, "Slice Location"); // skipped a bunch of stuff here - not used dict.put(0x00280002, "Samples per pixel"); dict.put(0x00280003, "Samples per pixel used"); dict.put(0x00280004, "Photometric Interpretation"); dict.put(0x00280006, "Planar Configuration"); dict.put(0x00280008, "Number of frames"); dict.put(0x00280009, "Frame Increment Pointer"); dict.put(0x0028000a, "Frame Dimension Pointer"); dict.put(0x00280010, "Rows"); dict.put(0x00280011, "Columns"); dict.put(0x00280012, "Planes"); dict.put(0x00280014, "Ultrasound Color Data Present"); dict.put(0x00280030, "Pixel Spacing"); dict.put(0x00280031, "Zoom Factor"); dict.put(0x00280032, "Zoom Center"); dict.put(0x00280034, "Pixel Aspect Ratio"); dict.put(0x00280051, "Corrected Image"); dict.put(0x00280100, "Bits Allocated"); dict.put(0x00280101, "Bits Stored"); dict.put(0x00280102, "High Bit"); dict.put(0x00280103, "Pixel Representation"); dict.put(0x00280106, "Smallest Image Pixel Value"); dict.put(0x00280107, "Largest Image Pixel Value"); dict.put(0x00280108, "Smallest Pixel Value in Series"); dict.put(0x00280109, "Largest Pixel Value in Series"); dict.put(0x00280110, "Smallest Image Pixel Value in Plane"); dict.put(0x00280111, "Largest Image Pixel Value in Plane"); dict.put(0x00280120, "Pixel Padding Value"); dict.put(0x00280300, "Quality Control Image"); dict.put(0x00280301, "Burned in Annotation"); dict.put(0x00281040, "Pixel Intensity Relationship"); dict.put(0x00281041, "Pixel Intensity Relationship Sign"); dict.put(0x00281050, "Window Center"); dict.put(0x00281051, "Window Width"); dict.put(0x00281052, "Rescale Intercept"); dict.put(0x00281053, "Rescale Slope"); dict.put(0x00281054, "Rescale Type"); dict.put(0x00281055, "Window Center and Width Explanation"); dict.put(0x00281090, "Recommended Viewing Mode"); dict.put(0x00281101, "Red Palette Color LUT Descriptor"); dict.put(0x00281102, "Green Palette Color LUT Descriptor"); dict.put(0x00281103, "Blue Palette Color LUT Descriptor"); dict.put(0x00281199, "Palette Color LUT UID"); dict.put(0x00281201, "Red Palette Color LUT Data"); dict.put(0x00281202, "Green Palette Color LUT Data"); dict.put(0x00281203, "Blue Palette Color LUT Data"); dict.put(0x00281221, "Segmented Red Palette Color LUT Data"); dict.put(0x00281222, "Segmented Green Palette Color LUT Data"); dict.put(0x00281223, "Segmented Blue Palette Color LUT Data"); dict.put(0x00281300, "Implant Present"); dict.put(0x00281350, "Partial View"); dict.put(0x00281351, "Partial View Description"); dict.put(0x00282110, "Lossy Image Compression"); dict.put(0x00282112, "Lossy Image Compression Ratio"); dict.put(0x00282114, "Lossy Image Compression Method"); dict.put(0x00283000, "Modality LUT Sequence"); dict.put(0x00283002, "LUT Descriptor"); dict.put(0x00283003, "LUT Explanation"); dict.put(0x00283004, "Modality LUT Type"); dict.put(0x00283006, "LUT Data"); dict.put(0x00283010, "VOI LUT Sequence"); dict.put(0x00283110, "Softcopy VOI LUT Sequence"); dict.put(0x00285000, "Bi-Plane Acquisition Sequence"); dict.put(0x00286010, "Representative Frame Number"); dict.put(0x00286020, "Frame Numbers of Interest (FOI)"); dict.put(0x00286022, "Frame(s) of Interest Description"); dict.put(0x00286023, "Frame of Interest Type"); dict.put(0x00286040, "R Wave Pointer"); dict.put(0x00286100, "Mask Subtraction Sequence"); dict.put(0x00286101, "Mask Operation"); dict.put(0x00286102, "Applicable Frame Range"); dict.put(0x00286110, "Mask Frame Numbers"); dict.put(0x00286112, "Contrast Frame Averaging"); dict.put(0x00286114, "Mask Sub-pixel Shift"); dict.put(0x00286120, "TID Offset"); dict.put(0x00286190, "Mask Operation Explanation"); dict.put(0x00289001, "Data Point Rows"); dict.put(0x00289002, "Data Point Columns"); dict.put(0x00289003, "Signal Domain Columns"); dict.put(0x00289108, "Data Representation"); dict.put(0x00289110, "Pixel Measures Sequence"); dict.put(0x00289132, "Frame VOI LUT Sequence"); dict.put(0x00289145, "Pixel Value Transformation Sequence"); dict.put(0x00289235, "Signal Domain Rows"); // skipping some more stuff dict.put(0x00540011, "Number of Energy Windows"); dict.put(0x00540021, "Number of Detectors"); dict.put(0x00540051, "Number of Rotations"); dict.put(0x00540080, "Slice Vector"); dict.put(0x00540081, "Number of Slices"); dict.put(0x00540202, "Type of Detector Motion"); dict.put(0x00540400, "Image ID"); dict.put(0x20100100, "Border Density"); return dict; } // -- Nested Classes -- public static class Metadata extends AbstractMetadata implements HasColorTable { // -- Fields -- byte[][] lut = null; short[][] shortLut = null; private ColorTable8 lut8; private ColorTable16 lut16; private long[] offsets = null; private boolean isJP2K = false; private boolean isJPEG = false; private boolean isRLE = false; private boolean isDeflate = false; private boolean oddLocations = false; private int maxPixelValue; private int imagesPerFile = 0; private double rescaleSlope = 1.0, rescaleIntercept = 0.0; private Hashtable<Integer, Vector<String>> fileList; private boolean inverted = false; private String pixelSizeX, pixelSizeY; private Double pixelSizeZ; private String date, time, imageType; private String originalDate, originalTime, originalInstance; private int originalSeries; private Vector<String> companionFiles = new Vector<String>(); // Getters and Setters public long[] getOffsets() { return offsets; } public void setOffsets(final long[] offsets) { this.offsets = offsets; } public double getRescaleSlope() { return rescaleSlope; } public void setRescaleSlope(final double rescaleSlope) { this.rescaleSlope = rescaleSlope; } public double getRescaleIntercept() { return rescaleIntercept; } public void setRescaleIntercept(final double rescaleIntercept) { this.rescaleIntercept = rescaleIntercept; } public String getPixelSizeX() { return pixelSizeX; } public void setPixelSizeX(final String pixelSizeX) { this.pixelSizeX = pixelSizeX; } public String getPixelSizeY() { return pixelSizeY; } public void setPixelSizeY(final String pixelSizeY) { this.pixelSizeY = pixelSizeY; } public Double getPixelSizeZ() { return pixelSizeZ; } public void setPixelSizeZ(final Double pixelSizeZ) { this.pixelSizeZ = pixelSizeZ; } public boolean isInverted() { return inverted; } public void setInverted(final boolean inverted) { this.inverted = inverted; } public boolean isJP2K() { return isJP2K; } public void setJP2K(final boolean isJP2K) { this.isJP2K = isJP2K; } public boolean isJPEG() { return isJPEG; } public void setJPEG(final boolean isJPEG) { this.isJPEG = isJPEG; } public boolean isRLE() { return isRLE; } public void setRLE(final boolean isRLE) { this.isRLE = isRLE; } public boolean isDeflate() { return isDeflate; } public void setDeflate(final boolean isDeflate) { this.isDeflate = isDeflate; } public boolean isOddLocations() { return oddLocations; } public void setOddLocations(final boolean oddLocations) { this.oddLocations = oddLocations; } public int getMaxPixelValue() { return maxPixelValue; } public void setMaxPixelValue(final int maxPixelValue) { this.maxPixelValue = maxPixelValue; } public int getImagesPerFile() { return imagesPerFile; } public void setImagesPerFile(final int imagesPerFile) { this.imagesPerFile = imagesPerFile; } public Hashtable<Integer, Vector<String>> getFileList() { return fileList; } public void setFileList(final Hashtable<Integer, Vector<String>> fileList) { this.fileList = fileList; } public String getDate() { return date; } public void setDate(final String date) { this.date = date; } public String getTime() { return time; } public void setTime(final String time) { this.time = time; } public String getImageType() { return imageType; } public void setImageType(final String imageType) { this.imageType = imageType; } public String getOriginalDate() { return originalDate; } public void setOriginalDate(final String originalDate) { this.originalDate = originalDate; } public String getOriginalTime() { return originalTime; } public void setOriginalTime(final String originalTime) { this.originalTime = originalTime; } public String getOriginalInstance() { return originalInstance; } public void setOriginalInstance(final String originalInstance) { this.originalInstance = originalInstance; } public int getOriginalSeries() { return originalSeries; } public void setOriginalSeries(final int originalSeries) { this.originalSeries = originalSeries; } public Vector<String> getCompanionFiles() { return companionFiles; } public void setCompanionFiles(final Vector<String> companionFiles) { this.companionFiles = companionFiles; } // -- ColorTable API Methods -- @Override public ColorTable getColorTable(final int imageIndex, final long planeIndex) { final int pixelType = get(0).getPixelType(); switch (pixelType) { case FormatTools.INT8: case FormatTools.UINT8: if (lut != null && lut8 == null) lut8 = new ColorTable8(lut); return lut8; case FormatTools.INT16: case FormatTools.UINT16: if (shortLut != null && lut16 == null) lut16 = new ColorTable16( shortLut); return lut16; } return null; } // -- Metadata API Methods -- @Override public void populateImageMetadata() { log().info("Populating metadata"); // TODO this isn't going to work because each parsing will // get the same filelist size and repeat infinitely final int seriesCount = fileList.size(); final Integer[] keys = fileList.keySet().toArray(new Integer[0]); Arrays.sort(keys); for (int i = 0; i < seriesCount; i++) { get(i).setAxisTypes(Axes.X, Axes.Y); int sizeZ = 0; if (seriesCount == 1) { sizeZ = getOffsets().length * fileList.get(keys[i]).size(); get(i).setMetadataComplete(true); get(i).setFalseColor(false); if (isRLE) { get(i).setAxisTypes(Axes.X, Axes.Y, Axes.CHANNEL); } if (get(i).getAxisLength(Axes.CHANNEL) > 1) { get(i).setPlanarAxisCount(3); } else { get(i).setPlanarAxisCount(2); } } else { try { final Parser p = (Parser) getFormat().createParser(); final Metadata m = p.parse(fileList.get(keys[i]).get(0), new SCIFIOConfig().groupableSetGroupFiles(false)); add(m.get(0)); sizeZ *= fileList.get(keys[i]).size(); } catch (final IOException e) { log().error("Error creating Metadata from DICOM companion files.", e); } catch (final FormatException e) { log().error("Error creating Metadata from DICOM companion files.", e); } } get(i).setAxisLength(Axes.Z, sizeZ); } } // -- HasSource API Methods -- @Override public void close(final boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { oddLocations = false; isJPEG = isJP2K = isRLE = isDeflate = false; lut = null; offsets = null; shortLut = null; maxPixelValue = 0; rescaleSlope = 1.0; rescaleIntercept = 0.0; pixelSizeX = pixelSizeY = null; pixelSizeZ = null; imagesPerFile = 0; fileList = null; inverted = false; date = time = imageType = null; originalDate = originalTime = originalInstance = null; originalSeries = 0; // TODO the resetting is a bit too aggressive, perhaps it should just // clear out fields.. // companionFiles.clear(); } } } public static class Checker extends AbstractChecker { // -- Constants -- private static final String[] DICOM_SUFFIXES = { "dic", "dcm", "dicom", "j2ki", "j2kr" }; // -- Checker API Methods -- @Override public boolean suffixNecessary() { return false; } @Override public boolean suffixSufficient() { return false; } @Override public boolean isFormat(final String name, final SCIFIOConfig config) { // extension is sufficient as long as it is DIC, DCM, DICOM, J2KI, or J2KR if (FormatTools.checkSuffix(name, DICOM_SUFFIXES)) return true; return super.isFormat(name, config); } @Override public boolean isFormat(final RandomAccessInputStream stream) throws IOException { final int blockLen = 2048; if (!FormatTools.validStream(stream, blockLen, true)) return false; stream.seek(128); if (stream.readString(4).equals(DICOM_MAGIC_STRING)) return true; stream.seek(0); try { final int tag = DICOMUtils.getNextTag(stream).get(); return TYPES.get(tag) != null; } catch (final NullPointerException e) {} catch (final FormatException e) {} return false; } } public static class Parser extends AbstractParser<Metadata> { // -- Constants -- private static final int PIXEL_REPRESENTATION = 0x00280103; private static final int PIXEL_SIGN = 0x00281041; private static final int TRANSFER_SYNTAX_UID = 0x00020010; private static final int SLICE_SPACING = 0x00180088; private static final int SAMPLES_PER_PIXEL = 0x00280002; private static final int PHOTOMETRIC_INTERPRETATION = 0x00280004; private static final int PLANAR_CONFIGURATION = 0x00280006; private static final int NUMBER_OF_FRAMES = 0x00280008; private static final int ROWS = 0x00280010; private static final int COLUMNS = 0x00280011; private static final int PIXEL_SPACING = 0x00280030; private static final int BITS_ALLOCATED = 0x00280100; private static final int WINDOW_CENTER = 0x00281050; private static final int WINDOW_WIDTH = 0x00281051; private static final int RESCALE_INTERCEPT = 0x00281052; private static final int RESCALE_SLOPE = 0x00281053; private static final int ICON_IMAGE_SEQUENCE = 0x00880200; private static final int ITEM = 0xFFFEE000; private static final int ITEM_DELIMINATION = 0xFFFEE00D; private static final int SEQUENCE_DELIMINATION = 0xFFFEE0DD; private static final int PIXEL_DATA = 0x7FE00010; @Parameter private CodecService codecService; // -- Parser API Methods -- @Override public int fileGroupOption(final String id) throws FormatException, IOException { return FormatTools.CAN_GROUP; } @Override protected void typedParse(final RandomAccessInputStream stream, final Metadata meta, final SCIFIOConfig config) throws IOException, FormatException { meta.createImageMetadata(1); stream.order(true); final ImageMetadata iMeta = meta.get(0); // look for companion files final Vector<String> companionFiles = new Vector<String>(); attachCompanionFiles(companionFiles); meta.setCompanionFiles(companionFiles); int location = 0; boolean isJP2K = false; boolean isJPEG = false; boolean isRLE = false; boolean isDeflate = false; boolean oddLocations = false; int maxPixelValue = -1; int imagesPerFile = 0; boolean bigEndianTransferSyntax = false; long[] offsets = null; int sizeX = 0; int sizeY = 0; int bitsPerPixel = 0; boolean interleaved; // some DICOM files have a 128 byte header followed by a 4 byte identifier log().info("Verifying DICOM format"); final MetadataLevel level = config.parserGetLevel(); getSource().seek(128); if (getSource().readString(4).equals("DICM")) { if (level != MetadataLevel.MINIMUM) { // header exists, so we'll read it getSource().seek(0); meta.getTable().put("Header information", getSource().readString( 128)); getSource().skipBytes(4); } location = 128; } else getSource().seek(0); log().info("Reading tags"); long baseOffset = 0; boolean decodingTags = true; boolean signed = false; while (decodingTags) { if (getSource().getFilePointer() + 4 >= getSource().length()) { break; } log().debug("Reading tag from " + getSource().getFilePointer()); final DICOMTag tag = DICOMUtils.getNextTag(getSource(), bigEndianTransferSyntax, oddLocations); iMeta.setLittleEndian(tag.isLittleEndian()); if (tag.getElementLength() <= 0) continue; oddLocations = (location & 1) != 0; log().debug(" tag=" + tag.get() + " len=" + tag.getElementLength() + " fp=" + getSource().getFilePointer()); String s = null; switch (tag.get()) { case TRANSFER_SYNTAX_UID: // this tag can indicate which compression scheme is used s = getSource().readString(tag.getElementLength()); addInfo(meta, tag, s); if (s.startsWith("1.2.840.10008.1.2.4.9")) isJP2K = true; else if (s.startsWith("1.2.840.10008.1.2.4")) isJPEG = true; else if (s.startsWith("1.2.840.10008.1.2.5")) isRLE = true; else if (s.equals("1.2.8.10008.1.2.1.99")) isDeflate = true; else if (s.contains("1.2.4") || s.contains("1.2.5")) { throw new UnsupportedCompressionException( "Sorry, compression type " + s + " not supported"); } if (s.contains("1.2.840.10008.1.2.2")) { bigEndianTransferSyntax = true; } break; case NUMBER_OF_FRAMES: s = getSource().readString(tag.getElementLength()); addInfo(meta, tag, s); final double frames = Double.parseDouble(s); if (frames > 1.0) imagesPerFile = (int) frames; break; case SAMPLES_PER_PIXEL: addInfo(meta, tag, getSource().readShort()); break; case PLANAR_CONFIGURATION: final int configuration = getSource().readShort(); interleaved = configuration == 0; if (interleaved) { iMeta.setAxisTypes(Axes.CHANNEL, Axes.X, Axes.Y); iMeta.setPlanarAxisCount(3); } addInfo(meta, tag, configuration); break; case ROWS: if (sizeY == 0) { sizeY = getSource().readShort(); iMeta.addAxis(Axes.Y, sizeY); } else getSource().skipBytes(2); addInfo(meta, tag, sizeY); break; case COLUMNS: if (sizeX == 0) { sizeX = getSource().readShort(); iMeta.addAxis(Axes.X, sizeX); } else getSource().skipBytes(2); addInfo(meta, tag, sizeX); break; case PHOTOMETRIC_INTERPRETATION: case PIXEL_SPACING: case SLICE_SPACING: case RESCALE_INTERCEPT: case WINDOW_CENTER: case RESCALE_SLOPE: addInfo(meta, tag, getSource().readString(tag.getElementLength())); break; case BITS_ALLOCATED: if (bitsPerPixel == 0) bitsPerPixel = getSource().readShort(); else getSource().skipBytes(2); addInfo(meta, tag, bitsPerPixel); break; case PIXEL_REPRESENTATION: final short ss = getSource().readShort(); signed = ss == 1; addInfo(meta, tag, ss); break; case PIXEL_SIGN: final short ss = getSource().readShort(); addInfo(meta, tag, ss); break; case 537262910: case WINDOW_WIDTH: final String t = getSource().readString(tag.getElementLength()); if (t.trim().length() == 0) maxPixelValue = -1; else { try { maxPixelValue = new Double(t.trim()).intValue(); } catch (final NumberFormatException e) { maxPixelValue = -1; } } addInfo(meta, tag, t); break; case PIXEL_DATA: case ITEM: case 0xffee000: if (tag.getElementLength() != 0) { baseOffset = getSource().getFilePointer(); addInfo(meta, tag, location); decodingTags = false; } else addInfo(meta, tag, null); break; case 0x7f880010: if (tag.getElementLength() != 0) { baseOffset = location + 4; decodingTags = false; } break; case 0x7fe00000: getSource().skipBytes(tag.getElementLength()); break; case 0: getSource().seek(getSource().getFilePointer() - 4); break; default: final long oldfp = getSource().getFilePointer(); addInfo(meta, tag, s); getSource().seek(oldfp + tag.getElementLength()); } if (getSource().getFilePointer() >= (getSource().length() - 4)) { decodingTags = false; } } if (imagesPerFile == 0) imagesPerFile = 1; int bpp = bitsPerPixel; while (bitsPerPixel % 8 != 0) bitsPerPixel++; if (bitsPerPixel == 24 || bitsPerPixel == 48) { bitsPerPixel /= 3; bpp /= 3; } final int pixelType = FormatTools.pixelTypeFromBytes(bitsPerPixel / 8, signed, false); iMeta.setBitsPerPixel(bpp); iMeta.setPixelType(pixelType); final int bytesPerPixel = FormatTools.getBytesPerPixel(pixelType); final int planeSize = sizeX * sizeY * (int) (meta.getColorTable(0, 0) == null ? meta.get(0).getAxisLength(Axes.CHANNEL) : 1) * bytesPerPixel; meta.setJP2K(isJP2K); meta.setJPEG(isJPEG); meta.setImagesPerFile(imagesPerFile); meta.setRLE(isRLE); meta.setDeflate(isDeflate); meta.setMaxPixelValue(maxPixelValue); meta.setOddLocations(oddLocations); log().info("Calculating image offsets"); // calculate the offset to each plane getSource().seek(baseOffset - 12); final int len = getSource().readInt(); if (len >= 0 && len + getSource().getFilePointer() < getSource() .length()) { getSource().skipBytes(len); final int check = getSource().readShort() & 0xffff; if (check == 0xfffe) { baseOffset = getSource().getFilePointer() + 2; } } offsets = new long[imagesPerFile]; meta.setOffsets(offsets); for (int i = 0; i < imagesPerFile; i++) { if (isRLE) { if (i == 0) getSource().seek(baseOffset); else { getSource().seek(offsets[i - 1]); final CodecOptions options = new CodecOptions(); options.maxBytes = planeSize / bytesPerPixel; for (int q = 0; q < bytesPerPixel; q++) { final PackbitsCodec codec = codecService.getCodec( PackbitsCodec.class); codec.decompress(getSource(), options); while (getSource().read() == 0) { /* Read to non-0 data */} getSource().seek(getSource().getFilePointer() - 1); } } getSource().skipBytes(i == 0 ? 64 : 53); while (getSource().read() == 0) { /* Read to non-0 data */} offsets[i] = getSource().getFilePointer() - 1; } else if (isJPEG || isJP2K) { // scan for next JPEG magic byte sequence if (i == 0) offsets[i] = baseOffset; else offsets[i] = offsets[i - 1] + 3; final byte secondCheck = isJPEG ? (byte) 0xd8 : (byte) 0x4f; getSource().seek(offsets[i]); final byte[] buf = new byte[8192]; int n = getSource().read(buf); boolean found = false; while (!found) { for (int q = 0; q < n - 2; q++) { if (buf[q] == (byte) 0xff && buf[q + 1] == secondCheck && buf[q + 2] == (byte) 0xff) { if (isJPEG || (isJP2K && buf[q + 3] == 0x51)) { found = true; offsets[i] = getSource().getFilePointer() + q - n; break; } } } if (!found) { for (int q = 0; q < 4; q++) { buf[q] = buf[buf.length + q - 4]; } n = getSource().read(buf, 4, buf.length - 4) + 4; } } } else offsets[i] = baseOffset + planeSize * i; } makeFileList(config); } @Override public String[] getImageUsedFiles(final int imageIndex, final boolean noPixels) { FormatTools.assertId(getSource(), true, 1); if (noPixels || getMetadata().getFileList() == null) return null; final Integer[] keys = getMetadata().getFileList().keySet().toArray( new Integer[0]); Arrays.sort(keys); final Vector<String> files = getMetadata().getFileList().get( keys[imageIndex]); for (final String f : getMetadata().getCompanionFiles()) { files.add(f); } return files == null ? null : files.toArray(new String[files.size()]); } // -- Helper methods -- private void makeFileList(final SCIFIOConfig config) throws FormatException, IOException { log().info("Building file list"); if (getMetadata().getFileList() == null && getMetadata() .getOriginalInstance() != null && getMetadata() .getOriginalDate() != null && getMetadata() .getOriginalTime() != null && config.groupableIsGroupFiles()) { final Hashtable<Integer, Vector<String>> fileList = new Hashtable<Integer, Vector<String>>(); final Integer s = new Integer(getMetadata().getOriginalSeries()); fileList.put(s, new Vector<String>()); final int instanceNumber = Integer.parseInt(getMetadata() .getOriginalInstance()) - 1; if (instanceNumber == 0) fileList.get(s).add(getSource().getFileName()); else { while (instanceNumber > fileList.get(s).size()) { fileList.get(s).add(null); } fileList.get(s).add(getSource().getFileName()); } // look for matching files in the current directory final Location currentFile = new Location(getContext(), getSource() .getFileName()).getAbsoluteFile(); Location directory = currentFile.getParentFile(); scanDirectory(fileList, directory, false); // move up a directory and look for other directories that // could contain matching files directory = directory.getParentFile(); final String[] subdirs = directory.list(true); if (subdirs != null) { for (final String subdir : subdirs) { final Location f = new Location(getContext(), directory, subdir) .getAbsoluteFile(); if (!f.isDirectory()) continue; scanDirectory(fileList, f, true); } } final Integer[] keys = fileList.keySet().toArray(new Integer[0]); Arrays.sort(keys); for (final Integer key : keys) { for (int j = 0; j < fileList.get(key).size(); j++) { if (fileList.get(key).get(j) == null) { fileList.get(key).remove(j); j } } } getMetadata().setFileList(fileList); } else if (getMetadata().getFileList() == null) { final Hashtable<Integer, Vector<String>> fileList = new Hashtable<Integer, Vector<String>>(); fileList.put(0, new Vector<String>()); fileList.get(0).add(getSource().getFileName()); getMetadata().setFileList(fileList); } } private void attachCompanionFiles(final Vector<String> companionFiles) { final Location parent = new Location(getContext(), getSource() .getFileName()).getAbsoluteFile().getParentFile(); final Location grandparent = parent.getParentFile(); if (new Location(getContext(), grandparent, parent.getName() + ".mif") .exists()) { final String[] list = grandparent.list(true); for (final String f : list) { final Location file = new Location(getContext(), grandparent, f); if (!file.isDirectory()) { companionFiles.add(file.getAbsolutePath()); } } } } /** * Scan the given directory for files that belong to this dataset. */ private void scanDirectory( final Hashtable<Integer, Vector<String>> fileList, final Location dir, final boolean checkSeries) throws FormatException, IOException { final Location currentFile = new Location(getContext(), getSource() .getFileName()).getAbsoluteFile(); final FilePattern pattern = new FilePattern(getContext(), currentFile .getName(), dir.getAbsolutePath()); String[] patternFiles = pattern.getFiles(); if (patternFiles == null) patternFiles = new String[0]; Arrays.sort(patternFiles); final String[] files = dir.list(true); if (files == null) return; Arrays.sort(files); for (final String f : files) { final String file = new Location(getContext(), dir, f) .getAbsolutePath(); log().debug("Checking file " + file); if (!f.equals(getSource().getFileName()) && !file.equals(getSource() .getFileName()) && getFormat().createChecker().isFormat(file) && Arrays.binarySearch(patternFiles, file) >= 0) { addFileToList(fileList, file, checkSeries); } } } /** * Determine if the given file belongs in the same dataset as this file. */ private void addFileToList( final Hashtable<Integer, Vector<String>> fileList, final String file, final boolean checkSeries) throws FormatException, IOException { final RandomAccessInputStream stream = new RandomAccessInputStream( getContext(), file); if (!getFormat().createChecker().isFormat(stream)) { stream.close(); return; } stream.order(true); stream.seek(128); if (!stream.readString(4).equals("DICM")) stream.seek(0); int fileSeries = -1; String date = null, time = null, instance = null; while (date == null || time == null || instance == null || (checkSeries && fileSeries < 0)) { final long fp = stream.getFilePointer(); if (fp + 4 >= stream.length() || fp < 0) break; final DICOMTag tag = DICOMUtils.getNextTag(stream); final String key = TYPES.get(new Integer(tag.get())); if ("Instance Number".equals(key)) { instance = stream.readString(tag.getElementLength()).trim(); if (instance.length() == 0) instance = null; } else if ("Acquisition Time".equals(key)) { time = stream.readString(tag.getElementLength()); } else if ("Acquisition Date".equals(key)) { date = stream.readString(tag.getElementLength()); } else if ("Series Number".equals(key)) { fileSeries = Integer.parseInt(stream.readString(tag .getElementLength()).trim()); } else stream.skipBytes(tag.getElementLength()); } stream.close(); if (date == null || time == null || instance == null || (checkSeries && fileSeries == getMetadata().getOriginalSeries())) { return; } int stamp = 0; try { stamp = Integer.parseInt(time); } catch (final NumberFormatException e) {} int timestamp = 0; try { timestamp = Integer.parseInt(getMetadata().getOriginalTime()); } catch (final NumberFormatException e) {} if (date.equals(getMetadata().getOriginalDate()) && (Math.abs(stamp - timestamp) < 150)) { int position = Integer.parseInt(instance) - 1; if (position < 0) position = 0; if (fileList.get(fileSeries) == null) { fileList.put(fileSeries, new Vector<String>()); } if (position < fileList.get(fileSeries).size()) { while (position < fileList.get(fileSeries).size() && fileList.get( fileSeries).get(position) != null) { position++; } if (position < fileList.get(fileSeries).size()) { fileList.get(fileSeries).setElementAt(file, position); } else fileList.get(fileSeries).add(file); } else { while (position > fileList.get(fileSeries).size()) { fileList.get(fileSeries).add(null); } fileList.get(fileSeries).add(file); } } } private void addInfo(final Metadata meta, final DICOMTag tag, final String value) throws IOException { final String oldValue = value; String info = getHeaderInfo(tag, value); if (info != null && tag.get() != ITEM) { info = info.trim(); if (info.equals("")) info = oldValue == null ? "" : oldValue.trim(); String key = TYPES.get(tag.get()); if (key == null) { key = formatTag(tag.get()); } if (key.equals("Samples per pixel")) { final int sizeC = Integer.parseInt(info); if (sizeC > 1) { meta.get(0).setAxisLength(Axes.CHANNEL, sizeC); meta.get(0).setPlanarAxisCount(2); } } else if (key.equals("Photometric Interpretation")) { if (info.equals("PALETTE COLOR")) { meta.get(0).setIndexed(true); meta.get(0).setAxisLength(Axes.CHANNEL, 1); meta.lut = new byte[3][]; meta.shortLut = new short[3][]; } else if (info.startsWith("MONOCHROME")) { meta.setInverted(info.endsWith("1")); } } else if (key.equals("Acquisition Date")) meta.setOriginalDate(info); else if (key.equals("Acquisition Time")) meta.setOriginalTime(info); else if (key.equals("Instance Number")) { if (info.trim().length() > 0) { meta.setOriginalInstance(info); } } else if (key.equals("Series Number")) { try { meta.setOriginalSeries(Integer.parseInt(info)); } catch (final NumberFormatException e) {} } else if (key.contains("Palette Color LUT Data")) { final String color = key.substring(0, key.indexOf(" ")).trim(); final int ndx = color.equals("Red") ? 0 : color.equals("Green") ? 1 : 2; final long fp = getSource().getFilePointer(); getSource().seek(getSource().getFilePointer() - tag .getElementLength() + 1); meta.shortLut[ndx] = new short[tag.getElementLength() / 2]; meta.lut[ndx] = new byte[tag.getElementLength() / 2]; for (int i = 0; i < meta.lut[ndx].length; i++) { meta.shortLut[ndx][i] = getSource().readShort(); meta.lut[ndx][i] = (byte) (meta.shortLut[ndx][i] & 0xff); } getSource().seek(fp); } else if (key.equals("Content Time")) meta.setTime(info); else if (key.equals("Content Date")) meta.setDate(info); else if (key.equals("Image Type")) meta.setImageType(info); else if (key.equals("Rescale Intercept")) { meta.setRescaleIntercept(Double.parseDouble(info)); } else if (key.equals("Rescale Slope")) { meta.setRescaleSlope(Double.parseDouble(info)); } else if (key.equals("Pixel Spacing")) { meta.setPixelSizeX(info.substring(0, info.indexOf("\\"))); meta.setPixelSizeY(info.substring(info.lastIndexOf("\\") + 1)); } else if (key.equals("Spacing Between Slices")) { meta.setPixelSizeZ(new Double(info)); } if (((tag.get() & 0xffff0000) >> 16) != 0x7fe0) { key = formatTag(tag.get()) + " " + key; final int imageIndex = meta.getImageCount() - 1; Object v; if ((v = meta.get(imageIndex).getTable().get(key)) != null) { // make sure that values are not overwritten meta.get(imageIndex).getTable().remove(key); meta.get(imageIndex).getTable().putList(key, v); meta.get(imageIndex).getTable().putList(key, info); } else { meta.get(imageIndex).getTable().put(key, info); } } } } private String formatTag(final int tag) { String s = Integer.toHexString(tag); while (s.length() < 8) { s = "0" + s; } return s.substring(0, 4) + "," + s.substring(4); } private void addInfo(final Metadata meta, final DICOMTag tag, final int value) throws IOException { addInfo(meta, tag, Integer.toString(value)); } private String getHeaderInfo(final DICOMTag tag, String value) throws IOException { if (tag.get() == ITEM_DELIMINATION || tag .get() == SEQUENCE_DELIMINATION) { tag.setInSequence(false); } String id = TYPES.get(new Integer(tag.get())); int vr = tag.getVR(); if (id != null) { if (vr == DICOMUtils.IMPLICIT_VR) { vr = (id.charAt(0) << 8) + id.charAt(1); tag.setVR(vr); } if (id.length() > 2) id = id.substring(2); } if (tag.get() == ITEM) return id != null ? id : null; if (value != null) return value; boolean skip = false; switch (vr) { case DICOMUtils.AE: case DICOMUtils.AS: case DICOMUtils.AT: // Cannot fix element length to 4, because AT value representation is // always final byte[] bytes = new byte[tag.getElementLength()]; // Read from stream getSource().readFully(bytes); // If little endian, swap bytes to get a string with a user friendly // representation of tag group and tag element if (tag.littleEndian) { for (int i = 0; i < bytes.length / 2; ++i) { final byte t = bytes[2 * i]; bytes[2 * i] = bytes[2 * i + 1]; bytes[2 * i + 1] = t; } } // Convert the bytes to a string value = DataTools.bytesToHex(bytes); break; case DICOMUtils.CS: case DICOMUtils.DA: case DICOMUtils.DS: case DICOMUtils.DT: case DICOMUtils.IS: case DICOMUtils.LO: case DICOMUtils.LT: case DICOMUtils.PN: case DICOMUtils.SH: case DICOMUtils.ST: case DICOMUtils.TM: case DICOMUtils.UI: value = getSource().readString(tag.getElementLength()); break; case DICOMUtils.US: if (tag.getElementLength() == 2) value = Integer.toString(getSource() .readShort()); else { value = ""; final int n = tag.getElementLength() / 2; for (int i = 0; i < n; i++) { value += Integer.toString(getSource().readShort()) + " "; } } break; case DICOMUtils.IMPLICIT_VR: value = getSource().readString(tag.getElementLength()); if (tag.getElementLength() <= 4 || tag.getElementLength() > 44) value = null; break; case DICOMUtils.SQ: value = ""; final boolean privateTag = ((tag.getElementLength() >> 16) & 1) != 0; if (tag.get() == ICON_IMAGE_SEQUENCE || privateTag) skip = true; break; default: skip = true; } if (skip) { final long skipCount = tag.getElementLength(); if (getSource().getFilePointer() + skipCount <= getSource().length()) { getSource().skipBytes((int) skipCount); } tag.addLocation(tag.getElementLength()); value = ""; } if (value != null && id == null && !value.equals("")) return value; else if (id == null) return null; else return value; } } public static class Reader extends ByteArrayReader<Metadata> { @Parameter private InitializeService initializeService; @Parameter private CodecService codecService; // -- AbstractReader API Methods -- @Override protected String[] createDomainArray() { return new String[] { FormatTools.MEDICAL_DOMAIN }; } // -- Reader API Methods -- @Override public boolean hasCompanionFiles() { return true; } @Override public ByteArrayPlane openPlane(final int imageIndex, long planeIndex, final ByteArrayPlane plane, final long[] planeMin, final long[] planeMax, final SCIFIOConfig config) throws FormatException, IOException { final Metadata meta = getMetadata(); plane.setColorTable(meta.getColorTable(imageIndex, planeIndex)); FormatTools.checkPlaneForReading(meta, imageIndex, planeIndex, plane .getData().length, planeMin, planeMax); final int xAxis = meta.get(imageIndex).getAxisIndex(Axes.X); final int yAxis = meta.get(imageIndex).getAxisIndex(Axes.Y); final int x = (int) planeMin[xAxis], y = (int) planeMin[yAxis], w = (int) planeMax[xAxis], h = (int) planeMax[yAxis]; final Hashtable<Integer, Vector<String>> fileList = meta.getFileList(); final Integer[] keys = fileList.keySet().toArray(new Integer[0]); Arrays.sort(keys); if (fileList.get(keys[imageIndex]).size() > 1) { final int fileNumber = (int) (planeIndex / meta.getImagesPerFile()); planeIndex = planeIndex % meta.getImagesPerFile(); final String file = fileList.get(keys[imageIndex]).get(fileNumber); final io.scif.Reader r = initializeService.initializeReader(file); return (ByteArrayPlane) r.openPlane(imageIndex, planeIndex, plane, planeMin, planeMax, config); } final int ec = meta.get(0).isIndexed() ? 1 : (int) meta.get(imageIndex) .getAxisLength(Axes.CHANNEL); final int bpp = FormatTools.getBytesPerPixel(meta.get(imageIndex) .getPixelType()); final int bytes = (int) (meta.get(imageIndex).getAxisLength(Axes.X) * meta .get(imageIndex).getAxisLength(Axes.Y) * bpp * ec); getStream().seek(meta.getOffsets()[(int) planeIndex]); if (meta.isRLE()) { // plane is compressed using run-length encoding final CodecOptions options = new CodecOptions(); options.maxBytes = (int) (meta.get(imageIndex).getAxisLength(Axes.X) * meta.get(imageIndex).getAxisLength(Axes.Y)); final PackbitsCodec codec = codecService.getCodec(PackbitsCodec.class); for (int c = 0; c < ec; c++) { byte[] t = null; if (bpp > 1) { // TODO unused int planeSize = bytes / (bpp * ec); final byte[][] tmp = new byte[bpp][]; for (int i = 0; i < bpp; i++) { tmp[i] = codec.decompress(getStream(), options); if (planeIndex < meta.getImagesPerFile() - 1 || i < bpp - 1) { while (getStream().read() == 0) { /* Read to non-0 data */} getStream().seek(getStream().getFilePointer() - 1); } } t = new byte[bytes / ec]; for (int i = 0; i < planeIndex; i++) { for (int j = 0; j < bpp; j++) { final int byteIndex = meta.get(imageIndex).isLittleEndian() ? bpp - j - 1 : j; if (i < tmp[byteIndex].length) { t[i * bpp + j] = tmp[byteIndex][i]; } } } } else { t = codec.decompress(getStream(), options); if (t.length < (bytes / ec)) { final byte[] tmp = t; t = new byte[bytes / ec]; System.arraycopy(tmp, 0, t, 0, tmp.length); } if (planeIndex < meta.getImagesPerFile() - 1 || c < ec - 1) { while (getStream().read() == 0) { /* Read to non-0 data */} getStream().seek(getStream().getFilePointer() - 1); } } final int rowLen = w * bpp; final int srcRowLen = (int) meta.get(imageIndex).getAxisLength( Axes.X) * bpp; // TODO unused int srcPlane = meta.getAxisLength(imageIndex, Axes.Y) * // srcRowLen; for (int row = 0; row < h; row++) { final int src = (row + y) * srcRowLen + x * bpp; final int dest = (h * c + row) * rowLen; final int len = Math.min(rowLen, t.length - src - 1); if (len < 0) break; System.arraycopy(t, src, plane.getBytes(), dest, len); } } } else if (meta.isJPEG() || meta.isJP2K()) { // plane is compressed using JPEG or JPEG-2000 final long end = planeIndex < meta.getOffsets().length - 1 ? meta .getOffsets()[(int) planeIndex + 1] : getStream().length(); byte[] b = new byte[(int) (end - getStream().getFilePointer())]; getStream().read(b); if (b[2] != (byte) 0xff) { final byte[] tmp = new byte[b.length + 1]; tmp[0] = b[0]; tmp[1] = b[1]; tmp[2] = (byte) 0xff; System.arraycopy(b, 2, tmp, 3, b.length - 2); b = tmp; } if ((b[3] & 0xff) >= 0xf0) { b[3] -= (byte) 0x30; } int pt = b.length - 2; while (pt >= 0 && b[pt] != (byte) 0xff || b[pt + 1] != (byte) 0xd9) { pt } if (pt < b.length - 2) { final byte[] tmp = b; b = new byte[pt + 2]; System.arraycopy(tmp, 0, b, 0, b.length); } final CodecOptions options = new CodecOptions(); options.littleEndian = meta.get(imageIndex).isLittleEndian(); options.interleaved = meta.get(imageIndex) .getInterleavedAxisCount() > 0; final Codec codec = codecService.getCodec(meta.isJPEG() ? JPEGCodec.class : JPEG2000Codec.class); b = codec.decompress(b, options); final int rowLen = w * bpp; final int srcRowLen = (int) meta.get(imageIndex).getAxisLength(Axes.X) * bpp; final int srcPlane = (int) meta.get(imageIndex).getAxisLength(Axes.Y) * srcRowLen; for (int c = 0; c < ec; c++) { for (int row = 0; row < h; row++) { System.arraycopy(b, c * srcPlane + (row + y) * srcRowLen + x * bpp, plane.getBytes(), h * rowLen * c + row * rowLen, rowLen); } } } else if (meta.isDeflate()) { // TODO throw new UnsupportedCompressionException( "Deflate data is not supported."); } else { // plane is not compressed readPlane(getStream(), imageIndex, planeMin, planeMax, plane); } if (meta.isInverted()) { // pixels are stored such that white -> 0; invert the values so that // white -> 255 (or 65535) if (bpp == 1) { for (int i = 0; i < plane.getBytes().length; i++) { plane.getBytes()[i] = (byte) (255 - plane.getBytes()[i]); } } else if (bpp == 2) { if (meta.getMaxPixelValue() == -1) meta.setMaxPixelValue(65535); final boolean little = meta.get(imageIndex).isLittleEndian(); for (int i = 0; i < plane.getBytes().length; i += 2) { final short s = DataTools.bytesToShort(plane.getBytes(), i, 2, little); DataTools.unpackBytes(meta.getMaxPixelValue() - s, plane.getBytes(), i, 2, little); } } } // NB: do *not* apply the rescale function return plane; } } // -- DICOM Helper Classes -- private static class DICOMUtils { private static final int AE = 0x4145, AS = 0x4153, AT = 0x4154, CS = 0x4353; private static final int DA = 0x4441, DS = 0x4453, DT = 0x4454, FD = 0x4644; private static final int FL = 0x464C, IS = 0x4953, LO = 0x4C4F, LT = 0x4C54; private static final int PN = 0x504E, SH = 0x5348, SL = 0x534C, SS = 0x5353; private static final int ST = 0x5354, TM = 0x544D, UI = 0x5549, UL = 0x554C; private static final int US = 0x5553, UT = 0x5554, OB = 0x4F42, OW = 0x4F57; private static final int SQ = 0x5351, UN = 0x554E, QQ = 0x3F3F; private static final int IMPLICIT_VR = 0x2d2d; private static DICOMTag getNextTag(final RandomAccessInputStream stream) throws FormatException, IOException { return getNextTag(stream, false); } private static DICOMTag getNextTag(final RandomAccessInputStream stream, final boolean bigEndianTransferSyntax) throws FormatException, IOException { return getNextTag(stream, bigEndianTransferSyntax, false); } private static DICOMTag getNextTag(final RandomAccessInputStream stream, final boolean bigEndianTransferSyntax, final boolean isOddLocations) throws FormatException, IOException { final long fp = stream.getFilePointer(); int groupWord = stream.readShort() & 0xffff; final DICOMTag diTag = new DICOMTag(); boolean littleEndian = true; if (groupWord == 0x0800 && bigEndianTransferSyntax) { littleEndian = false; groupWord = 0x0008; stream.order(false); } else if (groupWord == 0xfeff || groupWord == 0xfffe) { stream.skipBytes(6); return DICOMUtils.getNextTag(stream, bigEndianTransferSyntax); } int elementWord = stream.readShort(); int tag = ((groupWord << 16) & 0xffff0000) | (elementWord & 0xffff); diTag.setElementLength(getLength(stream, diTag)); if (diTag.getElementLength() > stream.length()) { stream.seek(fp); littleEndian = !littleEndian; stream.order(littleEndian); groupWord = stream.readShort() & 0xffff; elementWord = stream.readShort(); tag = ((groupWord << 16) & 0xffff0000) | (elementWord & 0xffff); diTag.setElementLength(getLength(stream, diTag)); if (diTag.getElementLength() > stream.length()) { throw new FormatException("Invalid tag length " + diTag .getElementLength()); } diTag.setTagValue(tag); return diTag; } if (diTag.getElementLength() < 0 && groupWord == 0x7fe0) { stream.skipBytes(12); diTag.setElementLength(stream.readInt()); if (diTag.getElementLength() < 0) diTag.setElementLength(stream .readInt()); } if (diTag.getElementLength() == 0 && (groupWord == 0x7fe0 || tag == 0x291014)) { diTag.setElementLength(getLength(stream, diTag)); } else if (diTag.getElementLength() == 0) { stream.seek(stream.getFilePointer() - 4); final String v = stream.readString(2); if (v.equals("UT")) { stream.skipBytes(2); diTag.setElementLength(stream.readInt()); } else stream.skipBytes(2); } // HACK - needed to read some GE files // The element length must be even! if (!isOddLocations && (diTag.getElementLength() % 2) == 1) diTag .incrementElementLength(); // "Undefined" element length. // This is a sort of bracket that encloses a sequence of elements. if (diTag.getElementLength() == -1) { diTag.setElementLength(0); diTag.setInSequence(true); } diTag.setTagValue(tag); diTag.setLittleEndian(littleEndian); return diTag; } private static int getLength(final RandomAccessInputStream stream, final DICOMTag tag) throws IOException { final byte[] b = new byte[4]; stream.read(b); // We cannot know whether the VR is implicit or explicit // without the full DICOM Data Dictionary for public and // private groups. // We will assume the VR is explicit if the two bytes // match the known codes. It is possible that these two // bytes are part of a 32-bit length for an implicit VR. final int vr = ((b[0] & 0xff) << 8) | (b[1] & 0xff); tag.setVR(vr); switch (vr) { case OB: case OW: case SQ: case UN: // Explicit VR with 32-bit length if other two bytes are zero if ((b[2] == 0) || (b[3] == 0)) { return stream.readInt(); } tag.setVR(IMPLICIT_VR); return DataTools.bytesToInt(b, stream.isLittleEndian()); case AE: case AS: case AT: case CS: case DA: case DS: case DT: case FD: case FL: case IS: case LO: case LT: case PN: case SH: case SL: case SS: case ST: case TM: case UI: case UL: case US: case UT: case QQ: // Explicit VR with 16-bit length if (tag.get() == 0x00283006) { return DataTools.bytesToInt(b, 2, 2, stream.isLittleEndian()); } int n1 = DataTools.bytesToShort(b, 2, 2, stream.isLittleEndian()); int n2 = DataTools.bytesToShort(b, 2, 2, !stream.isLittleEndian()); n1 &= 0xffff; n2 &= 0xffff; if (n1 < 0 || n1 + stream.getFilePointer() > stream.length()) return n2; if (n2 < 0 || n2 + stream.getFilePointer() > stream.length()) return n1; return n1; case 0xffff: tag.setVR(IMPLICIT_VR); return 8; default: tag.setVR(IMPLICIT_VR); int len = DataTools.bytesToInt(b, stream.isLittleEndian()); if (len + stream.getFilePointer() > stream.length() || len < 0) { len = DataTools.bytesToInt(b, 2, 2, stream.isLittleEndian()); len &= 0xffff; } return len; } } } public static class DICOMTag { private int elementLength = 0; private int tagValue; private int vr = 0; private boolean inSequence = false; private int location = 0; private boolean littleEndian; public int getLocation() { return location; } public void setLocation(final int location) { this.location = location; } public void addLocation(final int offset) { location += offset; } public int getVR() { return vr; } public void setVR(final int vr) { this.vr = vr; } public int getElementLength() { return elementLength; } public void setElementLength(final int elementLength) { this.elementLength = elementLength; } public void incrementElementLength() { elementLength++; } public int get() { return tagValue; } public void setTagValue(final int tagValue) { this.tagValue = tagValue; } public boolean isInSequence() { return inSequence; } public void setInSequence(final boolean inSequence) { this.inSequence = inSequence; } public boolean isLittleEndian() { return littleEndian; } public void setLittleEndian(final boolean littleEndian) { this.littleEndian = littleEndian; } } }
package jk_5.nailed.api.world; import java.util.Collection; import jk_5.nailed.api.gamerule.EditableGameRules; import jk_5.nailed.api.map.Map; import jk_5.nailed.api.mappack.metadata.MappackWorld; import jk_5.nailed.api.player.Player; /** * No description given * * @author jk-5 */ public interface World { /** * Get the dimensionid of this world. This is the id the world is registered to * * @return dimensionid of this world */ int getDimensionId(); /** * Get the unique name of the map. * * @return the worlds name */ String getName(); /** * Get the players in the map. * * @return the player list */ Collection<Player> getPlayers(); /** * What kind of dimension is this world? * -1 for nether * 0 for overworld * 1 for end * * Defaults to 0 (overworld) * * @return the world type */ Dimension getDimension(); void setMap(Map map); Map getMap(); MappackWorld getConfig(); EditableGameRules getGamerules(); //TODO: rename this to getGameRules then mixins support multiple methods with the same name void onPlayerJoined(Player player); void onPlayerLeft(Player player); int getTime(); void setTime(int time); WeatherType getWeather(); void setWeather(WeatherType weather); Difficulty getDifficultyValue(); //TODO: rename this to getDifficulty when mixins support multiple methods with the same name void setDifficulty(Difficulty difficulty); }
package logicaAccesoADatos; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import logicaDeNegocios.Curso; public class conexion { private static final String SQL_SERIALIZE_OBJECTUsuario = "INSERT INTO usuario(name, object_value) VALUES (?, ?)"; private static final String SQL_DESERIALIZE_OBJECTUsuario = "SELECT object_value FROM usuario WHERE name = ?"; private static final String SQL_SERIALIZE_OBJECTCurso = "INSERT INTO curso(name, object_value) VALUES (?, ?)"; private static final String SQL_DESERIALIZE_OBJECTCurso = "SELECT object_value FROM curso WHERE name = ?"; private static final String SQL_DELETE_OBJECTCursos = "DELETE FROM curso WHERE name=?"; private static final String SQL_DESERIALIZE_OBJECTCursos = "SELECT name FROM curso"; private static final String SQL_CLOSE_CONNECTION = "select concat('KILL ',id,';') from information_schema.processlist where user='b63d126d987374';"; public Connection conexionDB() throws ClassNotFoundException, SQLException { Connection connection = null; String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://us-cdbr-iron-east-03.cleardb.net/ad_df5e3357b4ef02b"; String username = "b63d126d987374"; String password = "5dc317b4"; Class.forName(driver); connection = DriverManager.getConnection(url, username, password); return connection; } public ArrayList<String> obtenerIdCursos(Connection connection) { ArrayList<String> cursosId = new ArrayList<String>(); Statement st; try { st = connection.createStatement(); ResultSet rs = st.executeQuery(SQL_DESERIALIZE_OBJECTCursos); while (rs.next()) { String name = rs.getString("name"); System.out.println(name); cursosId.add(name); } rs.close(); connection.close(); return cursosId; } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return cursosId; } public void actualizarCurso(Connection connection,Curso curso){ eliminarCurso(connection,curso.getId()); try { serializeJavaObjectToDBCurso(connection,curso.getId(),curso); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void eliminarCurso(Connection connection,String curso) { cerrarConexiones(connection); try { PreparedStatement ejecucionQuery = connection.prepareStatement(SQL_DELETE_OBJECTCursos); ejecucionQuery.setString(1, curso); ejecucionQuery.execute(); ejecucionQuery.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @SuppressWarnings("unused") public static void serializeJavaObjectToDB(Connection connection, String id, Object objetoGuardar) throws SQLException { cerrarConexiones(connection); // just setting the class name PreparedStatement ejecucionQuery = connection.prepareStatement(SQL_SERIALIZE_OBJECTUsuario); // just setting the class name ejecucionQuery.setString(1, id); ejecucionQuery.setObject(2, objetoGuardar); ejecucionQuery.executeUpdate(); ResultSet resultadoQuery = ejecucionQuery.getGeneratedKeys(); int serialized_id = -1; if (resultadoQuery.next()) { serialized_id = resultadoQuery.getInt(1); } resultadoQuery.close(); ejecucionQuery.close(); connection.close(); } /** * To de-serialize a java object from database * * @throws SQLException * @throws IOException * @throws ClassNotFoundException */ public static Object deSerializeJavaObjectFromDB(Connection connection, String serialized_id) { try { cerrarConexiones(connection); PreparedStatement ejecucionQuery = connection.prepareStatement(SQL_DESERIALIZE_OBJECTUsuario); ejecucionQuery.setString(1, serialized_id); ResultSet resultadoQuery = ejecucionQuery.executeQuery(); resultadoQuery.next(); byte[] buf = resultadoQuery.getBytes(1); ObjectInputStream objectIn = null; if (buf != null) objectIn = new ObjectInputStream(new ByteArrayInputStream(buf)); Object deSerializedObject = objectIn.readObject(); resultadoQuery.close(); ejecucionQuery.close(); connection.close(); cerrarConexiones(connection); return deSerializedObject; } catch (Exception e) { // TODO Auto-generated catch block return null; } } // CURSOS @SuppressWarnings("unused") public static void serializeJavaObjectToDBCurso(Connection connection, String id, Object objetoGuardar) throws SQLException { // just setting the class name PreparedStatement ejecucionQuery = connection.prepareStatement(SQL_SERIALIZE_OBJECTCurso); cerrarConexiones(connection); // just setting the class name ejecucionQuery.setString(1, id); ejecucionQuery.setObject(2, objetoGuardar); ejecucionQuery.executeUpdate(); ResultSet resultadoQuery = ejecucionQuery.getGeneratedKeys(); int serialized_id = -1; if (resultadoQuery.next()) { serialized_id = resultadoQuery.getInt(1); } resultadoQuery.close(); ejecucionQuery.close(); connection.close(); } /** * To de-serialize a java object from database * * @throws SQLException * @throws IOException * @throws ClassNotFoundException */ public static Object deSerializeJavaObjectFromDBCurso(Connection connection, String serialized_id) { try { cerrarConexiones(connection); PreparedStatement ejecucionQuery = connection.prepareStatement(SQL_DESERIALIZE_OBJECTCurso); ejecucionQuery.setString(1, serialized_id); ResultSet resultadoQuery = ejecucionQuery.executeQuery(); resultadoQuery.next(); byte[] buf = resultadoQuery.getBytes(1); ObjectInputStream objectIn = null; if (buf != null) objectIn = new ObjectInputStream(new ByteArrayInputStream(buf)); Object deSerializedObject = objectIn.readObject(); resultadoQuery.close(); ejecucionQuery.close(); connection.close(); return deSerializedObject; } catch (Exception e) { // TODO Auto-generated catch block return null; } } public static void cerrarConexiones(Connection connection) { PreparedStatement ejecucionQuery; try { ejecucionQuery = connection.prepareStatement(SQL_CLOSE_CONNECTION); ejecucionQuery.executeQuery(); ejecucionQuery.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package mcjty.gui.widgets; import mcjty.gui.Window; import mcjty.gui.events.TextEvent; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import org.lwjgl.input.Keyboard; import java.util.ArrayList; import java.util.List; public class TextField extends AbstractWidget<TextField> { private String text = ""; private int cursor = 0; private int startOffset = 0; // Start character where we are displaying private List<TextEvent> textEvents = null; public TextField(Minecraft mc, Gui gui) { super(mc, gui); } public String getText() { return text; } public TextField setText(String text) { this.text = text; cursor = text.length(); if (startOffset >= cursor) { startOffset = cursor-1; if (startOffset < 0) { startOffset = 0; } } return this; } @Override public Widget mouseClick(Window window, int x, int y, int button) { if (isEnabledAndVisible()) { window.setTextFocus(this); if (button == 1) { setText(""); } return this; } return null; } @Override public boolean keyTyped(Window window, char typedChar, int keyCode) { boolean rc = super.keyTyped(window, typedChar, keyCode); if (rc) { return true; } if (isEnabledAndVisible()) { if (keyCode == Keyboard.KEY_RETURN || keyCode == Keyboard.KEY_ESCAPE) { // window.setTextFocus(null); return false; } else if (keyCode == Keyboard.KEY_BACK) { if (!text.isEmpty() && cursor > 0) { text = text.substring(0, cursor-1) + text.substring(cursor); cursor fireTextEvents(text); } } else if (keyCode == Keyboard.KEY_DELETE) { if (cursor < text.length()) { text = text.substring(0, cursor) + text.substring(cursor+1); fireTextEvents(text); } } else if (keyCode == Keyboard.KEY_HOME) { cursor = 0; } else if (keyCode == Keyboard.KEY_END) { cursor = text.length(); } else if (keyCode == Keyboard.KEY_LEFT) { if (cursor > 0) { cursor } } else if (keyCode == Keyboard.KEY_RIGHT) { if (cursor < text.length()) { cursor++; } } else if (new Integer(typedChar).intValue() == 0) { // Do nothing } else { text = text.substring(0, cursor) + typedChar + text.substring(cursor); cursor++; fireTextEvents(text); } return true; } return false; } private int calculateVerticalOffset() { int h = mc.fontRenderer.FONT_HEIGHT; return (bounds.height - h)/2; } private void ensureVisible() { if (cursor < startOffset) { startOffset = cursor; } else { int w = mc.fontRenderer.getStringWidth(text.substring(startOffset, cursor)); while (w > bounds.width-12) { startOffset++; w = mc.fontRenderer.getStringWidth(text.substring(startOffset, cursor)); } } } @Override public void draw(Window window, int x, int y) { super.draw(window, x, y); int xx = x + bounds.x; int yy = y + bounds.y; ensureVisible(); int col = 0xff000000; if (window.getTextFocus() == this) { col = 0xff444444; } Gui.drawRect(xx, yy, xx + bounds.width - 1, yy + bounds.height - 1, col); mc.fontRenderer.drawString(mc.fontRenderer.trimStringToWidth(text.substring(startOffset), bounds.width-10), x + 5 + bounds.x, y + calculateVerticalOffset() + bounds.y, 0xffffffff); if (window.getTextFocus() == this) { int w = mc.fontRenderer.getStringWidth(text.substring(startOffset, cursor)); Gui.drawRect(xx+5+w, yy, xx+5+w+2, yy + bounds.height - 1, 0xffffffff); } } public TextField addTextEvent(TextEvent event) { if (textEvents == null) { textEvents = new ArrayList<TextEvent>(); } textEvents.add(event); return this; } public void removeTextEvent(TextEvent event) { if (textEvents != null) { textEvents.remove(event); } } private void fireTextEvents(String newText) { if (textEvents != null) { for (TextEvent event : textEvents) { event.textChanged(this, newText); } } } }
package model.generative; import model.time_insensitive.Count; import model.time_insensitive.MusicEvent; import model.time_insensitive.Note; import java.io.Serializable; import java.util.*; /** * A conceptualization of rhythm as gradual, equal * subdivisions of some concrete amount of time. * RhythmTrees operate like many other data structures * save that their only "real" storage is in their * leaf nodes. This */ public class RhythmTree implements Serializable, Cloneable, Iterable<MusicEvent>, Collection<MusicEvent>, NavigableSet<MusicEvent>, Set<MusicEvent>, SortedSet<MusicEvent> { private class Node { Count timing; Count length; Node parent; List<Node> children; } private Node root = null; /** * The RhythmTree default constructor */ public RhythmTree() { } /** * The RhythmTree copy constructor * @param other the RhythmTree to copy */ public RhythmTree(RhythmTree other) { } /* HERE BE OVERRIDE METHODS */ /* ABANDON ALL HOPE YE WHO ENTER */ @Override public Iterator<MusicEvent> iterator() { Iterator<MusicEvent> it = new Iterator<MusicEvent>() { private Node node = root; @Override public boolean hasNext() { Node nextNode = null; int parentsChildNumber = -1; nextNode= node.parent; for(int i = 0; i < nextNode.children.size(); i++) { if(nextNode.children.get(i).equals(node)) { parentsChildNumber = i; } } if(parentsChildNumber < nextNode.children.size()) { } return currentIndex < currentSize && arrayList[currentIndex] != null; } @Override public MusicEvent next() { return arrayList[currentIndex++]; } @Override public void remove() { throw new UnsupportedOperationException(); } }; return it; } @Override public Note lower(Note note) { return null; } @Override public Note floor(Note note) { return null; } @Override public Note ceiling(Note note) { return null; } @Override public Note higher(Note note) { return null; } @Override public Note pollFirst() { return null; } @Override public Note pollLast() { return null; } @Override public NavigableSet<Note> descendingSet() { return null; } @Override public Iterator<Note> descendingIterator() { return null; } @Override public NavigableSet<Note> subSet(Note fromElement, boolean fromInclusive, Note toElement, boolean toInclusive) { return null; } @Override public NavigableSet<Note> headSet(Note toElement, boolean inclusive) { return null; } @Override public NavigableSet<Note> tailSet(Note fromElement, boolean inclusive) { return null; } @Override public Comparator<? super Note> comparator() { return null; } @Override public SortedSet<Note> subSet(Note fromElement, Note toElement) { return null; } @Override public SortedSet<Note> headSet(Note toElement) { return null; } @Override public SortedSet<Note> tailSet(Note fromElement) { return null; } @Override public Note first() { return null; } @Override public Note last() { return null; } @Override public int size() { return 0; } @Override public boolean isEmpty() { return false; } @Override public boolean contains(Object o) { return false; } @Override public Object[] toArray() { return new Object[0]; } @Override public <T> T[] toArray(T[] a) { return null; } @Override public boolean add(Note note) { return false; } @Override public boolean remove(Object o) { return false; } @Override public boolean containsAll(Collection<?> c) { return false; } @Override public boolean addAll(Collection<? extends Note> c) { return false; } @Override public boolean removeAll(Collection<?> c) { return false; } @Override public boolean retainAll(Collection<?> c) { return false; } @Override public void clear() { } }
package org.digidoc4j; import static java.util.Arrays.asList; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.List; import java.util.concurrent.ExecutorService; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.digidoc4j.exceptions.ConfigurationException; import org.digidoc4j.exceptions.DigiDoc4JException; import org.digidoc4j.impl.ConfigurationSingeltonHolder; import org.digidoc4j.impl.asic.tsl.TslManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; import eu.europa.esig.dss.client.http.Protocol; public class Configuration implements Serializable { private static final Logger logger = LoggerFactory.getLogger(Configuration.class); private transient ExecutorService threadExecutor; private final Mode mode; private TslManager tslManager; private Hashtable<String, String> jDigiDocConfiguration = new Hashtable<>(); private ConfigurationRegistry registry = new ConfigurationRegistry(); private List<String> trustedTerritories = new ArrayList<>(); private ArrayList<String> inputSourceParseErrors = new ArrayList<>(); private LinkedHashMap configurationFromFile; private String configurationInputSourceName; /** * Application mode */ public enum Mode { TEST, PROD } /** * Getting the default Configuration object. <br/> * <p> * The default configuration object is a singelton, meaning that all the containers will use the same registry * object. It is a good idea to use only a single configuration object for all the containers so the operation times * would be faster. * * @return default configuration. */ public static Configuration getInstance() { return ConfigurationSingeltonHolder.getInstance(); } /** * Create new configuration */ public Configuration() { this(Mode.TEST.name().equalsIgnoreCase(System.getProperty("digidoc4j.mode")) ? Mode.TEST : Mode.PROD); } /** * Create new configuration for application mode specified * * @param mode Application mode */ public Configuration(Mode mode) { if (logger.isInfoEnabled() && !logger.isDebugEnabled()) { logger.info("DigiDoc4J will be executed in <{}> mode", mode); } logger.debug(" this.mode = mode; this.loadConfiguration("digidoc4j.yaml"); this.initDefaultValues(); logger.debug(" if (!logger.isDebugEnabled()) { logger.info("Configuration loaded ..."); } } /** * Are requirements met for signing OCSP certificate? * * @return value indicating if requirements are met */ public boolean isOCSPSigningConfigurationAvailable() { boolean available = StringUtils.isNotBlank(this.getOCSPAccessCertificateFileName()) && this.getOCSPAccessCertificatePassword().length != 0; logger.debug("Is OCSP signing configuration available? {}", available); return available; } /** * Get OCSP access certificate filename * * @return filename for the OCSP access certificate */ public String getOCSPAccessCertificateFileName() { String ocspAccessCertificateFile = this.getConfigurationParameter(ConfigurationParameter.OcspAccessCertificateFile); return ocspAccessCertificateFile == null ? "" : ocspAccessCertificateFile; } /** * Get OSCP access certificate password * * @return password */ public char[] getOCSPAccessCertificatePassword() { char[] result = {}; String password = this.getConfigurationParameter(ConfigurationParameter.OcspAccessCertificatePassword); if (StringUtils.isNotEmpty(password)) { result = password.toCharArray(); } return result; } /** * Get OSCP access certificate password As String * * @return password */ public String getOCSPAccessCertificatePasswordAsString() { return this.getConfigurationParameter(ConfigurationParameter.OcspAccessCertificatePassword); } /** * Set OCSP access certificate filename * * @param fileName filename for the OCSP access certficate */ public void setOCSPAccessCertificateFileName(String fileName) { this.setConfigurationParameter(ConfigurationParameter.OcspAccessCertificateFile, fileName); this.setJDigiDocParameter(Constant.JDigiDoc.OCSP_PKCS_12_CONTAINER, fileName); } /** * Set OCSP access certificate password * * @param password password to set */ public void setOCSPAccessCertificatePassword(char[] password) { String value = String.valueOf(password); this.setConfigurationParameter(ConfigurationParameter.OcspAccessCertificatePassword, value); this.setJDigiDocParameter(Constant.JDigiDoc.OCSP_PKCS_12_PASSWORD, value); } /** * Set flag if OCSP requests should be signed * * @param shouldSignOcspRequests True if should sign, False otherwise */ public void setSignOCSPRequests(boolean shouldSignOcspRequests) { String value = String.valueOf(shouldSignOcspRequests); this.setConfigurationParameter(ConfigurationParameter.SignOcspRequests, value); this.setJDigiDocParameter(Constant.JDigiDoc.OCSP_SIGN_REQUESTS, value); } /** * Add configuration settings from a stream. After loading closes stream. * * @param stream Input stream * @return configuration hashtable */ public Hashtable<String, String> loadConfiguration(InputStream stream) { this.configurationInputSourceName = "stream"; return this.loadConfigurationSettings(stream); } /** * Add configuration settings from a file * * @param file File name * @return configuration hashtable */ public Hashtable<String, String> loadConfiguration(String file) { return this.loadConfiguration(file, true); } /** * Add configuration settings from a file * * @param file File name * @param isReloadFromYaml True if this is reloading call * @return configuration hashtable */ public Hashtable<String, String> loadConfiguration(String file, boolean isReloadFromYaml) { if (!isReloadFromYaml) { logger.info("Should not reload conf from yaml when open container"); return jDigiDocConfiguration; } logger.info("Loading configuration from file " + file); configurationInputSourceName = file; InputStream resourceAsStream = null; try { resourceAsStream = new FileInputStream(file); } catch (FileNotFoundException e) { logger.info("Configuration file " + file + " not found. Trying to search from jar file."); } if (resourceAsStream == null) { resourceAsStream = getResourceAsStream(file); } return loadConfigurationSettings(resourceAsStream); } /** * Returns configuration needed for JDigiDoc library. * * @return configuration values. */ public Hashtable<String, String> getJDigiDocConfiguration() { this.loadCertificateAuthoritiesAndCertificates(); this.reportFileParseErrors(); return jDigiDocConfiguration; } /** * Enables big files support. Sets limit in MB when handling files are creating temporary file for streaming in * container creation and adding data files. * <p/> * Used by DigiDoc4J and by JDigiDoc. * * @param maxFileSizeCachedInMB Maximum size in MB. * @deprecated obnoxious naming. Use {@link Configuration#setMaxFileSizeCachedInMemoryInMB(long)} instead. */ @Deprecated public void enableBigFilesSupport(long maxFileSizeCachedInMB) { logger.debug("Set maximum datafile cached to: " + maxFileSizeCachedInMB); String value = Long.toString(maxFileSizeCachedInMB); if (isValidIntegerParameter("DIGIDOC_MAX_DATAFILE_CACHED", value)) { jDigiDocConfiguration.put("DIGIDOC_MAX_DATAFILE_CACHED", value); } } /** * Sets limit in MB when handling files are creating temporary file for streaming in * container creation and adding data files. * <p/> * Used by DigiDoc4J and by JDigiDoc. * * @param maxFileSizeCachedInMB maximum data file size in MB stored in memory. */ public void setMaxFileSizeCachedInMemoryInMB(long maxFileSizeCachedInMB) { enableBigFilesSupport(maxFileSizeCachedInMB); } /** * @return is big file support enabled * @deprecated obnoxious naming. Use {@link Configuration#storeDataFilesOnlyInMemory()} instead. */ @Deprecated public boolean isBigFilesSupportEnabled() { return getMaxDataFileCachedInMB() >= 0; } /** * If all the data files should be stored in memory. Default is true (data files are temporarily stored only in * memory). * * @return true if everything is stored in memory, and false if data is temporarily stored on disk. */ public boolean storeDataFilesOnlyInMemory() { long maxDataFileCachedInMB = getMaxDataFileCachedInMB(); return maxDataFileCachedInMB == -1 || maxDataFileCachedInMB == Long.MAX_VALUE; } /** * Returns configuration item must be OCSP request signed. Reads it from registry parameter SIGN_OCSP_REQUESTS. * Default value is false for {@link Configuration.Mode#PROD} and false for {@link Configuration.Mode#TEST} * * @return must be OCSP request signed */ public boolean hasToBeOCSPRequestSigned() { String signOcspRequests = getConfigurationParameter(ConfigurationParameter.SignOcspRequests); return StringUtils.equalsIgnoreCase("true", signOcspRequests); } /** * Get the maximum size of data files to be cached. Used by DigiDoc4J and by JDigiDoc. * * @return Size in MB. if size < 0 no caching is used */ public long getMaxDataFileCachedInMB() { String maxDataFileCached = jDigiDocConfiguration.get("DIGIDOC_MAX_DATAFILE_CACHED"); logger.debug("Maximum datafile cached in MB: " + maxDataFileCached); if (maxDataFileCached == null) return Constant.CACHE_ALL_DATA_FILES; return Long.parseLong(maxDataFileCached); } /** * Get the maximum size of data files to be cached. Used by DigiDoc4J and by JDigiDoc. * * @return Size in MB. if size < 0 no caching is used */ public long getMaxDataFileCachedInBytes() { long maxDataFileCachedInMB = getMaxDataFileCachedInMB(); if (maxDataFileCachedInMB == Constant.CACHE_ALL_DATA_FILES) { return Constant.CACHE_ALL_DATA_FILES; } else { return (maxDataFileCachedInMB * Constant.ONE_MB_IN_BYTES); } } /** * Get TSL location. * * @return url */ public String getTslLocation() { String urlString = getConfigurationParameter(ConfigurationParameter.TslLocation); if (!Protocol.isFileUrl(urlString)) return urlString; try { String filePath = new URL(urlString).getPath(); if (!new File(filePath).exists()) { URL resource = getClass().getClassLoader().getResource(filePath); if (resource != null) urlString = resource.toString(); } } catch (MalformedURLException e) { logger.warn(e.getMessage()); } return urlString == null ? "" : urlString; } /** * Set the TSL certificate source. * * @param certificateSource TSL certificate source * When certificateSource equals null then getTSL() will load the TSL according to the TSL * location specified . */ public void setTSL(TSLCertificateSource certificateSource) { tslManager.setTsl(certificateSource); } /** * Loads TSL certificates * If configuration mode is TEST then TSL signature is not checked. * * @return TSL source */ public TSLCertificateSource getTSL() { return tslManager.getTsl(); } /** * Flags that TSL signature should be validated. * * @return True if TSL signature should be validated, False otherwise. */ public boolean shouldValidateTslSignature() { return mode != Mode.TEST; } public void setTslLocation(String tslLocation) { this.setConfigurationParameter(ConfigurationParameter.TslLocation, tslLocation); this.tslManager.setTsl(null); } /** * Get the TSP Source * * @return TSP Source */ public String getTspSource() { return this.getConfigurationParameter(ConfigurationParameter.TspSource); } /** * Set HTTP connection timeout * * @param connectionTimeout connection timeout in milliseconds */ public void setConnectionTimeout(int connectionTimeout) { this.setConfigurationParameter(ConfigurationParameter.ConnectionTimeoutInMillis, String.valueOf(connectionTimeout)); } /** * Set HTTP socket timeout * * @param socketTimeoutMilliseconds socket timeout in milliseconds */ public void setSocketTimeout(int socketTimeoutMilliseconds) { this.setConfigurationParameter(ConfigurationParameter.SocketTimeoutInMillis, String.valueOf(socketTimeoutMilliseconds)); } /** * Get HTTP connection timeout * * @return connection timeout in milliseconds */ public int getConnectionTimeout() { return this.getConfigurationParameter(ConfigurationParameter.ConnectionTimeoutInMillis, Integer.class); } /** * Get HTTP socket timeout * * @return socket timeout in milliseconds */ public int getSocketTimeout() { return this.getConfigurationParameter(ConfigurationParameter.SocketTimeoutInMillis, Integer.class); } /** * Set the TSP Source * * @param tspSource TSPSource to be used */ public void setTspSource(String tspSource) { this.setConfigurationParameter(ConfigurationParameter.TspSource, tspSource); } /** * Get the OCSP Source * * @return OCSP Source */ public String getOcspSource() { return this.getConfigurationParameter(ConfigurationParameter.OcspSource); } /** * Set the KeyStore Location that holds potential TSL Signing certificates * * @param tslKeyStoreLocation KeyStore location to use */ public void setTslKeyStoreLocation(String tslKeyStoreLocation) { this.setConfigurationParameter(ConfigurationParameter.TslKeyStoreLocation, tslKeyStoreLocation); } /** * Get the Location to Keystore that holds potential TSL Signing certificates * * @return KeyStore Location */ public String getTslKeyStoreLocation() { return this.getConfigurationParameter(ConfigurationParameter.TslKeyStoreLocation); } /** * Set the password for Keystore that holds potential TSL Signing certificates * * @param tslKeyStorePassword Keystore password */ public void setTslKeyStorePassword(String tslKeyStorePassword) { this.setConfigurationParameter(ConfigurationParameter.TslKeyStorePassword, tslKeyStorePassword); } /** * Get the password for Keystore that holds potential TSL Signing certificates * * @return Tsl Keystore password */ public String getTslKeyStorePassword() { return getConfigurationParameter(ConfigurationParameter.TslKeyStorePassword); } /** * Sets the expiration time for TSL cache in milliseconds. * If more time has passed from the cache's creation time time, then a fresh TSL is downloaded and cached, * otherwise a cached copy is used. * * @param cacheExpirationTimeInMilliseconds cache expiration time in milliseconds */ public void setTslCacheExpirationTime(long cacheExpirationTimeInMilliseconds) { this.setConfigurationParameter(ConfigurationParameter.TslCacheExpirationTimeInMillis, String.valueOf(cacheExpirationTimeInMilliseconds)); } /** * Returns TSL cache expiration time in milliseconds. * * @return TSL cache expiration time in milliseconds. */ public long getTslCacheExpirationTime() { return this.getConfigurationParameter(ConfigurationParameter.TslCacheExpirationTimeInMillis, Long.class); } /** * Returns allowed delay between timestamp and OCSP response in minutes. * * @return Allowed delay between timestamp and OCSP response in minutes. */ public Integer getAllowedTimestampAndOCSPResponseDeltaInMinutes() { return this.getConfigurationParameter(ConfigurationParameter.AllowedTimestampAndOCSPResponseDeltaInMinutes, Integer.class); } /** * Set allowed delay between timestamp and OCSP response in minutes. * * @param timeInMinutes Allowed delay between timestamp and OCSP response in minutes */ public void setAllowedTimestampAndOCSPResponseDeltaInMinutes(int timeInMinutes) { this.setConfigurationParameter(ConfigurationParameter.AllowedTimestampAndOCSPResponseDeltaInMinutes, String.valueOf(timeInMinutes)); } /** * Set the OCSP source * * @param ocspSource OCSP Source to be used */ public void setOcspSource(String ocspSource) { this.setConfigurationParameter(ConfigurationParameter.OcspSource, ocspSource); } /** * Get the validation policy * * @return Validation policy */ public String getValidationPolicy() { return this.getConfigurationParameter(ConfigurationParameter.ValidationPolicy); } /** * Set the validation policy * * @param validationPolicy Policy to be used */ public void setValidationPolicy(String validationPolicy) { this.setConfigurationParameter(ConfigurationParameter.ValidationPolicy, validationPolicy); } /** * Revocation and timestamp delta in minutes. * * @return timestamp delta in minutes. */ public int getRevocationAndTimestampDeltaInMinutes() { return this.getConfigurationParameter(ConfigurationParameter.RevocationAndTimestampDeltaInMinutes, Integer.class); } /** * Set Revocation and timestamp delta in minutes. * * @param timeInMinutes delta in minutes. */ public void setRevocationAndTimestampDeltaInMinutes(int timeInMinutes) { this.setConfigurationParameter(ConfigurationParameter.RevocationAndTimestampDeltaInMinutes, String.valueOf(timeInMinutes)); } /** * Signature profile. * * @return SignatureProfile. */ public SignatureProfile getSignatureProfile() { return SignatureProfile.findByProfile(this.getConfigurationParameter(ConfigurationParameter.SignatureProfile)); } /** * Signature digest algorithm. * * @return DigestAlgorithm. */ public DigestAlgorithm getSignatureDigestAlgorithm() { return DigestAlgorithm.findByAlgorithm(getConfigurationParameter(ConfigurationParameter.SignatureDigestAlgorithm)); } public String getHttpsProxyHost() { return this.getConfigurationParameter(ConfigurationParameter.HttpsProxyHost); } /** * Set HTTPS network proxy host. * * @param httpsProxyHost https proxy host. */ public void setHttpsProxyHost(String httpsProxyHost) { this.setConfigurationParameter(ConfigurationParameter.HttpsProxyHost, httpsProxyHost); } public Integer getHttpsProxyPort() { return this.getConfigurationParameter(ConfigurationParameter.HttpsProxyPort, Integer.class); } /** * Set HTTPS network proxy port. * * @param httpsProxyPort https proxy port. */ public void setHttpsProxyPort(int httpsProxyPort) { this.setConfigurationParameter(ConfigurationParameter.HttpsProxyPort, String.valueOf(httpsProxyPort)); } /** * Get http proxy host. * * @return http proxy host. */ public String getHttpProxyHost() { return this.getConfigurationParameter(ConfigurationParameter.HttpProxyHost); } /** * Set HTTP network proxy host. * * @param httpProxyHost http proxy host. */ public void setHttpProxyHost(String httpProxyHost) { this.setConfigurationParameter(ConfigurationParameter.HttpProxyHost, httpProxyHost); } /** * Get http proxy port. * * @return http proxy port. */ public Integer getHttpProxyPort() { return this.getConfigurationParameter(ConfigurationParameter.HttpProxyPort, Integer.class); } /** * Set HTTP network proxy port. * * @param httpProxyPort Port number. */ public void setHttpProxyPort(int httpProxyPort) { this.setConfigurationParameter(ConfigurationParameter.HttpProxyPort, String.valueOf(httpProxyPort)); } /** * Set HTTP network proxy user name. * * @param httpProxyUser username. */ public void setHttpProxyUser(String httpProxyUser) { this.setConfigurationParameter(ConfigurationParameter.HttpProxyUser, httpProxyUser); } /** * Get http proxy user. * * @return http proxy user. */ public String getHttpProxyUser() { return this.getConfigurationParameter(ConfigurationParameter.HttpProxyUser); } /** * Set HTTP network proxy password. * * @param httpProxyPassword password. */ public void setHttpProxyPassword(String httpProxyPassword) { this.setConfigurationParameter(ConfigurationParameter.HttpProxyPassword, httpProxyPassword); } /** * Get http proxy password. * * @return http proxy password. */ public String getHttpProxyPassword() { return this.getConfigurationParameter(ConfigurationParameter.HttpProxyPassword); } /** * Is network proxy enabled? * * @return True if network proxy is enabled, otherwise False. */ public boolean isNetworkProxyEnabled() { return this.getConfigurationParameter(ConfigurationParameter.HttpProxyPort, Integer.class) != null && StringUtils.isNotBlank(this.getConfigurationParameter(ConfigurationParameter.HttpProxyHost)) || this.getConfigurationParameter(ConfigurationParameter.HttpsProxyPort, Integer.class) != null && StringUtils.isNotBlank(this.getConfigurationParameter(ConfigurationParameter.HttpsProxyHost)); } public boolean isProxyOfType(Protocol protocol) { switch (protocol) { case HTTP: return this.getConfigurationParameter(ConfigurationParameter.HttpProxyPort, Integer.class) != null && StringUtils.isNotBlank(this.getConfigurationParameter(ConfigurationParameter.HttpProxyHost)); case HTTPS: return this.getConfigurationParameter(ConfigurationParameter.HttpsProxyPort, Integer.class) != null && StringUtils.isNotBlank(this.getConfigurationParameter(ConfigurationParameter.HttpsProxyHost)); default: throw new RuntimeException(String.format("Protocol <%s> not supported", protocol)); } } /** * Is ssl configuration enabled? * * @return True if SSL configuration is enabled, otherwise False. */ public boolean isSslConfigurationEnabled() { return StringUtils.isNotBlank(this.getConfigurationParameter(ConfigurationParameter.SslKeystorePath)); } /** * Set SSL KeyStore path. * * @param sslKeystorePath path to a file */ public void setSslKeystorePath(String sslKeystorePath) { this.setConfigurationParameter(ConfigurationParameter.SslKeystorePath, sslKeystorePath); } /** * Get SSL KeyStore path. * * @return path to a file */ public String getSslKeystorePath() { return this.getConfigurationParameter(ConfigurationParameter.SslKeystorePath); } /** * Set SSL KeyStore type. Default is "jks". * * @param sslKeystoreType type. */ public void setSslKeystoreType(String sslKeystoreType) { this.setConfigurationParameter(ConfigurationParameter.SslKeystoreType, sslKeystoreType); } /** * Get SSL KeyStore type. * * @return type. */ public String getSslKeystoreType() { return this.getConfigurationParameter(ConfigurationParameter.SslKeystoreType); } /** * Set SSL KeyStore password. Default is an empty string. * * @param sslKeystorePassword password. */ public void setSslKeystorePassword(String sslKeystorePassword) { this.setConfigurationParameter(ConfigurationParameter.SslKeystorePassword, sslKeystorePassword); } /** * Get Ssl keystore password. * * @return password. */ public String getSslKeystorePassword() { return this.getConfigurationParameter(ConfigurationParameter.SslKeystorePassword); } /** * Set SSL TrustStore path. * * @param sslTruststorePath path to a file. */ public void setSslTruststorePath(String sslTruststorePath) { this.setConfigurationParameter(ConfigurationParameter.SslTruststorePath, sslTruststorePath); } /** * Get SSL TrustStore path. * * @return path to a file. */ public String getSslTruststorePath() { return this.getConfigurationParameter(ConfigurationParameter.SslTruststorePath); } /** * Set SSL TrustStore type. Default is "jks". * * @param sslTruststoreType type. */ public void setSslTruststoreType(String sslTruststoreType) { this.setConfigurationParameter(ConfigurationParameter.SslTruststoreType, sslTruststoreType); } /** * Get SSL TrustStore type. * * @return type. */ public String getSslTruststoreType() { return this.getConfigurationParameter(ConfigurationParameter.SslTruststoreType); } /** * Set SSL TrustStore password. Default is an empty string. * * @param sslTruststorePassword password. */ public void setSslTruststorePassword(String sslTruststorePassword) { this.setConfigurationParameter(ConfigurationParameter.SslTruststorePassword, sslTruststorePassword); } /** * Get Ssl truststore password. * * @return password. */ public String getSslTruststorePassword() { return this.getConfigurationParameter(ConfigurationParameter.SslTruststorePassword); } /** * Set thread executor service. * * @param threadExecutor Thread executor service object. */ public void setThreadExecutor(ExecutorService threadExecutor) { this.threadExecutor = threadExecutor; } /** * Get thread executor. It can be mull. * * @return thread executor. */ public ExecutorService getThreadExecutor() { return threadExecutor; } /** * Set countries and territories (2 letter country codes) whom to trust and accept certificates. * <p/> * It is possible accept signatures (and certificates) only from particular countries by filtering * trusted territories. Only the TSL (and certificates) from those countries are then downloaded and * others are skipped. * <p/> * For example, it is possible to trust signatures only from these three countries: Estonia, Latvia and France, * and skip all other countries: "EE", "LV", "FR". * * @param trustedTerritories list of 2 letter country codes. */ public void setTrustedTerritories(String... trustedTerritories) { this.trustedTerritories = Arrays.asList(trustedTerritories); } /** * Get trusted territories. * * @return trusted territories list. */ public List<String> getTrustedTerritories() { return trustedTerritories; } /** * @return true when configuration is Configuration.Mode.TEST * @see Configuration.Mode#TEST */ public boolean isTest() { boolean isTest = Mode.TEST.equals(this.mode); logger.debug("Is test: " + isTest); return isTest; } /** * Clones configuration * * @return new configuration object */ public Configuration copy() { ObjectOutputStream oos = null; ObjectInputStream ois = null; Configuration copyConfiguration = null; // deep copy ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { oos = new ObjectOutputStream(bos); oos.writeObject(this); oos.flush(); ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); ois = new ObjectInputStream(bin); copyConfiguration = (Configuration) ois.readObject(); } catch (Exception e) { throw new DigiDoc4JException(e); } finally { IOUtils.closeQuietly(oos); IOUtils.closeQuietly(ois); IOUtils.closeQuietly(bos); } return copyConfiguration; } /* * RESTRICTED METHODS */ protected ConfigurationRegistry getRegistry() { return this.registry; } private void initDefaultValues() { logger.debug(" this.tslManager = new TslManager(this); this.setConfigurationParameter(ConfigurationParameter.ConnectionTimeoutInMillis, String.valueOf(Constant.ONE_SECOND_IN_MILLISECONDS)); this.setConfigurationParameter(ConfigurationParameter.SocketTimeoutInMillis, String.valueOf(Constant.ONE_SECOND_IN_MILLISECONDS)); this.setConfigurationParameter(ConfigurationParameter.TslKeyStorePassword, "digidoc4j-password"); this.setConfigurationParameter(ConfigurationParameter.RevocationAndTimestampDeltaInMinutes, String.valueOf(Constant.ONE_DAY_IN_MINUTES)); this.setConfigurationParameter(ConfigurationParameter.TslCacheExpirationTimeInMillis, String.valueOf(Constant.ONE_DAY_IN_MILLISECONDS)); this.setConfigurationParameter(ConfigurationParameter.AllowedTimestampAndOCSPResponseDeltaInMinutes, "15"); this.setConfigurationParameter(ConfigurationParameter.SignatureProfile, Constant.Default.SIGNATURE_PROFILE); this.setConfigurationParameter(ConfigurationParameter.SignatureDigestAlgorithm, Constant.Default.SIGNATURE_DIGEST_ALGORITHM); if (Mode.TEST.equals(this.mode)) { this.setConfigurationParameter(ConfigurationParameter.TspSource, Constant.Test.TSP_SOURCE); this.setConfigurationParameter(ConfigurationParameter.TslLocation, Constant.Test.TSL_LOCATION); this.setConfigurationParameter(ConfigurationParameter.TslKeyStoreLocation, Constant.Test.TSL_KEYSTORE_LOCATION); this.setConfigurationParameter(ConfigurationParameter.ValidationPolicy, Constant.Test.VALIDATION_POLICY); this.setConfigurationParameter(ConfigurationParameter.OcspSource, Constant.Test.OCSP_SOURCE); this.setConfigurationParameter(ConfigurationParameter.SignOcspRequests, "false"); this.setJDigiDocParameter("SIGN_OCSP_REQUESTS", "false"); } else { this.setConfigurationParameter(ConfigurationParameter.TspSource, Constant.Production.TSP_SOURCE); this.setConfigurationParameter(ConfigurationParameter.TslLocation, Constant.Production.TSL_LOCATION); this.setConfigurationParameter(ConfigurationParameter.TslKeyStoreLocation, Constant.Production.TSL_KEYSTORE_LOCATION); this.setConfigurationParameter(ConfigurationParameter.ValidationPolicy, Constant.Production.VALIDATION_POLICY); this.setConfigurationParameter(ConfigurationParameter.OcspSource, Constant.Production.OCSP_SOURCE); this.setConfigurationParameter(ConfigurationParameter.SignOcspRequests, "false"); this.trustedTerritories = Constant.Production.DEFAULT_TRUESTED_TERRITORIES; this.setJDigiDocParameter("SIGN_OCSP_REQUESTS", "false"); } logger.debug("{} configuration: {}", this.mode, this.registry); this.loadInitialConfigurationValues(); } private void loadInitialConfigurationValues() { logger.debug(" this.setJDigiDocConfigurationValue("DIGIDOC_SECURITY_PROVIDER", Constant.JDigiDoc.SECURITY_PROVIDER); this.setJDigiDocConfigurationValue("DIGIDOC_SECURITY_PROVIDER_NAME", Constant.JDigiDoc.SECURITY_PROVIDER_NAME); this.setJDigiDocConfigurationValue("KEY_USAGE_CHECK", Constant.JDigiDoc.KEY_USAGE_CHECK); this.setJDigiDocConfigurationValue("DIGIDOC_OCSP_SIGN_CERT_SERIAL", ""); this.setJDigiDocConfigurationValue("DATAFILE_HASHCODE_MODE", "false"); this.setJDigiDocConfigurationValue("CANONICALIZATION_FACTORY_IMPL", Constant.JDigiDoc.CANONICALIZATION_FACTORY_IMPLEMENTATION); this.setJDigiDocConfigurationValue("DIGIDOC_MAX_DATAFILE_CACHED", Constant.JDigiDoc.MAX_DATAFILE_CACHED); this.setJDigiDocConfigurationValue("DIGIDOC_USE_LOCAL_TSL", Constant.JDigiDoc.USE_LOCAL_TSL); this.setJDigiDocConfigurationValue("DIGIDOC_NOTARY_IMPL", Constant.JDigiDoc.NOTARY_IMPLEMENTATION); this.setJDigiDocConfigurationValue("DIGIDOC_TSLFAC_IMPL", Constant.JDigiDoc.TSL_FACTORY_IMPLEMENTATION); this.setJDigiDocConfigurationValue("DIGIDOC_OCSP_RESPONDER_URL", this.getOcspSource()); this.setJDigiDocConfigurationValue("DIGIDOC_FACTORY_IMPL", Constant.JDigiDoc.FACTORY_IMPLEMENTATION); this.setJDigiDocConfigurationValue("DIGIDOC_DF_CACHE_DIR", null); this.setConfigurationValue("TSL_LOCATION", ConfigurationParameter.TslLocation); this.setConfigurationValue("TSP_SOURCE", ConfigurationParameter.TspSource); this.setConfigurationValue("VALIDATION_POLICY", ConfigurationParameter.ValidationPolicy); this.setConfigurationValue("OCSP_SOURCE", ConfigurationParameter.OcspSource); this.setConfigurationValue("DIGIDOC_PKCS12_CONTAINER", ConfigurationParameter.OcspAccessCertificateFile); this.setConfigurationValue("DIGIDOC_PKCS12_PASSWD", ConfigurationParameter.OcspAccessCertificatePassword); this.setConfigurationValue("CONNECTION_TIMEOUT", ConfigurationParameter.ConnectionTimeoutInMillis); this.setConfigurationValue("SOCKET_TIMEOUT", ConfigurationParameter.SocketTimeoutInMillis); this.setConfigurationValue("SIGN_OCSP_REQUESTS", ConfigurationParameter.SignOcspRequests); this.setConfigurationValue("TSL_KEYSTORE_LOCATION", ConfigurationParameter.TslKeyStoreLocation); this.setConfigurationValue("TSL_KEYSTORE_PASSWORD", ConfigurationParameter.TslKeyStorePassword); this.setConfigurationValue("TSL_CACHE_EXPIRATION_TIME", ConfigurationParameter.TslCacheExpirationTimeInMillis); this.setConfigurationValue("REVOCATION_AND_TIMESTAMP_DELTA_IN_MINUTES", ConfigurationParameter.RevocationAndTimestampDeltaInMinutes); this.setConfigurationValue("ALLOWED_TS_AND_OCSP_RESPONSE_DELTA_IN_MINUTES", ConfigurationParameter.AllowedTimestampAndOCSPResponseDeltaInMinutes); this.setConfigurationValue("SIGNATURE_PROFILE", ConfigurationParameter.SignatureProfile); this.setConfigurationValue("SIGNATURE_DIGEST_ALGORITHM", ConfigurationParameter.SignatureDigestAlgorithm); this.setJDigiDocConfigurationValue("SIGN_OCSP_REQUESTS", Boolean.toString(this.hasToBeOCSPRequestSigned())); this.setJDigiDocConfigurationValue("DIGIDOC_PKCS12_CONTAINER", this.getOCSPAccessCertificateFileName()); this.initOcspAccessCertPasswordForJDigidoc(); this.setConfigurationParameter(ConfigurationParameter.HttpProxyHost, this.getParameter(Constant.System.HTTP_PROXY_HOST, "HTTP_PROXY_HOST")); this.setConfigurationParameter(ConfigurationParameter.HttpProxyPort, this.getParameter(Constant.System.HTTP_PROXY_PORT, "HTTP_PROXY_PORT")); this.setConfigurationParameter(ConfigurationParameter.HttpsProxyHost, this.getParameter(Constant.System.HTTPS_PROXY_HOST, "HTTPS_PROXY_HOST")); this.setConfigurationParameter(ConfigurationParameter.HttpsProxyPort, this.getParameter(Constant.System.HTTPS_PROXY_PORT, "HTTPS_PROXY_PORT")); this.setConfigurationParameter(ConfigurationParameter.HttpProxyUser, this.getParameterFromFile("HTTP_PROXY_USER")); this.setConfigurationParameter(ConfigurationParameter.HttpProxyPassword, this.getParameterFromFile("HTTP_PROXY_PASSWORD")); this.setConfigurationParameter(ConfigurationParameter.SslKeystoreType, this.getParameterFromFile("SSL_KEYSTORE_TYPE")); this.setConfigurationParameter(ConfigurationParameter.SslTruststoreType, this.getParameterFromFile("SSL_TRUSTSTORE_TYPE")); this.setConfigurationParameter(ConfigurationParameter.SslKeystorePath, this.getParameter(Constant.System.JAVAX_NET_SSL_KEY_STORE, "SSL_KEYSTORE_PATH")); this.setConfigurationParameter(ConfigurationParameter.SslKeystorePassword, this.getParameter(Constant.System.JAVAX_NET_SSL_KEY_STORE_PASSWORD, "SSL_KEYSTORE_PASSWORD")); this.setConfigurationParameter(ConfigurationParameter.SslTruststorePath, this.getParameter(Constant.System.JAVAX_NET_SSL_TRUST_STORE, "SSL_TRUSTSTORE_PATH")); this.setConfigurationParameter(ConfigurationParameter.SslTruststorePassword, this.getParameter(Constant.System.JAVAX_NET_SSL_TRUST_STORE_PASSWORD, "SSL_TRUSTSTORE_PASSWORD")); this.updateTrustedTerritories(); } private Hashtable<String, String> loadConfigurationSettings(InputStream stream) { configurationFromFile = new LinkedHashMap(); Yaml yaml = new Yaml(); try { configurationFromFile = (LinkedHashMap) yaml.load(stream); } catch (Exception e) { ConfigurationException exception = new ConfigurationException("Configuration from " + configurationInputSourceName + " is not correctly formatted"); logger.error(exception.getMessage()); throw exception; } IOUtils.closeQuietly(stream); return mapToJDigiDocConfiguration(); } private InputStream getResourceAsStream(String certFile) { InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(certFile); if (resourceAsStream == null) { String message = "File " + certFile + " not found in classpath."; logger.error(message); throw new ConfigurationException(message); } return resourceAsStream; } private String defaultIfNull(String configParameter, String defaultValue) { logger.debug("Parameter: " + configParameter); if (configurationFromFile == null) return defaultValue; Object value = configurationFromFile.get(configParameter); if (value != null) { return valueIsAllowed(configParameter, value.toString()) ? value.toString() : ""; } String configuredValue = jDigiDocConfiguration.get(configParameter); return configuredValue != null ? configuredValue : defaultValue; } private boolean valueIsAllowed(String configParameter, String value) { List<String> mustBeBooleans = Arrays.asList("SIGN_OCSP_REQUESTS", "KEY_USAGE_CHECK", "DATAFILE_HASHCODE_MODE", "DIGIDOC_USE_LOCAL_TSL"); List<String> mustBeIntegers = Arrays.asList("DIGIDOC_MAX_DATAFILE_CACHED", "HTTP_PROXY_PORT"); boolean errorFound = false; if (mustBeBooleans.contains(configParameter)) { errorFound = !(isValidBooleanParameter(configParameter, value)); } if (mustBeIntegers.contains(configParameter)) { errorFound = !(isValidIntegerParameter(configParameter, value)) || errorFound; } return (!errorFound); } private boolean isValidBooleanParameter(String configParameter, String value) { if (!("true".equals(value.toLowerCase()) || "false".equals(value.toLowerCase()))) { String errorMessage = "Configuration parameter " + configParameter + " should be set to true or false" + " but the actual value is: " + value + "."; logError(errorMessage); return false; } return true; } private boolean isValidIntegerParameter(String configParameter, String value) { Integer parameterValue; try { parameterValue = Integer.parseInt(value); } catch (Exception e) { String errorMessage = "Configuration parameter " + configParameter + " should have an integer value" + " but the actual value is: " + value + "."; logError(errorMessage); return false; } if (configParameter.equals("DIGIDOC_MAX_DATAFILE_CACHED") && parameterValue < -1) { String errorMessage = "Configuration parameter " + configParameter + " should be greater or equal -1" + " but the actual value is: " + value + "."; logError(errorMessage); return false; } return true; } private void loadOCSPCertificates(LinkedHashMap digiDocCA, String caPrefix) { logger.debug(""); String errorMessage; @SuppressWarnings("unchecked") ArrayList<LinkedHashMap> ocsps = (ArrayList<LinkedHashMap>) digiDocCA.get("OCSPS"); if (ocsps == null) { errorMessage = "No OCSPS entry found or OCSPS entry is empty. Configuration from: " + configurationInputSourceName; logError(errorMessage); return; } int numberOfOCSPCertificates = ocsps.size(); jDigiDocConfiguration.put(caPrefix + "_OCSPS", String.valueOf(numberOfOCSPCertificates)); for (int i = 1; i <= numberOfOCSPCertificates; i++) { String prefix = caPrefix + "_OCSP" + i; LinkedHashMap ocsp = ocsps.get(i - 1); List<String> entries = asList("CA_CN", "CA_CERT", "CN", "URL"); for (String entry : entries) { if (!loadOCSPCertificateEntry(entry, ocsp, prefix)) { errorMessage = "OCSPS list entry " + i + " does not have an entry for " + entry + " or the entry is empty\n"; logError(errorMessage); } } if (!getOCSPCertificates(prefix, ocsp)) { errorMessage = "OCSPS list entry " + i + " does not have an entry for CERTS or the entry is empty\n"; logError(errorMessage); } } } /** * Gives back all configuration parameters needed for jDigiDoc * * @return Hashtable containing jDigiDoc configuration parameters */ private Hashtable<String, String> mapToJDigiDocConfiguration() { logger.debug("loading JDigiDoc configuration"); inputSourceParseErrors = new ArrayList<>(); loadInitialConfigurationValues(); reportFileParseErrors(); return jDigiDocConfiguration; } private void loadCertificateAuthoritiesAndCertificates() { logger.debug(""); @SuppressWarnings("unchecked") ArrayList<LinkedHashMap> digiDocCAs = (ArrayList<LinkedHashMap>) configurationFromFile.get("DIGIDOC_CAS"); if (digiDocCAs == null) { String errorMessage = "Empty or no DIGIDOC_CAS entry"; logError(errorMessage); return; } int numberOfDigiDocCAs = digiDocCAs.size(); jDigiDocConfiguration.put("DIGIDOC_CAS", String.valueOf(numberOfDigiDocCAs)); for (int i = 0; i < numberOfDigiDocCAs; i++) { String caPrefix = "DIGIDOC_CA_" + (i + 1); LinkedHashMap digiDocCA = (LinkedHashMap) digiDocCAs.get(i).get("DIGIDOC_CA"); if (digiDocCA == null) { String errorMessage = "Empty or no DIGIDOC_CA for entry " + (i + 1); logError(errorMessage); } else { loadCertificateAuthorityCerts(digiDocCA, caPrefix); loadOCSPCertificates(digiDocCA, caPrefix); } } } private void logError(String errorMessage) { logger.error(errorMessage); inputSourceParseErrors.add(errorMessage); } private void reportFileParseErrors() { logger.debug(""); if (inputSourceParseErrors.size() > 0) { StringBuilder errorMessage = new StringBuilder(); errorMessage.append("Configuration from "); errorMessage.append(configurationInputSourceName); errorMessage.append(" contains error(s):\n"); for (String message : inputSourceParseErrors) { errorMessage.append(message); } throw new ConfigurationException(errorMessage.toString()); } } private void updateTrustedTerritories() { List<String> territories = getStringListParameterFromFile("TRUSTED_TERRITORIES"); if (territories != null) { trustedTerritories = territories; } } private String getParameterFromFile(String key) { if (configurationFromFile == null) { return null; } Object fileValue = configurationFromFile.get(key); if (fileValue == null) { return null; } String value = fileValue.toString(); if (valueIsAllowed(key, value)) { return value; } return null; } private Integer getIntParameterFromFile(String key) { String value = getParameterFromFile(key); if (value == null) { return null; } return new Integer(value); } private List<String> getStringListParameterFromFile(String key) { String value = getParameterFromFile(key); if (value == null) { return null; } return Arrays.asList(value.split("\\s*,\\s*")); //Split by comma and trim whitespace } private void setConfigurationValue(String fileKey, ConfigurationParameter parameter) { if (this.configurationFromFile == null) { return; } Object fileValue = this.configurationFromFile.get(fileKey); if (fileValue != null) { this.setConfigurationParameter(parameter, fileValue.toString()); } } private void setJDigiDocConfigurationValue(String key, String defaultValue) { String value = defaultIfNull(key, defaultValue); if (value != null) { jDigiDocConfiguration.put(key, value); } } private boolean loadOCSPCertificateEntry(String ocspsEntryName, LinkedHashMap ocsp, String prefix) { Object ocspEntry = ocsp.get(ocspsEntryName); if (ocspEntry == null) return false; jDigiDocConfiguration.put(prefix + "_" + ocspsEntryName, ocspEntry.toString()); return true; } @SuppressWarnings("unchecked") private boolean getOCSPCertificates(String prefix, LinkedHashMap ocsp) { ArrayList<String> certificates = (ArrayList<String>) ocsp.get("CERTS"); if (certificates == null) { return false; } for (int j = 0; j < certificates.size(); j++) { if (j == 0) { this.setJDigiDocParameter(String.format("%s_CERT", prefix), certificates.get(0)); } else { this.setJDigiDocParameter(String.format("%s_CERT_%s", prefix, j), certificates.get(j)); } } return true; } private void loadCertificateAuthorityCerts(LinkedHashMap digiDocCA, String caPrefix) { logger.debug("Loading CA certificates"); ArrayList<String> certificateAuthorityCerts = this.getCACertsAsArray(digiDocCA); this.setJDigiDocParameter(String.format("%s_NAME", caPrefix), digiDocCA.get("NAME").toString()); this.setJDigiDocParameter(String.format("%s_TRADENAME", caPrefix), digiDocCA.get("TRADENAME").toString()); int numberOfCACertificates = certificateAuthorityCerts.size(); this.setJDigiDocParameter(String.format("%s_CERTS", caPrefix), String.valueOf(numberOfCACertificates)); for (int i = 0; i < numberOfCACertificates; i++) { this.setJDigiDocParameter(String.format("%s_CERT%s", caPrefix, i + 1), certificateAuthorityCerts.get(i)); } } @SuppressWarnings("unchecked") private ArrayList<String> getCACertsAsArray(LinkedHashMap digiDocCa) { return (ArrayList<String>) digiDocCa.get("CERTS"); } private void setConfigurationParameter(ConfigurationParameter parameter, String value) { if (StringUtils.isBlank(value)) { logger.info("Parameter <{}> has blank value, hence will not be registered", parameter); return; } logger.debug("Setting parameter <{}> to <{}>", parameter, value); this.registry.put(parameter, value); } private <T> T getConfigurationParameter(ConfigurationParameter parameter, Class<T> clazz) { String value = this.getConfigurationParameter(parameter); if (StringUtils.isNotBlank(value)) { if (clazz.isAssignableFrom(Integer.class)) { return (T) Integer.valueOf(value); } else if (clazz.isAssignableFrom(Long.class)) { return (T) Long.valueOf(value); } throw new RuntimeException(String.format("Type <%s> not supported", clazz.getSimpleName())); } return null; } private String getConfigurationParameter(ConfigurationParameter parameter) { if (!this.registry.containsKey(parameter)) { logger.debug("Requested parameter <{}> not found", parameter); return null; } String value = this.registry.get(parameter); logger.debug("Requesting parameter <{}>. Returned value is <{}>", parameter, value); return value; } private void initOcspAccessCertPasswordForJDigidoc() { char[] ocspAccessCertificatePassword = this.getOCSPAccessCertificatePassword(); if (ocspAccessCertificatePassword != null && ocspAccessCertificatePassword.length > 0) { this.setJDigiDocConfigurationValue(Constant.JDigiDoc.OCSP_PKCS_12_PASSWORD, String.valueOf(ocspAccessCertificatePassword)); } } /** * Get String value through JVM parameters or from configuration file * * @param systemKey jvm value key . * @param fileKey file value key. * @return String value from JVM parameters or from file */ private String getParameter(String systemKey, String fileKey) { String valueFromJvm = System.getProperty(systemKey); String valueFromFile = this.getParameterFromFile(fileKey); this.log(valueFromJvm, valueFromFile, systemKey, fileKey); return valueFromJvm != null ? valueFromJvm : valueFromFile; } private void setJDigiDocParameter(String key, String value) { logger.debug("Setting JDigiDoc parameter <{}> to <{}>", key, value); this.jDigiDocConfiguration.put(key, value); } private void log(Object jvmParam, Object fileParam, String sysParamKey, String fileKey) { if (jvmParam != null) { logger.debug(String.format("JVM parameter <%s> detected and applied with value <%s>", sysParamKey, jvmParam)); } if (jvmParam == null && fileParam != null) { logger.debug(String.format("YAML file parameter <%s> detected and applied with value <%s>", fileKey, fileParam)); } } }
package cubicchunks.world.column; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.TreeMap; import net.minecraft.block.Block; import net.minecraft.block.Blocks; import net.minecraft.block.entity.BlockEntity; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.network.play.packet.clientbound.PacketChunkData; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.Facing; import net.minecraft.util.MathHelper; import net.minecraft.world.LightType; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.BiomeManager; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.NibbleArray; import net.minecraft.world.chunk.storage.ChunkSection; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.common.base.Predicate; import cubicchunks.generator.GeneratorStage; import cubicchunks.util.AddressTools; import cubicchunks.util.Bits; import cubicchunks.util.Coords; import cubicchunks.util.RangeInt; import cubicchunks.world.ChunkSectionHelper; import cubicchunks.world.EntityContainer; import cubicchunks.world.LightIndex; import cubicchunks.world.WorldContexts; import cubicchunks.world.cube.Cube; public class Column extends Chunk { private static final Logger log = LogManager.getLogger(); private TreeMap<Integer,Cube> cubes; private LightIndex lightIndex; private int roundRobinLightUpdatePointer; private List<Cube> roundRobinCubes; private EntityContainer entities; public Column(World world, int x, int z) { // NOTE: this constructor is called by the chunk loader super(world, x, z); init(); } public Column(World world, int cubeX, int cubeZ, Biome[] biomes) { // NOTE: this constructor is called by the column generator this(world, cubeX, cubeZ); init(); // save the biome data for (int i = 0; i < biomes.length; i++) { biomeMap[i] = (byte)biomes[i].biomeID; } this.isModified = true; } private void init() { this.cubes = new TreeMap<Integer,Cube>(); this.lightIndex = new LightIndex(this.world.getSeaLevel()); this.roundRobinLightUpdatePointer = 0; this.roundRobinCubes = new ArrayList<Cube>(); this.entities = new EntityContainer(); // make sure no one's using data structures that have been replaced // also saves memory /* TODO: setting these vars to null would save memory, but they're final. =( * also... make sure we're actually not using them this.chunkSections = null; this.biomeMap = null; this.heightMap = null; this.skylightUpdateMap = null; */ Arrays.fill(this.biomeMap, (byte)-1); } public long getAddress() { return AddressTools.getAddress(this.chunkX, this.chunkZ); } public int getX() { return this.chunkX; } public int getZ() { return this.chunkZ; } public EntityContainer getEntityContainer() { return this.entities; } public LightIndex getLightIndex() { return this.lightIndex; } @Override public void generateHeightMap() { // override this so no height map is generated } public Collection<Cube> getCubes() { return Collections.unmodifiableCollection(this.cubes.values()); } public boolean hasCubes() { return !this.cubes.isEmpty(); } public Cube getCube(int y) { return this.cubes.get(y); } public Cube getOrCreateCube(int cubeY, boolean isModified) { Cube cube = this.cubes.get(cubeY); if (cube == null) { cube = new Cube(this.world, this, this.chunkX, cubeY, this.chunkZ, isModified); this.cubes.put(cubeY, cube); } return cube; } public Iterable<Cube> getCubes(int minY, int maxY) { return this.cubes.subMap(minY, true, maxY, true).values(); } public Cube removeCube(int cubeY) { return this.cubes.remove(cubeY); } public List<RangeInt> getCubeYRanges() { return getRanges(this.cubes.keySet()); } @Override public boolean needsSaving(boolean alwaysTrue) { return this.entities.needsSaving(this.world.getGameTime()) || this.isModified; } public void markSaved() { this.entities.markSaved(this.world.getGameTime()); this.isModified = false; } @Override public Block getBlockAt(final int x, final int y, final int z) { //compact to BlockPos BlockPos pos = new BlockPos(x, y, z); return getBlockAt(pos); } @Override public Block getBlockAt(final BlockPos pos) { // pass to cube int cubeY = Coords.blockToCube(pos.getY()); Cube cube = this.cubes.get(cubeY); if (cube != null) { return cube.getBlockAt(pos); } return Blocks.AIR; } @Override public IBlockState getBlockState(BlockPos pos) { // pass off to the cube int cubeY = Coords.blockToCube(pos.getY()); Cube cube = this.cubes.get(cubeY); if (cube != null) { return cube.getBlockState(pos); } return Blocks.AIR.getDefaultState(); } @Override public IBlockState setBlockState(BlockPos pos, IBlockState newBlockState) { // is there a chunk for this block? int cubeY = Coords.blockToCube(pos.getY()); Cube cube = this.cubes.get(cubeY); if (cube == null) { return null; } // did anything change? IBlockState oldBlockState = cube.setBlockState(pos, newBlockState); if (oldBlockState == null) { // nothing changed return null; } Block oldBlock = oldBlockState.getBlock(); Block newBlock = newBlockState.getBlock(); // update rain map // NOTE: rainfallMap[xzCoord] is he lowest block that will contain rain // so rainfallMap[xzCoord] - 1 is the block that is being rained on int x = Coords.blockToLocal(pos.getX()); int z = Coords.blockToLocal(pos.getZ()); int xzCoord = z << 4 | x; if (pos.getY() >= this.rainfallMap[xzCoord] - 1) { // invalidate the rain height map value this.rainfallMap[xzCoord] = -999; } int newOpacity = newBlock.getOpacity(); int oldOpacity = oldBlock.getOpacity(); // did the top non-transparent block change? Integer oldSkylightY = getSkylightBlockY(x, z); getLightIndex().setOpacity(x, pos.getY(), z, newOpacity); Integer newSkylightY = getSkylightBlockY(x, z); if (oldSkylightY != null && newSkylightY != null && !oldSkylightY.equals(newSkylightY)) { // sort the y-values int minBlockY = oldSkylightY; int maxBlockY = newSkylightY; if (minBlockY > maxBlockY) { minBlockY = newSkylightY; maxBlockY = oldSkylightY; } assert (minBlockY < maxBlockY) : "Values not sorted! " + minBlockY + ", " + maxBlockY; // update light and signal render update WorldContexts.get(this.world).getLightingManager().computeSkyLightUpdate(this, x, z, minBlockY, maxBlockY); this.world.markBlockRangeForRenderUpdate(pos.getX(), minBlockY, pos.getZ(), pos.getX(), maxBlockY, pos.getZ()); } // if opacity changed and ( opacity decreased or block now has any light ) int skyLight = getLightAt(LightType.SKY, pos); int blockLight = getLightAt(LightType.BLOCK, pos); if (newOpacity != oldOpacity && (newOpacity < oldOpacity || skyLight > 0 || blockLight > 0)) { WorldContexts.get(this.world).getLightingManager().queueSkyLightOcclusionCalculation(pos.getX(), pos.getZ()); } // update lighting index getLightIndex().setOpacity(x, pos.getY(), z, newBlock.getOpacity()); this.isModified = true; // NOTE: after this method, the World calls updateLights on the source block which changes light values again return oldBlockState; } @Override public int getBlockMetadata(BlockPos pos) { int x = Coords.blockToLocal(pos.getX()); int z = Coords.blockToLocal(pos.getZ()); return getBlockMetadata(x, pos.getY(), z); } @Override public int getBlockMetadata(int localX, int blockY, int localZ) { // pass off to the cube int cubeY = Coords.blockToCube(blockY); Cube cube = this.cubes.get(cubeY); if (cube != null) { int localY = Coords.blockToLocal(blockY); IBlockState blockState = cube.getBlockState(localX, localY, localZ); if (blockState != null) { return blockState.getBlock().getMetadataForBlockState(blockState); } } return 0; } public int getTopCubeY() { return this.cubes.lastKey(); } public int getBottomCubeY() { return this.cubes.firstKey(); } public Integer getTopFilledCubeY() { Integer blockY = getLightIndex().getTopNonTransparentBlockY(); if (blockY == null) { return null; } return Coords.blockToCube(blockY); } @Override @Deprecated // don't use this! It's only here because vanilla needs it, but we need to be hacky about it public int getBlockStoreY() { Integer cubeY = getTopFilledCubeY(); if (cubeY != null) { return Coords.cubeToMinBlock(cubeY); } else { // PANIC! // this column doesn't have any blocks in it that aren't air! // but we can't return null here because vanilla code expects there to be a surface down there somewhere // we don't actually know where the surface is yet, because maybe it hasn't been generated // but we do know that the surface has to be at least at sea level, // so let's go with that for now and hope for the best return this.world.getSeaLevel(); } } @Override public boolean getAreLevelsEmpty(int minBlockY, int maxBlockY) { int minCubeY = Coords.blockToCube(minBlockY); int maxCubeY = Coords.blockToCube(maxBlockY); for (int cubeY = minCubeY; cubeY <= maxCubeY; cubeY++) { Cube cube = this.cubes.get(cubeY); if (cube != null && cube.hasBlocks()) { return false; } } return true; } @Override public boolean canSeeSky(BlockPos pos) { int x = Coords.blockToLocal(pos.getX()); int z = Coords.blockToLocal(pos.getZ()); Integer skylightBlockY = getSkylightBlockY(x, z); if (skylightBlockY == null) { return true; } return pos.getY() >= skylightBlockY; } public Integer getSkylightBlockY(int localX, int localZ) { // NOTE: a "skylight" block is the transparent block that is directly one block above the top non-transparent block Integer topBlockY = getLightIndex().getTopNonTransparentBlockY(localX, localZ); if (topBlockY != null) { return topBlockY + 1; } return null; } @Override @Deprecated // don't use this! It's only here because vanilla needs it, but we need to be hacky about it public int getHeightAtCoords(int localX, int localZ) { // NOTE: the "height value" here is the height of the transparent block on top of the highest non-transparent block Integer skylightBlockY = getSkylightBlockY(localX, localZ); if (skylightBlockY == null) { // PANIC! // this column doesn't have any blocks in it that aren't air! // but we can't return null here because vanilla code expects there to be a surface down there somewhere // we don't actually know where the surface is yet, because maybe it hasn't been generated // but we do know that the surface has to be at least at sea level, // so let's go with that for now and hope for the best skylightBlockY = this.world.getSeaLevel() + 1; } return skylightBlockY; } @Override public int getBlockOpacityAt(BlockPos pos) { int x = Coords.blockToLocal(pos.getX()); int z = Coords.blockToLocal(pos.getZ()); return getLightIndex().getOpacity(x, pos.getY(), z); } public Iterable<Entity> entities() { return this.entities.entities(); } @Override public void addEntity(Entity entity) { int cubeY = Coords.getCubeYForEntity(entity); // pass off to the cube Cube cube = this.cubes.get(cubeY); if (cube != null) { cube.addEntity(entity); } else { // entities don't have to be in cubes, just add it directly to the column entity.addedToChunk = true; entity.chunkX = this.chunkX; entity.chunkY = cubeY; entity.chunkZ = this.chunkZ; this.entities.add(entity); this.isModified = true; } } @Override public void removeEntity(Entity entity) { removeEntity(entity, entity.chunkY); } @Override public void removeEntity(Entity entity, int cubeY) { if (!entity.addedToChunk) { return; } // pass off to the cube Cube cube = this.cubes.get(cubeY); if (cube != null) { cube.removeEntity(entity); } else if (this.entities.remove(entity)) { entity.addedToChunk = false; this.isModified = true; } else { log.warn(String.format("%s Tried to remove entity %s from column (%d,%d), but it was not there. Entity thinks it's in cube (%d,%d,%d)", this.world.isClient ? "CLIENT" : "SERVER", entity.getClass().getName(), this.chunkX, this.chunkZ, entity.chunkX, entity.chunkY, entity.chunkZ )); } } @Override public void findEntitiesExcept(Entity excludedEntity, AxisAlignedBB queryBox, List<Entity> out, Predicate<? super Entity> predicate) { // get a y-range that 2 blocks wider than the box for safety int minCubeY = Coords.blockToCube(MathHelper.floor(queryBox.minY - 2)); int maxCubeY = Coords.blockToCube(MathHelper.floor(queryBox.maxY + 2)); for (Cube cube : getCubes(minCubeY, maxCubeY)) { cube.findEntitiesExcept(excludedEntity, queryBox, out, predicate); } // check the column too this.entities.findEntitiesExcept(excludedEntity, queryBox, out, predicate); } @Override public <T extends Entity> void findEntities(Class<? extends T> entityType, AxisAlignedBB queryBox, List<T> out, Predicate<? super T> predicate) { // get a y-range that 2 blocks wider than the box for safety int minCubeY = Coords.blockToCube(MathHelper.floor(queryBox.minY - 2)); int maxCubeY = Coords.blockToCube(MathHelper.floor(queryBox.maxY + 2)); for (Cube cube : getCubes(minCubeY, maxCubeY)) { cube.findEntities(entityType, queryBox, out, predicate); } // check the column too this.entities.findEntities(entityType, queryBox, out, predicate); } @Override public BlockEntity getBlockEntityAt(BlockPos pos, ChunkEntityCreationType creationType) { // pass off to the cube int cubeY = Coords.blockToCube(pos.getY()); Cube cube = this.cubes.get(cubeY); if (cube != null) { return cube.getBlockEntity(pos, creationType); } return null; } @Override public void setBlockEntityAt(BlockPos pos, BlockEntity blockEntity) { // pass off to the cube int cubeY = Coords.blockToCube(pos.getY()); Cube cube = this.cubes.get(cubeY); if (cube != null) { cube.addBlockEntity(pos, blockEntity); } else { log.warn(String.format("No cube at (%d,%d,%d) to add tile entity (block %d,%d,%d)!", this.chunkX, cubeY, this.chunkZ, pos.getX(), pos.getY(), pos.getZ() )); } } @Override public void removeBlockEntityAt(BlockPos pos) { // pass off to the cube int cubeY = Coords.blockToCube(pos.getY()); Cube cube = this.cubes.get(cubeY); if (cube != null) { cube.removeBlockEntity(pos); } } @Override public void onChunkLoad() { this.chunkLoaded = true; } @Override public void onChunkUnload() { this.chunkLoaded = false; } public PacketChunkData.EncodedChunk encode(boolean isFirstTime, boolean hasSky, int sectionFlags) throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(buf); // NOTE: there's no need to do compression here. This output is compressed later // how many cubes are we sending? int numCubes = getCubes().size(); out.writeShort(numCubes); // send the actual cube data for (Cube cube : getCubes()) { // signal we're sending this cube out.writeInt(cube.getY()); out.writeBoolean(cube.isEmpty()); if (!cube.isEmpty()) { ChunkSection storage = cube.getStorage(); // 1. block IDs, low bits out.write(ChunkSectionHelper.getBlockLSBArray(storage)); // 2. block IDs, high bits NibbleArray blockIdMsbs = ChunkSectionHelper.getBlockMSBArray(storage); if (blockIdMsbs != null) { out.writeByte(1); out.write(blockIdMsbs.get()); } else { // signal we're not sending this data out.writeByte(0); } // 3. metadata out.write(ChunkSectionHelper.getBlockMetaArray(storage).get()); // 4. block light out.write(storage.getBlockLightArray().get()); if (hasSky) { // 5. sky light out.write(storage.getSkyLightArray().get()); } } } if (isFirstTime) { // 6. biomes out.write(getBiomeMap()); } // 7. light index getLightIndex().writeData(out); out.close(); PacketChunkData.EncodedChunk encodedChunk = new PacketChunkData.EncodedChunk(); encodedChunk.data = buf.toByteArray(); encodedChunk.sectionFlags = 0; return encodedChunk; } @Override public void readChunkIn(byte[] data, int segmentsToCopyBitFlags, boolean isFirstTime) { // NOTE: this is called on the client when it receives chunk data from the server ByteArrayInputStream buf = new ByteArrayInputStream(data); DataInputStream in = new DataInputStream(buf); try { // how many cubes are we reading? int numCubes = in.readUnsignedShort(); for (int i = 0; i < numCubes; i++) { int cubeY = in.readInt(); Cube cube = getOrCreateCube(cubeY, false); // if the cube came from the server, it must be live cube.setGeneratorStage(GeneratorStage.getLastStage()); // is the cube empty? boolean isEmpty = in.readBoolean(); cube.setEmpty(isEmpty); if (!isEmpty) { ChunkSection storage = cube.getStorage(); // 1. block IDs, low bits byte[] blockIdLsbs = new byte[16*16*16]; in.read(blockIdLsbs); // 2. block IDs, high bits NibbleArray blockIdMsbs = null; boolean isHighBitsAttached = in.readByte() != 0; if (isHighBitsAttached) { blockIdMsbs = new NibbleArray(); in.read(blockIdMsbs.get()); } // 3. metadata NibbleArray blockMetadata = new NibbleArray(); in.read(blockMetadata.get()); ChunkSectionHelper.setBlockStates(storage, blockIdLsbs, blockIdMsbs, blockMetadata); // 4. block light in.read(storage.getBlockLightArray().get()); if (!this.world.dimension.hasNoSky()) { // 5. sky light in.read(storage.getSkyLightArray().get()); } storage.countBlocksInSection(); } // flag cube for render update cube.markForRenderUpdate(); } if (isFirstTime) { // 6. biomes in.read(getBiomeMap()); } // 7. light index getLightIndex().readData(in); in.close(); } catch (IOException ex) { log.error(String.format("Unable to read data for column (%d,%d)", this.chunkX, this.chunkZ), ex); } // update lighting flags this.terrainPopulated = true; // update tile entities in each chunk for (Cube cube : this.cubes.values()) { for (BlockEntity blockEntity : cube.getBlockEntities()) { blockEntity.updateContainingBlockInfo(); } } } /** * This method retrieves the biome at a set of coordinates */ @Override public Biome getBiome(BlockPos pos, BiomeManager biomeManager) { int biomeID = this.biomeMap[Coords.blockToLocal(pos.getZ()) << 4 | Coords.blockToLocal(pos.getX())] & 255; if (biomeID == 255) { Biome biome = biomeManager.getBiome(pos); biomeID = biome.biomeID; this.biomeMap[Coords.blockToLocal(pos.getZ()) << 4 | Coords.blockToLocal(pos.getX())] = (byte) (biomeID & 255); } return Biome.getBiome(biomeID) == null ? Biome.PLAINS : Biome.getBiome(biomeID); } @Override public boolean isPopulated() { boolean isAnyCubeLive = false; for (Cube cube : this.cubes.values()) { isAnyCubeLive |= cube.getGeneratorStage().isLastStage(); } return this.ticked && this.terrainPopulated && isAnyCubeLive; } @Override public void tickChunk(boolean tryToTickFaster) { this.ticked = true; // don't need to do anything else here // lighting is handled elsewhere now } @Override @Deprecated public void generateSkylightMap() { // don't call this, use the lighting manager throw new UnsupportedOperationException(); } public void resetPrecipitationHeight() { // init the rain map to -999, which is a kind of null value // this array is actually a cache // values will be calculated by the getter for (int localX = 0; localX < 16; localX++) { for (int localZ = 0; localZ < 16; localZ++) { int xzCoord = localX | localZ << 4; this.rainfallMap[xzCoord] = -999; } } } @Override public BlockPos getRainfallHeight(BlockPos pos) { // TODO: update this calculation to use better data structures int x = Coords.blockToLocal(pos.getX()); int z = Coords.blockToLocal(pos.getZ()); int xzCoord = x | z << 4; int height = this.rainfallMap[xzCoord]; if (height == -999) { /* TODO: compute a new rain height look over the blocks in the top filled cube (if one exists) and do something like this: int maxBlockY = getTopFilledSegment() + 15; int minBlockY = Coords.cubeToMinBlock( getBottomCubeY() ); Block block = cube.getBlock( ... ); Material material = block.getMaterial(); if( material.blocksMovement() || material.isLiquid() ) { height = maxBlockY + 1; } */ // TEMP: just rain down to the sea this.rainfallMap[xzCoord] = this.world.getSeaLevel(); } return new BlockPos(pos.getX(), height, pos.getZ()); } @Override public int getBrightestLight(BlockPos pos, int skyLightDampeningTerm) { // NOTE: this is called by WorldRenderers // pass off to cube int cubeY = Coords.blockToCube(pos.getY()); Cube cube = this.cubes.get(cubeY); if (cube != null) { return cube.getBrightestLight(pos, skyLightDampeningTerm); } // defaults if (!this.world.dimension.hasNoSky() && skyLightDampeningTerm < LightType.SKY.defaultValue) { return LightType.SKY.defaultValue - skyLightDampeningTerm; } return 0; } @Override public int getLightAt(LightType lightType, BlockPos pos) { // NOTE: this is the light function that is called by the rendering code on client // pass off to cube int cubeY = Coords.blockToCube(pos.getY()); Cube cube = this.cubes.get(cubeY); if (cube != null) { return cube.getLightValue(lightType, pos); } // there's no cube, rely on defaults if (lightType == LightType.SKY) { if (canSeeSky(pos)) { return lightType.defaultValue; } else { return 0; } } return 0; } @Override public void setLightAt(LightType lightType, BlockPos pos, int light) { // pass off to cube int cubeY = Coords.blockToCube(pos.getY()); Cube cube = this.cubes.get(cubeY); if (cube != null) { cube.setLightValue(lightType, pos, light); this.isModified = true; } } protected List<RangeInt> getRanges(Iterable<Integer> yValues) { // compute a kind of run-length encoding on the cube y-values List<RangeInt> ranges = new ArrayList<RangeInt>(); Integer start = null; Integer stop = null; for (int cubeY : yValues) { if (start == null) { // start a new range start = cubeY; stop = cubeY; } else if (cubeY == stop + 1) { // extend the range stop = cubeY; } else { // end the range ranges.add(new RangeInt(start, stop)); // start a new range start = cubeY; stop = cubeY; } } if (start != null) { // finish the last range ranges.add(new RangeInt(start, stop)); } return ranges; } @Override public void resetRelightChecks() { this.roundRobinLightUpdatePointer = 0; this.roundRobinCubes.clear(); this.roundRobinCubes.addAll(this.cubes.values()); } @Override public void processRelightChecks() { if (this.roundRobinCubes.isEmpty()) { resetRelightChecks(); } // we get just a few updates this time BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(); for (int i = 0; i < 2; i++) { // once we've checked all the blocks, stop checking int maxPointer = 16 * 16 * this.roundRobinCubes.size(); if (this.roundRobinLightUpdatePointer >= maxPointer) { break; } // get this update's arguments int cubeIndex = Bits.unpackUnsigned(this.roundRobinLightUpdatePointer, 4, 8); int localX = Bits.unpackUnsigned(this.roundRobinLightUpdatePointer, 4, 4); int localZ = Bits.unpackUnsigned(this.roundRobinLightUpdatePointer, 4, 0); // advance to the next block // this pointer advances over segment block columns // starting from the block columns in the bottom segment and moving upwards this.roundRobinLightUpdatePointer++; // get the cube that was pointed to Cube cube = this.roundRobinCubes.get(cubeIndex); int blockX = Coords.localToBlock(this.chunkX, localX); int blockZ = Coords.localToBlock(this.chunkZ, localZ); // for each block in this segment block column... for (int localY = 0; localY < 16; ++localY) { int blockY = Coords.localToBlock(cube.getY(), localY); pos.setBlockPos(blockX, blockY, blockZ); if (cube.getBlockState(pos).getBlock().getMaterial() == Material.AIR) { // if there's a light source next to this block, update the light source for (Facing facing : Facing.values()) { BlockPos neighborPos = pos.addDirection(facing, 1); if (this.world.getBlockStateAt(neighborPos).getBlock().getBrightness() > 0) { this.world.updateLightingAt(neighborPos); } } // then update this block this.world.updateLightingAt(pos); } } } } public void doRandomTicks() { if (isEmpty()) { return; } for (Cube cube : this.cubes.values()) { cube.doRandomTicks(); } } }
package org.gitlab4j.api; import org.gitlab4j.api.models.Job; import org.gitlab4j.api.models.JobStatus; import org.gitlab4j.api.models.Runner; import org.gitlab4j.api.models.RunnerDetail; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.Response; import java.util.List; /** * This class provides an entry point to all the GitLab API repository files calls. */ public class RunnersApi extends AbstractApi { public RunnersApi(GitLabApi gitLabApi) { super(gitLabApi); } /** * Get a list of all available runners available to the user. * * GET /runners * * @return List of Runners * @throws GitLabApiException if any exception occurs */ public List<Runner> getRunners() throws GitLabApiException { return getRunners(null, null, null); } /** * Get a list of all available runners available to the user with pagination support. * * GET /runners * * @param scope The scope of specific runners to show, one of: active, paused, online; showing all runners null * @return List of Runners * @throws GitLabApiException if any exception occurs */ public List<Runner> getRunners(Runner.RunnerStatus scope) throws GitLabApiException { return getRunners(scope, null, null); } /** * Get a list of all available runners available to the user with pagination support. * * GET /runners * * @param page The page offset of runners * @param perPage The number of runners to get after the page offset * @return List of Runners * @throws GitLabApiException if any exception occurs */ public List<Runner> getRunners(int page, int perPage) throws GitLabApiException { return getRunners(null, page, perPage); } /** * Get a list of specific runners available to the user. * * GET /runners * * @param scope The scope of specific runners to show, one of: active, paused, online; showing all runners null * @param page The page offset of runners * @param perPage The number of runners to get after the page offset * @return List of Runners * @throws GitLabApiException if any exception occurs */ public List<Runner> getRunners(Runner.RunnerStatus scope, Integer page, Integer perPage) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm() .withParam("scope", scope, false) .withParam("page", page, false) .withParam("per_page", perPage, false); Response response = get(Response.Status.OK, formData.asMap(), "runners"); return (response.readEntity(new GenericType<List<Runner>>() { })); } /** * Get a list of all available runners available to the user. * * GET /runners * * @param itemsPerPage the number of Runner instances that will be fetched per page * @return a Pager containing the Runners for the user * @throws GitLabApiException if any exception occurs */ public Pager<Runner> getRunners(int itemsPerPage) throws GitLabApiException { return getRunners(null, itemsPerPage); } /** * Get a list of specific runners available to the user. * * GET /runners * * @param scope The scope of specific runners to show, one of: active, paused, online; showing all runners null * @param itemsPerPage The number of Runner instances that will be fetched per page * @return a Pager containing the Runners for the user * @throws GitLabApiException if any exception occurs */ public Pager<Runner> getRunners(Runner.RunnerStatus scope, int itemsPerPage) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm() .withParam("scope", scope, false); return (new Pager<>(this, Runner.class, itemsPerPage, formData.asMap(), "runners")); } /** * Get a list of all runners in the GitLab instance (specific and shared). Access is restricted to users with admin privileges. * * GET /runners/all * * @return List of Runners * @throws GitLabApiException if any exception occurs */ public List<Runner> getAllRunners() throws GitLabApiException { return getAllRunners(null, null, null); } /** * Get a list of all runners in the GitLab instance (specific and shared). Access is restricted to users with admin privileges. * * GET /runners/all * * @param scope The scope of specific runners to show, one of: active, paused, online; showing all runners null * @return List of Runners * @throws GitLabApiException if any exception occurs */ public List<Runner> getAllRunners(Runner.RunnerStatus scope) throws GitLabApiException { return getAllRunners(scope, null, null); } /** * Get a list of all runners in the GitLab instance (specific and shared). Access is restricted to users with admin privileges. * * GET /runners/all * * @param page The page offset of runners * @param perPage The number of runners to get after the page offset * @return List of Runners * @throws GitLabApiException if any exception occurs */ public List<Runner> getAllRunners(int page, int perPage) throws GitLabApiException { return getAllRunners(null, page, perPage); } /** * Get a list of all runners in the GitLab instance (specific and shared). Access is restricted to users with admin privileges. * * GET /runners/all * * @param scope The scope of specific runners to show, one of: active, paused, online; showing all runners null * @param page The page offset of runners * @param perPage The number of runners to get after the page offset * @return List of Runners * @throws GitLabApiException if any exception occurs */ public List<Runner> getAllRunners(Runner.RunnerStatus scope, Integer page, Integer perPage) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm() .withParam("scope", scope, false) .withParam("page", page, false) .withParam("per_page", perPage, false); Response response = get(Response.Status.OK, formData.asMap(), "runners", "all"); return (response.readEntity(new GenericType<List<Runner>>() { })); } /** * Get a list of all runners in the GitLab instance (specific and shared). Access is restricted to users with admin privileges. * * GET /runners/all * * @param itemsPerPage The number of Runner instances that will be fetched per page * @return List of Runners * @throws GitLabApiException if any exception occurs */ public Pager<Runner> getAllRunners(int itemsPerPage) throws GitLabApiException { return getAllRunners(null, itemsPerPage); } /** * Get a list of all runners in the GitLab instance (specific and shared). Access is restricted to users with admin privileges. * * GET /runners/all * * @param scope The scope of specific runners to show, one of: active, paused, online; showing all runners null * @param itemsPerPage The number of Runner instances that will be fetched per page * @return a Pager containing the Runners * @throws GitLabApiException if any exception occurs */ public Pager<Runner> getAllRunners(Runner.RunnerStatus scope, int itemsPerPage) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm() .withParam("scope", scope, false); return (new Pager<>(this, Runner.class, itemsPerPage, formData.asMap(), "runners")); } /** * Get details of a runner. * * GET /runners/:id * * @param runnerId Runner id to get details for * @return RunnerDetail instance. * @throws GitLabApiException if any exception occurs */ public RunnerDetail getRunnerDetail(Integer runnerId) throws GitLabApiException { if (runnerId == null) { throw new RuntimeException("runnerId cannot be null"); } Response response = get(Response.Status.OK, null, "runners", runnerId); return (response.readEntity(RunnerDetail.class)); } /** * Update details of a runner. * * PUT /runners/:id * * @param runnerId The ID of a runner * @param description The description of a runner * @param active The state of a runner; can be set to true or false * @param tagList The list of tags for a runner; put array of tags, that should be finally assigned to a runner * @param runUntagged Flag indicating the runner can execute untagged jobs * @param locked Flag indicating the runner is locked * @param accessLevel The access_level of the runner; not_protected or ref_protected * @return RunnerDetail instance. * @throws GitLabApiException if any exception occurs */ public RunnerDetail updateRunner(Integer runnerId, String description, Boolean active, List<String> tagList, Boolean runUntagged, Boolean locked, RunnerDetail.RunnerAccessLevel accessLevel) throws GitLabApiException { if (runnerId == null) { throw new RuntimeException("runnerId cannot be null"); } GitLabApiForm formData = new GitLabApiForm() .withParam("description", description, false) .withParam("active", active, false) .withParam("tag_list", tagList, false) .withParam("run_untagged", runUntagged, false) .withParam("locked", locked, false) .withParam("access_level", accessLevel, false); Response response = put(Response.Status.OK, formData.asMap(), "runners", runnerId); return (response.readEntity(RunnerDetail.class)); } /** * Remove a runner. * * DELETE /runners/:id * * @param runnerId The ID of a runner * @throws GitLabApiException if any exception occurs */ public void removeRunner(Integer runnerId) throws GitLabApiException { if (runnerId == null) { throw new RuntimeException("runnerId cannot be null"); } delete(Response.Status.NO_CONTENT, null, "runners", runnerId); } /** * List jobs that are being processed or were processed by specified Runner. * * GET /runners/:id/jobs * * @param runnerId The ID of a runner * @return List jobs that are being processed or were processed by specified Runner * @throws GitLabApiException if any exception occurs */ public List<Job> getJobs(Integer runnerId) throws GitLabApiException { if (runnerId == null) { throw new RuntimeException("runnerId cannot be null"); } return getJobs(runnerId, null); } /** * List jobs that are being processed or were processed by specified Runner. * * GET /runners/:id/jobs * * @param runnerId The ID of a runner * @param status Status of the job; one of: running, success, failed, canceled * @return List jobs that are being processed or were processed by specified Runner * @throws GitLabApiException if any exception occurs */ public List<Job> getJobs(Integer runnerId, JobStatus status) throws GitLabApiException { if (runnerId == null) { throw new RuntimeException("runnerId cannot be null"); } GitLabApiForm formData = new GitLabApiForm() .withParam("status", status, false); Response response = get(Response.Status.OK, formData.asMap(), "runners", runnerId, "jobs"); return (response.readEntity(new GenericType<List<Job>>() { })); } /** * List jobs that are being processed or were processed by specified Runner. * * GET /runners/:id/jobs * * @param runnerId The ID of a runner * @param itemsPerPage The number of Runner instances that will be fetched per page * @return a Pager containing the Jobs for the Runner * @throws GitLabApiException if any exception occurs */ public Pager<Job> getJobs(Integer runnerId, int itemsPerPage) throws GitLabApiException { if (runnerId == null) { throw new RuntimeException("runnerId cannot be null"); } return getJobs(runnerId, null, itemsPerPage); } /** * List jobs that are being processed or were processed by specified Runner. * * GET /runners/:id/jobs * * @param runnerId The ID of a runner * @param status Status of the job; one of: running, success, failed, canceled * @param itemsPerPage The number of Runner instances that will be fetched per page * @return a Pager containing the Jobs for the Runner * @throws GitLabApiException if any exception occurs */ public Pager<Job> getJobs(Integer runnerId, JobStatus status, int itemsPerPage) throws GitLabApiException { if (runnerId == null) { throw new RuntimeException("runnerId cannot be null"); } GitLabApiForm formData = new GitLabApiForm() .withParam("status", status, false); return (new Pager<>(this, Job.class, itemsPerPage, formData.asMap(), "runners", runnerId, "jobs")); } /** * List all runners (specific and shared) available in the project. Shared runners are listed if at least one * shared runner is defined and shared runners usage is enabled in the project's settings. * * GET /projects/:id/runners * * @param projectId The ID of the project owned by the authenticated user * @return List of all Runner available in the project * @throws GitLabApiException if any exception occurs */ public List<Runner> getProjectRunners(Integer projectId) throws GitLabApiException { if (projectId == null) { throw new RuntimeException("projectId cannot be null"); } Response response = get(Response.Status.OK, null, "projects", projectId, "runners"); return (response.readEntity(new GenericType<List<Runner>>() { })); } /** * List all runners (specific and shared) available in the project. Shared runners are listed if at least one * shared runner is defined and shared runners usage is enabled in the project's settings. * * GET /projects/:id/runners * * @param projectId The ID of the project owned by the authenticated user * @param itemsPerPage the number of Project instances that will be fetched per page * @return Pager of all Runner available in the project * @throws GitLabApiException if any exception occurs */ public Pager<Runner> getProjectRunners(Integer projectId, int itemsPerPage) throws GitLabApiException { if (projectId == null) { throw new RuntimeException("projectId cannot be null"); } return (new Pager<>(this, Runner.class, itemsPerPage, null, "projects", projectId, "runners")); } /** * Enable an available specific runner in the project. * * POST /projects/:id/runners * * @param projectId The ID of the project owned by the authenticated user * @param runnerId The ID of a runner * @return Runner instance of the Runner enabled * @throws GitLabApiException if any exception occurs */ public Runner enableRunner(Integer projectId, Integer runnerId) throws GitLabApiException { if (projectId == null || runnerId == null) { throw new RuntimeException("projectId or runnerId cannot be null"); } GitLabApiForm formData = new GitLabApiForm() .withParam("runner_id", runnerId, true); Response response = post(Response.Status.CREATED, formData.asMap(), "projects", projectId, "runners"); return (response.readEntity(Runner.class)); } /** * Disable a specific runner from the project. It works only if the project isn't the only project associated with * the specified runner. If so, an error is returned. Use the {@link #removeRunner(Integer)} instead. * * DELETE /projects/:id/runners/:runner_id * * @param projectId The ID of the project owned by the authenticated user * @param runnerId The ID of a runner * @return Runner instance of the Runner disabled * @throws GitLabApiException if any exception occurs */ public Runner disableRunner(Integer projectId, Integer runnerId) throws GitLabApiException { if (projectId == null || runnerId == null) { throw new RuntimeException("projectId or runnerId cannot be null"); } GitLabApiForm formData = new GitLabApiForm() .withParam("runner_id", runnerId, true); Response response = delete(Response.Status.OK, formData.asMap(), "projects", projectId, "runners"); return (response.readEntity(Runner.class)); } }
package org.janvs.util; public class BooleanMaker { public static boolean[] getBooleanRepresentationFor(final int value, final int numberOfPlaces) { String binary = getBinaryStringOfProperSize(value, numberOfPlaces); final boolean[] booleans = convertToBooleans(binary); return booleans; } static private String getBinaryStringOfProperSize(final int value, final int numberOfPlaces) { final String binary = Integer.toBinaryString(value); if (binary.length() < numberOfPlaces) { return padWithZeros(binary, numberOfPlaces); } return binary; } static private String padWithZeros(String binary, final double numberOfPlaces) { final double numberOfZerosToAdd = numberOfPlaces - binary.length(); for (int i = 0; i < numberOfZerosToAdd; i++) { binary = "0" + binary; } return binary; } static private boolean[] convertToBooleans(final String binary) { final char[] binaryArray = binary.toCharArray(); final boolean[] booleans = new boolean[binaryArray.length]; for (int i = 0; i < binary.length(); i++) booleans[i] = binaryArray[i] == '1' ? true : false; return booleans; } }
package org.jboss.aesh.terminal; import org.jboss.aesh.console.Config; public enum Key { UNKNOWN(new int[]{0}), CTRL_A(new int[]{1}), CTRL_B(new int[]{2}), CTRL_C(new int[]{3}), CTRL_D(new int[]{4}), CTRL_E(new int[]{5}), CTRL_F(new int[]{6}), CTRL_G(new int[]{7}), CTRL_H(new int[]{8}), CTRL_I(new int[]{9}), CTRL_J(new int[]{10}), CTRL_K(new int[]{11}), CTRL_L(new int[]{12}), CTRL_M(new int[]{13}), CTRL_N(new int[]{14}), CTRL_O(new int[]{15}), CTRL_P(new int[]{16}), CTRL_Q(new int[]{17}), CTRL_R(new int[]{18}), CTRL_S(new int[]{19}), CTRL_T(new int[]{20}), CTRL_U(new int[]{21}), CTRL_V(new int[]{22}), CTRL_W(new int[]{23}), CTRL_X(new int[]{24}), CTRL_Y(new int[]{25}), CTRL_Z(new int[]{26}), ESC(new int[]{27}), //ctrl-[ and esc FILE_SEPARATOR(new int[]{28}), //ctrl-\ GROUP_SEPARATOR(new int[]{29}), //ctrl-] RECORD_SEPARATOR(new int[]{30}), //ctrl-ctrl UNIT_SEPARATOR(new int[]{31}), //ctrl-_ SPACE(new int[]{32}), EXCLAMATION(new int[]{33}), QUOTE(new int[]{34}), HASH(new int[]{35}), // DOLLAR(new int[]{36}), PERCENT(new int[]{37}), AMPERSAND(new int[]{38}), APOSTROPHE(new int[]{39}), LEFT_PARANTHESIS(new int[]{40}), RIGHT_PARANTHESIS(new int[]{41}), STAR(new int[]{42}), PLUS(new int[]{43}), COMMA(new int[]{44}), MINUS(new int[]{45}), PERIOD(new int[]{46}), SLASH(new int[]{47}), ZERO(new int[]{48}), ONE(new int[]{49}), TWO(new int[]{50}), THREE(new int[]{51}), FOUR(new int[]{52}), FIVE(new int[]{53}), SIX(new int[]{54}), SEVEN(new int[]{55}), EIGHT(new int[]{56}), NINE(new int[]{57}), COLON(new int[]{58}), SEMI_COLON(new int[]{59}), LESS_THAN(new int[]{60}), EQUALS(new int[]{61}), GREATER_THAN(new int[]{62}), QUESTION_MARK(new int[]{63}), AT(new int[]{64}), A(new int[]{65}), B(new int[]{66}), C(new int[]{67}), D(new int[]{68}), E(new int[]{69}), F(new int[]{70}), G(new int[]{71}), H(new int[]{72}), I(new int[]{73}), J(new int[]{74}), K(new int[]{75}), L(new int[]{76}), M(new int[]{77}), N(new int[]{78}), O(new int[]{79}), P(new int[]{80}), Q(new int[]{81}), R(new int[]{82}), S(new int[]{83}), T(new int[]{84}), U(new int[]{85}), V(new int[]{86}), W(new int[]{87}), X(new int[]{88}), Y(new int[]{89}), Z(new int[]{90}), LEFT_SQUARE_BRACKET(new int[]{91}), BACKSLASH(new int[]{92}), RIGHT_SQUARE_BRACKET(new int[]{93}), HAT(new int[]{94}), UNDERSCORE(new int[]{95}), GRAVE(new int[]{96}), a(new int[]{97}), b(new int[]{98}), c(new int[]{99}), d(new int[]{100}), e(new int[]{101}), f(new int[]{102}), g(new int[]{103}), h(new int[]{104}), i(new int[]{105}), j(new int[]{106}), k(new int[]{107}), l(new int[]{108}), m(new int[]{109}), n(new int[]{110}), o(new int[]{111}), p(new int[]{112}), q(new int[]{113}), r(new int[]{114}), s(new int[]{115}), t(new int[]{116}), u(new int[]{117}), v(new int[]{118}), w(new int[]{119}), x(new int[]{120}), y(new int[]{121}), z(new int[]{122}), LEFT_CURLY_BRACKET(new int[]{123}), VERTICAL_BAR(new int[]{124}), RIGHT_CURLY_BRACKET(new int[]{125}), TILDE(new int[]{126}), WINDOWS_ESC(new int[]{224}), // just used to identify win special chars WINDOWS_ESC_2(new int[]{341}), // just used to identify win special chars //movement UP(Config.isOSPOSIXCompatible() ? new int[]{ESC.getFirstValue(),91,65} : new int[]{WINDOWS_ESC.getFirstValue(),72}), DOWN(Config.isOSPOSIXCompatible() ? new int[]{ESC.getFirstValue(),91,66} : new int[]{WINDOWS_ESC.getFirstValue(),80}), RIGHT(Config.isOSPOSIXCompatible() ? new int[]{ESC.getFirstValue(),91,67} : new int[]{WINDOWS_ESC.getFirstValue(),77}), LEFT(Config.isOSPOSIXCompatible() ? new int[]{ESC.getFirstValue(),91,68} : new int[]{WINDOWS_ESC.getFirstValue(),75}), UP_2(Config.isOSPOSIXCompatible() ? InfocmpManager.getUp() : new int[]{WINDOWS_ESC.getFirstValue(),72}), DOWN_2(Config.isOSPOSIXCompatible() ? InfocmpManager.getDown() : new int[]{WINDOWS_ESC.getFirstValue(),80}), RIGHT_2(Config.isOSPOSIXCompatible() ? InfocmpManager.getRight() : new int[]{WINDOWS_ESC.getFirstValue(),77}), LEFT_2(Config.isOSPOSIXCompatible() ? InfocmpManager.getLeft() : new int[]{WINDOWS_ESC.getFirstValue(),75}), //meta META_F(Config.isOSPOSIXCompatible() ? new int[]{ESC.getFirstValue(),102} : new int[]{0,33}), META_B(Config.isOSPOSIXCompatible() ? new int[]{ESC.getFirstValue(),98} : new int[]{0,48}), META_D(Config.isOSPOSIXCompatible() ? new int[]{ESC.getFirstValue(),100} : new int[]{0,32}), META_A(new int[]{ESC.getFirstValue(),97}), //div DELETE(Config.isOSPOSIXCompatible() ? InfocmpManager.getDelete() : new int[]{WINDOWS_ESC.getFirstValue(),83}), INSERT(Config.isOSPOSIXCompatible() ? InfocmpManager.getIns() : new int[]{WINDOWS_ESC.getFirstValue(),82}), PGUP(Config.isOSPOSIXCompatible() ? InfocmpManager.getPgUp() : new int[]{WINDOWS_ESC.getFirstValue(),73}), PGDOWN(Config.isOSPOSIXCompatible() ? InfocmpManager.getPgDown() : new int[]{WINDOWS_ESC.getFirstValue(),81}), HOME(Config.isOSPOSIXCompatible() ? InfocmpManager.getKeyHome() : new int[]{WINDOWS_ESC.getFirstValue(),71}), END(Config.isOSPOSIXCompatible() ? InfocmpManager.getEnd() : new int[]{WINDOWS_ESC.getFirstValue(),79}), META_CTRL_J(Config.isOSPOSIXCompatible() ? new int[]{ESC.getFirstValue(),10} : new int[]{0,36}), META_CTRL_D(new int[]{ESC.getFirstValue(),4}), CTRL_X_CTRL_U(Config.isOSPOSIXCompatible() ? new int[]{ESC.getFirstValue(),21} : new int[]{0,36}), BACKSPACE(Config.isOSPOSIXCompatible() ? new int[]{127} : new int[]{8}), CTRL_LEFT(Config.isOSPOSIXCompatible() ? new int[] {ESC.getFirstValue(),91,49,59,53,68} : new int[]{WINDOWS_ESC.getFirstValue(), 115}), CTRL_RIGHT(Config.isOSPOSIXCompatible() ? new int[] {ESC.getFirstValue(),91,49,59,53,67} : new int[]{WINDOWS_ESC.getFirstValue(), 116}), CTRL_UP(Config.isOSPOSIXCompatible() ? new int[] {ESC.getFirstValue(),91,49,59,53,65} : new int[]{WINDOWS_ESC.getFirstValue(), 141}), CTRL_DOWN(Config.isOSPOSIXCompatible() ? new int[] {ESC.getFirstValue(),91,49,59,53,66} : new int[]{WINDOWS_ESC.getFirstValue(), 145}), ENTER(Config.isOSPOSIXCompatible() ? new int[]{10} : new int[]{13}), //needed to support stupid \r\n on windows... ENTER_2(Config.isOSPOSIXCompatible() ? new int[]{10} : new int[]{13,10}); private int[] keyValues; Key(int[] keyValues) { this.keyValues = keyValues; } /** * is of type a-z or A-Z */ public boolean isCharacter() { return (keyValues.length == 1 && ((keyValues[0] > 63 && keyValues[0] < 91) || (keyValues[0] > 96 && keyValues[0] < 123))); } /** * @return true if input is 0-9 */ public boolean isNumber() { return (keyValues.length == 1 && ((keyValues[0] > 47) && (keyValues[0] < 58))); } /** * @return true if input is a valid char */ public boolean isValidInput() { return (keyValues.length == 1 && (keyValues[0] > 31 && keyValues[0] < 127)); } public char getAsChar() { return (char) keyValues[0]; } public int[] getKeyValues() { return keyValues; } public int getFirstValue() { return keyValues[0]; } public static boolean startsWithEscape(int[] input) { return ((Config.isOSPOSIXCompatible() && input[0] == Key.ESC.getFirstValue()) || (!Config.isOSPOSIXCompatible() && input[0] == Key.WINDOWS_ESC.getFirstValue())); } public static Key getKey(int[] otherValues) { for(Key key : Key.values()) { if(key.equalTo(otherValues)) return key; } return Key.UNKNOWN; } public static Key findStartKey(int[] input) { for(Key key : values()) { if(key != Key.ESC && key != Key.WINDOWS_ESC && key.inputStartsWithKey(input)) { if(Config.isOSPOSIXCompatible() && key == Key.CTRL_J) { return key.ENTER; } else if(!Config.isOSPOSIXCompatible() && key == Key.CTRL_M) { if(input.length > 1 && input[1] == Key.CTRL_J.getFirstValue()) return key.ENTER_2; else return key.ENTER; } else return key; } } //need to do this in two steps since esc/windows_esc would be returned always if(Key.ESC.inputStartsWithKey(input)) return Key.ESC; else if(Key.WINDOWS_ESC.inputStartsWithKey(input)) return Key.WINDOWS_ESC; return Key.UNKNOWN; } public static Key findStartKey(int[] input, int position) { for(Key key : values()) { if(key != Key.ESC && key != Key.WINDOWS_ESC && key.inputStartsWithKey(input, position)) { if(Config.isOSPOSIXCompatible() && key == Key.CTRL_J) { return key.ENTER; } else if(!Config.isOSPOSIXCompatible() && key == Key.CTRL_M) { if(input.length > position + 1 && input[position+1] == Key.CTRL_J.getFirstValue()) return key.ENTER_2; else return key.ENTER; } else return key; } } //need to do this in two steps since esc/windows_esc would be returned always if(Key.ESC.inputStartsWithKey(input, position)) return Key.ESC; else if(Key.WINDOWS_ESC.inputStartsWithKey(input, position)) return Key.WINDOWS_ESC; return Key.UNKNOWN; } public boolean inputStartsWithKey(int[] input) { if(keyValues.length > input.length) return false; for(int i=0; i < keyValues.length; i++) { if(keyValues[i] != input[i]) return false; } return true; } public boolean inputStartsWithKey(int[] input, int position) { if(keyValues.length+position > input.length) return false; for(int i=0; i < keyValues.length; i++) { if(keyValues[i] != input[i+position]) return false; } return true; } public boolean containKey(int[] input) { for(int i=0; i < input.length; i++) { if(input[i] == keyValues[0]) { if(keyValues.length == 1) return true; else if((i + keyValues.length) < input.length) { int j = i; for(int k : keyValues) { if(input[j] != k) { return false; } j++; } return true; } } } return false; } public boolean equalTo(int[] otherValues) { if(keyValues.length == otherValues.length) { for(int i=0; i < keyValues.length; i++) { if(keyValues[i] != otherValues[i]) return false; } return true; } return false; } }
package com.chiorichan.site; import groovy.lang.Binding; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import java.net.ConnectException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import org.json.JSONObject; import com.chiorichan.Loader; import com.chiorichan.configuration.ConfigurationSection; import com.chiorichan.configuration.file.YamlConfiguration; import com.chiorichan.database.DatabaseEngine; import com.chiorichan.event.EventException; import com.chiorichan.event.server.SiteLoadEvent; import com.chiorichan.factory.EvalFactory; import com.chiorichan.factory.EvalMetaData; import com.chiorichan.http.Routes; import com.chiorichan.lang.EvalFactoryException; import com.chiorichan.lang.SiteException; import com.chiorichan.lang.StartupException; import com.chiorichan.util.FileFunc; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; public class Site { protected String siteId = null, title = null, domain = null; protected File source, resource; protected Map<String, String> subdomains = Maps.newConcurrentMap(), aliases = Maps.newConcurrentMap(); protected List<String> metatags = Lists.newCopyOnWriteArrayList(), protectedFiles = Lists.newCopyOnWriteArrayList(); protected YamlConfiguration config; protected DatabaseEngine sql; protected SiteType siteType = SiteType.NOTSET; protected File filePath = null; protected File cacheDir = null; protected List<String> cachePatterns = Lists.newArrayList(); protected Routes routes = null; // Binding and evaling for use inside each site for executing site scripts outside of web requests. Binding binding = new Binding(); EvalFactory factory = EvalFactory.create( binding ); protected Site( File f ) throws SiteException, StartupException { siteType = SiteType.FILE; filePath = f; config = YamlConfiguration.loadConfiguration( f ); if ( config == null ) throw new SiteException( "Could not load site from YAML FileBase '" + f.getAbsolutePath() + "'" ); siteId = config.getString( "site.siteId", null ); title = config.getString( "site.title", Loader.getConfig().getString( "framework.sites.defaultTitle", "Unnamed Site" ) ); domain = config.getString( "site.domain", null ); String reason = null; if ( siteId == null ) reason = "the provided Site Id is NULL. Check configs"; else siteId = siteId.toLowerCase(); if ( domain == null ) reason = "the provided domain is NULL. Check configs"; else domain = domain.toLowerCase(); if ( Loader.getSiteManager().getSiteById( siteId ) != null ) reason = "there already exists a site by the provided Site Id '" + siteId + "'"; if ( reason != null ) throw new SiteException( "Could not load site from YAML FileBase '" + f.getAbsolutePath() + "' because " + reason + "." ); Loader.getLogger().info( "Loading site '" + siteId + "' with title '" + title + "' from YAML FileBase '" + f.getAbsolutePath() + "'." ); // Load protected files list List<?> protectedFilesPre = config.getList( "protected", new CopyOnWriteArrayList<String>() ); for ( Object o : protectedFilesPre ) { if ( o instanceof String ) protectedFiles.add( ( String ) o ); else Loader.getLogger().warning( "Site '" + siteId + "' had an incorrect data object type under the YAML config for option 'protected', found type '" + o.getClass() + "'." ); } // Load sources location String sources = config.getString( "site.source", "" ); if ( sources == null || sources.isEmpty() ) { source = getAbsoluteRoot(); } else if ( sources.startsWith( "." ) ) { source = new File( getAbsoluteRoot() + sources ); } else { source = new File( getAbsoluteRoot(), sources ); protectedFiles.add( "/" + sources ); } FileFunc.directoryHealthCheck( source ); // Load resources location String resources = config.getString( "site.resource", "resource" ); if ( resources == null || resources.isEmpty() ) { resource = getAbsoluteRoot(); } else if ( resources.startsWith( "." ) ) { resource = new File( getAbsoluteRoot() + resources ); protectedFiles.add( "/" + resources ); } else { resource = new File( getAbsoluteRoot(), resources ); protectedFiles.add( "/" + resources ); } FileFunc.directoryHealthCheck( resource ); // Load metatags List<?> metatagsPre = config.getList( "metatags", new CopyOnWriteArrayList<String>() ); for ( Object o : metatagsPre ) { if ( o instanceof String ) metatags.add( ( String ) o ); else Loader.getLogger().warning( "Site '" + siteId + "' had an incorrect data object type under the YAML config for option 'metatags', found type '" + o.getClass() + "'." ); } // Load aliases map ConfigurationSection aliasesPre = config.getConfigurationSection( "aliases" ); if ( aliasesPre != null ) { Set<String> akeys = aliasesPre.getKeys( false ); if ( akeys != null ) for ( String k : akeys ) { if ( aliasesPre.getString( k, null ) != null ) aliases.put( k, aliasesPre.getString( k ) ); } } // Loader subdomains map ConfigurationSection subdomainsPre = config.getConfigurationSection( "subdomains" ); if ( subdomainsPre != null ) { Set<String> skeys = subdomainsPre.getKeys( false ); if ( skeys != null ) for ( String k : skeys ) { if ( subdomainsPre.getString( k, null ) != null ) subdomains.put( k, subdomainsPre.getString( k ) ); } } finishLoad(); } @SuppressWarnings( "unchecked" ) protected Site( ResultSet rs ) throws SiteException, StartupException { siteType = SiteType.SQL; try { Type mapType = new TypeToken<HashMap<String, String>>() { }.getType(); siteId = rs.getString( "siteId" ); title = rs.getString( "title" ); domain = rs.getString( "domain" ); String reason = null; if ( siteId == null ) reason = "the provided Site Id is NULL. Check configs"; else siteId = siteId.toLowerCase(); if ( title == null ) title = Loader.getConfig().getString( "framework.sites.defaultTitle", "Unnamed Chiori-chan's Web Server Site" ); if ( domain == null ) reason = "the provided domain is NULL. Check configs"; else domain = domain.toLowerCase(); if ( Loader.getSiteManager().getSiteById( siteId ) != null ) reason = "there already exists a site by the provided Site Id '" + siteId + "'"; if ( reason != null ) throw new SiteException( "Could not load site from Database because " + reason + "." ); Loader.getLogger().info( "Loading site '" + siteId + "' with title '" + title + "' from Database." ); Gson gson = new GsonBuilder().create(); try { if ( !rs.getString( "protected" ).isEmpty() ) protectedFiles.addAll( gson.fromJson( new JSONObject( rs.getString( "protected" ) ).toString(), ArrayList.class ) ); } catch ( Exception e ) { Loader.getLogger().warning( "MALFORMED JSON EXPRESSION for 'protected' field for site '" + siteId + "'" ); } String sources = rs.getString( "source" ); if ( sources == null || sources.isEmpty() ) { source = getAbsoluteRoot(); } else if ( sources.startsWith( "." ) ) { source = new File( getAbsoluteRoot() + sources ); } else { source = new File( getAbsoluteRoot(), sources ); protectedFiles.add( "/" + sources ); } if ( source.isFile() ) source.delete(); if ( !source.exists() ) source.mkdirs(); String resources = rs.getString( "resource" ); if ( resources == null || resources.isEmpty() ) { resource = getAbsoluteRoot(); } else if ( resources.startsWith( "." ) ) { resource = new File( getAbsoluteRoot() + resources ); } else { resource = new File( getAbsoluteRoot(), resources ); protectedFiles.add( "/" + resources ); } if ( resource.isFile() ) resource.delete(); if ( !resource.exists() ) resource.mkdirs(); try { if ( !rs.getString( "metatags" ).isEmpty() ) metatags.addAll( gson.fromJson( new JSONObject( rs.getString( "metatags" ) ).toString(), ArrayList.class ) ); } catch ( Exception e ) { Loader.getLogger().warning( "MALFORMED JSON EXPRESSION for 'metatags' field for site '" + siteId + "'" ); } try { if ( !rs.getString( "aliases" ).isEmpty() ) aliases = gson.fromJson( new JSONObject( rs.getString( "aliases" ) ).toString(), mapType ); } catch ( Exception e ) { Loader.getLogger().warning( "MALFORMED JSON EXPRESSION for 'aliases' field for site '" + siteId + "'" ); } try { if ( !rs.getString( "subdomains" ).isEmpty() ) subdomains = gson.fromJson( new JSONObject( rs.getString( "subdomains" ) ).toString(), mapType ); } catch ( Exception e ) { Loader.getLogger().warning( "MALFORMED JSON EXPRESSION for 'subdomains' field for site '" + siteId + "'" ); } try { String yaml = rs.getString( "configYaml" ); InputStream is = new ByteArrayInputStream( yaml.getBytes( "ISO-8859-1" ) ); config = YamlConfiguration.loadConfiguration( is ); } catch ( Exception e ) { Loader.getLogger().warning( "MALFORMED YAML EXPRESSION for 'configYaml' field for site '" + siteId + "'" ); config = new YamlConfiguration(); } finishLoad(); } catch ( SQLException e ) { throw new SiteException( e ); } } private void finishLoad() throws SiteException, StartupException { // Framework site always uses the Builtin SQL Connector. Ignore YAML FileBase on this one. if ( siteId.equalsIgnoreCase( "framework" ) ) { sql = Loader.getDatabase(); } else if ( config != null && config.getConfigurationSection( "database" ) != null ) { String type = config.getString( "database.type" ); String host = config.getString( "database.host" ); String port = config.getString( "database.port" ); String database = config.getString( "database.database" ); String username = config.getString( "database.username" ); String password = config.getString( "database.password" ); String filename = config.getString( "database.filename" ); sql = new DatabaseEngine(); try { if ( type.equalsIgnoreCase( "mysql" ) ) sql.init( database, username, password, host, port ); else if ( type.equalsIgnoreCase( "sqlite" ) ) sql.init( filename ); else throw new SiteException( "The SqlConnector for site '" + siteId + "' can not support anything other then mySql or sqLite at the moment. Please change 'database.type' in the site config to 'mysql' or 'sqLite' and set the connection params." ); } catch ( SQLException e ) { if ( e.getCause() instanceof ConnectException ) throw new SiteException( "We had a problem connecting to database '" + database + "'. Reason: " + e.getCause().getMessage() ); else throw new SiteException( e.getMessage() ); } } if ( config != null ) { List<String> onLoadScripts = config.getStringList( "scripts.on-load" ); if ( onLoadScripts != null ) { for ( String script : onLoadScripts ) { try { EvalMetaData meta = new EvalMetaData(); meta.shell = "groovy"; File file = getResourceWithException( script ); String result = factory.eval( file, meta, this ).getString(); if ( result == null || result.isEmpty() ) Loader.getLogger().info( "Finsihed evaling onLoadScript '" + script + "' for site '" + siteId + "'" ); else Loader.getLogger().info( "Finsihed evaling onLoadScript '" + script + "' for site '" + siteId + "' with result: " + result ); } catch ( EvalFactoryException e ) { SiteManager.getLogger().warning( "There was an exception encountered while evaling onLoadScript '" + script + "' for site '" + siteId + "'.", e ); } catch ( FileNotFoundException e ) { SiteManager.getLogger().warning( "The onLoadScript '" + script + "' was not found for site '" + siteId + "'." ); } } } } SiteLoadEvent event = new SiteLoadEvent( this ); try { Loader.getEventBus().callEventWithException( event ); } catch ( EventException e ) { throw new SiteException( e ); } // Plugins are not permitted to cancel the loading of the framework site if ( event.isCancelled() && !siteId.equalsIgnoreCase( "framework" ) ) throw new SiteException( "Loading of site '" + siteId + "' was cancelled by an internal event." ); if ( new File( getAbsoluteRoot(), "fw" ).exists() && !siteId.equalsIgnoreCase( "framework" ) ) SiteManager.getLogger().warning( "It would appear that site '" + siteId + "' contains a subfolder by the name of 'fw', since this server uses the uri '/fw' for special functions, you will be unable to serve files from this folder!" ); } protected void save() { switch ( siteType ) { case FILE: break; case SQL: break; default: // DO NOTHING } } protected Site setDatabase( DatabaseEngine sql ) { this.sql = sql; return this; } public YamlConfiguration getYaml() { if ( config == null ) config = new YamlConfiguration(); return config; } public List<String> getMetatags() { if ( metatags == null ) return new CopyOnWriteArrayList<String>(); return metatags; } public Map<String, String> getAliases() { return aliases; } public Site( String id, String title0, String domain0 ) { siteId = id; title = title0; domain = domain0; protectedFiles = Lists.newCopyOnWriteArrayList(); metatags = Lists.newCopyOnWriteArrayList(); aliases = Maps.newLinkedHashMap(); subdomains = Maps.newLinkedHashMap(); source = getAbsoluteRoot(); resource = new File( getAbsoluteRoot(), "resource" ); if ( !source.exists() ) source.mkdirs(); if ( !resource.exists() ) resource.mkdirs(); } public boolean protectCheck( String file ) { if ( protectedFiles == null ) return false; // Does this file belong to our webroot if ( file.startsWith( getRoot() ) ) { // Strip our webroot from file file = file.substring( getRoot().length() ); for ( String n : protectedFiles ) { if ( n != null && !n.isEmpty() ) { // If the length is greater then 1 and file starts with this string. if ( n.length() > 1 && file.startsWith( n ) ) return true; // Does our file end with this. ie: .php, .txt, .etc if ( file.endsWith( n ) ) return true; // If the pattern does not start with a /, see if name contain this string. if ( !n.startsWith( "/" ) && file.contains( n ) ) return true; // Lastly try the string as a RegEx pattern if ( file.matches( n ) ) return true; } } } return false; } public File getAbsoluteRoot() { try { return getAbsoluteRoot( null ); } catch ( SiteException e ) { return null; // A SiteException will never be thrown when the subdomain is empty. } } public File getAbsoluteRoot( String subdomain ) throws SiteException { File target = new File( Loader.webroot, getRoot( subdomain ) ); if ( target.isFile() ) target.delete(); if ( !target.exists() ) target.mkdirs(); return target; } public String getRoot() { try { return getRoot( null ); } catch ( SiteException e ) { return null; // A SiteException will never be thrown when the subdomain is empty. } } public String getRoot( String subdomain ) throws SiteException { String target = siteId; if ( subdomains != null && subdomain != null && !subdomain.isEmpty() ) { String sub = subdomains.get( subdomain ); if ( sub != null ) target = siteId + "/" + sub; else if ( Loader.getConfig().getBoolean( "framework.sites.autoCreateSubdomains", true ) ) target = siteId + "/" + subdomain; else if ( !Loader.getConfig().getBoolean( "framework.sites.subdomainsDefaultToRoot" ) ) throw new SiteException( "This subdomain was not found on this server. If your the website owner, please check documentation." ); } return target; } public DatabaseEngine getDatabase() { return sql; } public String getName() { return siteId; } public File getResourceDirectory() { if ( resource == null ) resource = new File( getAbsoluteRoot(), "resource" ); return resource; } public File getCacheDirectory() { if ( cacheDir == null ) cacheDir = new File( Loader.getTempFileDirectory(), this.getSiteId() ); cacheDir.mkdirs(); return cacheDir; } public File getSourceDirectory() { if ( source == null ) source = getAbsoluteRoot(); return source; } public void setAutoSave( boolean b ) { // TODO Auto-generated method stub } // TODO: Add methods to add protected files, metatags and aliases to site and save public void setGlobal( String key, Object val ) { binding.setVariable( key, val ); } public Object getGlobal( String key ) { return binding.getVariable( key ); } @SuppressWarnings( "unchecked" ) public Map<String, Object> getGlobals() { return binding.getVariables(); } protected Binding getBinding() { return binding; } public File getResource( String packageNode ) { try { return getResourceWithException( packageNode ); } catch ( FileNotFoundException e ) { if ( !packageNode.contains( ".includes." ) ) Loader.getLogger().warning( e.getMessage() ); return null; } } public File getResourceWithException( String pack ) throws FileNotFoundException { if ( pack == null || pack.isEmpty() ) throw new FileNotFoundException( "Package can't be empty!" ); pack = pack.replace( ".", System.getProperty( "file.separator" ) ); File root = getResourceDirectory(); File packFile = new File( root, pack ); if ( packFile.exists() ) return packFile; root = packFile.getParentFile(); if ( root.exists() && root.isDirectory() ) { File[] files = root.listFiles(); String[] exts = new String[] {"html", "htm", "groovy", "gsp", "jsp", "chi"}; for ( File child : files ) if ( child.getName().startsWith( packFile.getName() ) ) for ( String ext : exts ) if ( child.getName().toLowerCase().endsWith( "." + ext ) ) return child; } throw new FileNotFoundException( "Could not find the package `" + pack + "` file in site `" + getName() + "`." ); } public String readResource( String pack ) { try { return readResourceWithException( pack ); } catch ( EvalFactoryException e ) { return ""; } } public String readResourceWithException( String pack ) throws EvalFactoryException { EvalMetaData codeMeta = new EvalMetaData(); try { File file = getResourceWithException( pack ); codeMeta.shell = "text";// FileInterpreter.determineShellFromName( file.getName() ); codeMeta.fileName = file.getAbsolutePath(); return factory.eval( file, this ).getString(); } catch ( IOException e ) { throw new EvalFactoryException( e, factory.getShellFactory() ); } } public String getSiteId() { return siteId; } public String getTitle() { return title; } public String getDomain() { return domain; } public File getFile() { return filePath; } public void addToCachePatterns( String pattern ) { if ( !cachePatterns.contains( pattern.toLowerCase() ) ) cachePatterns.add( pattern.toLowerCase() ); } public List<String> getCachePatterns() { return cachePatterns; } public Routes getRoutes() { if ( routes == null ) routes = new Routes( this ); return routes; } /** * TODO Make it so site config can change the location the the temp directory. * * @return The temp directory for this site. */ public File getTempFileDirectory() { File tmpFileDirectory = new File( Loader.getTempFileDirectory(), getSiteId() ); if ( !tmpFileDirectory.exists() ) tmpFileDirectory.mkdirs(); if ( !tmpFileDirectory.isDirectory() ) SiteManager.getLogger().severe( "The temp directory specified in the server configs is not a directory, File Uploads will FAIL until this problem is resolved." ); if ( !tmpFileDirectory.canWrite() ) SiteManager.getLogger().severe( "The temp directory specified in the server configs is not writable, File Uploads will FAIL until this problem is resolved." ); return tmpFileDirectory; } @Override public String toString() { return getSiteId() + "(Name:" + getName() + ",Title:" + title + ",Domain:" + getDomain() + ",SiteType:" + siteType + ",SourceDir:" + source + ")"; } }