answer
stringlengths
17
10.2M
package org.smerty.jham; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.smerty.jham.Passert.assertMaxError; import org.junit.Test; public class AngleTest { private static double[] anglesDeg = { 0, 45, 90, 180, 270, 360, 720, -45, -90, -180, -270, -360, 1.23, Math.PI, Math.E, Math.sqrt(2), 37.646, 51.479, 46.26519, 46.2508, 46.29106, -82.49518, -121.791, -0.458, 60.09951, 60.08436, 60.1656, -51.1908 }; @Test public void testHashCode() { Angle angle1 = new Angle(1); Angle angle2 = new Angle(1); Angle angle3 = new Angle(1.1); assertEquals(angle1, angle2); assertFalse(angle1 == angle3); } @Test public void testAngle() { Angle angle = new Angle(); assertNotNull(angle); assert (angle instanceof Angle); } @Test public void testAngleDouble() { Angle angle = new Angle(1.0); assertMaxError(1.0, angle.getRadians(), Passert.NO_ERROR); } @Test public void testEqualsObject() { Angle angle = new Angle(); Angle angle1 = new Angle(1.31); Angle angle2 = new Angle(1.31); Angle angle3 = new Angle(-2.1); assert (angle1.equals(angle2)); assert (angle2.equals(angle1)); assertFalse(angle1.equals(angle3)); assertFalse(angle1.equals(null)); assertFalse(angle1.equals(new String("hello"))); assertFalse(angle1.equals(angle)); assertFalse(angle.equals(angle1)); } @Test public void testToFromDegrees() { for (int i = 0; i < anglesDeg.length; i++) { Angle angle = Angle.fromDegrees(anglesDeg[i]); assertMaxError(anglesDeg[i], angle.toDegrees(), Passert.NO_ERROR); } for (int i = 0; i < 1000; i++) { Angle directSetRads = new Angle((double) i / 10000); assertMaxError(directSetRads.toDegrees(), directSetRads.toDegrees(), Passert.NO_ERROR); } } @Test public void testGetSetRadians() { Angle angle = new Angle(); angle.setRadians(-2); assertMaxError(-2, angle.getRadians(), Passert.NO_ERROR); } @Test public void testRadiansToDegreesToRadians() { for (int i = 0; i < anglesDeg.length; i++) { // small error is expected sometimes since we are not tracking the // original input assertMaxError(anglesDeg[i], Angle.radiansToDegrees(Angle.degreesToRadians(anglesDeg[i])), Passert.TINY_ERROR); } } @Test public void testEqualsHashCode() { Angle angle = new Angle(); Angle angle2 = new Angle(1.0); Angle angle3 = new Angle(1.0); Angle angle4 = new Angle(1.1); assertTrue(angle2.equals(angle3)); assertTrue(angle3.equals(angle2)); assertTrue(angle2.equals(angle2)); assertFalse(angle2.equals(angle)); assertFalse(angle4.equals(angle2)); assertFalse(angle2.equals(null)); assertFalse(angle2.equals(new String("moo"))); } }
package prm4j.util; import java.util.Collection; import java.util.Iterator; import java.util.Map; import prm4j.api.Alphabet; import prm4j.api.MatchHandler; import prm4j.api.Parameter; import prm4j.api.Symbol0; import prm4j.api.Symbol1; import prm4j.api.Symbol2; import prm4j.api.fsm.FSM; import prm4j.api.fsm.FSMState; import prm4j.indexing.realtime.AwareMatchHandler; import prm4j.indexing.realtime.AwareMatchHandler.AwareMatchHandler0; import prm4j.indexing.realtime.AwareMatchHandler.AwareMatchHandler1; import prm4j.indexing.realtime.AwareMatchHandler.AwareMatchHandler2; public abstract class FSMDefinitions { @SuppressWarnings("rawtypes") public static class FSM_unsafeMapIterator { public final Alphabet alphabet = new Alphabet(); public final Parameter<Map> m = alphabet.createParameter("m", Map.class); public final Parameter<Collection> c = alphabet.createParameter("c", Collection.class); public final Parameter<Iterator> i = alphabet.createParameter("i", Iterator.class); public final Symbol2<Map, Collection> createColl = alphabet.createSymbol2("createColl", m, c); public final Symbol2<Collection, Iterator> createIter = alphabet.createSymbol2("createIter", c, i); public final Symbol1<Map> updateMap = alphabet.createSymbol1("updateMap", m); public final Symbol1<Iterator> useIter = alphabet.createSymbol1("useIter", i); public final FSM fsm = new FSM(alphabet); public final AwareMatchHandler0 matchHandler = AwareMatchHandler.create(); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState s2 = fsm.createState(); public final FSMState s3 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(matchHandler); public FSM_unsafeMapIterator() { initial.addTransition(createColl, s1); initial.addTransition(updateMap, initial); s1.addTransition(updateMap, s1); s1.addTransition(createIter, s2); s2.addTransition(useIter, s2); s2.addTransition(updateMap, s3); s3.addTransition(updateMap, s3); s3.addTransition(useIter, error); } } /** * Do not call the hasNext method before the next method of an iterator. */ @SuppressWarnings("rawtypes") public class FSM_HasNext { public final Alphabet alphabet = new Alphabet(); public final Parameter<Iterator> i = alphabet.createParameter("i", Iterator.class); public final Symbol1<Iterator> hasNext = alphabet.createSymbol1("hasNext", i); public final Symbol1<Iterator> next = alphabet.createSymbol1("next", i); public final FSM fsm = new FSM(alphabet); public final AwareMatchHandler0 matchHandler = AwareMatchHandler.create(); public final FSMState initial = fsm.createInitialState(); public final FSMState safe = fsm.createState("safe"); public final FSMState error = fsm.createAcceptingState(matchHandler, "error"); public FSM_HasNext() { initial.addTransition(hasNext, safe); initial.addTransition(next, error); safe.addTransition(hasNext, safe); safe.addTransition(next, initial); error.addTransition(hasNext, safe); error.addTransition(next, error); } } @SuppressWarnings("rawtypes") public static class FSM_SafeSyncCollection { public final Alphabet alphabet = new Alphabet(); public final Parameter<Collection> c = alphabet.createParameter("c", Collection.class); public final Parameter<Iterator> i = alphabet.createParameter("i", Iterator.class); public final Symbol1<Collection> sync = alphabet.createSymbol1("sync", c); public final Symbol2<Collection, Iterator> asyncCreateIter = alphabet.createSymbol2("asyncCreateIter", c, i); public final Symbol2<Collection, Iterator> syncCreateIter = alphabet.createSymbol2("syncCreateIter", c, i); public final Symbol1<Iterator> accessIter = alphabet.createSymbol1("accessIter", i); public final FSM fsm = new FSM(alphabet); public final AwareMatchHandler0 matchHandler = AwareMatchHandler.create(); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState s2 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(matchHandler); public FSM_SafeSyncCollection() { initial.addTransition(sync, s1); s1.addTransition(asyncCreateIter, error); s1.addTransition(syncCreateIter, s2); s2.addTransition(accessIter, error); } } public static class FSM_SafeSyncCollection_NotRaw { public final Alphabet alphabet = new Alphabet(); public final Parameter<Collection<Object>> c = alphabet.addParameter(new Parameter<Collection<Object>>("c")); public final Parameter<Iterator<Object>> i = alphabet.addParameter(new Parameter<Iterator<Object>>("i")); public final Symbol1<Collection<Object>> sync = alphabet.createSymbol1("sync", c); public final Symbol2<Collection<Object>, Iterator<Object>> asyncCreateIter = alphabet.createSymbol2("asyncCreateIter", c, i); public final Symbol2<Collection<Object>, Iterator<Object>> syncCreateIter = alphabet.createSymbol2("syncCreateIter", c, i); public final Symbol1<Iterator<Object>> accessIter = alphabet.createSymbol1("accessIter", i); public final FSM fsm = new FSM(alphabet); public final AwareMatchHandler0 matchHandler = AwareMatchHandler.create(); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState s2 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(matchHandler); public FSM_SafeSyncCollection_NotRaw() { initial.addTransition(sync, s1); s1.addTransition(asyncCreateIter, error); s1.addTransition(syncCreateIter, s2); s2.addTransition(accessIter, error); } } /** * Twos <b>A</b>s trigger the error state, a <b>B</b> will end in a dead state. */ public static abstract class AbstractFSM_2symbols3states { public final Alphabet alphabet = new Alphabet(); public final Symbol0 a = alphabet.createSymbol0("a"); public final Symbol0 b = alphabet.createSymbol0("b"); public final FSM fsm = new FSM(alphabet); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(MatchHandler.NO_OP); public AbstractFSM_2symbols3states() { setupTransitions(); } public abstract void setupTransitions(); } /** * Watches for <code>e1e3</code> traces. Taken from * "Efficient Formalism-Independent Monitoring of Parametric Properties". */ public static abstract class FSM_e1e3 { public final Alphabet alphabet = new Alphabet(); public final Parameter<String> p1 = alphabet.createParameter("p1", String.class); public final Parameter<String> p2 = alphabet.createParameter("p2", String.class); public final Symbol1<String> e1 = alphabet.createSymbol1("e1", p1); public final Symbol1<String> e2 = alphabet.createSymbol1("e2", p2); public final Symbol2<String, String> e3 = alphabet.createSymbol2("e3", p1, p2); public final FSM fsm = new FSM(alphabet); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(MatchHandler.NO_OP); public FSM_e1e3() { initial.addTransition(e1, s1); initial.addTransition(e2, initial); // self-loop s1.addTransition(e3, error); } } public static class FSM_a_a_a { public final Alphabet alphabet = new Alphabet(); public final Parameter<String> p1 = alphabet.createParameter("p1", String.class); public final Symbol1<String> e1 = alphabet.createSymbol1("e1", p1); public final AwareMatchHandler1<String> matchHandler = AwareMatchHandler.create(p1); public final FSM fsm = new FSM(alphabet); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState s2 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(matchHandler); public FSM_a_a_a() { initial.addTransition(e1, s1); s1.addTransition(e1, s2); s2.addTransition(e1, error); } } public static class FSM_obj_obj { public final Alphabet alphabet = new Alphabet(); public final Parameter<Object> p1 = alphabet.createParameter("p1", Object.class); public final Symbol1<Object> e1 = alphabet.createSymbol1("e1", p1); public final AwareMatchHandler1<Object> matchHandler = AwareMatchHandler.create(p1); public final FSM fsm = new FSM(alphabet); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(matchHandler); public FSM_obj_obj() { initial.addTransition(e1, s1); s1.addTransition(e1, error); } } public static class FSM_a_ab_a_b { public final Alphabet alphabet = new Alphabet(); public final Parameter<String> p1 = alphabet.createParameter("p1", String.class); public final Parameter<String> p2 = alphabet.createParameter("p2", String.class); public final Symbol1<String> e1 = alphabet.createSymbol1("e1", p1); public final Symbol2<String, String> e2 = alphabet.createSymbol2("e2", p1, p2); public final Symbol1<String> e3 = alphabet.createSymbol1("e3", p2); public final AwareMatchHandler2<String, String> matchHandler = AwareMatchHandler.create(p1, p2); public final FSM fsm = new FSM(alphabet); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState s2 = fsm.createState(); public final FSMState s3 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(matchHandler); public FSM_a_ab_a_b() { initial.addTransition(e1, s1); s1.addTransition(e2, s2); s2.addTransition(e1, s3); s3.addTransition(e3, error); } } public static class FSM_ab_bc_c { public final Alphabet alphabet = new Alphabet(); public final Parameter<String> p1 = alphabet.createParameter("p1", String.class); public final Parameter<String> p2 = alphabet.createParameter("p2", String.class); public final Parameter<String> p3 = alphabet.createParameter("p3", String.class); public final Symbol2<String, String> e1 = alphabet.createSymbol2("e1", p1, p2); public final Symbol2<String, String> e2 = alphabet.createSymbol2("e2", p2, p3); public final Symbol1<String> e3 = alphabet.createSymbol1("e3", p3); public final AwareMatchHandler2<String, String> matchHandler = AwareMatchHandler.create(p1, p3); public final FSM fsm = new FSM(alphabet); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState s2 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(matchHandler); public FSM_ab_bc_c() { initial.addTransition(e1, s1); s1.addTransition(e2, s2); s2.addTransition(e3, error); } } /** * A sequence of as, with b destroying the trace. */ public static class FSM_ab_b_with_initial_b_loop { public final Alphabet alphabet = new Alphabet(); public final Parameter<String> p1 = alphabet.createParameter("p1", String.class); public final Parameter<String> p2 = alphabet.createParameter("p2", String.class); public final Symbol2<String, String> e1 = alphabet.createSymbol2("e1", p1, p2); public final Symbol1<String> e2 = alphabet.createSymbol1("e2", p2); public final AwareMatchHandler0 matchHandler = AwareMatchHandler.create(); public final FSM fsm = new FSM(alphabet); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(matchHandler); public FSM_ab_b_with_initial_b_loop() { initial.addTransition(e1, s1); initial.addTransition(e2, initial); s1.addTransition(e2, error); } } /** * A sequence of as, with b destroying the trace. Specifications of this kind will not be handled in the moment. */ public static class FSM_a_a_no_b { public final Alphabet alphabet = new Alphabet(); public final Parameter<String> p1 = alphabet.createParameter("p1", String.class); public final Parameter<String> p2 = alphabet.createParameter("p2", String.class); public final Symbol1<String> e1 = alphabet.createSymbol1("e1", p1); public final Symbol1<String> e2 = alphabet.createSymbol1("e2", p2); public final AwareMatchHandler0 matchHandler = AwareMatchHandler.create(); public final FSM fsm = new FSM(alphabet); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(matchHandler); public FSM_a_a_no_b() { initial.addTransition(e1, s1); initial.addTransition(e2, initial); s1.addTransition(e1, error); } } }
package us.kbase.test.auth2.cli; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static us.kbase.test.auth2.TestCommon.assertClear; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import org.bson.Document; import org.ini4j.Ini; import org.ini4j.Profile.Section; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; import us.kbase.auth2.cli.AuthCLI; import us.kbase.auth2.cli.AuthCLI.ConsoleWrapper; import us.kbase.auth2.cryptutils.PasswordCrypt; import us.kbase.auth2.lib.PasswordHashAndSalt; import us.kbase.auth2.lib.UserName; import us.kbase.auth2.lib.storage.mongo.MongoStorage; import us.kbase.common.test.controllers.mongo.MongoController; import us.kbase.test.auth2.TestCommon; public class AuthCLITest { private final static String USAGE = "Usage: manage_auth [options]\n" + " Options:\n" + " * -d, --deploy\n" + " Path to the auth deploy.cfg file.\n" + " -g, --globus-token\n" + " A Globus OAuth2 user token for use when importing users. Providing a\n" + " token without a users file does nothing.\n" + " -h, --help\n" + " Display help.\n" + " Default: false\n" + " --import-globus-users\n" + " A UTF-8 encoded file of whitespace, comma, or semicolon separated Globus\n" + " user names in the Nexus format (for example, kbasetest). A Nexus Globus token\n" + " for an admin of the kbase_users group must be provided in the -n option, and\n" + " a OAuth2 Globus token in the -g option. Globus must be configured as an\n" + " identity provider in the deploy.cfg file.\n" + " -n, --nexus-token\n" + " A Globus Nexus user token for use when importing users. Providing a token\n" + " without a users file does nothing.\n" + " -r, --set-root-password\n" + " Set the root user password. If this option is selected no other specified\n" + " operations will be executed. If the root account is disabled it will be enabled with\n" + " the enabling user set to the root user name.\n" + " Default: false\n" + " -v, --verbose\n" + " Show error stacktraces.\n" + " Default: false\n"; private final static Path WORK_DIR = Paths.get("").toAbsolutePath(); private final static String DB_NAME = "authclitest"; private static MongoController mongo; private static MongoClient mc; private static MongoDatabase db; private static MongoStorage storage; //TODO NOW make mongo test manger class that does this stuff @BeforeClass public static void beforeClass() throws Exception { TestCommon.stfuLoggers(); mongo = new MongoController(TestCommon.getMongoExe().toString(), TestCommon.getTempDir(), TestCommon.useWiredTigerEngine()); System.out.println(String.format("Testing against mongo excutable %s on port %s", TestCommon.getMongoExe(), mongo.getServerPort())); mc = new MongoClient("localhost:" + mongo.getServerPort()); db = mc.getDatabase(DB_NAME); storage = new MongoStorage(db); } @AfterClass public static void tearDownClass() throws Exception { if (mc != null) { mc.close(); } if (mongo != null) { try { mongo.destroy(TestCommon.isDeleteTempFiles()); } catch (IOException e) { System.out.println("Error deleting temporarary files at: " + TestCommon.getTempDir()); e.printStackTrace(); } } } @Before public void clearDB() throws Exception { TestCommon.destroyDB(db); } public class CollectingPrintStream extends PrintStream { public final List<Object> out = new LinkedList<>(); public CollectingPrintStream() { super(new OutputStream() { @Override public void write(int b) throws IOException { throw new UnsupportedOperationException(); } }); } @Override public void println(final Object line) { out.add(line.toString()); } @Override public void println(final String line) { out.add(line); } } @Test public void setRootPassword() throws Exception { setRootPassword("-r", "-d"); setRootPassword("--set-root-password", "--deploy"); } private void setRootPassword(final String param, final String deployparam) throws Exception { /* just checks that the record is created in the db. The detailed tests are in the * main authentication class unit tests. */ final Path deploy = generateTempConfigFile(); final ConsoleWrapper consoleMock = mock(ConsoleWrapper.class); final CollectingPrintStream out = new CollectingPrintStream(); final CollectingPrintStream err = new CollectingPrintStream(); final AuthCLI cli = new AuthCLI(new String[] {deployparam, deploy.toString(), param}, consoleMock, out, err); final char[] pwd = "foobarbazbat".toCharArray(); final char[] pwdcopy = Arrays.copyOf(pwd, pwd.length); when(consoleMock.hasConsole()).thenReturn(true); when(consoleMock.readPassword()).thenReturn(pwd); final int retcode = cli.execute(); assertThat("incorrect error", err.out, is(Collections.emptyList())); assertThat("incorrect output", out.out, is(Arrays.asList("Enter the new root password:"))); assertThat("incorrect return code", retcode, is(0)); assertClear(pwd); final PasswordHashAndSalt creds = storage.getPasswordHashAndSalt(UserName.ROOT); assertThat("incorrect creds", new PasswordCrypt().authenticate( pwdcopy, creds.getPasswordHash(), creds.getSalt()), is(true)); } private Path generateTempConfigFile() throws IOException { final Ini ini = new Ini(); final Section sec = ini.add("authserv2"); sec.add("mongo-host", "localhost:" + mongo.getServerPort()); sec.add("mongo-db", DB_NAME); sec.add("token-cookie-name", "foobar"); final Path temp = TestCommon.getTempDir(); final Path deploy = temp.resolve(Files.createTempFile(temp, "cli_test_deploy", ".cfg")); ini.store(deploy.toFile()); deploy.toFile().deleteOnExit(); System.out.println("Generated temporary config file " + deploy); return deploy; } @Test public void help() throws Exception { runCliPriorToPwdInput(new String[] {"-h"}, 0, Arrays.asList(USAGE), Collections.emptyList()); } @Test public void parseFailNulls() throws Exception { final CollectingPrintStream out = new CollectingPrintStream(); final CollectingPrintStream err = new CollectingPrintStream(); final ConsoleWrapper console = mock(ConsoleWrapper.class); failConstructCLI(null, console, out, err, new NullPointerException("args")); failConstructCLI(new String[] {}, null, out, err, new NullPointerException("console")); failConstructCLI(new String[] {}, console, null, err, new NullPointerException("out")); failConstructCLI(new String[] {}, console, out, null, new NullPointerException("err")); } @Test public void parseFailNoArgs() throws Exception { runCliPriorToPwdInput(new String[] {}, 1, Collections.emptyList(), Arrays.asList( "Error: The following option is required: -d, --deploy ")); } @Test public void parseFailVerboseOnly() throws Exception { runCliPriorToPwdInput(new String[] {"-v"}, 1, Collections.emptyList(), Arrays.asList( "Error: The following option is required: -d, --deploy ", "com.beust.jcommander.ParameterException: " + "The following option is required: -d, --deploy "), 2); } @Test public void parseFailNonsenseArgs() throws Exception { runCliPriorToPwdInput(new String[] {"foobarbazbat"}, 1, Collections.emptyList(), Arrays.asList("Error: Was passed main parameter 'foobarbazbat' " + "but no main parameter was defined")); } @Test public void parseInvalidConfigFile() throws Exception { runCliPriorToPwdInput(new String[] {"-d", "imreallyhopingthisfiledoesntexist"}, 1, Collections.emptyList(), Arrays.asList("Error: Could not read configuration file " + WORK_DIR + "/imreallyhopingthisfiledoesntexist: " + WORK_DIR + "/imreallyhopingthisfiledoesntexist " + "(No such file or directory)")); } @Test public void parseInvalidConfigFileVerbose() throws Exception { runCliPriorToPwdInput(new String[] {"-v", "-d", "imreallyhopingthisfiledoesntexist"}, 1, Collections.emptyList(), Arrays.asList("Error: Could not read configuration file " + WORK_DIR + "/imreallyhopingthisfiledoesntexist: " + WORK_DIR + "/imreallyhopingthisfiledoesntexist " + "(No such file or directory)", "us.kbase.auth2.service.exceptions.AuthConfigurationException: " + "Could not read configuration file " + WORK_DIR + "/imreallyhopingthisfiledoesntexist: " + WORK_DIR + "/imreallyhopingthisfiledoesntexist " + "(No such file or directory)"), 2); } @Test public void authStartupFail() throws Exception { db.getCollection("config").insertOne( new Document("schemaver", 40) .append("schema", "schema") .append("inupdate", false)); final Path deploy = generateTempConfigFile(); runCliPriorToPwdInput(new String[] {"-d", deploy.toString()}, 1, Collections.emptyList(), Arrays.asList("Error: Incompatible database schema. Server is v1, DB is v40")); } @Test public void incompleteArgsUsage() throws Exception { final Path deploy = generateTempConfigFile(); runCliPriorToPwdInput(new String[] {"-d", deploy.toString()}, 0, Arrays.asList(USAGE), Collections.emptyList()); } @Test public void nullConsole() throws Exception { final Path deploy = generateTempConfigFile(); final ConsoleWrapper consoleMock = mock(ConsoleWrapper.class); when(consoleMock.hasConsole()).thenReturn(false); runCliPriorToPwdInput(new String[] {"-d", deploy.toString(), "-r"}, 1, Collections.emptyList(), Arrays.asList("No console available for entering password. Aborting."), consoleMock); } @Test public void noPassword() throws Exception { final Path deploy = generateTempConfigFile(); final ConsoleWrapper consoleMock = mock(ConsoleWrapper.class); when(consoleMock.hasConsole()).thenReturn(true); when(consoleMock.readPassword()).thenReturn(null).thenReturn(new char[0]); runCliPriorToPwdInput(new String[] {"-d", deploy.toString(), "-r"}, 1, Arrays.asList("Enter the new root password:"), Arrays.asList("No password provided"), consoleMock); runCliPriorToPwdInput(new String[] {"-d", deploy.toString(), "-r"}, 1, Arrays.asList("Enter the new root password:"), Arrays.asList("No password provided"), consoleMock); } @Test public void illegalPassword() throws Exception { final Path deploy = generateTempConfigFile(); final ConsoleWrapper consoleMock = mock(ConsoleWrapper.class); when(consoleMock.hasConsole()).thenReturn(true); when(consoleMock.readPassword()).thenReturn("short".toCharArray()).thenReturn(null); runCliPriorToPwdInput(new String[] {"-d", deploy.toString(), "-r"}, 1, Arrays.asList("Enter the new root password:"), Arrays.asList("Error: 30030 Illegal password: Password is not strong enough. " + "A word by itself is easy to guess."), consoleMock); } @Test public void illegalPasswordVerbose() throws Exception { final Path deploy = generateTempConfigFile(); final ConsoleWrapper consoleMock = mock(ConsoleWrapper.class); when(consoleMock.hasConsole()).thenReturn(true); when(consoleMock.readPassword()).thenReturn("short".toCharArray()).thenReturn(null); runCliPriorToPwdInput(new String[] {"-d", deploy.toString(), "-r", "-v"}, 1, Arrays.asList("Enter the new root password:"), Arrays.asList("Error: 30030 Illegal password: Password is not strong enough. " + "A word by itself is easy to guess.", "us.kbase.auth2.lib.exceptions.IllegalPasswordException: " + "30030 Illegal password: Password is not strong enough. " + "A word by itself is easy to guess."), consoleMock, 2); } private void runCliPriorToPwdInput( final String[] args, final int retcode, final List<String> out, final List<String> err) { runCliPriorToPwdInput(args, retcode, out, err, -1); } private void runCliPriorToPwdInput( final String[] args, final int retcode, final List<String> out, final List<String> err, final ConsoleWrapper consoleMock) { runCliPriorToPwdInput(args, retcode, out, err, consoleMock, -1); } private void runCliPriorToPwdInput( final String[] args, final int retcode, final List<String> out, final List<String> err, final int numErrLines) { final ConsoleWrapper consoleMock = mock(ConsoleWrapper.class); runCliPriorToPwdInput(args, retcode, out, err, consoleMock, numErrLines); } private void runCliPriorToPwdInput( final String[] args, final int retcode, final List<String> out, final List<String> err, final ConsoleWrapper consoleMock, final int numErrLines) { final CollectingPrintStream outs = new CollectingPrintStream(); final CollectingPrintStream errs = new CollectingPrintStream(); final int ret = new AuthCLI(args, consoleMock, outs, errs).execute(); List<Object> errfinal = errs.out; if (numErrLines > 0) { errfinal = errfinal.subList(0, numErrLines); } assertThat("incorrect ret", ret, is(retcode)); assertThat("incorrect output", outs.out, is(out)); assertThat("incorrect error", errfinal, is(err)); } private void failConstructCLI( final String[] args, final ConsoleWrapper consoleMock, final CollectingPrintStream out, final CollectingPrintStream err, final Exception e) { try { new AuthCLI(args, consoleMock, out, err); fail("expected exception"); } catch (Exception got) { TestCommon.assertExceptionCorrect(got, e); } } }
package com.facebook.presto.server; import com.facebook.presto.OutputBuffers; import com.facebook.presto.ScheduledSplit; import com.facebook.presto.TaskSource; import com.facebook.presto.client.FailureInfo; import com.facebook.presto.execution.BufferInfo; import com.facebook.presto.execution.ExecutionStats.ExecutionStatsSnapshot; import com.facebook.presto.execution.RemoteTask; import com.facebook.presto.execution.SharedBuffer.QueueState; import com.facebook.presto.execution.SharedBufferInfo; import com.facebook.presto.execution.TaskInfo; import com.facebook.presto.execution.TaskState; import com.facebook.presto.metadata.Node; import com.facebook.presto.operator.OperatorStats.SplitExecutionStats; import com.facebook.presto.split.RemoteSplit; import com.facebook.presto.split.Split; import com.facebook.presto.sql.analyzer.Session; import com.facebook.presto.sql.planner.PlanFragment; import com.facebook.presto.sql.planner.plan.PlanNode; import com.facebook.presto.sql.planner.plan.PlanNodeId; import com.facebook.presto.tuple.TupleInfo; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; import com.google.common.net.HttpHeaders; import com.google.common.net.MediaType; import com.google.common.util.concurrent.AbstractFuture; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.RateLimiter; import io.airlift.http.client.AsyncHttpClient; import io.airlift.http.client.FullJsonResponseHandler.JsonResponse; import io.airlift.http.client.HttpStatus; import io.airlift.http.client.Request; import io.airlift.json.JsonCodec; import io.airlift.log.Logger; import io.airlift.units.Duration; import javax.annotation.concurrent.GuardedBy; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URI; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.CancellationException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import static com.facebook.presto.util.Failures.toFailure; import static com.google.common.collect.Iterables.transform; import static io.airlift.http.client.FullJsonResponseHandler.createFullJsonResponseHandler; import static io.airlift.http.client.HttpUriBuilder.uriBuilderFrom; import static io.airlift.http.client.JsonBodyGenerator.jsonBodyGenerator; import static io.airlift.http.client.Request.Builder.prepareDelete; import static io.airlift.http.client.Request.Builder.preparePost; public class HttpRemoteTask implements RemoteTask { private static final Logger log = Logger.get(HttpRemoteTask.class); private static final int MAX_CONSECUTIVE_ERROR_COUNT = 10; private static final Duration MIN_ERROR_DURATION = new Duration(30, TimeUnit.SECONDS); private final Session session; private final String nodeId; private final PlanFragment planFragment; private final AtomicLong nextSplitId = new AtomicLong(); @GuardedBy("this") private TaskInfo taskInfo; @GuardedBy("this") private boolean canceled; @GuardedBy("this") private CurrentRequest currentRequest; @GuardedBy("this") private final SetMultimap<PlanNodeId, ScheduledSplit> pendingSplits = HashMultimap.create(); @GuardedBy("this") private boolean noMoreSplits; @GuardedBy("this") private final SetMultimap<PlanNodeId, URI> exchangeLocations = HashMultimap.create(); @GuardedBy("this") private boolean noMoreExchangeLocations; @GuardedBy("this") private final Set<String> outputIds = new TreeSet<>(); @GuardedBy("this") private boolean noMoreOutputIds; private final AsyncHttpClient httpClient; private final JsonCodec<TaskInfo> taskInfoCodec; private final JsonCodec<TaskUpdateRequest> taskUpdateRequestCodec; private final List<TupleInfo> tupleInfos; private final RateLimiter requestRateLimiter = RateLimiter.create(10); private final AtomicLong lastSuccessfulRequest = new AtomicLong(System.nanoTime()); private final AtomicLong consecutiveErrorCount = new AtomicLong(); public HttpRemoteTask(Session session, String queryId, String stageId, String taskId, Node node, URI location, PlanFragment planFragment, Split initialSplit, Multimap<PlanNodeId, URI> initialExchangeLocations, Set<String> initialOutputIds, AsyncHttpClient httpClient, JsonCodec<TaskInfo> taskInfoCodec, JsonCodec<TaskUpdateRequest> taskUpdateRequestCodec) { Preconditions.checkNotNull(session, "session is null"); Preconditions.checkNotNull(queryId, "queryId is null"); Preconditions.checkNotNull(stageId, "stageId is null"); Preconditions.checkNotNull(taskId, "taskId is null"); Preconditions.checkNotNull(location, "location is null"); Preconditions.checkNotNull(planFragment, "planFragment1 is null"); Preconditions.checkNotNull(initialOutputIds, "initialOutputIds is null"); Preconditions.checkNotNull(httpClient, "httpClient is null"); Preconditions.checkNotNull(taskInfoCodec, "taskInfoCodec is null"); Preconditions.checkNotNull(taskUpdateRequestCodec, "taskUpdateRequestCodec is null"); this.session = session; this.nodeId = node.getNodeIdentifier(); this.planFragment = planFragment; this.outputIds.addAll(initialOutputIds); this.httpClient = httpClient; this.taskInfoCodec = taskInfoCodec; this.taskUpdateRequestCodec = taskUpdateRequestCodec; tupleInfos = planFragment.getTupleInfos(); for (Entry<PlanNodeId, URI> entry : initialExchangeLocations.entries()) { ScheduledSplit scheduledSplit = new ScheduledSplit(nextSplitId.getAndIncrement(), createRemoteSplitFor(entry.getValue())); pendingSplits.put(entry.getKey(), scheduledSplit); } this.exchangeLocations.putAll(initialExchangeLocations); List<BufferInfo> bufferStates = ImmutableList.copyOf(transform(initialOutputIds, new Function<String, BufferInfo>() { @Override public BufferInfo apply(String outputId) { return new BufferInfo(outputId, false, 0, 0); } })); if (initialSplit != null) { Preconditions.checkState(planFragment.isPartitioned(), "Plan is not partitioned"); pendingSplits.put(planFragment.getPartitionedSource(), new ScheduledSplit(nextSplitId.getAndIncrement(), initialSplit)); } taskInfo = new TaskInfo(queryId, stageId, taskId, TaskInfo.MIN_VERSION, TaskState.PLANNED, location, new SharedBufferInfo(QueueState.OPEN, 0, bufferStates), ImmutableSet.<PlanNodeId>of(), new ExecutionStatsSnapshot(), ImmutableList.<SplitExecutionStats>of(), ImmutableList.<FailureInfo>of()); } @Override public synchronized String getTaskId() { return taskInfo.getTaskId(); } @Override public synchronized TaskInfo getTaskInfo() { return taskInfo; } @Override public void addSplit(Split split) { synchronized (this) { Preconditions.checkNotNull(split, "split is null"); Preconditions.checkState(!noMoreSplits, "noMoreSplits has already been set"); Preconditions.checkState(planFragment.isPartitioned(), "Plan is not partitioned"); // only add pending split if not canceled if (!canceled) { pendingSplits.put(planFragment.getPartitionedSource(), new ScheduledSplit(nextSplitId.getAndIncrement(), split)); } } updateState(false); } @Override public void noMoreSplits() { synchronized (this) { Preconditions.checkState(!noMoreSplits, "noMoreSplits has already been set"); noMoreSplits = true; } updateState(false); } @Override public void addExchangeLocations(Multimap<PlanNodeId, URI> additionalLocations, boolean noMore) { // determine which locations are new synchronized (this) { Preconditions.checkState(!noMoreExchangeLocations || exchangeLocations.entries().containsAll(additionalLocations.entries()), "Locations can not be added after noMoreExchangeLocations has been set"); SetMultimap<PlanNodeId, URI> newExchangeLocations = HashMultimap.create(additionalLocations); newExchangeLocations.entries().removeAll(exchangeLocations.entries()); // only add pending split if not canceled if (!canceled) { for (Entry<PlanNodeId, URI> entry : newExchangeLocations.entries()) { ScheduledSplit scheduledSplit = new ScheduledSplit(nextSplitId.getAndIncrement(), createRemoteSplitFor(entry.getValue())); pendingSplits.put(entry.getKey(), scheduledSplit); } } noMoreExchangeLocations = noMore; this.exchangeLocations.putAll(additionalLocations); } updateState(false); } @Override public void addOutputBuffers(Set<String> outputBuffers, boolean noMore) { synchronized (this) { if (noMoreOutputIds == noMore && this.outputIds.containsAll(outputBuffers)) { // duplicate request return; } Preconditions.checkState(!noMoreOutputIds, "New buffers can not be added after noMoreOutputIds has been set"); noMoreOutputIds = noMore; this.outputIds.addAll(outputBuffers); } updateState(false); } private synchronized void updateTaskInfo(TaskInfo newValue) { if (taskInfo.getState().isDone()) { // never update if the task has reached a terminal state return; } if (newValue.getVersion() < taskInfo.getVersion()) { // don't update to an older version (same version is ok) return; } taskInfo = newValue; if (newValue.getState().isDone()) { // splits can be huge so clear the list pendingSplits.clear(); } } @Override public ListenableFuture<?> updateState(boolean forceRefresh) { Preconditions.checkState(!Thread.holdsLock(this), "Update state can not be called while holding a lock on this"); Request request; CurrentRequest currentRequest; synchronized (this) { // don't update if the task hasn't been started yet or if it is already finished if (taskInfo.getState().isDone()) { return Futures.immediateFuture(null); } if (!forceRefresh) { if (this.currentRequest != null) { // if current request is old, cancel it so we can begin a new request this.currentRequest.cancelIfOlderThan(new Duration(2, TimeUnit.SECONDS)); if (!this.currentRequest.isDone()) { // request is still running, but when it finishes, it should update again this.currentRequest.requestAnotherUpdate(); // todo return existing pending request future? return Futures.immediateFuture(null); } this.currentRequest = null; } // don't update too fast if (!requestRateLimiter.tryAcquire()) { // todo return existing pending request future? return Futures.immediateFuture(null); } } List<TaskSource> sources = getSources(); currentRequest = new CurrentRequest(sources); if (canceled) { request = prepareDelete().setUri(taskInfo.getSelf()).build(); } else { TaskUpdateRequest updateRequest = new TaskUpdateRequest(session, taskInfo.getQueryId(), taskInfo.getStageId(), planFragment, sources, new OutputBuffers(outputIds, noMoreOutputIds)); request = preparePost() .setUri(uriBuilderFrom(taskInfo.getSelf()).build()) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()) .setBodyGenerator(jsonBodyGenerator(taskUpdateRequestCodec, updateRequest)) .build(); } this.currentRequest = currentRequest; } ListenableFuture<JsonResponse<TaskInfo>> future = httpClient.executeAsync(request, createFullJsonResponseHandler(taskInfoCodec)); currentRequest.setRequestFuture(future); return currentRequest; } @Override public synchronized int getQueuedSplits() { int pendingSplitCount = 0; if (planFragment.isPartitioned()) { pendingSplitCount = pendingSplits.get(planFragment.getPartitionedSource()).size(); } return pendingSplitCount + taskInfo.getStats().getQueuedSplits(); } private synchronized List<TaskSource> getSources() { ImmutableList.Builder<TaskSource> sources = ImmutableList.builder(); if (planFragment.isPartitioned()) { Set<ScheduledSplit> splits = pendingSplits.get(planFragment.getPartitionedSource()); if (!splits.isEmpty() || noMoreSplits) { sources.add(new TaskSource(planFragment.getPartitionedSource(), splits, noMoreSplits)); } } for (PlanNode planNode : planFragment.getSources()) { PlanNodeId planNodeId = planNode.getId(); if (!planNodeId.equals(planFragment.getPartitionedSource())) { Set<ScheduledSplit> splits = pendingSplits.get(planNodeId); if (!splits.isEmpty() || noMoreExchangeLocations) { sources.add(new TaskSource(planNodeId, splits, noMoreExchangeLocations)); } } } return sources.build(); } private synchronized void acknowledgeSources(List<TaskSource> sources) { for (TaskSource source : sources) { PlanNodeId planNodeId = source.getPlanNodeId(); for (ScheduledSplit split : source.getSplits()) { pendingSplits.remove(planNodeId, split); } } } @Override public void cancel() { CurrentRequest requestToCancel = null; synchronized (this) { pendingSplits.clear(); if (!canceled) { requestToCancel = currentRequest; canceled = true; } } // must cancel out side of synchronized block to avoid potential deadlocks if (requestToCancel != null) { requestToCancel.cancel(true); } updateState(false); } private void requestFailed() { consecutiveErrorCount.incrementAndGet(); // fail the task, if we have more than X failures in a row and more than Y seconds have passed since the last request if (consecutiveErrorCount.get() > MAX_CONSECUTIVE_ERROR_COUNT && Duration.nanosSince(lastSuccessfulRequest.get()).compareTo(MIN_ERROR_DURATION) > 0) { // it is weird to mark the task failed locally and then cancel the remote task, but there is no way to tell a remote task that it is failed failTask(new RuntimeException("Too many requests failed")); cancel(); } } /** * Move the task directly to the failed state */ private void failTask(Exception cause) { TaskInfo taskInfo = getTaskInfo(); updateTaskInfo(new TaskInfo(taskInfo.getQueryId(), taskInfo.getStageId(), taskInfo.getTaskId(), TaskInfo.MAX_VERSION, TaskState.FAILED, taskInfo.getSelf(), taskInfo.getOutputBuffers(), taskInfo.getNoMoreSplits(), taskInfo.getStats(), ImmutableList.<SplitExecutionStats>of(), ImmutableList.of(toFailure(cause)))); } private RemoteSplit createRemoteSplitFor(URI taskLocation) { URI splitLocation = uriBuilderFrom(taskLocation).appendPath("results").appendPath(nodeId).build(); return new RemoteSplit(splitLocation, tupleInfos); } @Override public String toString() { return Objects.toStringHelper(this) .addValue(getTaskInfo()) .toString(); } private class CurrentRequest extends AbstractFuture<Void> implements FutureCallback<JsonResponse<TaskInfo>> { private final long startTime = System.nanoTime(); private final List<TaskSource> sources; @GuardedBy("this") private Future<?> requestFuture; @GuardedBy("this") private boolean anotherUpdateRequested; private CurrentRequest(List<TaskSource> sources) { this.sources = ImmutableList.copyOf(sources); } public void requestAnotherUpdate() { synchronized (HttpRemoteTask.this) { this.anotherUpdateRequested = true; } } public void setRequestFuture(ListenableFuture<JsonResponse<TaskInfo>> requestFuture) { synchronized (HttpRemoteTask.this) { Preconditions.checkNotNull(requestFuture, "requestFuture is null"); Preconditions.checkState(this.requestFuture == null, "requestFuture already set"); this.requestFuture = requestFuture; } if (isDone()) { requestFuture.cancel(true); } else { Futures.addCallback(requestFuture, this); } } public boolean cancel(boolean mayInterruptIfRunning) { Future<?> requestToCancel; synchronized (HttpRemoteTask.this) { requestToCancel = requestFuture; } // must cancel out side of synchronized block to avoid potential deadlocks if (requestToCancel != null) { requestFuture.cancel(true); } return super.cancel(true); } public void cancelIfOlderThan(Duration maxRequestTime) { if (isDone() || Duration.nanosSince(startTime).compareTo(maxRequestTime) < 0) { return; } cancel(true); } @Override public void onSuccess(JsonResponse<TaskInfo> response) { try { TaskInfo taskInfo = getTaskInfo(); if (response.getStatusCode() == HttpStatus.OK.code() && response.hasValue()) { // update task info updateTaskInfo(response.getValue()); lastSuccessfulRequest.set(System.nanoTime()); consecutiveErrorCount.set(0); // remove acknowledged splits, which frees memory acknowledgeSources(sources); updateIfNecessary(); } else if (response.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR.code()) { // log failure log.debug(String.format("Server at %s returned %s: %s", taskInfo.getSelf(), response.getStatusCode(), response.getStatusMessage())); requestFailed(); updateState(false); } else if (response.getStatusCode() == HttpStatus.SERVICE_UNAVAILABLE.code()) { requestFailed(); // don't update immediately so the server can get a break } else { // Something is broken in the server or the client, so fail the task immediately Exception cause = response.getException(); if (cause == null) { cause = new RuntimeException(String.format("Expected response code from %s to be %s, but was %s: %s", taskInfo.getSelf(), HttpStatus.OK.code(), response.getStatusCode(), response.getStatusMessage())); } failTask(cause); } } catch (Throwable t) { setException(t); requestFailed(); } finally { set(null); } } private void updateIfNecessary() { synchronized (HttpRemoteTask.this) { if (!anotherUpdateRequested) { return; } // if this is no longer the current request, don't do anything if (currentRequest != this) { return; } } updateState(false); } @Override public void onFailure(Throwable t) { synchronized (HttpRemoteTask.this) { setException(t); if (!(t instanceof CancellationException)) { TaskInfo taskInfo = getTaskInfo(); if (isSocketError(t)) { log.warn("%s task %s: %s: %s", "Error updating", taskInfo.getTaskId(), t.getMessage(), taskInfo.getSelf()); } else { log.warn(t, "%s task %s: %s", "Error updating", taskInfo.getTaskId(), taskInfo.getSelf()); } } } requestFailed(); updateState(false); } private boolean isSocketError(Throwable t) { while (t != null) { if ((t instanceof SocketException) || (t instanceof SocketTimeoutException)) { return true; } t = t.getCause(); } return false; } } }
package gov.nih.nci.cabig.caaers.domain; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; /** * @author Krikor Krumlian * @author Kulasekaran */ @Entity @Table (name = "study_sites") @GenericGenerator(name="id-generator", strategy = "native", parameters = { @Parameter(name="sequence", value="seq_study_sites_id") } ) public class StudySite extends AbstractDomainObject { private Site site; private Study study; private Date irbApprovalDate; private String roleCode; private String statusCode; private Date startDate; private Date endDate; private List<StudyParticipantAssignment> studyParticipantAssignments = new ArrayList<StudyParticipantAssignment>(); private List<StudyInvestigator> studyInvestigators = new ArrayList<StudyInvestigator>(); private List<StudyPersonnel> studyPersonnels = new ArrayList<StudyPersonnel>(); //////LOGIC public void addStudyPersonnel(StudyPersonnel studyPersonnel) { studyPersonnels.add(studyPersonnel); studyPersonnel.setStudySite(this); } public void addStudyInvestigators(StudyInvestigator studyInvestigator) { getStudyInvestigators().add(studyInvestigator); studyInvestigator.setStudySite(this); } public void addAssignment(StudyParticipantAssignment assignment) { getStudyParticipantAssignments().add(assignment); assignment.setStudySite(this); } /** Are there any assignments using this relationship? */ @Transient public boolean isUsed() { return getStudyParticipantAssignments().size() > 0; } @Transient public String getSiteStudyNames() { return study.getShortTitle() + " : " + site.getName(); } /// BEAN PROPERTIES public void setSite(Site site) { this.site = site; } @ManyToOne @JoinColumn(name = "site_id") public Site getSite() { return site; } public void setStudy(Study study) { this.study = study; } @ManyToOne @JoinColumn(name = "study_id") public Study getStudy() { return study; } public void setStudyParticipantAssignments(List<StudyParticipantAssignment> studyParticipantAssignments) { this.studyParticipantAssignments = studyParticipantAssignments; } @OneToMany (mappedBy = "studySite") @Cascade (value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) public List<StudyParticipantAssignment> getStudyParticipantAssignments() { return studyParticipantAssignments; } @OneToMany (mappedBy = "studySite") @Cascade (value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) public List<StudyInvestigator> getStudyInvestigators() { return studyInvestigators; } public void setStudyInvestigators(List<StudyInvestigator> studyInvestigators) { this.studyInvestigators = studyInvestigators; } public void setIrbApprovalDate(Date irbApprovalDate) { this.irbApprovalDate = irbApprovalDate; } public Date getIrbApprovalDate() { return irbApprovalDate; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public String getStatusCode() { return statusCode; } public void setStatusCode(String statusCode) { this.statusCode = statusCode; } public String getRoleCode() { return roleCode; } public void setRoleCode(String roleCode) { this.roleCode = roleCode; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } @OneToMany (mappedBy = "studySite", fetch=FetchType.LAZY) @Cascade (value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) public List<StudyPersonnel> getStudyPersonnels() { return studyPersonnels; } public void setStudyPersonnels(List<StudyPersonnel> studyPersonnels) { this.studyPersonnels = studyPersonnels; } //////OBJECT METHODS /* public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof StudySite)) return false; final StudySite studySite = (StudySite) obj; Study study = studySite.getStudy(); Site site = studySite.getSite(); if (!getStudy().equals(study)) return false; if (!getSite().equals(site)) return false; return true; } public int hashCode() { int result; result = (site != null ? site.hashCode() : 0); //result = 29 * result + (study != null ? study.hashCode() : 0); result = 29 * result + (studyParticipantAssignments != null ? studyParticipantAssignments.hashCode() : 0); return result; } */ }
package org.bouncycastle.jce.provider; import java.io.IOException; import java.security.AccessController; import java.security.PrivateKey; import java.security.PrivilegedAction; import java.security.Provider; import java.security.PublicKey; import java.util.HashMap; import java.util.Map; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.config.ProviderConfiguration; import org.bouncycastle.jcajce.provider.util.AlgorithmProvider; import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; /** * To add the provider at runtime use: * <pre> * import java.security.Security; * import org.bouncycastle.jce.provider.BouncyCastleProvider; * * Security.addProvider(new BouncyCastleProvider()); * </pre> * The provider can also be configured as part of your environment via * static registration by adding an entry to the java.security properties * file (found in $JAVA_HOME/jre/lib/security/java.security, where * $JAVA_HOME is the location of your JDK/JRE distribution). You'll find * detailed instructions in the file but basically it comes down to adding * a line: * <pre> * <code> * security.provider.&lt;n&gt;=org.bouncycastle.jce.provider.BouncyCastleProvider * </code> * </pre> * Where &lt;n&gt; is the preference you want the provider at (1 being the * most preferred). * <p>Note: JCE algorithm names should be upper-case only so the case insensitive * test for getInstance works. */ public final class BouncyCastleProvider extends Provider implements ConfigurableProvider { private static String info = "BouncyCastle Security Provider v1.55b"; public static final String PROVIDER_NAME = "BC"; public static final ProviderConfiguration CONFIGURATION = new BouncyCastleProviderConfiguration(); private static final Map keyInfoConverters = new HashMap(); /* * Configurable symmetric ciphers */ private static final String SYMMETRIC_PACKAGE = "org.bouncycastle.jcajce.provider.symmetric."; private static final String[] SYMMETRIC_GENERIC = { "PBEPBKDF2", "PBEPKCS12" }; private static final String[] SYMMETRIC_MACS = { "SipHash" }; private static final String[] SYMMETRIC_CIPHERS = { "AES", "ARC4", "Blowfish", "Camellia", "CAST5", "CAST6", "ChaCha", "DES", "DESede", "GOST28147", "Grainv1", "Grain128", "HC128", "HC256", "IDEA", "Noekeon", "RC2", "RC5", "RC6", "Rijndael", "Salsa20", "SEED", "Serpent", "Shacal2", "Skipjack", "SM4", "TEA", "Twofish", "Threefish", "VMPC", "VMPCKSA3", "XTEA", "XSalsa20", "OpenSSLPBKDF" }; /* * Configurable asymmetric ciphers */ private static final String ASYMMETRIC_PACKAGE = "org.bouncycastle.jcajce.provider.asymmetric."; // this one is required for GNU class path - it needs to be loaded first as the // later ones configure it. private static final String[] ASYMMETRIC_GENERIC = { "X509", "IES" }; private static final String[] ASYMMETRIC_CIPHERS = { "DSA", "DH", "EC", "RSA", "GOST", "ECGOST", "ElGamal", "DSTU4145" }; /* * Configurable digests */ private static final String DIGEST_PACKAGE = "org.bouncycastle.jcajce.provider.digest."; private static final String[] DIGESTS = { "GOST3411", "Keccak", "MD2", "MD4", "MD5", "SHA1", "RIPEMD128", "RIPEMD160", "RIPEMD256", "RIPEMD320", "SHA224", "SHA256", "SHA384", "SHA512", "SHA3", "Skein", "SM3", "Tiger", "Whirlpool", "Blake2b" }; /* * Configurable keystores */ private static final String KEYSTORE_PACKAGE = "org.bouncycastle.jcajce.provider.keystore."; private static final String[] KEYSTORES = { "BC", "PKCS12" }; /** * Construct a new provider. This should only be required when * using runtime registration of the provider using the * <code>Security.addProvider()</code> mechanism. */ public BouncyCastleProvider() { super(PROVIDER_NAME, 1.545, info); AccessController.doPrivileged(new PrivilegedAction() { public Object run() { setup(); return null; } }); } private void setup() { loadAlgorithms(DIGEST_PACKAGE, DIGESTS); loadAlgorithms(SYMMETRIC_PACKAGE, SYMMETRIC_GENERIC); loadAlgorithms(SYMMETRIC_PACKAGE, SYMMETRIC_MACS); loadAlgorithms(SYMMETRIC_PACKAGE, SYMMETRIC_CIPHERS); loadAlgorithms(ASYMMETRIC_PACKAGE, ASYMMETRIC_GENERIC); loadAlgorithms(ASYMMETRIC_PACKAGE, ASYMMETRIC_CIPHERS); loadAlgorithms(KEYSTORE_PACKAGE, KEYSTORES); // X509Store put("X509Store.CERTIFICATE/COLLECTION", "org.bouncycastle.jce.provider.X509StoreCertCollection"); put("X509Store.ATTRIBUTECERTIFICATE/COLLECTION", "org.bouncycastle.jce.provider.X509StoreAttrCertCollection"); put("X509Store.CRL/COLLECTION", "org.bouncycastle.jce.provider.X509StoreCRLCollection"); put("X509Store.CERTIFICATEPAIR/COLLECTION", "org.bouncycastle.jce.provider.X509StoreCertPairCollection"); put("X509Store.CERTIFICATE/LDAP", "org.bouncycastle.jce.provider.X509StoreLDAPCerts"); put("X509Store.CRL/LDAP", "org.bouncycastle.jce.provider.X509StoreLDAPCRLs"); put("X509Store.ATTRIBUTECERTIFICATE/LDAP", "org.bouncycastle.jce.provider.X509StoreLDAPAttrCerts"); put("X509Store.CERTIFICATEPAIR/LDAP", "org.bouncycastle.jce.provider.X509StoreLDAPCertPairs"); // X509StreamParser put("X509StreamParser.CERTIFICATE", "org.bouncycastle.jce.provider.X509CertParser"); put("X509StreamParser.ATTRIBUTECERTIFICATE", "org.bouncycastle.jce.provider.X509AttrCertParser"); put("X509StreamParser.CRL", "org.bouncycastle.jce.provider.X509CRLParser"); put("X509StreamParser.CERTIFICATEPAIR", "org.bouncycastle.jce.provider.X509CertPairParser"); // cipher engines put("Cipher.BROKENPBEWITHMD5ANDDES", "org.bouncycastle.jce.provider.BrokenJCEBlockCipher$BrokePBEWithMD5AndDES"); put("Cipher.BROKENPBEWITHSHA1ANDDES", "org.bouncycastle.jce.provider.BrokenJCEBlockCipher$BrokePBEWithSHA1AndDES"); put("Cipher.OLDPBEWITHSHAANDTWOFISH-CBC", "org.bouncycastle.jce.provider.BrokenJCEBlockCipher$OldPBEWithSHAAndTwofish"); // Certification Path API put("CertPathValidator.RFC3281", "org.bouncycastle.jce.provider.PKIXAttrCertPathValidatorSpi"); put("CertPathBuilder.RFC3281", "org.bouncycastle.jce.provider.PKIXAttrCertPathBuilderSpi"); put("CertPathValidator.RFC3280", "org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi"); put("CertPathBuilder.RFC3280", "org.bouncycastle.jce.provider.PKIXCertPathBuilderSpi"); put("CertPathValidator.PKIX", "org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi"); put("CertPathBuilder.PKIX", "org.bouncycastle.jce.provider.PKIXCertPathBuilderSpi"); put("CertStore.Collection", "org.bouncycastle.jce.provider.CertStoreCollectionSpi"); put("CertStore.LDAP", "org.bouncycastle.jce.provider.X509LDAPCertStoreSpi"); put("CertStore.Multi", "org.bouncycastle.jce.provider.MultiCertStoreSpi"); put("Alg.Alias.CertStore.X509LDAP", "LDAP"); } private void loadAlgorithms(String packageName, String[] names) { for (int i = 0; i != names.length; i++) { Class clazz = null; try { ClassLoader loader = this.getClass().getClassLoader(); if (loader != null) { clazz = loader.loadClass(packageName + names[i] + "$Mappings"); } else { clazz = Class.forName(packageName + names[i] + "$Mappings"); } } catch (ClassNotFoundException e) { // ignore } if (clazz != null) { try { ((AlgorithmProvider)clazz.newInstance()).configure(this); } catch (Exception e) { // this should never ever happen!! throw new InternalError("cannot create instance of " + packageName + names[i] + "$Mappings : " + e); } } } } public void setParameter(String parameterName, Object parameter) { synchronized (CONFIGURATION) { ((BouncyCastleProviderConfiguration)CONFIGURATION).setParameter(parameterName, parameter); } } public boolean hasAlgorithm(String type, String name) { return containsKey(type + "." + name) || containsKey("Alg.Alias." + type + "." + name); } public void addAlgorithm(String key, String value) { if (containsKey(key)) { throw new IllegalStateException("duplicate provider key (" + key + ") found"); } put(key, value); } public void addAlgorithm(String type, ASN1ObjectIdentifier oid, String className) { addAlgorithm(type + "." + oid, className); addAlgorithm(type + ".OID." + oid, className); } public void addKeyInfoConverter(ASN1ObjectIdentifier oid, AsymmetricKeyInfoConverter keyInfoConverter) { synchronized (keyInfoConverters) { keyInfoConverters.put(oid, keyInfoConverter); } } private static AsymmetricKeyInfoConverter getAsymmetricKeyInfoConverter(ASN1ObjectIdentifier algorithm) { synchronized (keyInfoConverters) { return (AsymmetricKeyInfoConverter)keyInfoConverters.get(algorithm); } } public static PublicKey getPublicKey(SubjectPublicKeyInfo publicKeyInfo) throws IOException { AsymmetricKeyInfoConverter converter = getAsymmetricKeyInfoConverter(publicKeyInfo.getAlgorithm().getAlgorithm()); if (converter == null) { return null; } return converter.generatePublic(publicKeyInfo); } public static PrivateKey getPrivateKey(PrivateKeyInfo privateKeyInfo) throws IOException { AsymmetricKeyInfoConverter converter = getAsymmetricKeyInfoConverter(privateKeyInfo.getPrivateKeyAlgorithm().getAlgorithm()); if (converter == null) { return null; } return converter.generatePrivate(privateKeyInfo); } }
package com.mysema.query.codegen; import static com.mysema.codegen.Symbols.ASSIGN; import static com.mysema.codegen.Symbols.COMMA; import static com.mysema.codegen.Symbols.DOT; import static com.mysema.codegen.Symbols.DOT_CLASS; import static com.mysema.codegen.Symbols.EMPTY; import static com.mysema.codegen.Symbols.NEW; import static com.mysema.codegen.Symbols.QUOTE; import static com.mysema.codegen.Symbols.RETURN; import static com.mysema.codegen.Symbols.SEMICOLON; import static com.mysema.codegen.Symbols.STAR; import static com.mysema.codegen.Symbols.SUPER; import static com.mysema.codegen.Symbols.THIS; import static com.mysema.codegen.Symbols.UNCHECKED; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.inject.Inject; import javax.inject.Named; import net.jcip.annotations.Immutable; import org.apache.commons.collections15.Transformer; import org.apache.commons.lang.StringUtils; import com.mysema.codegen.CodeWriter; import com.mysema.codegen.model.ClassType; import com.mysema.codegen.model.Constructor; import com.mysema.codegen.model.Parameter; import com.mysema.codegen.model.SimpleType; import com.mysema.codegen.model.Type; import com.mysema.codegen.model.TypeCategory; import com.mysema.codegen.model.TypeExtends; import com.mysema.codegen.model.Types; import com.mysema.commons.lang.Assert; import com.mysema.query.types.ConstructorExpression; import com.mysema.query.types.Expression; import com.mysema.query.types.Path; import com.mysema.query.types.PathMetadata; import com.mysema.query.types.PathMetadataFactory; import com.mysema.query.types.expr.ComparableExpression; import com.mysema.query.types.path.ArrayPath; import com.mysema.query.types.path.BeanPath; import com.mysema.query.types.path.BooleanPath; import com.mysema.query.types.path.CollectionPath; import com.mysema.query.types.path.ComparablePath; import com.mysema.query.types.path.DatePath; import com.mysema.query.types.path.DateTimePath; import com.mysema.query.types.path.EntityPathBase; import com.mysema.query.types.path.EnumPath; import com.mysema.query.types.path.ListPath; import com.mysema.query.types.path.MapPath; import com.mysema.query.types.path.NumberPath; import com.mysema.query.types.path.PathInits; import com.mysema.query.types.path.SetPath; import com.mysema.query.types.path.SimplePath; import com.mysema.query.types.path.StringPath; import com.mysema.query.types.path.TimePath; /** * EntitySerializer is a Serializer implementation for entity types * * @author tiwe * */ @Immutable public class EntitySerializer implements Serializer{ private static final Parameter PATH_METADATA = new Parameter("metadata", new ClassType(PathMetadata.class, (Type)null)); private static final Parameter PATH_INITS = new Parameter("inits", new ClassType(PathInits.class)); protected final TypeMappings typeMappings; protected final Collection<String> keywords; @Inject public EntitySerializer(TypeMappings mappings, @Named("keywords") Collection<String> keywords){ this.typeMappings = Assert.notNull(mappings,"mappings"); this.keywords = Assert.notNull(keywords,"keywords"); } protected void constructors(EntityType model, SerializerConfig config, CodeWriter writer) throws IOException { String localName = writer.getRawName(model); String genericName = writer.getGenericName(true, model); boolean hasEntityFields = model.hasEntityFields(); String thisOrSuper = hasEntityFields ? THIS : SUPER; boolean stringOrBoolean = model.getOriginalCategory() == TypeCategory.STRING || model.getOriginalCategory() == TypeCategory.BOOLEAN; constructorsForVariables(writer, model); if (!hasEntityFields){ if (model.isFinal()){ Type type = new ClassType(BeanPath.class, model); writer.beginConstructor(new Parameter("entity", type)); }else{ Type type = new ClassType(BeanPath.class, new TypeExtends(model)); writer.beginConstructor(new Parameter("entity", type)); } if (stringOrBoolean){ writer.line("super(entity.getMetadata());"); }else{ writer.line("super(entity.getType(), entity.getMetadata());"); } writer.end(); } if (hasEntityFields){ writer.beginConstructor(PATH_METADATA); writer.line("this(metadata, metadata.isRoot() ? INITS : PathInits.DEFAULT);"); writer.end(); }else{ if (!localName.equals(genericName)){ writer.suppressWarnings(UNCHECKED); } writer.beginConstructor(PATH_METADATA); if (stringOrBoolean){ writer.line("super(metadata);"); }else{ writer.line("super(", localName.equals(genericName) ? EMPTY : "(Class)", localName, ".class, metadata);"); } writer.end(); } if (hasEntityFields){ if (!localName.equals(genericName)){ writer.suppressWarnings(UNCHECKED); } writer.beginConstructor(PATH_METADATA, PATH_INITS); writer.line(thisOrSuper, "(", localName.equals(genericName) ? EMPTY : "(Class)", localName, ".class, metadata, inits);"); writer.end(); } if (hasEntityFields){ Type type; if (model.isFinal()){ type = new ClassType(Class.class, model); }else{ type = new ClassType(Class.class, new TypeExtends(model)); } writer.beginConstructor(new Parameter("type", type), PATH_METADATA, PATH_INITS); writer.line("super(type, metadata, inits);"); initEntityFields(writer, config, model); writer.end(); } } protected void constructorsForVariables(CodeWriter writer, EntityType model) throws IOException { String localName = writer.getRawName(model); String genericName = writer.getGenericName(true, model); boolean hasEntityFields = model.hasEntityFields(); String thisOrSuper = hasEntityFields ? THIS : SUPER; if (!localName.equals(genericName)){ writer.suppressWarnings(UNCHECKED); } writer.beginConstructor(new Parameter("variable", Types.STRING)); writer.line(thisOrSuper,"(", localName.equals(genericName) ? EMPTY : "(Class)", localName, ".class, forVariable(variable)", hasEntityFields ? ", INITS" : EMPTY, ");"); writer.end(); } protected void entityAccessor(EntityType model, Property field, CodeWriter writer) throws IOException { Type queryType = typeMappings.getPathType(field.getType(), model, false); writer.beginPublicMethod(queryType, field.getEscapedName()); writer.line("if (", field.getEscapedName(), " == null){"); writer.line(" ", field.getEscapedName(), " = new ", writer.getRawName(queryType), "(forProperty(\"", field.getName(), "\"));"); writer.line("}"); writer.line(RETURN, field.getEscapedName(), SEMICOLON); writer.end(); } protected void entityField(EntityType model, Property field, SerializerConfig config, CodeWriter writer) throws IOException { Type queryType = typeMappings.getPathType(field.getType(), model, false); if (field.isInherited()){ writer.line("// inherited"); } if (config.useEntityAccessors()){ writer.protectedField(queryType, field.getEscapedName()); }else{ writer.publicFinal(queryType, field.getEscapedName()); } } protected boolean hasOwnEntityProperties(EntityType model){ if (model.hasEntityFields()){ for (Property property : model.getProperties()){ if (!property.isInherited() && property.getType().getCategory() == TypeCategory.ENTITY){ return true; } } } return false; } protected void initEntityFields(CodeWriter writer, SerializerConfig config, EntityType model) throws IOException { Supertype superType = model.getSuperType(); if (superType != null && superType.getEntityType().hasEntityFields()){ Type superQueryType = typeMappings.getPathType(superType.getEntityType(), model, false); writer.line("this._super = new " + writer.getRawName(superQueryType) + "(type, metadata, inits);"); } for (Property field : model.getProperties()){ if (field.getType().getCategory() == TypeCategory.ENTITY){ initEntityField(writer, config, model, field); }else if (field.isInherited() && superType != null && superType.getEntityType().hasEntityFields()){ writer.line("this.", field.getEscapedName(), " = _super.", field.getEscapedName(), SEMICOLON); } } } protected void initEntityField(CodeWriter writer, SerializerConfig config, EntityType model, Property field) throws IOException { Type queryType = typeMappings.getPathType(field.getType(), model, false); if (!field.isInherited()){ boolean hasEntityFields = field.getType() instanceof EntityType && ((EntityType)field.getType()).hasEntityFields(); writer.line("this." + field.getEscapedName() + ASSIGN, "inits.isInitialized(\""+field.getName()+"\") ? ", NEW + writer.getRawName(queryType) + "(forProperty(\"" + field.getName() + "\")", hasEntityFields ? (", inits.get(\""+field.getName()+"\")") : EMPTY, ") : null;"); }else if (!config.useEntityAccessors()){ writer.line("this.", field.getEscapedName(), ASSIGN, "_super.", field.getEscapedName(), SEMICOLON); } } protected void intro(EntityType model, SerializerConfig config, CodeWriter writer) throws IOException { introPackage(writer, model); introImports(writer, config, model); writer.nl(); introJavadoc(writer, model); introClassHeader(writer, model); introFactoryMethods(writer, model); introInits(writer, model); if (config.createDefaultVariable()){ introDefaultInstance(writer, model); } if (model.getSuperType() != null && model.getSuperType().getEntityType() != null){ introSuper(writer, model); } } @SuppressWarnings(UNCHECKED) protected void introClassHeader(CodeWriter writer, EntityType model) throws IOException { Type queryType = typeMappings.getPathType(model, model, true); TypeCategory category = model.getOriginalCategory(); Class<? extends Path> pathType; if (model.getProperties().isEmpty()){ switch(category){ case COMPARABLE : pathType = ComparablePath.class; break; case ENUM: pathType = EnumPath.class; break; case DATE: pathType = DatePath.class; break; case DATETIME: pathType = DateTimePath.class; break; case TIME: pathType = TimePath.class; break; case NUMERIC: pathType = NumberPath.class; break; case STRING: pathType = StringPath.class; break; case BOOLEAN: pathType = BooleanPath.class; break; default : pathType = EntityPathBase.class; } }else{ pathType = EntityPathBase.class; } for (Annotation annotation : model.getAnnotations()){ writer.annotation(annotation); } if (category == TypeCategory.BOOLEAN || category == TypeCategory.STRING){ writer.beginClass(queryType, new ClassType(pathType)); }else{ writer.beginClass(queryType, new ClassType(category, pathType, model)); } // TODO : generate proper serialVersionUID here writer.privateStaticFinal(Types.LONG_P, "serialVersionUID", String.valueOf(model.hashCode())); } protected void introDefaultInstance(CodeWriter writer, EntityType model) throws IOException { String simpleName = model.getUncapSimpleName(); Type queryType = typeMappings.getPathType(model, model, true); String alias = simpleName; if (keywords.contains(simpleName.toUpperCase())){ alias += "1"; } writer.publicStaticFinal(queryType, simpleName, NEW + queryType.getSimpleName() + "(\"" + alias + "\")"); } protected void introFactoryMethods(CodeWriter writer, final EntityType model) throws IOException { String localName = writer.getRawName(model); String genericName = writer.getGenericName(true, model); for (Constructor c : model.getConstructors()){ // begin if (!localName.equals(genericName)){ writer.suppressWarnings(UNCHECKED); } Type returnType = new ClassType(ConstructorExpression.class, model); writer.beginStaticMethod(returnType, "create", c.getParameters(), new Transformer<Parameter, Parameter>(){ @Override public Parameter transform(Parameter p) { return new Parameter(p.getName(), typeMappings.getExprType(p.getType(), model, false, false, true)); } }); // body // TODO : replace with class reference writer.beginLine("return new ConstructorExpression<" + genericName + ">("); if (!localName.equals(genericName)){ writer.append("(Class)"); } writer.append(localName + DOT_CLASS); writer.append(", new Class[]{"); boolean first = true; for (Parameter p : c.getParameters()){ if (!first){ writer.append(COMMA); } if (p.getType().getPrimitiveName() != null){ writer.append(p.getType().getPrimitiveName()+DOT_CLASS); }else{ writer.append(writer.getRawName(p.getType())); writer.append(DOT_CLASS); } first = false; } writer.append("}"); for (Parameter p : c.getParameters()){ writer.append(COMMA + p.getName()); } // end writer.append(");\n"); writer.end(); } } protected void introImports(CodeWriter writer, SerializerConfig config, EntityType model) throws IOException { writer.staticimports(PathMetadataFactory.class); // import package of query type Type queryType = typeMappings.getPathType(model, model, true); if (!queryType.getPackageName().isEmpty() && !queryType.getPackageName().equals(model.getPackageName()) && !queryType.getSimpleName().equals(model.getSimpleName())){ writer.importPackages(queryType.getPackageName()); } introDelegatePackages(writer, model); List<Package> packages = new ArrayList<Package>(); packages.add(PathMetadata.class.getPackage()); packages.add(SimplePath.class.getPackage()); if (!model.getConstructors().isEmpty() || !model.getDelegates().isEmpty()){ packages.add(ComparableExpression.class.getPackage()); } writer.imports(packages.toArray(new Package[packages.size()])); } protected void introDelegatePackages(CodeWriter writer, EntityType model) throws IOException { Set<String> packages = new HashSet<String>(); for (Delegate delegate : model.getDelegates()){ if (!delegate.getDelegateType().getPackageName().equals(model.getPackageName())){ packages.add(delegate.getDelegateType().getPackageName()); } } writer.importPackages(packages.toArray(new String[packages.size()])); } protected void introInits(CodeWriter writer, EntityType model) throws IOException { if (model.hasEntityFields()){ List<String> inits = new ArrayList<String>(); for (Property property : model.getProperties()){ if (property.getType().getCategory() == TypeCategory.ENTITY){ for (String init : property.getInits()){ inits.add(property.getEscapedName() + DOT + init); } } } ClassType pathInitsType = new ClassType(PathInits.class); if (!inits.isEmpty()){ inits.add(0, STAR); String initsAsString = QUOTE + StringUtils.join(inits, "\", \"") + QUOTE; writer.privateStaticFinal(pathInitsType, "INITS", "new PathInits(" + initsAsString + ")"); }else{ writer.privateStaticFinal(pathInitsType, "INITS", "PathInits.DIRECT"); } } } protected void introJavadoc(CodeWriter writer, EntityType model) throws IOException { Type queryType = typeMappings.getPathType(model, model, true); writer.javadoc(queryType.getSimpleName() + " is a Querydsl query type for " + model.getSimpleName()); } protected void introPackage(CodeWriter writer, EntityType model) throws IOException { Type queryType = typeMappings.getPathType(model, model, false); if (!queryType.getPackageName().isEmpty()){ writer.packageDecl(queryType.getPackageName()); } } protected void introSuper(CodeWriter writer, EntityType model) throws IOException { EntityType superType = model.getSuperType().getEntityType(); Type superQueryType = typeMappings.getPathType(superType, model, false); if (!superType.hasEntityFields()){ writer.publicFinal(superQueryType, "_super", NEW + writer.getRawName(superQueryType) + "(this)"); }else{ writer.publicFinal(superQueryType, "_super"); } } protected void listAccessor(EntityType model, Property field, CodeWriter writer) throws IOException { String escapedName = field.getEscapedName(); Type queryType = typeMappings.getPathType(field.getParameter(0), model, false); writer.beginPublicMethod(queryType, escapedName, new Parameter("index", Types.INT)); writer.line(RETURN + escapedName + ".get(index);").end(); writer.beginPublicMethod(queryType, escapedName, new Parameter("index", new ClassType(Expression.class, Types.INTEGER))); writer.line(RETURN + escapedName +".get(index);").end(); } protected void mapAccessor(EntityType model, Property field, CodeWriter writer) throws IOException { String escapedName = field.getEscapedName(); Type queryType = typeMappings.getPathType(field.getParameter(1), model, false); writer.beginPublicMethod(queryType, escapedName, new Parameter("key", field.getParameter(0))); writer.line(RETURN + escapedName + ".get(key);").end(); writer.beginPublicMethod(queryType, escapedName, new Parameter("key", new ClassType(Expression.class, field.getParameter(0)))); writer.line(RETURN + escapedName + ".get(key);").end(); } private void delegate(final EntityType model, Delegate delegate, SerializerConfig config, CodeWriter writer) throws IOException { Parameter[] params = delegate.getParameters().toArray(new Parameter[delegate.getParameters().size()]); writer.beginPublicMethod(delegate.getReturnType(), delegate.getName(), params); // body start writer.beginLine(RETURN + delegate.getDelegateType().getSimpleName() + "."+delegate.getName()+"("); writer.append("this"); if (!model.equals(delegate.getDeclaringType())){ int counter = 0; EntityType type = model; while (type != null && !type.equals(delegate.getDeclaringType())){ type = type.getSuperType() != null ? type.getSuperType().getEntityType() : null; counter++; } for (int i = 0; i < counter; i++){ writer.append("._super"); } } for (Parameter parameter : delegate.getParameters()){ writer.append(COMMA + parameter.getName()); } writer.append(");\n"); // body end writer.end(); } protected void outro(EntityType model, CodeWriter writer) throws IOException { writer.end(); } public void serialize(EntityType model, SerializerConfig config, CodeWriter writer) throws IOException{ intro(model, config, writer); // properties serializeProperties(model, config, writer); // constructors constructors(model, config, writer); // delegates for (Delegate delegate : model.getDelegates()){ delegate(model, delegate, config, writer); } // property accessors for (Property property : model.getProperties()){ TypeCategory category = property.getType().getCategory(); if (category == TypeCategory.MAP && config.useMapAccessors()){ mapAccessor(model, property, writer); }else if (category == TypeCategory.LIST && config.useListAccessors()){ listAccessor(model, property, writer); }else if (category == TypeCategory.ENTITY && config.useEntityAccessors()){ entityAccessor(model, property, writer); } } outro(model, writer); } protected void serialize(EntityType model, Property field, Type type, CodeWriter writer, String factoryMethod, String... args) throws IOException{ Supertype superType = model.getSuperType(); // construct value StringBuilder value = new StringBuilder(); if (field.isInherited() && superType != null){ if (!superType.getEntityType().hasEntityFields()){ value.append("_super." + field.getEscapedName()); } }else{ value.append(factoryMethod + "(\"" + field.getName() + QUOTE); for (String arg : args){ value.append(COMMA + arg); } value.append(")"); } // serialize it if (field.isInherited()){ writer.line("//inherited"); } if (value.length() > 0){ writer.publicFinal(type, field.getEscapedName(), value.toString()); }else{ writer.publicFinal(type, field.getEscapedName()); } } private void customField(EntityType model, Property field, SerializerConfig config, CodeWriter writer) throws IOException { Type queryType = typeMappings.getPathType(field.getType(), model, false); writer.line("// custom"); if (field.isInherited()){ writer.line("// inherited"); Supertype superType = model.getSuperType(); if (!superType.getEntityType().hasEntityFields()){ writer.publicFinal(queryType, field.getEscapedName(),"_super." + field.getEscapedName()); }else{ writer.publicFinal(queryType, field.getEscapedName()); } }else{ String value = NEW + writer.getRawName(queryType) + "(forProperty(\"" + field.getName() + "\"))"; writer.publicFinal(queryType, field.getEscapedName(), value); } } protected void serializeProperties(EntityType model, SerializerConfig config, CodeWriter writer) throws IOException { for (Property property : model.getProperties()){ // FIXME : the custom types should have the custom type category if (typeMappings.isRegistered(property.getType()) && property.getType().getCategory() != TypeCategory.CUSTOM && property.getType().getCategory() != TypeCategory.ENTITY){ customField(model, property, config, writer); continue; } // strips of "? extends " etc Type propertyType = new SimpleType(property.getType(), property.getType().getParameters()); Type queryType = typeMappings.getPathType(propertyType, model, false); Type genericQueryType = null; String localRawName = writer.getRawName(property.getType()); switch(property.getType().getCategory()){ case STRING: serialize(model, property, queryType, writer, "createString"); break; case BOOLEAN: serialize(model, property, queryType, writer, "createBoolean"); break; case SIMPLE: serialize(model, property, queryType, writer, "createSimple", localRawName + DOT_CLASS); break; case COMPARABLE: serialize(model, property, queryType, writer, "createComparable", localRawName + DOT_CLASS); break; case ENUM: serialize(model, property, queryType, writer, "createEnum", localRawName + DOT_CLASS); break; case DATE: serialize(model, property, queryType, writer, "createDate", localRawName + DOT_CLASS); break; case DATETIME: serialize(model, property, queryType, writer, "createDateTime", localRawName + DOT_CLASS); break; case TIME: serialize(model, property, queryType, writer, "createTime", localRawName + DOT_CLASS); break; case NUMERIC: serialize(model, property, queryType, writer, "createNumber", localRawName + DOT_CLASS); break; case CUSTOM: customField(model, property, config, writer); break; case ARRAY: serialize(model, property, new ClassType(ArrayPath.class, property.getType().getComponentType()), writer, "createArray", localRawName + DOT_CLASS); break; case COLLECTION: genericQueryType = typeMappings.getPathType(getRaw(property.getParameter(0)), model, false); String genericKey = writer.getGenericName(true, property.getParameter(0)); localRawName = writer.getRawName(property.getParameter(0)); queryType = typeMappings.getPathType(property.getParameter(0), model, true); serialize(model, property, new ClassType(CollectionPath.class, getRaw(property.getParameter(0)), genericQueryType), writer, "this.<"+genericKey + COMMA + writer.getGenericName(true, genericQueryType) + ">createCollection", localRawName + DOT_CLASS, writer.getRawName(queryType) + DOT_CLASS); break; case SET: genericQueryType = typeMappings.getPathType(getRaw(property.getParameter(0)), model, false); genericKey = writer.getGenericName(true, property.getParameter(0)); localRawName = writer.getRawName(property.getParameter(0)); queryType = typeMappings.getPathType(property.getParameter(0), model, true); serialize(model, property, new ClassType(SetPath.class, getRaw(property.getParameter(0)), genericQueryType), writer, "this.<"+genericKey + COMMA + writer.getGenericName(true, genericQueryType) + ">createSet", localRawName + DOT_CLASS, writer.getRawName(queryType) + DOT_CLASS); break; case LIST: genericQueryType = typeMappings.getPathType(getRaw(property.getParameter(0)), model, false); genericKey = writer.getGenericName(true, property.getParameter(0)); localRawName = writer.getRawName(property.getParameter(0)); queryType = typeMappings.getPathType(property.getParameter(0), model, true); serialize(model, property, new ClassType(ListPath.class, getRaw(property.getParameter(0)), genericQueryType), writer, "this.<"+genericKey + COMMA + writer.getGenericName(true, genericQueryType) + ">createList", localRawName + DOT_CLASS, writer.getRawName(queryType) + DOT_CLASS); break; case MAP: genericKey = writer.getGenericName(true, property.getParameter(0)); String genericValue = writer.getGenericName(true, property.getParameter(1)); genericQueryType = typeMappings.getPathType(getRaw(property.getParameter(1)), model, false); String keyType = writer.getRawName(property.getParameter(0)); String valueType = writer.getRawName(property.getParameter(1)); queryType = typeMappings.getPathType(property.getParameter(1), model, true); serialize(model, property, new ClassType(MapPath.class, getRaw(property.getParameter(0)), getRaw(property.getParameter(1)), genericQueryType), writer, "this.<" + genericKey + COMMA + genericValue + COMMA + writer.getGenericName(true, genericQueryType) + ">createMap", keyType+DOT_CLASS, valueType+DOT_CLASS, writer.getRawName(queryType)+DOT_CLASS); break; case ENTITY: entityField(model, property, config, writer); break; } } } private Type getRaw(Type type) { if (type instanceof EntityType && type.getPackageName().startsWith("ext.java")){ return type; }else{ return new SimpleType(type, type.getParameters()); } } }
package org.rakam; import com.google.common.eventbus.EventBus; import org.rakam.analysis.ContinuousQueryService; import org.rakam.analysis.InMemoryQueryMetadataStore; import org.rakam.analysis.TestContinuousQueryService; import org.rakam.analysis.metadata.Metastore; import org.rakam.collection.FieldDependencyBuilder; import org.rakam.event.TestingEnvironment; import org.rakam.presto.analysis.PrestoContinuousQueryService; import org.rakam.presto.analysis.PrestoMetastore; import org.rakam.presto.analysis.PrestoQueryExecutor; import org.rakam.report.realtime.RealTimeConfig; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; @Test(enabled=false) public class TestPrestoContinuousQueryService { private PrestoContinuousQueryService continuousQueryService; private Metastore metastore; private TestingEnvironment testEnvironment; // @BeforeSuite public void setUp() throws Exception { testEnvironment = new TestingEnvironment(); metastore = new PrestoMetastore(testEnvironment.getPrestoMetastore(), new EventBus(), new FieldDependencyBuilder().build(), testEnvironment.getPrestoConfig()); metastore.setup(); InMemoryQueryMetadataStore queryMetadataStore = new InMemoryQueryMetadataStore(); PrestoQueryExecutor prestoQueryExecutor = new PrestoQueryExecutor(testEnvironment.getPrestoConfig(), null, null, metastore); continuousQueryService = new PrestoContinuousQueryService(queryMetadataStore, new RealTimeConfig(), prestoQueryExecutor, testEnvironment.getPrestoConfig()); } // @Override public ContinuousQueryService getContinuousQueryService() { return continuousQueryService; } // @Override public Metastore getMetastore() { return metastore; } }
package zorbage.type.data.util; import zorbage.type.algebra.AbsoluteValue; import zorbage.type.algebra.Equality; import zorbage.type.algebra.Group; import zorbage.type.algebra.IntegralDivision; import zorbage.type.algebra.Multiplication; /** * * @author Barry DeZonia * */ public class GcdLcmHelper { private GcdLcmHelper() {} // TODO: negative friendly? public static <T extends Group<T,U> & IntegralDivision<U> & Equality<U>, U> void findGcd(T group, U a, U b, U result) { U aTmp = group.construct(a); U bTmp = group.construct(b); U t = group.construct(); U zero = group.construct(); while (group.isNotEqual(bTmp, zero)) { group.assign(bTmp, t); group.mod(aTmp, bTmp, bTmp); group.assign(t, aTmp); } group.assign(aTmp, result); } // TODO: negative friendly? overflow prone? is abs() a requirement and what would it do to // polynomials? public static <T extends Group<T,U> & AbsoluteValue<U> & IntegralDivision<U> & Multiplication<U> & Equality<U>, U> void findLcm(T group, U a, U b, U result) { U n = group.construct(); U d = group.construct(); group.multiply(a,b,n); group.abs(n,n); findGcd(group, a, b, d); group.div(n,d,result); } }
package VASSAL.build.module; import java.awt.AWTEventMulticaster; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Component; import java.awt.Composite; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.Window; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragSource; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.AffineTransform; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLayeredPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JToolBar; import javax.swing.KeyStroke; import javax.swing.OverlayLayout; import javax.swing.RootPaneContainer; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import net.miginfocom.swing.MigLayout; import org.jdesktop.animation.timing.Animator; import org.jdesktop.animation.timing.TimingTargetAdapter; import org.w3c.dom.Element; import VASSAL.build.AbstractConfigurable; import VASSAL.build.AutoConfigurable; import VASSAL.build.Buildable; import VASSAL.build.Configurable; import VASSAL.build.GameModule; import VASSAL.build.IllegalBuildException; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.map.BoardPicker; import VASSAL.build.module.map.CounterDetailViewer; import VASSAL.build.module.map.DefaultPieceCollection; import VASSAL.build.module.map.DrawPile; import VASSAL.build.module.map.Drawable; import VASSAL.build.module.map.ForwardToChatter; import VASSAL.build.module.map.ForwardToKeyBuffer; import VASSAL.build.module.map.GlobalMap; import VASSAL.build.module.map.HidePiecesButton; import VASSAL.build.module.map.HighlightLastMoved; import VASSAL.build.module.map.ImageSaver; import VASSAL.build.module.map.KeyBufferer; import VASSAL.build.module.map.LOS_Thread; import VASSAL.build.module.map.LayeredPieceCollection; import VASSAL.build.module.map.MapCenterer; import VASSAL.build.module.map.MapShader; import VASSAL.build.module.map.MassKeyCommand; import VASSAL.build.module.map.MenuDisplayer; import VASSAL.build.module.map.PieceCollection; import VASSAL.build.module.map.PieceMover; import VASSAL.build.module.map.PieceRecenterer; import VASSAL.build.module.map.Scroller; import VASSAL.build.module.map.SelectionHighlighters; import VASSAL.build.module.map.SetupStack; import VASSAL.build.module.map.StackExpander; import VASSAL.build.module.map.StackMetrics; import VASSAL.build.module.map.TextSaver; import VASSAL.build.module.map.Zoomer; import VASSAL.build.module.map.boardPicker.Board; import VASSAL.build.module.map.boardPicker.board.MapGrid; import VASSAL.build.module.map.boardPicker.board.Region; import VASSAL.build.module.map.boardPicker.board.RegionGrid; import VASSAL.build.module.map.boardPicker.board.ZonedGrid; import VASSAL.build.module.map.boardPicker.board.mapgrid.Zone; import VASSAL.build.module.properties.ChangePropertyCommandEncoder; import VASSAL.build.module.properties.GlobalProperties; import VASSAL.build.module.properties.MutablePropertiesContainer; import VASSAL.build.module.properties.MutableProperty; import VASSAL.build.module.properties.PropertySource; import VASSAL.build.widget.MapWidget; import VASSAL.command.AddPiece; import VASSAL.command.Command; import VASSAL.command.MoveTracker; import VASSAL.configure.BooleanConfigurer; import VASSAL.configure.ColorConfigurer; import VASSAL.configure.CompoundValidityChecker; import VASSAL.configure.Configurer; import VASSAL.configure.ConfigurerFactory; import VASSAL.configure.IconConfigurer; import VASSAL.configure.IntConfigurer; import VASSAL.configure.MandatoryComponent; import VASSAL.configure.NamedHotKeyConfigurer; import VASSAL.configure.PlayerIdFormattedStringConfigurer; import VASSAL.configure.VisibilityCondition; import VASSAL.counters.ColoredBorder; import VASSAL.counters.Deck; import VASSAL.counters.DeckVisitor; import VASSAL.counters.DeckVisitorDispatcher; import VASSAL.counters.DragBuffer; import VASSAL.counters.GamePiece; import VASSAL.counters.Highlighter; import VASSAL.counters.KeyBuffer; import VASSAL.counters.PieceFinder; import VASSAL.counters.PieceVisitorDispatcher; import VASSAL.counters.Properties; import VASSAL.counters.ReportState; import VASSAL.counters.Stack; import VASSAL.i18n.Resources; import VASSAL.i18n.TranslatableConfigurerFactory; import VASSAL.preferences.PositionOption; import VASSAL.preferences.Prefs; import VASSAL.tools.AdjustableSpeedScrollPane; import VASSAL.tools.ComponentSplitter; import VASSAL.tools.KeyStrokeSource; import VASSAL.tools.LaunchButton; import VASSAL.tools.NamedKeyStroke; import VASSAL.tools.ToolBarComponent; import VASSAL.tools.UniqueIdManager; import VASSAL.tools.WrapLayout; import VASSAL.tools.menu.MenuManager; import VASSAL.tools.swing.SplitPane; import VASSAL.tools.swing.SwingUtils; /** * The Map is the main component for displaying and containing {@link GamePiece}s during play. Pieces are displayed on * a Map and moved by clicking and dragging. Keyboard events are forwarded to selected pieces. Multiple map windows are * supported in a single game, with dragging between windows allowed. * * A Map may contain many different {@link Buildable} subcomponents. Components which are added directly to a Map are * contained in the <code>VASSAL.build.module.map</code> package */ public class Map extends AbstractConfigurable implements GameComponent, MouseListener, MouseMotionListener, DropTargetListener, Configurable, UniqueIdManager.Identifyable, ToolBarComponent, MutablePropertiesContainer, PropertySource, PlayerRoster.SideChangeListener { protected static boolean changeReportingEnabled = true; protected String mapID = ""; //$NON-NLS-1$ protected String mapName = ""; //$NON-NLS-1$ protected static final String MAIN_WINDOW_HEIGHT = "mainWindowHeight"; //$NON-NLS-1$ protected static UniqueIdManager idMgr = new UniqueIdManager("Map"); //$NON-NLS-1$ protected JPanel theMap; protected ArrayList<Drawable> drawComponents = new ArrayList<>(); protected JLayeredPane layeredPane = new JLayeredPane(); protected JScrollPane scroll; /** * @deprecated type will change to {@link SplitPane} */ @Deprecated protected ComponentSplitter.SplitPane mainWindowDock; protected BoardPicker picker; protected JToolBar toolBar = new JToolBar(); protected Zoomer zoom; protected StackMetrics metrics; protected Dimension edgeBuffer = new Dimension(0, 0); protected Color bgColor = Color.white; protected LaunchButton launchButton; protected boolean useLaunchButton = false; protected boolean useLaunchButtonEdit = false; protected String markMovedOption = GlobalOptions.ALWAYS; protected String markUnmovedIcon = "/images/unmoved.gif"; //$NON-NLS-1$ protected String markUnmovedText = ""; //$NON-NLS-1$ protected String markUnmovedTooltip = Resources.getString("Map.mark_unmoved"); //$NON-NLS-1$ protected MouseListener multicaster = null; protected ArrayList<MouseListener> mouseListenerStack = new ArrayList<>(); protected List<Board> boards = new CopyOnWriteArrayList<>(); protected int[][] boardWidths; // Cache of board widths by row/column protected int[][] boardHeights; // Cache of board heights by row/column protected PieceCollection pieces = new DefaultPieceCollection(); protected Highlighter highlighter = new ColoredBorder(); protected ArrayList<Highlighter> highlighters = new ArrayList<>(); protected boolean clearFirst = false; // Whether to clear the display before // drawing the map protected boolean hideCounters = false; // Option to hide counters to see // map protected float pieceOpacity = 1.0f; protected boolean allowMultiple = false; protected VisibilityCondition visibilityCondition; protected DragGestureListener dragGestureListener; protected String moveWithinFormat; protected String moveToFormat; protected String createFormat; protected String changeFormat = "$" + MESSAGE + "$"; //$NON-NLS-1$ //$NON-NLS-2$ protected NamedKeyStroke moveKey; protected PropertyChangeListener globalPropertyListener; protected String tooltip = ""; //$NON-NLS-1$ protected MutablePropertiesContainer propsContainer = new MutablePropertiesContainer.Impl(); protected PropertyChangeListener repaintOnPropertyChange = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { repaint(); } }; protected PieceMover pieceMover; protected KeyListener[] saveKeyListeners = null; public Map() { getView(); theMap.addMouseListener(this); if (shouldDockIntoMainWindow()) { toolBar.setLayout(new MigLayout("ins 0,gapx 0,hidemode 3")); } else { toolBar.setLayout(new WrapLayout(WrapLayout.LEFT, 0, 0)); } toolBar.setAlignmentX(0.0F); toolBar.setFloatable(false); } // Global Change Reporting control public static void setChangeReportingEnabled(boolean b) { changeReportingEnabled = b; } public static boolean isChangeReportingEnabled() { return changeReportingEnabled; } public static final String NAME = "mapName"; //$NON-NLS-1$ public static final String MARK_MOVED = "markMoved"; //$NON-NLS-1$ public static final String MARK_UNMOVED_ICON = "markUnmovedIcon"; //$NON-NLS-1$ public static final String MARK_UNMOVED_TEXT = "markUnmovedText"; //$NON-NLS-1$ public static final String MARK_UNMOVED_TOOLTIP = "markUnmovedTooltip"; //$NON-NLS-1$ public static final String EDGE_WIDTH = "edgeWidth"; //$NON-NLS-1$ public static final String EDGE_HEIGHT = "edgeHeight"; //$NON-NLS-1$ public static final String BACKGROUND_COLOR = "backgroundcolor"; public static final String HIGHLIGHT_COLOR = "color"; //$NON-NLS-1$ public static final String HIGHLIGHT_THICKNESS = "thickness"; //$NON-NLS-1$ public static final String ALLOW_MULTIPLE = "allowMultiple"; //$NON-NLS-1$ public static final String USE_LAUNCH_BUTTON = "launch"; //$NON-NLS-1$ public static final String BUTTON_NAME = "buttonName"; //$NON-NLS-1$ public static final String TOOLTIP = "tooltip"; //$NON-NLS-1$ public static final String ICON = "icon"; //$NON-NLS-1$ public static final String HOTKEY = "hotkey"; //$NON-NLS-1$ public static final String SUPPRESS_AUTO = "suppressAuto"; //$NON-NLS-1$ public static final String MOVE_WITHIN_FORMAT = "moveWithinFormat"; //$NON-NLS-1$ public static final String MOVE_TO_FORMAT = "moveToFormat"; //$NON-NLS-1$ public static final String CREATE_FORMAT = "createFormat"; //$NON-NLS-1$ public static final String CHANGE_FORMAT = "changeFormat"; //$NON-NLS-1$ public static final String MOVE_KEY = "moveKey"; //$NON-NLS-1$ public static final String MOVING_STACKS_PICKUP_UNITS = "movingStacksPickupUnits"; //$NON-NLS-1$ @Override public void setAttribute(String key, Object value) { if (NAME.equals(key)) { setMapName((String) value); } else if (MARK_MOVED.equals(key)) { markMovedOption = (String) value; } else if (MARK_UNMOVED_ICON.equals(key)) { markUnmovedIcon = (String) value; if (pieceMover != null) { pieceMover.setAttribute(key, value); } } else if (MARK_UNMOVED_TEXT.equals(key)) { markUnmovedText = (String) value; if (pieceMover != null) { pieceMover.setAttribute(key, value); } } else if (MARK_UNMOVED_TOOLTIP.equals(key)) { markUnmovedTooltip = (String) value; } else if ("edge".equals(key)) { // Backward-compatible //$NON-NLS-1$ String s = (String) value; int i = s.indexOf(','); //$NON-NLS-1$ if (i > 0) { edgeBuffer = new Dimension(Integer.parseInt(s.substring(0, i)), Integer.parseInt(s.substring(i + 1))); } } else if (EDGE_WIDTH.equals(key)) { if (value instanceof String) { value = Integer.valueOf((String) value); } try { edgeBuffer = new Dimension((Integer) value, edgeBuffer.height); } catch (NumberFormatException ex) { throw new IllegalBuildException(ex); } } else if (EDGE_HEIGHT.equals(key)) { if (value instanceof String) { value = Integer.valueOf((String) value); } try { edgeBuffer = new Dimension(edgeBuffer.width, (Integer) value); } catch (NumberFormatException ex) { throw new IllegalBuildException(ex); } } else if (BACKGROUND_COLOR.equals(key)) { if (value instanceof String) { value = ColorConfigurer.stringToColor((String)value); } bgColor = (Color)value; } else if (ALLOW_MULTIPLE.equals(key)) { if (value instanceof String) { value = Boolean.valueOf((String) value); } allowMultiple = (Boolean) value; if (picker != null) { picker.setAllowMultiple(allowMultiple); } } else if (HIGHLIGHT_COLOR.equals(key)) { if (value instanceof String) { value = ColorConfigurer.stringToColor((String) value); } if (value != null) { ((ColoredBorder) highlighter).setColor((Color) value); } } else if (HIGHLIGHT_THICKNESS.equals(key)) { if (value instanceof String) { value = Integer.valueOf((String) value); } if (highlighter instanceof ColoredBorder) { ((ColoredBorder) highlighter).setThickness((Integer) value); } } else if (USE_LAUNCH_BUTTON.equals(key)) { if (value instanceof String) { value = Boolean.valueOf((String) value); } useLaunchButtonEdit = (Boolean) value; launchButton.setVisible(useLaunchButton); } else if (SUPPRESS_AUTO.equals(key)) { if (value instanceof String) { value = Boolean.valueOf((String) value); } if (Boolean.TRUE.equals(value)) { moveWithinFormat = ""; //$NON-NLS-1$ } } else if (MOVE_WITHIN_FORMAT.equals(key)) { moveWithinFormat = (String) value; } else if (MOVE_TO_FORMAT.equals(key)) { moveToFormat = (String) value; } else if (CREATE_FORMAT.equals(key)) { createFormat = (String) value; } else if (CHANGE_FORMAT.equals(key)) { changeFormat = (String) value; } else if (MOVE_KEY.equals(key)) { if (value instanceof String) { value = NamedHotKeyConfigurer.decode((String) value); } moveKey = (NamedKeyStroke) value; } else if (TOOLTIP.equals(key)) { tooltip = (String) value; launchButton.setAttribute(key, value); } else { launchButton.setAttribute(key, value); } } @Override public String getAttributeValueString(String key) { if (NAME.equals(key)) { return getMapName(); } else if (MARK_MOVED.equals(key)) { return markMovedOption; } else if (MARK_UNMOVED_ICON.equals(key)) { return markUnmovedIcon; } else if (MARK_UNMOVED_TEXT.equals(key)) { return markUnmovedText; } else if (MARK_UNMOVED_TOOLTIP.equals(key)) { return markUnmovedTooltip; } else if (EDGE_WIDTH.equals(key)) { return String.valueOf(edgeBuffer.width); //$NON-NLS-1$ } else if (EDGE_HEIGHT.equals(key)) { return String.valueOf(edgeBuffer.height); //$NON-NLS-1$ } else if (BACKGROUND_COLOR.equals(key)) { return ColorConfigurer.colorToString(bgColor); } else if (ALLOW_MULTIPLE.equals(key)) { return String.valueOf(picker.isAllowMultiple()); //$NON-NLS-1$ } else if (HIGHLIGHT_COLOR.equals(key)) { if (highlighter instanceof ColoredBorder) { return ColorConfigurer.colorToString( ((ColoredBorder) highlighter).getColor()); } else { return null; } } else if (HIGHLIGHT_THICKNESS.equals(key)) { if (highlighter instanceof ColoredBorder) { return String.valueOf( ((ColoredBorder) highlighter).getThickness()); //$NON-NLS-1$ } else { return null; } } else if (USE_LAUNCH_BUTTON.equals(key)) { return String.valueOf(useLaunchButtonEdit); } else if (MOVE_WITHIN_FORMAT.equals(key)) { return getMoveWithinFormat(); } else if (MOVE_TO_FORMAT.equals(key)) { return getMoveToFormat(); } else if (CREATE_FORMAT.equals(key)) { return getCreateFormat(); } else if (CHANGE_FORMAT.equals(key)) { return getChangeFormat(); } else if (MOVE_KEY.equals(key)) { return NamedHotKeyConfigurer.encode(moveKey); } else if (TOOLTIP.equals(key)) { return (tooltip == null || tooltip.length() == 0) ? launchButton.getAttributeValueString(name) : tooltip; } else { return launchButton.getAttributeValueString(key); } } @Override public void build(Element e) { ActionListener al = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (mainWindowDock == null && launchButton.isEnabled() && theMap.getTopLevelAncestor() != null) { theMap.getTopLevelAncestor().setVisible(!theMap.getTopLevelAncestor().isVisible()); } } }; launchButton = new LaunchButton(Resources.getString("Editor.Map.map"), TOOLTIP, BUTTON_NAME, HOTKEY, ICON, al); launchButton.setEnabled(false); launchButton.setVisible(false); if (e != null) { super.build(e); getBoardPicker(); getStackMetrics(); } else { getBoardPicker(); getStackMetrics(); addChild(new ForwardToKeyBuffer()); addChild(new Scroller()); addChild(new ForwardToChatter()); addChild(new MenuDisplayer()); addChild(new MapCenterer()); addChild(new StackExpander()); addChild(new PieceMover()); addChild(new KeyBufferer()); addChild(new ImageSaver()); addChild(new CounterDetailViewer()); setMapName("Main Map"); } if (getComponentsOf(GlobalProperties.class).isEmpty()) { addChild(new GlobalProperties()); } if (getComponentsOf(SelectionHighlighters.class).isEmpty()) { addChild(new SelectionHighlighters()); } if (getComponentsOf(HighlightLastMoved.class).isEmpty()) { addChild(new HighlightLastMoved()); } setup(false); } private void addChild(Buildable b) { add(b); b.addTo(this); } /** * Every map must include a {@link BoardPicker} as one of its build components */ public void setBoardPicker(BoardPicker picker) { if (this.picker != null) { GameModule.getGameModule().removeCommandEncoder(picker); GameModule.getGameModule().getGameState().addGameComponent(picker); } this.picker = picker; if (picker != null) { picker.setAllowMultiple(allowMultiple); GameModule.getGameModule().addCommandEncoder(picker); GameModule.getGameModule().getGameState().addGameComponent(picker); } } /** * Every map must include a {@link BoardPicker} as one of its build components * * @return the BoardPicker for this map */ public BoardPicker getBoardPicker() { if (picker == null) { picker = new BoardPicker(); picker.build(null); add(picker); picker.addTo(this); } return picker; } /** * A map may include a {@link Zoomer} as one of its build components */ public void setZoomer(Zoomer z) { zoom = z; } /** * A map may include a {@link Zoomer} as one of its build components * * @return the Zoomer for this map */ public Zoomer getZoomer() { return zoom; } /** * Every map must include a {@link StackMetrics} as one of its build components, which governs the stacking behavior * of GamePieces on the map */ public void setStackMetrics(StackMetrics sm) { metrics = sm; } /** * Every map must include a {@link StackMetrics} as one of its build * components, which governs the stacking behavior of GamePieces on the map * * @return the StackMetrics for this map */ public StackMetrics getStackMetrics() { if (metrics == null) { metrics = new StackMetrics(); metrics.build(null); add(metrics); metrics.addTo(this); } return metrics; } /** * @return the current zoom factor for the map */ public double getZoom() { return zoom == null ? 1.0 : zoom.getZoomFactor(); } /** * @return the toolbar for this map's window */ @Override public JToolBar getToolBar() { return toolBar; } /** * Add a {@link Drawable} component to this map * * @see #paint */ public void addDrawComponent(Drawable theComponent) { drawComponents.add(theComponent); } /** * Remove a {@link Drawable} component from this map * * @see #paint */ public void removeDrawComponent(Drawable theComponent) { drawComponents.remove(theComponent); } /** * Expects to be added to a {@link GameModule}. Determines a unique id for * this Map. Registers itself as {@link KeyStrokeSource}. Registers itself * as a {@link GameComponent}. Registers itself as a drop target and drag * source. * * @see #getId * @see DragBuffer */ @Override public void addTo(Buildable b) { useLaunchButton = useLaunchButtonEdit; idMgr.add(this); final GameModule g = GameModule.getGameModule(); g.addCommandEncoder(new ChangePropertyCommandEncoder(this)); validator = new CompoundValidityChecker( new MandatoryComponent(this, BoardPicker.class), new MandatoryComponent(this, StackMetrics.class)).append(idMgr); final DragGestureListener dgl = new DragGestureListener() { @Override public void dragGestureRecognized(DragGestureEvent dge) { if (dragGestureListener != null && mouseListenerStack.isEmpty() && SwingUtils.isDragTrigger(dge)) { dragGestureListener.dragGestureRecognized(dge); } } }; DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer( theMap, DnDConstants.ACTION_MOVE, dgl); theMap.setDropTarget(PieceMover.DragHandler.makeDropTarget( theMap, DnDConstants.ACTION_MOVE, this)); g.getGameState().addGameComponent(this); g.getToolBar().add(launchButton); if (shouldDockIntoMainWindow()) { final IntConfigurer config = new IntConfigurer(MAIN_WINDOW_HEIGHT, null, -1); Prefs.getGlobalPrefs().addOption(null, config); mainWindowDock = g.getPlayerWindow().splitControlPanel(layeredPane, SplitPane.HIDE_BOTTOM, true); mainWindowDock.setResizeWeight(0.0); g.addKeyStrokeSource( new KeyStrokeSource(theMap, JComponent.WHEN_FOCUSED)); } else { g.addKeyStrokeSource( new KeyStrokeSource(theMap, JComponent.WHEN_IN_FOCUSED_WINDOW)); } // Fix for bug 1630993: toolbar buttons not appearing toolBar.addHierarchyListener(new HierarchyListener() { @Override public void hierarchyChanged(HierarchyEvent e) { Window w; if ((w = SwingUtilities.getWindowAncestor(toolBar)) != null) { w.validate(); } if (toolBar.getSize().width > 0) { toolBar.removeHierarchyListener(this); } } }); GameModule.getGameModule().addSideChangeListenerToPlayerRoster(this); g.getPrefs().addOption( Resources.getString("Prefs.general_tab"), //$NON-NLS-1$ new IntConfigurer( PREFERRED_EDGE_DELAY, Resources.getString("Map.scroll_delay_preference"), //$NON-NLS-1$ PREFERRED_EDGE_SCROLL_DELAY ) ); g.getPrefs().addOption( Resources.getString("Prefs.general_tab"), //$NON-NLS-1$ new BooleanConfigurer( MOVING_STACKS_PICKUP_UNITS, Resources.getString("Map.moving_stacks_preference"), //$NON-NLS-1$ Boolean.FALSE ) ); } public void setPieceMover(PieceMover mover) { pieceMover = mover; } @Override public void removeFrom(Buildable b) { GameModule.getGameModule().getGameState().removeGameComponent(this); Window w = SwingUtilities.getWindowAncestor(theMap); if (w != null) { w.dispose(); } GameModule.getGameModule().getToolBar().remove(launchButton); idMgr.remove(this); if (picker != null) { GameModule.getGameModule().removeCommandEncoder(picker); GameModule.getGameModule().getGameState().addGameComponent(picker); } PlayerRoster.removeSideChangeListener(this); } @Override public void sideChanged(String oldSide, String newSide) { repaint(); } /** * Set the boards for this map. Each map may contain more than one * {@link Board}. */ public synchronized void setBoards(Collection<Board> c) { boards.clear(); for (Board b : c) { b.setMap(this); boards.add(b); } setBoardBoundaries(); } @Override public Command getRestoreCommand() { return null; } /** * @return the {@link Board} on this map containing the argument point */ public Board findBoard(Point p) { for (Board b : boards) { if (b.bounds().contains(p)) return b; } return null; } /** * * @return the {@link Zone} on this map containing the argument point */ public Zone findZone(Point p) { Board b = findBoard(p); if (b != null) { MapGrid grid = b.getGrid(); if (grid instanceof ZonedGrid) { Rectangle r = b.bounds(); p.translate(-r.x, -r.y); // Translate to Board co-ords return ((ZonedGrid) grid).findZone(p); } } return null; } /** * Search on all boards for a Zone with the given name * @param Zone name * @return Located zone */ public Zone findZone(String name) { for (Board b : boards) { for (ZonedGrid zg : b.getAllDescendantComponentsOf(ZonedGrid.class)) { Zone z = zg.findZone(name); if (z != null) { return z; } } } return null; } /** * Search on all boards for a Region with the given name * @param Region name * @return Located region */ public Region findRegion(String name) { for (Board b : boards) { for (RegionGrid rg : b.getAllDescendantComponentsOf(RegionGrid.class)) { Region r = rg.findRegion(name); if (r != null) { return r; } } } return null; } /** * Return the board with the given name * * @param name * @return null if no such board found */ public Board getBoardByName(String name) { if (name != null) { for (Board b : boards) { if (name.equals(b.getName())) { return b; } } } return null; } public Dimension getPreferredSize() { final Dimension size = mapSize(); size.width *= getZoom(); size.height *= getZoom(); return size; } /** * @return the size of the map in pixels at 100% zoom, * including the edge buffer */ // FIXME: why synchronized? public synchronized Dimension mapSize() { final Rectangle r = new Rectangle(0, 0); for (Board b : boards) r.add(b.bounds()); r.width += edgeBuffer.width; r.height += edgeBuffer.height; return r.getSize(); } public boolean isLocationRestricted(Point p) { Board b = findBoard(p); if (b != null) { Rectangle r = b.bounds(); Point snap = new Point(p); snap.translate(-r.x, -r.y); return b.isLocationRestricted(snap); } else { return false; } } /** * @return the nearest allowable point according to the {@link VASSAL.build.module.map.boardPicker.board.MapGrid} on * the {@link Board} at this point * * @see Board#snapTo * @see VASSAL.build.module.map.boardPicker.board.MapGrid#snapTo */ public Point snapTo(Point p) { Point snap = new Point(p); final Board b = findBoard(p); if (b == null) return snap; final Rectangle r = b.bounds(); snap.translate(-r.x, -r.y); snap = b.snapTo(snap); snap.translate(r.x, r.y); // RFE 882378 // If we have snapped to a point 1 pixel off the edge of the map, move // back // onto the map. if (findBoard(snap) == null) { snap.translate(-r.x, -r.y); if (snap.x == r.width) { snap.x = r.width - 1; } else if (snap.x == -1) { snap.x = 0; } if (snap.y == r.height) { snap.y = r.height - 1; } else if (snap.y == -1) { snap.y = 0; } snap.translate(r.x, r.y); } return snap; } /** * The buffer of empty space around the boards in the Map window, * in component coordinates at 100% zoom */ public Dimension getEdgeBuffer() { return new Dimension(edgeBuffer); } /** * Translate a point from component coordinates (i.e., x,y position on * the JPanel) to map coordinates (i.e., accounting for zoom factor). * * @see #componentCoordinates */ @Deprecated public Point mapCoordinates(Point p) { return componentToMap(p); } /** * Translate a point from map coordinates to component coordinates * * @see #mapCoordinates */ @Deprecated public Point componentCoordinates(Point p) { return mapToComponent(p); } protected int scale(int c, double zoom) { return (int)(c * zoom); } protected Point scale(Point p, double zoom) { return new Point((int)(p.x * zoom), (int)(p.y * zoom)); } protected Rectangle scale(Rectangle r, double zoom) { return new Rectangle( (int)(r.x * zoom), (int)(r.y * zoom), (int)(r.width * zoom), (int)(r.height * zoom) ); } public int mapToDrawing(int c, double os_scale) { return scale(c, getZoom() * os_scale); } public Point mapToDrawing(Point p, double os_scale) { return scale(p, getZoom() * os_scale); } public Rectangle mapToDrawing(Rectangle r, double os_scale) { return scale(r, getZoom() * os_scale); } public int mapToComponent(int c) { return scale(c, getZoom()); } public Point mapToComponent(Point p) { return scale(p, getZoom()); } public Rectangle mapToComponent(Rectangle r) { return scale(r, getZoom()); } public int componentToDrawing(int c, double os_scale) { return scale(c, os_scale); } public Point componentToDrawing(Point p, double os_scale) { return scale(p, os_scale); } public Rectangle componentToDrawing(Rectangle r, double os_scale) { return scale(r, os_scale); } public int componentToMap(int c) { return scale(c, 1.0/getZoom()); } public Point componentToMap(Point p) { return scale(p, 1.0/getZoom()); } public Rectangle componentToMap(Rectangle r) { return scale(r, 1.0/getZoom()); } public int drawingToMap(int c, double os_scale) { return scale(c, 1.0/(getZoom() * os_scale)); } public Point drawingToMap(Point p, double os_scale) { return scale(p, 1.0/(getZoom() * os_scale)); } public Rectangle drawingToMap(Rectangle r, double os_scale) { return scale(r, 1.0/(getZoom() * os_scale)); } public int drawingToComponent(int c, double os_scale) { return scale(c, 1.0/os_scale); } public Point drawingToComponent(Point p, double os_scale) { return scale(p, 1.0/os_scale); } public Rectangle drawingToComponent(Rectangle r, double os_scale) { return scale(r, 1.0/os_scale); } /** * @return a String name for the given location on the map * * @see Board#locationName */ public String locationName(Point p) { String loc = getDeckNameAt(p); if (loc == null) { Board b = findBoard(p); if (b != null) { loc = b.locationName(new Point(p.x - b.bounds().x, p.y - b.bounds().y)); } } if (loc == null) { loc = Resources.getString("Map.offboard"); //$NON-NLS-1$ } return loc; } public String localizedLocationName(Point p) { String loc = getLocalizedDeckNameAt(p); if (loc == null) { Board b = findBoard(p); if (b != null) { loc = b.localizedLocationName(new Point(p.x - b.bounds().x, p.y - b.bounds().y)); } } if (loc == null) { loc = Resources.getString("Map.offboard"); //$NON-NLS-1$ } return loc; } /** * @return a String name for the given location on the map. Include Map name if requested. Report deck name instead of * location if point is inside the bounds of a deck. Do not include location if this map is not visible to all * players. */ // public String getFullLocationName(Point p, boolean includeMap) { // String loc = ""; //$NON-NLS-1$ // if (includeMap && getMapName() != null && getMapName().length() > 0) { // loc = "[" + getMapName() + "]"; //$NON-NLS-1$ //$NON-NLS-2$ // if (isVisibleToAll() && p != null) { // String pos = getDeckNameContaining(p); // if (pos == null) { // if (locationName(p) != null) { // loc = locationName(p) + loc; // else { // loc = pos; // return loc; /** * Is this map visible to all players */ public boolean isVisibleToAll() { if (this instanceof PrivateMap) { if (!getAttributeValueString(PrivateMap.VISIBLE).equals("true")) { //$NON-NLS-1$ return false; } } return true; } /** * Return the name of the deck whose bounding box contains p */ public String getDeckNameContaining(Point p) { String deck = null; if (p != null) { for (DrawPile d : getComponentsOf(DrawPile.class)) { Rectangle box = d.boundingBox(); if (box != null && box.contains(p)) { deck = d.getConfigureName(); break; } } } return deck; } /** * Return the name of the deck whose position is p * * @param p * @return */ public String getDeckNameAt(Point p) { String deck = null; if (p != null) { for (DrawPile d : getComponentsOf(DrawPile.class)) { if (d.getPosition().equals(p)) { deck = d.getConfigureName(); break; } } } return deck; } public String getLocalizedDeckNameAt(Point p) { String deck = null; if (p != null) { for (DrawPile d : getComponentsOf(DrawPile.class)) { if (d.getPosition().equals(p)) { deck = d.getLocalizedConfigureName(); break; } } } return deck; } /** * Because MouseEvents are received in component coordinates, it is * inconvenient for MouseListeners on the map to have to translate to map * coordinates. MouseListeners added with this method will receive mouse * events with points already translated into map coordinates. * addLocalMouseListenerFirst inserts the new listener at the start of the * chain. */ public void addLocalMouseListener(MouseListener l) { multicaster = AWTEventMulticaster.add(multicaster, l); } public void addLocalMouseListenerFirst(MouseListener l) { multicaster = AWTEventMulticaster.add(l, multicaster); } public void removeLocalMouseListener(MouseListener l) { multicaster = AWTEventMulticaster.remove(multicaster, l); } /** * MouseListeners on a map may be pushed and popped onto a stack. * Only the top listener on the stack receives mouse events. */ public void pushMouseListener(MouseListener l) { mouseListenerStack.add(l); } /** * MouseListeners on a map may be pushed and popped onto a stack. Only the top listener on the stack receives mouse * events */ public void popMouseListener() { mouseListenerStack.remove(mouseListenerStack.size()-1); } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } public MouseEvent translateEvent(MouseEvent e) { // don't write over Java's mouse event final MouseEvent mapEvent = new MouseEvent( e.getComponent(), e.getID(), e.getWhen(), e.getModifiersEx(), e.getX(), e.getY(), e.getXOnScreen(), e.getYOnScreen(), e.getClickCount(), e.isPopupTrigger(), e.getButton() ); final Point p = componentToMap(mapEvent.getPoint()); mapEvent.translatePoint(p.x - mapEvent.getX(), p.y - mapEvent.getY()); return mapEvent; } /** * Mouse events are first translated into map coordinates. Then the event is forwarded to the top MouseListener in the * stack, if any, otherwise forwarded to all LocalMouseListeners * * @see #pushMouseListener * @see #popMouseListener * @see #addLocalMouseListener */ @Override public void mouseClicked(MouseEvent e) { if (!mouseListenerStack.isEmpty()) { mouseListenerStack.get(mouseListenerStack.size()-1).mouseClicked(translateEvent(e)); } else if (multicaster != null) { multicaster.mouseClicked(translateEvent(e)); } } /** * Mouse events are first translated into map coordinates. Then the event is forwarded to the top MouseListener in the * stack, if any, otherwise forwarded to all LocalMouseListeners * * @see #pushMouseListener * @see #popMouseListener * @see #addLocalMouseListener */ public static Map activeMap = null; public static void clearActiveMap() { if (activeMap != null) { activeMap.repaint(); activeMap = null; } } @Override public void mousePressed(MouseEvent e) { // Deselect any counters on the last Map with focus if (!this.equals(activeMap)) { boolean dirty = false; final KeyBuffer kbuf = KeyBuffer.getBuffer(); final ArrayList<GamePiece> l = new ArrayList<>(kbuf.asList()); for (GamePiece p : l) { if (p.getMap() == activeMap) { kbuf.remove(p); dirty = true; } } if (dirty && activeMap != null) { activeMap.repaint(); } } activeMap = this; if (!mouseListenerStack.isEmpty()) { mouseListenerStack.get(mouseListenerStack.size()-1).mousePressed(translateEvent(e)); } else if (multicaster != null) { multicaster.mousePressed(translateEvent(e)); } } /** * Mouse events are first translated into map coordinates. * Then the event is forwarded to the top MouseListener in the * stack, if any, otherwise forwarded to all LocalMouseListeners. * * @see #pushMouseListener * @see #popMouseListener * @see #addLocalMouseListener */ @Override public void mouseReleased(MouseEvent e) { // don't write over Java's mouse event Point p = e.getPoint(); p.translate(theMap.getX(), theMap.getY()); if (theMap.getBounds().contains(p)) { if (!mouseListenerStack.isEmpty()) { mouseListenerStack.get(mouseListenerStack.size()-1).mouseReleased(translateEvent(e)); } else if (multicaster != null) { multicaster.mouseReleased(translateEvent(e)); } // Request Focus so that keyboard input will be recognized theMap.requestFocus(); } // Clicking with mouse always repaints the map clearFirst = true; theMap.repaint(); activeMap = this; } /** * Save all current Key Listeners and remove them from the * map. Used by Traits that need to prevent Key Commands * at certain times. */ public void enableKeyListeners() { if (saveKeyListeners == null) return; for (KeyListener kl : saveKeyListeners) { theMap.addKeyListener(kl); } saveKeyListeners = null; } /** * Restore the previously disabled KeyListeners */ public void disableKeyListeners() { if (saveKeyListeners != null) return; saveKeyListeners = theMap.getKeyListeners(); for (KeyListener kl : saveKeyListeners) { theMap.removeKeyListener(kl); } } /** * This listener will be notified when a drag event is initiated, assuming * that no MouseListeners are on the stack. * * @see #pushMouseListener * @param dragGestureListener */ public void setDragGestureListener(DragGestureListener dragGestureListener) { this.dragGestureListener = dragGestureListener; } public DragGestureListener getDragGestureListener() { return dragGestureListener; } @Override public void dragEnter(DropTargetDragEvent dtde) { } @Override public void dragOver(DropTargetDragEvent dtde) { scrollAtEdge(dtde.getLocation(), SCROLL_ZONE); } @Override public void dropActionChanged(DropTargetDragEvent dtde) { } /* * Cancel final scroll and repaint map */ @Override public void dragExit(DropTargetEvent dte) { if (scroller.isRunning()) scroller.stop(); repaint(); } @Override public void drop(DropTargetDropEvent dtde) { if (dtde.getDropTargetContext().getComponent() == theMap) { final MouseEvent evt = new MouseEvent( theMap, MouseEvent.MOUSE_RELEASED, System.currentTimeMillis(), 0, dtde.getLocation().x, dtde.getLocation().y, 1, false, MouseEvent.NOBUTTON ); theMap.dispatchEvent(evt); dtde.dropComplete(true); } if (scroller.isRunning()) scroller.stop(); } /** * Mouse motion events are not forwarded to LocalMouseListeners or to listeners on the stack */ @Override public void mouseMoved(MouseEvent e) { } /** * Mouse motion events are not forwarded to LocalMouseListeners or to * listeners on the stack. * * The map scrolls when dragging the mouse near the edge. */ @Override public void mouseDragged(MouseEvent e) { if (!SwingUtils.isContextMouseButtonDown(e)) { scrollAtEdge(e.getPoint(), SCROLL_ZONE); } else { if (scroller.isRunning()) scroller.stop(); } } /* * Delay before starting scroll at edge */ public static final int PREFERRED_EDGE_SCROLL_DELAY = 200; public static final String PREFERRED_EDGE_DELAY = "PreferredEdgeDelay"; //$NON-NLS-1$ /** The width of the hot zone for triggering autoscrolling. */ public static final int SCROLL_ZONE = 30; /** The horizontal component of the autoscrolling vector, -1, 0, or 1. */ protected int sx; /** The vertical component of the autoscrolling vector, -1, 0, or 1. */ protected int sy; protected int dx, dy; /** * Begin autoscrolling the map if the given point is within the given * distance from a viewport edge. * * @param evtPt * @param dist */ public void scrollAtEdge(Point evtPt, int dist) { final Rectangle vrect = scroll.getViewport().getViewRect(); final int px = evtPt.x - vrect.x; final int py = evtPt.y - vrect.y; // determine scroll vector sx = 0; if (px < dist && px >= 0) { sx = -1; dx = dist - px; } else if (px < vrect.width && px >= vrect.width - dist) { sx = 1; dx = dist - (vrect.width - px); } sy = 0; if (py < dist && py >= 0) { sy = -1; dy = dist - py; } else if (py < vrect.height && py >= vrect.height - dist) { sy = 1; dy = dist - (vrect.height - py); } dx /= 2; dy /= 2; // start autoscrolling if we have a nonzero scroll vector if (sx != 0 || sy != 0) { if (!scroller.isRunning()) { scroller.setStartDelay((Integer) GameModule.getGameModule().getPrefs().getValue(PREFERRED_EDGE_DELAY)); scroller.start(); } } else { if (scroller.isRunning()) scroller.stop(); } } /** The animator which controls autoscrolling. */ protected Animator scroller = new Animator(Animator.INFINITE, new TimingTargetAdapter() { private long t0; @Override public void timingEvent(float fraction) { // Constant velocity along each axis, 0.5px/ms final long t1 = System.currentTimeMillis(); final int dt = (int)((t1 - t0)/2); t0 = t1; scroll(sx*dt, sy*dt); // Check whether we have hit an edge final Rectangle vrect = scroll.getViewport().getViewRect(); if ((sx == -1 && vrect.x == 0) || (sx == 1 && vrect.x + vrect.width >= theMap.getWidth())) sx = 0; if ((sy == -1 && vrect.y == 0) || (sy == 1 && vrect.y + vrect.height >= theMap.getHeight())) sy = 0; // Stop if the scroll vector is zero if (sx == 0 && sy == 0) scroller.stop(); } @Override public void begin() { t0 = System.currentTimeMillis(); } } ); public void repaint(boolean cf) { clearFirst = cf; theMap.repaint(); } public void paintRegion(Graphics g, Rectangle visibleRect) { paintRegion(g, visibleRect, theMap); } public void paintRegion(Graphics g, Rectangle visibleRect, Component c) { clearMapBorder(g); // To avoid ghost pieces around the edge drawBoardsInRegion(g, visibleRect, c); drawDrawable(g, false); drawPiecesInRegion(g, visibleRect, c); drawDrawable(g, true); } public void drawBoardsInRegion(Graphics g, Rectangle visibleRect, Component c) { final Graphics2D g2d = (Graphics2D) g; final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX(); final double dzoom = getZoom() * os_scale; for (Board b : boards) { b.drawRegion(g, getLocation(b, dzoom), visibleRect, dzoom, c); } } public void drawBoardsInRegion(Graphics g, Rectangle visibleRect) { drawBoardsInRegion(g, visibleRect, theMap); } public void repaint() { theMap.repaint(); } public void drawPiecesInRegion(Graphics g, Rectangle visibleRect, Component c) { if (hideCounters) { return; } final Graphics2D g2d = (Graphics2D) g; final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX(); final double dzoom = getZoom() * os_scale; Composite oldComposite = g2d.getComposite(); g2d.setComposite( AlphaComposite.getInstance(AlphaComposite.SRC_OVER, pieceOpacity)); final GamePiece[] stack = pieces.getPieces(); for (GamePiece gamePiece : stack) { final Point pt = mapToDrawing(gamePiece.getPosition(), os_scale); if (gamePiece.getClass() == Stack.class) { getStackMetrics().draw( (Stack) gamePiece, pt, g, this, dzoom, visibleRect ); } else { gamePiece.draw(g, pt.x, pt.y, c, dzoom); if (Boolean.TRUE.equals(gamePiece.getProperty(Properties.SELECTED))) { highlighter.draw(gamePiece, g, pt.x, pt.y, c, dzoom); } } /* // draw bounding box for debugging final Rectangle bb = stack[i].boundingBox(); g.drawRect(pt.x + bb.x, pt.y + bb.y, bb.width, bb.height); */ } g2d.setComposite(oldComposite); } public void drawPiecesInRegion(Graphics g, Rectangle visibleRect) { drawPiecesInRegion(g, visibleRect, theMap); } public void drawPieces(Graphics g, int xOffset, int yOffset) { if (hideCounters) { return; } Graphics2D g2d = (Graphics2D) g; final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX(); Composite oldComposite = g2d.getComposite(); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, pieceOpacity)); GamePiece[] stack = pieces.getPieces(); for (GamePiece gamePiece : stack) { Point pt = mapToDrawing(gamePiece.getPosition(), os_scale); gamePiece.draw(g, pt.x + xOffset, pt.y + yOffset, theMap, getZoom()); if (Boolean.TRUE.equals(gamePiece.getProperty(Properties.SELECTED))) { highlighter.draw(gamePiece, g, pt.x - xOffset, pt.y - yOffset, theMap, getZoom()); } } g2d.setComposite(oldComposite); } public void drawDrawable(Graphics g, boolean aboveCounters) { for (Drawable drawable : drawComponents) { if (!(aboveCounters ^ drawable.drawAboveCounters())) { drawable.draw(g, this); } } } public Highlighter getHighlighter() { return highlighter; } public void setHighlighter(Highlighter h) { highlighter = h; } public void addHighlighter(Highlighter h) { highlighters.add(h); } public void removeHighlighter(Highlighter h) { highlighters.remove(h); } public Iterator<Highlighter> getHighlighters() { return highlighters.iterator(); } /** * @return a Collection of all {@link Board}s on the Map */ public Collection<Board> getBoards() { return Collections.unmodifiableCollection(boards); } /** * @return an Enumeration of all {@link Board}s on the map * @deprecated Use {@link #getBoards()} instead. */ @Deprecated public Enumeration<Board> getAllBoards() { return Collections.enumeration(boards); } public int getBoardCount() { return boards.size(); } /** * Returns the boundingBox of a GamePiece accounting for the offset of a piece within its parent stack. Return null if * this piece is not on the map * * @see GamePiece#boundingBox */ public Rectangle boundingBoxOf(GamePiece p) { Rectangle r = null; if (p.getMap() == this) { r = p.boundingBox(); final Point pos = p.getPosition(); r.translate(pos.x, pos.y); if (Boolean.TRUE.equals(p.getProperty(Properties.SELECTED))) { r.add(highlighter.boundingBox(p)); for (Iterator<Highlighter> i = getHighlighters(); i.hasNext();) { r.add(i.next().boundingBox(p)); } } if (p.getParent() != null) { final Point pt = getStackMetrics().relativePosition(p.getParent(), p); r.translate(pt.x, pt.y); } } return r; } /** * Returns the selection bounding box of a GamePiece accounting for the offset of a piece within a stack * * @see GamePiece#getShape */ public Rectangle selectionBoundsOf(GamePiece p) { if (p.getMap() != this) { throw new IllegalArgumentException( Resources.getString("Map.piece_not_on_map")); //$NON-NLS-1$ } final Rectangle r = p.getShape().getBounds(); r.translate(p.getPosition().x, p.getPosition().y); if (p.getParent() != null) { Point pt = getStackMetrics().relativePosition(p.getParent(), p); r.translate(pt.x, pt.y); } return r; } /** * Returns the position of a GamePiece accounting for the offset within a parent stack, if any */ public Point positionOf(GamePiece p) { if (p.getMap() != this) { throw new IllegalArgumentException( Resources.getString("Map.piece_not_on_map")); //$NON-NLS-1$ } final Point point = p.getPosition(); if (p.getParent() != null) { final Point pt = getStackMetrics().relativePosition(p.getParent(), p); point.translate(pt.x, pt.y); } return point; } /** * @return an array of all GamePieces on the map. This is a read-only copy. * Altering the array does not alter the pieces on the map. */ public GamePiece[] getPieces() { return pieces.getPieces(); } public GamePiece[] getAllPieces() { return pieces.getAllPieces(); } public void setPieceCollection(PieceCollection pieces) { this.pieces = pieces; } public PieceCollection getPieceCollection() { return pieces; } protected void clearMapBorder(Graphics g) { final Graphics2D g2d = (Graphics2D) g.create(); final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX(); if (clearFirst || boards.isEmpty()) { g.setColor(bgColor); g.fillRect( 0, 0, componentToDrawing(theMap.getWidth(), os_scale), componentToDrawing(theMap.getHeight(), os_scale) ); clearFirst = false; } else { final int mw = componentToDrawing(theMap.getWidth(), os_scale); final int mh = componentToDrawing(theMap.getHeight(), os_scale); final int ew = mapToDrawing(edgeBuffer.width, os_scale); final int eh = mapToDrawing(edgeBuffer.height, os_scale); g.setColor(bgColor); g.fillRect(0, 0, ew, mh); g.fillRect(0, 0, mw, eh); g.fillRect(mw - ew, 0, ew, mh); g.fillRect(0, mh - eh, mw, eh); } } /** * Adjusts the bounds() rectangle to account for the Board's relative * position to other boards. In other words, if Board A is N pixels wide * and Board B is to the right of Board A, then the origin of Board B * will be adjusted N pixels to the right. */ protected void setBoardBoundaries() { int maxX = 0; int maxY = 0; for (Board b : boards) { Point relPos = b.relativePosition(); maxX = Math.max(maxX, relPos.x); maxY = Math.max(maxY, relPos.y); } boardWidths = new int[maxX + 1][maxY + 1]; boardHeights = new int[maxX + 1][maxY + 1]; for (Board b : boards) { Point relPos = b.relativePosition(); boardWidths[relPos.x][relPos.y] = b.bounds().width; boardHeights[relPos.x][relPos.y] = b.bounds().height; } Point offset = new Point(edgeBuffer.width, edgeBuffer.height); for (Board b : boards) { Point relPos = b.relativePosition(); Point location = getLocation(relPos.x, relPos.y, 1.0); b.setLocation(location.x, location.y); b.translate(offset.x, offset.y); } theMap.revalidate(); } protected Point getLocation(Board b, double zoom) { Point p; if (zoom == 1.0) { p = b.bounds().getLocation(); } else { Point relPos = b.relativePosition(); p = getLocation(relPos.x, relPos.y, zoom); p.translate((int) (zoom * edgeBuffer.width), (int) (zoom * edgeBuffer.height)); } return p; } protected Point getLocation(int column, int row, double zoom) { Point p = new Point(); for (int x = 0; x < column; ++x) { p.translate((int) Math.floor(zoom * boardWidths[x][row]), 0); } for (int y = 0; y < row; ++y) { p.translate(0, (int) Math.floor(zoom * boardHeights[column][y])); } return p; } /** * Draw the boards of the map at the given point and zoom factor onto * the given Graphics object */ public void drawBoards(Graphics g, int xoffset, int yoffset, double zoom, Component obs) { for (Board b : boards) { Point p = getLocation(b, zoom); p.translate(xoffset, yoffset); b.draw(g, p.x, p.y, zoom, obs); } } /** * Repaint the given area, specified in map coordinates */ public void repaint(Rectangle r) { r.setLocation(mapToComponent(new Point(r.x, r.y))); r.setSize((int) (r.width * getZoom()), (int) (r.height * getZoom())); theMap.repaint(r.x, r.y, r.width, r.height); } /** * @param show * if true, enable drawing of GamePiece. If false, don't draw GamePiece when painting the map */ public void setPiecesVisible(boolean show) { hideCounters = !show; } public boolean isPiecesVisible() { return !hideCounters && pieceOpacity != 0; } public float getPieceOpacity() { return pieceOpacity; } public void setPieceOpacity(float pieceOpacity) { this.pieceOpacity = pieceOpacity; } @Override public Object getProperty(Object key) { Object value = null; MutableProperty p = propsContainer.getMutableProperty(String.valueOf(key)); if (p != null) { value = p.getPropertyValue(); } else { value = GameModule.getGameModule().getProperty(key); } return value; } @Override public Object getLocalizedProperty(Object key) { Object value = null; MutableProperty p = propsContainer.getMutableProperty(String.valueOf(key)); if (p != null) { value = p.getPropertyValue(); } if (value == null) { value = GameModule.getGameModule().getLocalizedProperty(key); } return value; } /** * Return the auto-move key. It may be named, so just return * the allocated KeyStroke. * @return auto move keystroke */ public KeyStroke getMoveKey() { return moveKey == null ? null : moveKey.getKeyStroke(); } /** * @return the top-level window containing this map */ protected Window createParentFrame() { if (GlobalOptions.getInstance().isUseSingleWindow()) { JDialog d = new JDialog(GameModule.getGameModule().getPlayerWindow()); d.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); d.setTitle(getDefaultWindowTitle()); return d; } else { JFrame d = new JFrame(); d.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); d.setTitle(getDefaultWindowTitle()); d.setJMenuBar(MenuManager.getInstance().getMenuBarFor(d)); return d; } } public boolean shouldDockIntoMainWindow() { // set to show via a button, or no combined window at all, don't dock if (useLaunchButton || !GlobalOptions.getInstance().isUseSingleWindow()) { return false; } // otherwise dock if this map is the first not to show via a button for (Map m : GameModule.getGameModule().getComponentsOf(Map.class)) { if (m == this) { return true; } else if (m.shouldDockIntoMainWindow()) { return false; } } // should be impossible return true; } /** * When a game is started, create a top-level window, if none exists. * When a game is ended, remove all boards from the map. * * @see GameComponent */ @Override public void setup(boolean show) { if (show) { final GameModule g = GameModule.getGameModule(); if (shouldDockIntoMainWindow()) { if (mainWindowDock != null) { // This is protected from null elsewhere, and crashed null here, so I'm thinking protect here too. mainWindowDock.showComponent(); final int height = (Integer) Prefs.getGlobalPrefs().getValue(MAIN_WINDOW_HEIGHT); if (height > 0) { final Container top = mainWindowDock.getTopLevelAncestor(); top.setSize(top.getWidth(), height); } } if (toolBar.getParent() == null) { g.getToolBar().addSeparator(); g.getToolBar().add(toolBar); } toolBar.setVisible(true); } else { if (SwingUtilities.getWindowAncestor(theMap) == null) { final Window topWindow = createParentFrame(); topWindow.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (useLaunchButton) { topWindow.setVisible(false); } else { g.getGameState().setup(false); } } }); ((RootPaneContainer) topWindow).getContentPane().add("North", getToolBar()); //$NON-NLS-1$ ((RootPaneContainer) topWindow).getContentPane().add("Center", layeredPane); //$NON-NLS-1$ topWindow.setSize(600, 400); final PositionOption option = new PositionOption(PositionOption.key + getIdentifier(), topWindow); g.getPrefs().addOption(option); } theMap.getTopLevelAncestor().setVisible(!useLaunchButton); theMap.revalidate(); } } else { pieces.clear(); boards.clear(); if (mainWindowDock != null) { if (mainWindowDock.getHideableComponent().isShowing()) { Prefs.getGlobalPrefs().getOption(MAIN_WINDOW_HEIGHT) .setValue(mainWindowDock.getTopLevelAncestor().getHeight()); } mainWindowDock.hideComponent(); toolBar.setVisible(false); } else if (theMap.getTopLevelAncestor() != null) { theMap.getTopLevelAncestor().setVisible(false); } } launchButton.setEnabled(show); launchButton.setVisible(useLaunchButton); } public void appendToTitle(String s) { if (mainWindowDock == null) { Component c = theMap.getTopLevelAncestor(); if (s == null) { if (c instanceof JFrame) { ((JFrame) c).setTitle(getDefaultWindowTitle()); } if (c instanceof JDialog) { ((JDialog) c).setTitle(getDefaultWindowTitle()); } } else { if (c instanceof JFrame) { ((JFrame) c).setTitle(((JFrame) c).getTitle() + s); } if (c instanceof JDialog) { ((JDialog) c).setTitle(((JDialog) c).getTitle() + s); } } } } protected String getDefaultWindowTitle() { return getLocalizedMapName().length() > 0 ? getLocalizedMapName() : Resources.getString("Map.window_title", GameModule.getGameModule().getLocalizedGameName()); //$NON-NLS-1$ } /** * Use the provided {@link PieceFinder} instance to locate a visible piece at the given location */ public GamePiece findPiece(Point pt, PieceFinder finder) { GamePiece[] stack = pieces.getPieces(); for (int i = stack.length - 1; i >= 0; --i) { GamePiece p = finder.select(this, stack[i], pt); if (p != null) { return p; } } return null; } /** * Use the provided {@link PieceFinder} instance to locate any piece at the given location, regardless of whether it * is visible or not */ public GamePiece findAnyPiece(Point pt, PieceFinder finder) { GamePiece[] stack = pieces.getAllPieces(); for (int i = stack.length - 1; i >= 0; --i) { GamePiece p = finder.select(this, stack[i], pt); if (p != null) { return p; } } return null; } /** * Place a piece at the destination point. If necessary, remove the piece from its parent Stack or Map * * @return a {@link Command} that reproduces this action */ public Command placeAt(GamePiece piece, Point pt) { Command c = null; if (GameModule.getGameModule().getGameState().getPieceForId(piece.getId()) == null) { piece.setPosition(pt); addPiece(piece); GameModule.getGameModule().getGameState().addPiece(piece); c = new AddPiece(piece); } else { MoveTracker tracker = new MoveTracker(piece); piece.setPosition(pt); addPiece(piece); c = tracker.getMoveCommand(); } return c; } /** * Apply the provided {@link PieceVisitorDispatcher} to all pieces on this map. Returns the first non-null * {@link Command} returned by <code>commandFactory</code> * * @param commandFactory * */ public Command apply(PieceVisitorDispatcher commandFactory) { GamePiece[] stack = pieces.getPieces(); Command c = null; for (int i = 0; i < stack.length && c == null; ++i) { c = (Command) commandFactory.accept(stack[i]); } return c; } /** * Move a piece to the destination point. If a piece is at the point (i.e. has a location exactly equal to it), merge * with the piece by forwarding to {@link StackMetrics#merge}. Otherwise, place by forwarding to placeAt() * * @see StackMetrics#merge */ public Command placeOrMerge(final GamePiece p, final Point pt) { Command c = apply(new DeckVisitorDispatcher(new Merger(this, pt, p))); if (c == null || c.isNull()) { c = placeAt(p, pt); // If no piece at destination and this is a stacking piece, create // a new Stack containing the piece if (!(p instanceof Stack) && !Boolean.TRUE.equals(p.getProperty(Properties.NO_STACK))) { final Stack parent = getStackMetrics().createStack(p); if (parent != null) { c = c.append(placeAt(parent, pt)); } } } return c; } /** * Adds a GamePiece to this map. Removes the piece from its parent Stack and from its current map, if different from * this map */ public void addPiece(GamePiece p) { if (indexOf(p) < 0) { if (p.getParent() != null) { p.getParent().remove(p); p.setParent(null); } if (p.getMap() != null && p.getMap() != this) { p.getMap().removePiece(p); } pieces.add(p); p.setMap(this); theMap.repaint(); } } /** * Returns the index of a piece. When painting the map, pieces are drawn in order of index Return -1 if the piece is * not on this map */ public int indexOf(GamePiece s) { return pieces.indexOf(s); } /** * Removes a piece from the map */ public void removePiece(GamePiece p) { pieces.remove(p); theMap.repaint(); } /** * Center the map at given map coordinates within its JScrollPane container */ public void centerAt(Point p) { centerAt(p, 0, 0); } /** * Center the map at the given map coordinates, if the point is not * already within (dx,dy) of the center. */ public void centerAt(Point p, int dx, int dy) { if (scroll != null) { p = mapToComponent(p); final Rectangle r = theMap.getVisibleRect(); r.x = p.x - r.width/2; r.y = p.y - r.height/2; final Dimension d = getPreferredSize(); if (r.x + r.width > d.width) r.x = d.width - r.width; if (r.y + r.height > d.height) r.y = d.height - r.height; r.width = dx > r.width ? 0 : r.width - dx; r.height = dy > r.height ? 0 : r.height - dy; theMap.scrollRectToVisible(r); } } /** Ensure that the given region (in map coordinates) is visible */ public void ensureVisible(Rectangle r) { if (scroll != null) { final Point p = mapToComponent(r.getLocation()); r = new Rectangle(p.x, p.y, (int) (getZoom() * r.width), (int) (getZoom() * r.height)); theMap.scrollRectToVisible(r); } } /** * Scrolls the map in the containing JScrollPane. * * @param dx number of pixels to scroll horizontally * @param dy number of pixels to scroll vertically */ public void scroll(int dx, int dy) { Rectangle r = scroll.getViewport().getViewRect(); r.translate(dx, dy); r = r.intersection(new Rectangle(getPreferredSize())); theMap.scrollRectToVisible(r); } public static String getConfigureTypeName() { return Resources.getString("Editor.Map.component_type"); //$NON-NLS-1$ } public String getMapName() { return getConfigureName(); } public String getLocalizedMapName() { return getLocalizedConfigureName(); } public void setMapName(String s) { mapName = s; setConfigureName(mapName); if (tooltip == null || tooltip.length() == 0) { launchButton.setToolTipText(s != null ? Resources.getString("Map.show_hide", s) : Resources.getString("Map.show_hide", Resources.getString("Map.map"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } @Override public HelpFile getHelpFile() { return HelpFile.getReferenceManualPage("Map.htm"); //$NON-NLS-1$ } @Override public String[] getAttributeDescriptions() { return new String[] { Resources.getString("Editor.Map.map_name"), //$NON-NLS-1$ Resources.getString("Editor.Map.mark_pieces_moved"), //$NON-NLS-1$ Resources.getString("Editor.Map.mark_unmoved_button_text"), //$NON-NLS-1$ Resources.getString("Editor.Map.mark_unmoved_tooltip_text"), //$NON-NLS-1$ Resources.getString("Editor.Map.mark_unmoved_button_icon"), //$NON-NLS-1$ Resources.getString("Editor.Map.horizontal"), //$NON-NLS-1$ Resources.getString("Editor.Map.vertical"), //$NON-NLS-1$ Resources.getString("Editor.Map.bkgdcolor"), //$NON-NLS-1$ Resources.getString("Editor.Map.multiboard"), //$NON-NLS-1$ Resources.getString("Editor.Map.bc_selected_counter"), //$NON-NLS-1$ Resources.getString("Editor.Map.bt_selected_counter"), //$NON-NLS-1$ Resources.getString("Editor.Map.show_hide"), //$NON-NLS-1$ Resources.getString(Resources.BUTTON_TEXT), Resources.getString(Resources.TOOLTIP_TEXT), Resources.getString(Resources.BUTTON_ICON), Resources.getString(Resources.HOTKEY_LABEL), Resources.getString("Editor.Map.report_move_within"), //$NON-NLS-1$ Resources.getString("Editor.Map.report_move_to"), //$NON-NLS-1$ Resources.getString("Editor.Map.report_created"), //$NON-NLS-1$ Resources.getString("Editor.Map.report_modified"), //$NON-NLS-1$ Resources.getString("Editor.Map.key_applied_all") //$NON-NLS-1$ }; } @Override public String[] getAttributeNames() { return new String[] { NAME, MARK_MOVED, MARK_UNMOVED_TEXT, MARK_UNMOVED_TOOLTIP, MARK_UNMOVED_ICON, EDGE_WIDTH, EDGE_HEIGHT, BACKGROUND_COLOR, ALLOW_MULTIPLE, HIGHLIGHT_COLOR, HIGHLIGHT_THICKNESS, USE_LAUNCH_BUTTON, BUTTON_NAME, TOOLTIP, ICON, HOTKEY, MOVE_WITHIN_FORMAT, MOVE_TO_FORMAT, CREATE_FORMAT, CHANGE_FORMAT, MOVE_KEY }; } @Override public Class<?>[] getAttributeTypes() { return new Class<?>[] { String.class, GlobalOptions.Prompt.class, String.class, String.class, UnmovedIconConfig.class, Integer.class, Integer.class, Color.class, Boolean.class, Color.class, Integer.class, Boolean.class, String.class, String.class, IconConfig.class, NamedKeyStroke.class, MoveWithinFormatConfig.class, MoveToFormatConfig.class, CreateFormatConfig.class, ChangeFormatConfig.class, NamedKeyStroke.class }; } public static final String LOCATION = "location"; //$NON-NLS-1$ public static final String OLD_LOCATION = "previousLocation"; //$NON-NLS-1$ public static final String OLD_MAP = "previousMap"; //$NON-NLS-1$ public static final String MAP_NAME = "mapName"; //$NON-NLS-1$ public static final String PIECE_NAME = "pieceName"; //$NON-NLS-1$ public static final String MESSAGE = "message"; //$NON-NLS-1$ public static class IconConfig implements ConfigurerFactory { @Override public Configurer getConfigurer(AutoConfigurable c, String key, String name) { return new IconConfigurer(key, name, "/images/map.gif"); //$NON-NLS-1$ } } public static class UnmovedIconConfig implements ConfigurerFactory { @Override public Configurer getConfigurer(AutoConfigurable c, String key, String name) { return new IconConfigurer(key, name, "/images/unmoved.gif"); //$NON-NLS-1$ } } public static class MoveWithinFormatConfig implements TranslatableConfigurerFactory { @Override public Configurer getConfigurer(AutoConfigurable c, String key, String name) { return new PlayerIdFormattedStringConfigurer(key, name, new String[] { PIECE_NAME, LOCATION, MAP_NAME, OLD_LOCATION }); } } public static class MoveToFormatConfig implements TranslatableConfigurerFactory { @Override public Configurer getConfigurer(AutoConfigurable c, String key, String name) { return new PlayerIdFormattedStringConfigurer(key, name, new String[] { PIECE_NAME, LOCATION, OLD_MAP, MAP_NAME, OLD_LOCATION }); } } public static class CreateFormatConfig implements TranslatableConfigurerFactory { @Override public Configurer getConfigurer(AutoConfigurable c, String key, String name) { return new PlayerIdFormattedStringConfigurer(key, name, new String[] { PIECE_NAME, MAP_NAME, LOCATION }); } } public static class ChangeFormatConfig implements TranslatableConfigurerFactory { @Override public Configurer getConfigurer(AutoConfigurable c, String key, String name) { return new PlayerIdFormattedStringConfigurer(key, name, new String[] { MESSAGE, ReportState.COMMAND_NAME, ReportState.OLD_UNIT_NAME, ReportState.NEW_UNIT_NAME, ReportState.MAP_NAME, ReportState.LOCATION_NAME }); } } public String getCreateFormat() { if (createFormat != null) { return createFormat; } else { String val = "$" + PIECE_NAME + "$ created in $" + LOCATION + "$"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (!boards.isEmpty()) { Board b = boards.get(0); if (b.getGrid() == null || b.getGrid().getGridNumbering() == null) { val = ""; //$NON-NLS-1$ } } return val; } } public String getChangeFormat() { return isChangeReportingEnabled() ? changeFormat : ""; } public String getMoveToFormat() { if (moveToFormat != null) { return moveToFormat; } else { String val = "$" + PIECE_NAME + "$" + " moves $" + OLD_LOCATION + "$ -> $" + LOCATION + "$ *"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ if (!boards.isEmpty()) { Board b = boards.get(0); if (b.getGrid() == null || b.getGrid().getGridNumbering() != null) { val = ""; //$NON-NLS-1$ } } return val; } } public String getMoveWithinFormat() { if (moveWithinFormat != null) { return moveWithinFormat; } else { String val = "$" + PIECE_NAME + "$" + " moves $" + OLD_LOCATION + "$ -> $" + LOCATION + "$ *"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ if (!boards.isEmpty()) { Board b = boards.get(0); if (b.getGrid() == null) { val = ""; //$NON-NLS-1$ } } return val; } } @Override public Class<?>[] getAllowableConfigureComponents() { Class<?>[] c = { GlobalMap.class, LOS_Thread.class, ToolbarMenu.class, MultiActionButton.class, HidePiecesButton.class, Zoomer.class, CounterDetailViewer.class, HighlightLastMoved.class, LayeredPieceCollection.class, ImageSaver.class, TextSaver.class, DrawPile.class, SetupStack.class, MassKeyCommand.class, MapShader.class, PieceRecenterer.class }; return c; } @Override public VisibilityCondition getAttributeVisibility(String name) { if (visibilityCondition == null) { visibilityCondition = new VisibilityCondition() { @Override public boolean shouldBeVisible() { return useLaunchButton; } }; } if (List.of(HOTKEY, BUTTON_NAME, TOOLTIP, ICON).contains(name)) { return visibilityCondition; } else if (List.of(MARK_UNMOVED_TEXT, MARK_UNMOVED_ICON, MARK_UNMOVED_TOOLTIP).contains(name)) { return new VisibilityCondition() { @Override public boolean shouldBeVisible() { return !GlobalOptions.NEVER.equals(markMovedOption); } }; } else { return super.getAttributeVisibility(name); } } /** * Each Map must have a unique String id */ @Override public void setId(String id) { mapID = id; } public static Map getMapById(String id) { return (Map) idMgr.findInstance(id); } /** * Utility method to return a {@link List} of all map components in the * module. * * @return the list of <code>Map</code>s */ public static List<Map> getMapList() { final GameModule g = GameModule.getGameModule(); final List<Map> l = g.getComponentsOf(Map.class); for (ChartWindow cw : g.getComponentsOf(ChartWindow.class)) { for (MapWidget mw : cw.getAllDescendantComponentsOf(MapWidget.class)) { l.add(mw.getMap()); } } return l; } /** * Utility method to return a list of all map components in the module * * @return Iterator over all maps * @deprecated Use {@link #getMapList()} instead. */ @Deprecated public static Iterator<Map> getAllMaps() { return getMapList().iterator(); } /** * Find a contained Global Variable by name */ @Override public MutableProperty getMutableProperty(String name) { return propsContainer.getMutableProperty(name); } @Override public void addMutableProperty(String key, MutableProperty p) { propsContainer.addMutableProperty(key, p); p.addMutablePropertyChangeListener(repaintOnPropertyChange); } @Override public MutableProperty removeMutableProperty(String key) { MutableProperty p = propsContainer.removeMutableProperty(key); if (p != null) { p.removeMutablePropertyChangeListener(repaintOnPropertyChange); } return p; } @Override public String getMutablePropertiesContainerId() { return getMapName(); } /** * Each Map must have a unique String id * * @return the id for this map */ @Override public String getId() { return mapID; } /** * Make a best gues for a unique identifier for the target. Use * {@link VASSAL.tools.UniqueIdManager.Identifyable#getConfigureName} if non-null, otherwise use * {@link VASSAL.tools.UniqueIdManager.Identifyable#getId} * * @return */ public String getIdentifier() { return UniqueIdManager.getIdentifier(this); } /** @return the Swing component representing the map */ public JComponent getView() { if (theMap == null) { theMap = new View(this); scroll = new AdjustableSpeedScrollPane( theMap, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); scroll.unregisterKeyboardAction( KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0)); scroll.unregisterKeyboardAction( KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0)); scroll.setAlignmentX(0.0f); scroll.setAlignmentY(0.0f); layeredPane.setLayout(new InsetLayout(layeredPane, scroll)); layeredPane.add(scroll, JLayeredPane.DEFAULT_LAYER); } return theMap; } /** @return the JLayeredPane holding map insets */ public JLayeredPane getLayeredPane() { return layeredPane; } /** * The Layout responsible for arranging insets which overlay the Map * InsetLayout currently is responsible for keeping the {@link GlobalMap} * in the upper-left corner of the {@link Map.View}. */ public static class InsetLayout extends OverlayLayout { private static final long serialVersionUID = 1L; private final JScrollPane base; public InsetLayout(Container target, JScrollPane base) { super(target); this.base = base; } @Override public void layoutContainer(Container target) { super.layoutContainer(target); base.getLayout().layoutContainer(base); final Dimension viewSize = base.getViewport().getSize(); final Insets insets = base.getInsets(); viewSize.width += insets.left; viewSize.height += insets.top; // prevent non-base components from overlapping the base's scrollbars final int n = target.getComponentCount(); for (int i = 0; i < n; ++i) { Component c = target.getComponent(i); if (c != base && c.isVisible()) { final Rectangle b = c.getBounds(); b.width = Math.min(b.width, viewSize.width); b.height = Math.min(b.height, viewSize.height); c.setBounds(b); } } } } /** * Implements default logic for merging pieces at a given location within * a map Returns a {@link Command} that merges the input {@link GamePiece} * with an existing piece at the input position, provided the pieces are * stackable, visible, in the same layer, etc. */ public static class Merger implements DeckVisitor { private Point pt; private Map map; private GamePiece p; public Merger(Map map, Point pt, GamePiece p) { this.map = map; this.pt = pt; this.p = p; } @Override public Object visitDeck(Deck d) { if (d.getPosition().equals(pt)) { return map.getStackMetrics().merge(d, p); } else { return null; } } @Override public Object visitStack(Stack s) { if (s.getPosition().equals(pt) && map.getStackMetrics().isStackingEnabled() && !Boolean.TRUE.equals(p.getProperty(Properties.NO_STACK)) && s.topPiece() != null && map.getPieceCollection().canMerge(s, p)) { return map.getStackMetrics().merge(s, p); } else { return null; } } @Override public Object visitDefault(GamePiece piece) { if (piece.getPosition().equals(pt) && map.getStackMetrics().isStackingEnabled() && !Boolean.TRUE.equals(p.getProperty(Properties.NO_STACK)) && !Boolean.TRUE.equals(piece.getProperty(Properties.INVISIBLE_TO_ME)) && !Boolean.TRUE.equals(piece.getProperty(Properties.NO_STACK)) && map.getPieceCollection().canMerge(piece, p)) { return map.getStackMetrics().merge(piece, p); } else { return null; } } } /** * The component that represents the map itself */ public static class View extends JPanel { private static final long serialVersionUID = 1L; protected Map map; public View(Map m) { setFocusTraversalKeysEnabled(false); map = m; } @Override public void paint(Graphics g) { // Don't draw the map until the game is updated. if (GameModule.getGameModule().getGameState().isUpdating()) { return; } final Graphics2D g2d = (Graphics2D) g; g2d.addRenderingHints(SwingUtils.FONT_HINTS); final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX(); // HDPI: We may get a transform where scale != 1. This means we // are running on an HDPI system. We want to draw at the effective // scale factor to prevent poor quality upscaling, so reset the // transform to scale of 1 and multiply the map zoom by the OS scaling. final AffineTransform orig_t = g2d.getTransform(); g2d.setTransform(SwingUtils.descaleTransform(orig_t)); final Rectangle r = map.componentToDrawing(getVisibleRect(), os_scale); g2d.setColor(map.bgColor); g2d.fillRect(r.x, r.y, r.width, r.height); map.paintRegion(g2d, r); g2d.setTransform(orig_t); } @Override public void update(Graphics g) { // To avoid flicker, don't clear the display first paint(g); } @Override public Dimension getPreferredSize() { return map.getPreferredSize(); } public Map getMap() { return map; } } }
package org.cbioportal.security.spring.authentication.saml; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.cbioportal.model.User; import org.cbioportal.model.UserAuthorities; import org.cbioportal.persistence.SecurityRepository; import org.cbioportal.security.spring.authentication.PortalUserDetails; import org.opensaml.saml2.core.Attribute; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.saml.SAMLCredential; import org.springframework.security.saml.userdetails.SAMLUserDetailsService; import org.springframework.stereotype.Service; /** * Custom UserDetailsService which parses SAML messages and checks authorization of * user against cbioportal's `authorities` configuration. Authentication is done by the SAML IDP. * * @author Pieter Lukasse */ @Service public class SAMLUserDetailsServiceImpl implements SAMLUserDetailsService { private static final Log log = LogFactory.getLog(SAMLUserDetailsServiceImpl.class); private static String samlIdpMetadataEmailAttributeName; @Value("${saml.idp.metadata.attribute.email:mail}") public void setSamlIdpMetadataEmailAttributeName(String property) { this.samlIdpMetadataEmailAttributeName = property; } @Autowired private SecurityRepository securityRepository; /** * Constructor. */ public SAMLUserDetailsServiceImpl() { } /** * Implementation of {@code SAMLUserDetailsService}. Parses user details from given * SAML credential object. */ @Override public Object loadUserBySAML(SAMLCredential credential) { PortalUserDetails toReturn = null; String userId = null; // get userid and name: iterate over attributes searching for "mail" and "displayName": for (Attribute cAttribute : credential.getAttributes()) { log.debug("loadUserBySAML(), parsing attribute - " + cAttribute.toString()); log.debug("loadUserBySAML(), parsing attribute - " + cAttribute.getName()); log.debug("loadUserBySAML(), parsing attribute - " + credential.getAttributeAsString(cAttribute.getName())); if (userId == null && cAttribute.getName().equals(samlIdpMetadataEmailAttributeName)) { userId = credential.getAttributeAsString(cAttribute.getName()); //userid = credential.getNameID().getValue(); needed to support OneLogin...?? Although with OneLogin we haven't gotten this far yet... } } //check if this user exists in our DB try { //validate parsing: if (userId == null) { String errorMessage = "loadUserBySAML(), Could not parse the user details from credential message. Expected 'mail' attribute, but attribute was not found. " + " Previous debug messages show which attributes were found and parsed."; log.error(errorMessage); throw new Exception(errorMessage); } log.debug("loadUserBySAML(), IDP successfully authenticated user, userid: " + userId); log.debug("loadUserBySAML(), now attempting to fetch portal user authorities for userid: " + userId); //try to find user in DB User user = securityRepository.getPortalUser(userId); if (user != null && user.isEnabled()) { log.debug("loadUserBySAML(), user is enabled; attempting to fetch portal user authorities, userid: " + userId); UserAuthorities authorities = securityRepository.getPortalUserAuthorities(userId); if (authorities != null) { List<GrantedAuthority> grantedAuthorities = AuthorityUtils.createAuthorityList(authorities.getAuthorities().toArray(new String[authorities.getAuthorities().size()])); //add granted authorities: toReturn = new PortalUserDetails(userId, grantedAuthorities); toReturn.setEmail(userId); toReturn.setName(userId); } } else if (user == null) { // new user log.debug("loadUserBySAML(), user authorities is null, userid: " + userId + ". Depending on property always_show_study_group, " + "he could still have default access (to PUBLIC studies)"); toReturn = new PortalUserDetails(userId, getInitialEmptyAuthoritiesList()); toReturn.setEmail(userId); toReturn.setName(userId); } else { //user WAS found in DB but has been actively disabled: throw new UsernameNotFoundException("Error: Your user access to cBioPortal has been disabled"); } return toReturn; } catch (UsernameNotFoundException unnf) { //throw this exception, so that the user gets redirected to the error HTML page: throw unnf; } catch (Exception e) { //other (unexpected) errors: just throw (will result in http 500 page with error message): log.error(e.getMessage()); e.printStackTrace(); throw new RuntimeException("Error during authentication parsing: " + e.getMessage()); } } /** * Returns an initial empty authorities list. * * @return */ private List<GrantedAuthority> getInitialEmptyAuthoritiesList() { return AuthorityUtils.createAuthorityList(new String[0]); } }
package gow.fcm.pantallas; import gow.fcm.footballcoachmanager.R; import gow.fcm.footballcoachmanager.R.layout; import gow.fcm.footballcoachmanager.R.menu; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class EstadisticasJugador extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_estadisticas_jugador); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.estadisticas_jugador, menu); return true; } //jajajajajaja }
package eu.bcvsolutions.idm.core.rest.impl; import java.util.List; import org.joda.time.LocalDate; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import eu.bcvsolutions.idm.core.api.dto.IdmContractPositionDto; import eu.bcvsolutions.idm.core.api.dto.IdmIdentityContractDto; import eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto; import eu.bcvsolutions.idm.core.api.dto.IdmIdentityRoleDto; import eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityRoleFilter; import eu.bcvsolutions.idm.core.api.rest.AbstractReadWriteDtoController; import eu.bcvsolutions.idm.core.api.rest.AbstractReadWriteDtoControllerRestTest; public class IdmIdentityRoleControllerRestTest extends AbstractReadWriteDtoControllerRestTest<IdmIdentityRoleDto> { @Autowired private IdmIdentityRoleController controller; @Override protected AbstractReadWriteDtoController<IdmIdentityRoleDto, ?> getController() { return controller; } @Override protected boolean isReadOnly() { return true; } @Override protected IdmIdentityRoleDto prepareDto() { IdmIdentityRoleDto dto = new IdmIdentityRoleDto(); dto.setIdentityContractDto(getHelper().getPrimeContract(getHelper().createIdentity().getId())); dto.setRole(getHelper().createRole().getId()); dto.setValidFrom(new LocalDate()); dto.setValidTill(new LocalDate().plusDays(1)); return dto; } @Test public void findByText() { // username IdmIdentityDto identity = getHelper().createIdentity(); IdmIdentityRoleDto createIdentityRole = getHelper().createIdentityRole(identity, getHelper().createRole()); IdmIdentityDto other = getHelper().createIdentity(); getHelper().createIdentityRole(other, getHelper().createRole()); IdmIdentityRoleFilter filter = new IdmIdentityRoleFilter(); filter.setText(identity.getUsername()); List<IdmIdentityRoleDto> results = find(filter); Assert.assertEquals(1, results.size()); Assert.assertTrue(results.stream().anyMatch(ir -> ir.getId().equals(createIdentityRole.getId()))); } @Test public void findInvalidRoles() { IdmIdentityDto identity = getHelper().createIdentity(); getHelper().createIdentityRole(identity, getHelper().createRole()); // valid IdmIdentityRoleDto inValidByDate = getHelper().createIdentityRole(identity, getHelper().createRole(), null, LocalDate.now().minusDays(2)); IdmIdentityContractDto invalidContract = getHelper().createIdentityContact(identity, null, null, LocalDate.now().minusDays(2)); IdmIdentityRoleDto inValidByContract = getHelper().createIdentityRole(invalidContract, getHelper().createRole()); IdmIdentityRoleFilter filter = new IdmIdentityRoleFilter(); filter.setIdentityId(identity.getId()); filter.setValid(Boolean.FALSE); List<IdmIdentityRoleDto> results = find(filter); Assert.assertEquals(2, results.size()); Assert.assertTrue(results.stream().anyMatch(ir -> ir.getId().equals(inValidByDate.getId()))); Assert.assertTrue(results.stream().anyMatch(ir -> ir.getId().equals(inValidByContract.getId()))); } @Test public void findAutomaticRoles() { IdmIdentityContractDto contract = getHelper().getPrimeContract(getHelper().createIdentity().getId()); IdmIdentityRoleDto normal = getHelper().createIdentityRole(contract, getHelper().createRole()); // normal // automatic IdmIdentityRoleDto automaticIdentityRole = new IdmIdentityRoleDto(); automaticIdentityRole.setIdentityContract(contract.getId()); automaticIdentityRole.setRole(getHelper().createRole().getId()); automaticIdentityRole.setAutomaticRole(getHelper().createAutomaticRole(getHelper().createRole().getId()).getId()); IdmIdentityRoleDto automatic = createDto(automaticIdentityRole); IdmIdentityRoleFilter filter = new IdmIdentityRoleFilter(); filter.setIdentityContractId(contract.getId()); filter.setAutomaticRole(Boolean.TRUE); List<IdmIdentityRoleDto> results = find(filter); Assert.assertEquals(1, results.size()); Assert.assertTrue(results.stream().anyMatch(ir -> ir.getId().equals(automatic.getId()))); filter.setAutomaticRole(Boolean.FALSE); results = find(filter); Assert.assertEquals(1, results.size()); Assert.assertTrue(results.stream().anyMatch(ir -> ir.getId().equals(normal.getId()))); } @Test public void findDirectRoles() { IdmIdentityContractDto contract = getHelper().getPrimeContract(getHelper().createIdentity().getId()); IdmIdentityRoleDto normal = getHelper().createIdentityRole(contract, getHelper().createRole()); // normal // not direct IdmIdentityRoleDto notDirectIdentityRole = new IdmIdentityRoleDto(); notDirectIdentityRole.setIdentityContract(contract.getId()); notDirectIdentityRole.setRole(getHelper().createRole().getId()); notDirectIdentityRole.setDirectRole(normal.getId()); IdmIdentityRoleDto notDirect = createDto(notDirectIdentityRole); IdmIdentityRoleFilter filter = new IdmIdentityRoleFilter(); filter.setIdentityContractId(contract.getId()); filter.setDirectRole(Boolean.TRUE); List<IdmIdentityRoleDto> results = find(filter); Assert.assertEquals(1, results.size()); Assert.assertTrue(results.stream().anyMatch(ir -> ir.getId().equals(normal.getId()))); filter.setDirectRole(Boolean.FALSE); results = find(filter); Assert.assertEquals(1, results.size()); Assert.assertTrue(results.stream().anyMatch(ir -> ir.getId().equals(notDirect.getId()))); } @Test public void findByContractPosition() { IdmIdentityDto identity = getHelper().createIdentity(); IdmIdentityContractDto contract = getHelper().getPrimeContract(identity.getId()); IdmContractPositionDto contractPositionOne = getHelper().createContractPosition(contract); IdmContractPositionDto contractPositionOther = getHelper().createContractPosition(contract); IdmIdentityRoleDto one = getHelper().createIdentityRole(contractPositionOne, getHelper().createRole()); getHelper().createIdentityRole(contractPositionOther, getHelper().createRole()); // other IdmIdentityRoleFilter filter = new IdmIdentityRoleFilter(); filter.setIdentityId(identity.getId()); filter.setContractPositionId(contractPositionOne.getId()); List<IdmIdentityRoleDto> results = find(filter); Assert.assertEquals(1, results.size()); Assert.assertTrue(results.stream().anyMatch(ir -> ir.getId().equals(one.getId()))); } @Test @Ignore @Override public void testSaveFormDefinition() throws Exception { // We don't want testing form definition - IdentityRole has extra behavior (role attributes) for Form (definition is changing by role) } }
package com.rgi.g2t; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import java.util.zip.DataFormatException; import javax.activation.MimeType; import javax.activation.MimeTypeParseException; import javax.imageio.ImageIO; import javax.imageio.stream.ImageOutputStream; import javax.naming.OperationNotSupportedException; import org.gdal.gdal.Dataset; import utility.GdalUtility; import utility.GdalUtility.GdalRasterParameters; import com.rgi.common.BoundingBox; import com.rgi.common.Dimensions; import com.rgi.common.Range; import com.rgi.common.coordinate.Coordinate; import com.rgi.common.coordinate.CoordinateReferenceSystem; import com.rgi.common.coordinate.CrsCoordinate; import com.rgi.common.coordinate.referencesystem.profile.CrsProfile; import com.rgi.common.coordinate.referencesystem.profile.CrsProfileFactory; import com.rgi.common.tile.TileOrigin; import com.rgi.common.tile.scheme.TileMatrixDimensions; import com.rgi.common.tile.scheme.TileScheme; import com.rgi.common.tile.scheme.ZoomTimesTwo; import com.rgi.common.util.FileUtility; import com.rgi.store.tiles.TileHandle; import com.rgi.store.tiles.TileStoreException; import com.rgi.store.tiles.TileStoreReader; /** * TileStoreReader implementation for GDAL-readable image files * * @author Steven D. Lander * @author Luke D. Lambert * */ public class RawImageTileReader implements TileStoreReader { /** * Constructor * * @param rawImage * A raster image * @param tileSize * A {@link Dimensions} that describes what an individual tile * looks like * @param noDataColor * The {@link Color} of the NODATA fields within the raster image * @throws TileStoreException * Thrown when GDAL could not get the correct * {@link CoordinateReferenceSystem} of the input raster OR if * the raw image could not be loaded as a {@link Dataset} */ public RawImageTileReader(final File rawImage, final Dimensions<Integer> tileSize, final Color noDataColor) throws TileStoreException { this(rawImage, tileSize, noDataColor, null); } /** * Constructor * * @param rawImage * A raster image {@link File} * @param tileSize * A {@link Dimensions} that describes what an individual tile * looks like * @param noDataColor * The {@link Color} of the NODATA fields within the raster image * @param coordinateReferenceSystem * The {@link CoordinateReferenceSystem} the tiles should be * output in * @throws TileStoreException * Thrown when GDAL could not get the correct * {@link CoordinateReferenceSystem} of the input raster OR if * the raw image could not be loaded as a {@link Dataset} */ public RawImageTileReader(final File rawImage, final Dimensions<Integer> tileSize, final Color noDataColor, final CoordinateReferenceSystem coordinateReferenceSystem) throws TileStoreException { if(rawImage == null || !rawImage.canRead()) { throw new IllegalArgumentException("Raw image may not be null, and must represent a valid file on disk."); } if(tileSize == null) { throw new IllegalArgumentException("Tile size may not be null."); } this.rawImage = rawImage; this.tileSize = tileSize; // TODO check noDataColor for null when the feature is implemented this.noDataColor = noDataColor; this.dataset = GdalUtility.open(rawImage, coordinateReferenceSystem); try { if(this.dataset.GetRasterBand(1).GetColorTable() != null) { System.out.println("expand this raster to RGB/RGBA"); // TODO: make a temporary vrt with gdal_translate to expand this to RGB/RGBA } if(this.dataset.GetRasterCount() == 0) { throw new IllegalArgumentException("Input file has no raster bands"); } // We cannot tile an image with no geo referencing information if(!GdalUtility.hasGeoReference(this.dataset)) { throw new IllegalArgumentException("Input raster image has no georeference."); } this.coordinateReferenceSystem = GdalUtility.getCoordinateReferenceSystem(GdalUtility.getSpatialReference(this.dataset)); if(this.coordinateReferenceSystem == null) { throw new IllegalArgumentException("Image file is not in a recognized coordinate reference system"); } this.profile = CrsProfileFactory.create(this.coordinateReferenceSystem); this.tileScheme = new ZoomTimesTwo(0, 31, 1, 1); // Use absolute tile numbering final BoundingBox datasetBounds = GdalUtility.getBounds(this.dataset); this.tileRanges = GdalUtility.calculateTileRanges(this.tileScheme, datasetBounds, this.profile.getBounds(), this.profile, RawImageTileReader.Origin); final int minimumZoom = GdalUtility.getMinimalZoom(this.dataset, this.tileRanges, Origin, this.tileScheme, tileSize); final int maximumZoom = GdalUtility.getMaximalZoom(this.dataset, this.tileRanges, Origin, this.tileScheme, tileSize); // The bounds of the dataset is **almost never** the bounds of the // data. The bounds of the dataset fit inside the bounds of the // data because the bounds of the data must align to the tile grid. // The minimum zoom level is selected such that the entire dataset // fits inside a single tile. that single tile is the minimum data // bounds. final Coordinate<Integer> minimumTile = this.tileRanges.get(minimumZoom).getMinimum(); // The minimum and maximum for the range returned from tileRanges.get() should be identical (it's a single tile) this.dataBounds = this.getTileBoundingBox(minimumTile.getX(), minimumTile.getY(), this.tileScheme.dimensions(minimumZoom)); this.zoomLevels = IntStream.rangeClosed(minimumZoom, maximumZoom) .boxed() .collect(Collectors.toSet()); this.tileCount = IntStream.rangeClosed(minimumZoom, maximumZoom) .map(zoomLevel -> { final Range<Coordinate<Integer>> range = this.tileRanges.get(zoomLevel); return (range.getMaximum().getX() - range.getMinimum().getX() + 1) * (range.getMinimum().getY() - range.getMaximum().getY() + 1); }) .sum(); } catch(final DataFormatException dfe) { this.close(); throw new TileStoreException(dfe); } this.cachedTiles = new HashMap<String, Path>(); } @Override public void close() { if(this.dataset != null) { this.dataset.delete(); } } @Override public BoundingBox getBounds() { return this.dataBounds; } @Override public long countTiles() { return this.tileCount; } @Override public long getByteSize() { return this.rawImage.length(); } @Override public BufferedImage getTile(final int column, final int row, final int zoomLevel) throws TileStoreException { throw new TileStoreException(new OperationNotSupportedException()); } @Override public BufferedImage getTile(final CrsCoordinate coordinate, final int zoomLevel) throws TileStoreException { throw new TileStoreException(new OperationNotSupportedException()); } @Override public Set<Integer> getZoomLevels() { return this.zoomLevels; } @Override public Stream<TileHandle> stream() throws TileStoreException { final List<TileHandle> tileHandles = new ArrayList<>(); final Range<Integer> zoomRange = new Range<>(this.zoomLevels, Integer::compare); // Should always start with the lowest-integer-zoom-level that has only one tile final Range<Coordinate<Integer>> zoomInfo = this.tileRanges.get(zoomRange.getMinimum()); // Get the coordinate information final Coordinate<Integer> topLeftCoordinate = zoomInfo.getMinimum(); final Coordinate<Integer> bottomRightCoordinate = zoomInfo.getMaximum(); // Parse each coordinate into min/max tiles for X/Y final int zoomMinXTile = topLeftCoordinate.getX(); final int zoomMaxXTile = bottomRightCoordinate.getX(); final int zoomMinYTile = bottomRightCoordinate.getY(); final int zoomMaxYTile = topLeftCoordinate.getY(); if (zoomMaxYTile == zoomMinYTile && zoomMinXTile == zoomMaxXTile) { this.makeTiles(tileHandles, new RawImageTileHandle(zoomRange.getMinimum(), zoomMinXTile, zoomMinYTile), zoomRange.getMaximum()); } else { throw new TileStoreException("Min zoom has more than one tile."); } tileHandles.sort((o1, o2) -> Integer.compare(o2.getZoomLevel(), o1.getZoomLevel())); return tileHandles.stream(); } private boolean tileIntersectsData(final RawImageTileHandle tile) { final int zoom = tile.getZoomLevel(); final int column = tile.getColumn(); final int row = tile.getRow(); final Range<Coordinate<Integer>> zoomRange = this.tileRanges.get(zoom); return column >= zoomRange.getMinimum().getX() && column <= zoomRange.getMaximum().getX() && row >= zoomRange.getMaximum().getY() && row <= zoomRange.getMinimum().getY(); } private void makeTiles(final List<TileHandle> tileHandles, final RawImageTileHandle tile, final int maxZoom) throws TileStoreException { if(!this.tileIntersectsData(tile)) { return; } if(tile.getZoomLevel() == maxZoom) { // tell the RawImageTileHandle this is a special case: a gdalImage tileHandles.add(new RawImageTileHandle(tile.getZoomLevel(), tile.getColumn(), tile.getRow(), true)); } else { // calculate all the tiles below this current one final int zoomBelow = tile.getZoomLevel() + 1; final int zoomColumnBelow = tile.getColumn() * 2; final int zoomRowBelow = tile.getRow() * 2; // recurse final RawImageTileHandle tileBelow1 = new RawImageTileHandle(zoomBelow, zoomColumnBelow, zoomRowBelow); final RawImageTileHandle tileBelow2 = new RawImageTileHandle(zoomBelow, zoomColumnBelow + 1, zoomRowBelow); final RawImageTileHandle tileBelow3 = new RawImageTileHandle(zoomBelow, zoomColumnBelow, zoomRowBelow + 1); final RawImageTileHandle tileBelow4 = new RawImageTileHandle(zoomBelow, zoomColumnBelow + 1, zoomRowBelow + 1); this.makeTiles(tileHandles, tileBelow1, maxZoom); this.makeTiles(tileHandles, tileBelow2, maxZoom); this.makeTiles(tileHandles, tileBelow3, maxZoom); this.makeTiles(tileHandles, tileBelow4, maxZoom); tileHandles.add(tile); } } @Override public Stream<TileHandle> stream(final int zoomLevel) { final Range<Coordinate<Integer>> zoomInfo = this.tileRanges.get(zoomLevel); // Get the coordinate information final Coordinate<Integer> topLeftCoordinate = zoomInfo.getMinimum(); final Coordinate<Integer> bottomRightCoordinate = zoomInfo.getMaximum(); // Parse each coordinate into min/max tiles for X/Y final int zoomMinXTile = topLeftCoordinate.getX(); final int zoomMaxXTile = bottomRightCoordinate.getX(); final int zoomMinYTile = bottomRightCoordinate.getY(); final int zoomMaxYTile = topLeftCoordinate.getY(); // Create a tile handle list that we can append to final List<TileHandle> tileHandles = new ArrayList<>(); for(int tileY = zoomMaxYTile; tileY >= zoomMinYTile; --tileY) { for(int tileX = zoomMinXTile; tileX <= zoomMaxXTile; ++tileX) { tileHandles.add(new RawImageTileHandle(zoomLevel, tileX, tileY)); } } // Return the entire tile handle list as a stream return tileHandles.stream(); } @Override public CoordinateReferenceSystem getCoordinateReferenceSystem() { return this.coordinateReferenceSystem; } @Override public String getName() { return FileUtility.nameWithoutExtension(this.rawImage); } @Override public String getImageType() throws TileStoreException { try { final MimeType mimeType = new MimeType(Files.probeContentType(this.rawImage.toPath())); if(mimeType.getPrimaryType().toLowerCase().equals("image")) { return mimeType.getSubType(); } return null; } catch(final MimeTypeParseException | IOException ex) { throw new TileStoreException(ex); } } @Override public Dimensions<Integer> getImageDimensions() throws TileStoreException { return this.tileSize; } @Override public TileScheme getTileScheme() throws TileStoreException { return this.tileScheme; } @Override public TileOrigin getTileOrigin() { return Origin; } private class RawImageTileHandle implements TileHandle { private final TileMatrixDimensions matrix; private boolean gotImage = false; private boolean gdalImage = false; private Path cachedImageLocation = null; private BufferedImage image; private final int zoomLevel; private final int column; private final int row; RawImageTileHandle(final int zoom, final int column, final int row) { this.zoomLevel = zoom; this.column = column; this.row = row; this.matrix = RawImageTileReader.this.tileScheme.dimensions(this.zoomLevel); } RawImageTileHandle(final int zoom, final int column, final int row, final Path cachedImageLocation) { this.zoomLevel = zoom; this.column = column; this.row = row; this.matrix = RawImageTileReader.this.tileScheme.dimensions(this.zoomLevel); this.cachedImageLocation = cachedImageLocation; } RawImageTileHandle(final int zoom, final int column, final int row, final boolean gdalImage) { this.zoomLevel = zoom; this.column = column; this.row = row; this.matrix = RawImageTileReader.this.tileScheme.dimensions(this.zoomLevel); this.gdalImage = gdalImage; } @Override public int getZoomLevel() { return this.zoomLevel; } @Override public int getColumn() { return this.column; } @Override public int getRow() { return this.row; } public Path getCachedImagePath() { return this.cachedImageLocation; } @Override public TileMatrixDimensions getMatrix() throws TileStoreException { return this.matrix; } @Override public CrsCoordinate getCrsCoordinate() throws TileStoreException { return RawImageTileReader.this.tileToCrsCoordinate(this.column, this.row, this.matrix, RawImageTileReader.Origin); } @Override public CrsCoordinate getCrsCoordinate(final TileOrigin corner) throws TileStoreException { return RawImageTileReader.this.tileToCrsCoordinate(this.column, this.row, this.matrix, corner); } @Override public BoundingBox getBounds() throws TileStoreException { return RawImageTileReader.this.getTileBoundingBox(this.column, this.row, this.matrix); } @Override public BufferedImage getImage() throws TileStoreException { if(this.gotImage == true) { return this.image; } if(this.gdalImage == true) { // Build the parameters for GDAL read raster call final GdalRasterParameters params = GdalUtility.getGdalRasterParameters(RawImageTileReader.this.dataset.GetGeoTransform(), this.getBounds(), RawImageTileReader.this.tileSize, RawImageTileReader.this.dataset); try { // Read image data directly from the raster final byte[] imageData = GdalUtility.readRaster(params, RawImageTileReader.this.dataset); // TODO: logic goes here in the case that the querysize == tile size (gdalconstConstants.GRA_NearestNeighbour) (write directly) final Dataset querySizeImageCanvas = GdalUtility.writeRaster(params, imageData, RawImageTileReader.this.dataset.GetRasterCount()); try { // Scale each band of tileDataInMemory down to the tile size (down from the query size) final Dataset tileDataInMemory = GdalUtility.scaleQueryToTileSize(querySizeImageCanvas, RawImageTileReader.this.tileSize); this.image = GdalUtility.convert(tileDataInMemory); // Write this image to disk for later overview generation final Path baseTilePath = this.writeTempTile(this.image); // Add the image path to the reader map RawImageTileReader.this.cachedTiles.put(this.tileKey(this.zoomLevel, this.column, this.row), baseTilePath); // Clean up dataset tileDataInMemory.delete(); this.gotImage = true; return this.image; } catch(final TilingException | IOException ex) { throw new TileStoreException(ex); } finally { querySizeImageCanvas.delete(); } } catch(final TilingException ex) { throw new TileStoreException(ex); } catch(final IOException ex) { // Return a transparent tile this.gotImage = true; return this.createTransparentImage(); } } // Make this tile by getting the tiles below it and scaling them to fit return this.generateScaledTileFromChildren(); } private Path writeTempTile(final BufferedImage tileImage) throws IOException { final Path baseTilePath = File.createTempFile("baseTile" + String.valueOf(this.getZoomLevel()) + String.valueOf(this.getColumn()) + String.valueOf(this.getRow()), ".png") .toPath(); try(final ImageOutputStream fileOutputStream = ImageIO.createImageOutputStream(baseTilePath.toFile())) { ImageIO.write(tileImage, "png", baseTilePath.toFile()); } return baseTilePath; } private BufferedImage createTransparentImage() { final int tileWidth = RawImageTileReader.this.tileSize.getWidth(); final int tileHeight = RawImageTileReader.this.tileSize.getHeight(); final BufferedImage transparentImage = new BufferedImage(tileWidth, tileHeight, BufferedImage.TYPE_INT_ARGB); final Graphics2D graphics = transparentImage.createGraphics(); graphics.setComposite(AlphaComposite.Clear); graphics.fillRect(0, 0, tileWidth, tileHeight); graphics.dispose(); // Return the transparent tile return transparentImage; } private BufferedImage generateScaledTileFromChildren() throws TileStoreException { final int tileWidth = RawImageTileReader.this.tileSize.getWidth(); final int tileHeight = RawImageTileReader.this.tileSize.getHeight(); // Create the full-sized buffered image from the child tiles final BufferedImage fullCanvas = new BufferedImage(tileWidth * 2, tileHeight * 2, BufferedImage.TYPE_INT_ARGB); // Create the full-sized graphics object final Graphics2D fullCanvasGraphics = fullCanvas.createGraphics(); // Get child handles final List<RawImageTileHandle> children = new ArrayList<>(); final int childZoom = this.getZoomLevel() + 1; final int childColumn = this.getColumn() * 2; final int childRow = this.getRow() * 2; final Path origin = RawImageTileReader.this.cachedTiles.get(this.tileKey(childZoom, childColumn, childRow)); final Path columnShifted = RawImageTileReader.this.cachedTiles.get(this.tileKey(childZoom, childColumn + 1, childRow)); final Path rowShifted = RawImageTileReader.this.cachedTiles.get(this.tileKey(childZoom, childColumn, childRow + 1)); final Path bothShifted = RawImageTileReader.this.cachedTiles.get(this.tileKey(childZoom, childColumn + 1, childRow + 1)); children.add(new RawImageTileHandle(childZoom, childColumn, childRow, origin)); children.add(new RawImageTileHandle(childZoom, childColumn + 1, childRow, columnShifted)); children.add(new RawImageTileHandle(childZoom, childColumn, childRow + 1, rowShifted)); children.add(new RawImageTileHandle(childZoom, childColumn + 1, childRow + 1, bothShifted)); // Get the cached children of this tile final List<RawImageTileHandle> transformedChildren = new ArrayList<>(); for (final RawImageTileHandle tileHandle : children) { final Coordinate<Integer> resultCoordinate = RawImageTileReader.Origin.transform(TileOrigin.UpperLeft, tileHandle.getColumn(), tileHandle.getRow(), this.matrix); transformedChildren.add(new RawImageTileHandle(tileHandle.getZoomLevel(), resultCoordinate.getX(), resultCoordinate.getY(), tileHandle.getCachedImagePath())); } transformedChildren.sort((o1, o2) -> { final int columnCompare = Integer.compare(o1.getColumn(), o2.getColumn()); final int rowCompare = Integer.compare(o1.getRow(), o2.getRow()); // column values are the same if (columnCompare == 0) { return rowCompare; } if (rowCompare == 0) { return columnCompare; } // TODO: Duplicate tile case? return 0; }); try { // Origin tile if(transformedChildren.get(2).getCachedImagePath() != null) { final BufferedImage originImage = ImageIO.read(transformedChildren.get(2).getCachedImagePath().toFile()); fullCanvasGraphics.drawImage(originImage, null, 0, 0); } // Tile that is Y+1 in relation to the origin if(transformedChildren.get(0).getCachedImagePath() != null) { final BufferedImage rowShiftedImage = ImageIO.read(transformedChildren.get(0).getCachedImagePath().toFile()); fullCanvasGraphics.drawImage(rowShiftedImage, null, 0, tileHeight); } // Tile that is X+1 in relation to the origin if(transformedChildren.get(3).getCachedImagePath() != null) { final BufferedImage columnShiftedImage = ImageIO.read(transformedChildren.get(3).getCachedImagePath().toFile()); fullCanvasGraphics.drawImage(columnShiftedImage, null, tileWidth, 0); } // Tile that is both X+1 and Y+1 in relation to the origin if(transformedChildren.get(1).getCachedImagePath() != null) { final BufferedImage bothShiftedImage = ImageIO.read(transformedChildren.get(1).getCachedImagePath().toFile()); fullCanvasGraphics.drawImage(bothShiftedImage, null, tileWidth, tileHeight); } } catch(final IOException ex) { throw new TileStoreException(ex); } final BufferedImage tileCanvas = new BufferedImage(tileWidth, tileHeight, BufferedImage.TYPE_INT_ARGB); final AffineTransform affineTransform = new AffineTransform(); affineTransform.scale(0.5, 0.5); final AffineTransformOp scaleOp = new AffineTransformOp(affineTransform, AffineTransformOp.TYPE_BILINEAR); final BufferedImage scaledTile = scaleOp.filter(fullCanvas, tileCanvas); // Clean-up step fullCanvasGraphics.dispose(); if(origin != null) { origin.toFile().delete(); } RawImageTileReader.this.cachedTiles.remove(this.tileKey(childZoom, childColumn, childRow)); if(columnShifted != null) { columnShifted.toFile().delete(); } RawImageTileReader.this.cachedTiles.remove(this.tileKey(childZoom, childColumn + 1, childRow)); if(rowShifted != null) { rowShifted.toFile().delete(); } RawImageTileReader.this.cachedTiles.remove(this.tileKey(childZoom, childColumn, childRow + 1)); if(bothShifted != null) { bothShifted.toFile().delete(); } RawImageTileReader.this.cachedTiles.remove(this.tileKey(childZoom, childColumn + 1, childRow + 1)); // Write cached tile try { RawImageTileReader.this.cachedTiles.put(this.tileKey(this.zoomLevel, this.column, this.row), this.writeTempTile(scaledTile)); } catch(final IOException ex) { throw new TileStoreException(ex); } return scaledTile; } private String tileKey(final int zoom, final int column, final int row) { return String.format("%d/%d/%d", zoom, column, row); } @Override public String toString() { return this.tileKey(this.getZoomLevel(), this.getColumn(), this.getRow()); } } private CrsCoordinate tileToCrsCoordinate(final int column, final int row, final TileMatrixDimensions tileMatrixDimensions, final TileOrigin corner) { if(corner == null) { throw new IllegalArgumentException("Corner may not be null"); } return this.profile.tileToCrsCoordinate(column + corner.getHorizontal(), row + corner.getVertical(), this.profile.getBounds(), // RawImageTileReader uses absolute tiling, which covers the whole globe tileMatrixDimensions, RawImageTileReader.Origin); } private BoundingBox getTileBoundingBox(final int column, final int row, final TileMatrixDimensions tileMatrixDimensions) { return this.profile.getTileBounds(column, row, this.profile.getBounds(), tileMatrixDimensions, RawImageTileReader.Origin); } private final File rawImage; private final CoordinateReferenceSystem coordinateReferenceSystem; private final Dimensions<Integer> tileSize; private final Color noDataColor; // TODO implement no-data color handling private final Dataset dataset; private final BoundingBox dataBounds; private final Set<Integer> zoomLevels; private final ZoomTimesTwo tileScheme; private final CrsProfile profile; private final int tileCount; private final Map<Integer, Range<Coordinate<Integer>>> tileRanges; private final Map<String, Path> cachedTiles; private static final TileOrigin Origin = TileOrigin.LowerLeft; private static final String tmpDir = System.getProperty("java.io.tmpdir"); }
package org.csstudio.sds.components.ui.internal.figures; import org.csstudio.sds.ui.figures.IBorderEquippedWidget; import org.csstudio.sds.util.CustomMediaFactory; import org.eclipse.draw2d.AbstractBorder; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.LineBorder; import org.eclipse.draw2d.SchemeBorder; import org.eclipse.draw2d.SchemeBorder.Scheme; import org.eclipse.draw2d.geometry.Insets; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.swt.graphics.Color; /** * This adapter enriches <code>IFigure</code> instances with the abilities * that are defined by the <code>IBorderEquippedWidget</code> interface. * * @author Sven Wende * @version $Revision$ * */ public final class BorderAdapter implements IBorderEquippedWidget { /** * The enriched <code>IFigure</code> instance. */ private IFigure _figure; /** * The border width. */ private int _borderWidth = 1; /** * The border color. */ private Color _borderColor = CustomMediaFactory.getInstance().getColor(0, 0, 0); /** * The border style. */ private Integer _borderStyle = 1; /** * Standard constructor. * * @param figure * The enriched <code>IFigure</code> instance. */ public BorderAdapter(final IFigure figure) { _figure = figure; } /** * {@inheritDoc} */ public void setBorderWidth(final int width) { _borderWidth = width; refreshBorder(); } /** * {@inheritDoc} */ public void setBorderColor(final Color borderColor) { _borderColor = borderColor; refreshBorder(); } /** * {@inheritDoc} */ public void setBorderStyle(final int style) { _borderStyle = style; refreshBorder(); } /** * Refresh the border. */ private void refreshBorder() { if (_borderWidth > 0) { AbstractBorder border; switch (_borderStyle) { case 0 : border = this.createLineBorder(); break; case 1 : border = this.createSchemeBorder(); break; case 2 : border = this.createStriatedBorder(); break; default : border = this.createLineBorder(); break; } _figure.setBorder(border); _figure.repaint(); } else { _figure.setBorder(null); } } /** * Creates a LineBorder. * @return AbstractBorder * The requested Border */ private AbstractBorder createLineBorder() { LineBorder border = new LineBorder(); border.setWidth(_borderWidth); border.setColor(_borderColor); return border; } /** * Creates a SchemeBorder. * @return AbstractBorder * The requested Border */ private AbstractBorder createSchemeBorder() { SchemeBorder border = new SchemeBorder(new Scheme(new Color[] {_borderColor})); return border; } /** * Creates a StriatedBorder. * @return AbstractBorder * The requested Border */ private AbstractBorder createStriatedBorder() { StriatedBorder border = new StriatedBorder(_borderWidth); return border; } /** * A striated Border. * @author Kai Meyer */ private final class StriatedBorder extends AbstractBorder { /** * The insets for this Border. */ private Insets _insets; /** * The Width of the Border */ private int _borderWidth; /** * Constructor. * @param borderWidth * The width of the Border */ public StriatedBorder(final int borderWidth) { _insets = new Insets(borderWidth); _borderWidth = borderWidth; } /** * {@inheritDoc} */ public Insets getInsets(IFigure figure) { return _insets; } /** * {@inheritDoc} */ public void paint(IFigure figure, Graphics graphics, Insets insets) { Rectangle bounds = figure.getBounds(); graphics.setForegroundColor(CustomMediaFactory.getInstance().getColor(255, 0, 0)); graphics.setBackgroundColor(CustomMediaFactory.getInstance().getColor(255, 0, 0)); //System.out.println("StriatedBorder.paint() X: "+bounds.x+" Y:"+bounds.y+" Width: "+_borderWidth+" Height: "+_borderWidth); int xPos = bounds.x; while (xPos+_borderWidth<bounds.x+bounds.width) { Rectangle rec = new Rectangle(xPos,bounds.y, _borderWidth, _borderWidth); graphics.fillRectangle(rec); rec = new Rectangle(xPos,bounds.y+bounds.height-_borderWidth, _borderWidth, _borderWidth); graphics.fillRectangle(rec); xPos = xPos + 2*_borderWidth; } int yPos = bounds.y; while (yPos+_borderWidth<bounds.y+bounds.height) { Rectangle rec = new Rectangle(bounds.x, yPos, _borderWidth, _borderWidth); graphics.fillRectangle(rec); rec = new Rectangle(bounds.x+bounds.width-_borderWidth, yPos, _borderWidth, _borderWidth); graphics.fillRectangle(rec); yPos = yPos + 2*_borderWidth; } Rectangle rec = new Rectangle(bounds.x+bounds.width-_borderWidth,bounds.y+bounds.height-_borderWidth, _borderWidth, _borderWidth); graphics.fillRectangle(rec); } } }
package org.hisp.dhis.artemis.audit.listener; import static com.google.common.base.Preconditions.checkNotNull; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import lombok.extern.slf4j.Slf4j; import org.hibernate.Hibernate; import org.hibernate.event.spi.EventSource; import org.hibernate.event.spi.PostDeleteEvent; import org.hibernate.event.spi.PostInsertEvent; import org.hibernate.event.spi.PostUpdateEvent; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.proxy.HibernateProxy; import org.hisp.dhis.artemis.audit.AuditManager; import org.hisp.dhis.artemis.audit.legacy.AuditObjectFactory; import org.hisp.dhis.artemis.config.UsernameSupplier; import org.hisp.dhis.audit.AuditType; import org.hisp.dhis.audit.Auditable; import org.hisp.dhis.common.BaseIdentifiableObject; import org.hisp.dhis.common.IdentifiableObjectUtils; import org.hisp.dhis.commons.util.DebugUtils; import org.hisp.dhis.hibernate.HibernateProxyUtils; import org.hisp.dhis.schema.Property; import org.hisp.dhis.schema.Schema; import org.hisp.dhis.schema.SchemaService; import org.hisp.dhis.system.util.AnnotationUtils; import org.hisp.dhis.system.util.ReflectionUtils; /** * @author Luciano Fiandesio */ @Slf4j public abstract class AbstractHibernateListener { protected final AuditManager auditManager; protected final AuditObjectFactory objectFactory; private final UsernameSupplier usernameSupplier; private final SchemaService schemaService; public AbstractHibernateListener( AuditManager auditManager, AuditObjectFactory objectFactory, UsernameSupplier usernameSupplier, SchemaService schemaService ) { checkNotNull( auditManager ); checkNotNull( objectFactory ); checkNotNull( usernameSupplier ); checkNotNull( schemaService ); this.auditManager = auditManager; this.objectFactory = objectFactory; this.usernameSupplier = usernameSupplier; this.schemaService = schemaService; } Optional<Auditable> getAuditable( Object object, String type ) { if ( AnnotationUtils.isAnnotationPresent( HibernateProxyUtils.getRealClass( object ), Auditable.class ) ) { Auditable auditable = AnnotationUtils.getAnnotation( HibernateProxyUtils.getRealClass( object ), Auditable.class ); boolean shouldAudit = Arrays.stream( auditable.eventType() ) .anyMatch( s -> s.contains( "all" ) || s.contains( type ) ); if ( shouldAudit ) { return Optional.of( auditable ); } } return Optional.empty(); } public String getCreatedBy() { return usernameSupplier.get(); } abstract AuditType getAuditType(); /** * Create serializable Map<String, Object> for delete event Because the * entity has already been deleted and transaction is committed all lazy * collections or properties that haven't been loaded will be ignored. * * @return Map<String, Object> with key is property name and value is * property value. */ protected Object createAuditEntry( PostDeleteEvent event ) { Map<String, Object> objectMap = new HashMap<>(); Schema schema = schemaService.getDynamicSchema( HibernateProxyUtils.getRealClass( event.getEntity() ) ); Map<String, Property> properties = schema.getFieldNameMapProperties(); for ( int i = 0; i < event.getDeletedState().length; i++ ) { if ( event.getDeletedState()[i] == null ) { continue; } Object value = event.getDeletedState()[i]; String pName = event.getPersister().getPropertyNames()[i]; Property property = properties.get( pName ); if ( property == null || !property.isOwner() ) { continue; } if ( Hibernate.isInitialized( value ) ) { if ( property.isCollection() && BaseIdentifiableObject.class.isAssignableFrom( property.getItemKlass() ) ) { objectMap.put( pName, IdentifiableObjectUtils.getUids( (Collection) value ) ); } else { objectMap.put( pName, getId( value ) ); } } } return objectMap; } /** * Create serializable Map<String, Object> based on given Audit Entity and * related objects that are produced by {@link PostUpdateEvent} or * {@link PostInsertEvent} The returned object must comply with below rules: * 1. Only includes referenced properties that are owned by the current * Audit Entity. Means that the property's schema has attribute "owner = * true" 2. Do not include any lazy HibernateProxy or PersistentCollection * that is not loaded. 3. All referenced properties that extend * BaseIdentifiableObject should be mapped to only UID string * * @return Map<String, Object> with key is property name and value is * property value. */ protected Object createAuditEntry( Object entity, Object[] state, EventSource session, Serializable id, EntityPersister persister ) { Map<String, Object> objectMap = new HashMap<>(); Schema schema = schemaService.getDynamicSchema( HibernateProxyUtils.getRealClass( entity ) ); Map<String, Property> properties = schema.getFieldNameMapProperties(); HibernateProxy entityProxy = null; for ( int i = 0; i < state.length; i++ ) { if ( state[i] == null ) continue; Object value = state[i]; String pName = persister.getPropertyNames()[i]; Property property = properties.get( pName ); if ( property == null || (!property.isOwner() && !property.isEmbeddedObject()) ) { continue; } if ( shouldInitializeProxy( value ) || property.isEmbeddedObject() ) { if ( entityProxy == null ) { entityProxy = createProxy( id, session, persister ); } value = getPropertyValue( entityProxy, persister, pName ); } if ( value == null ) { continue; } putValueToMap( property, objectMap, value ); } return objectMap; } private HibernateProxy createProxy( Serializable id, EventSource session, EntityPersister persister ) { try { return (HibernateProxy) persister.createProxy( id, session ); } catch ( Exception ex ) { log.debug( "Couldn't create proxy " + DebugUtils.getStackTrace( ex ) ); } return null; } private void handleNonIdentifiableCollection( Property property, Object value, Map<String, Object> objectMap ) { if ( value == null ) return; Schema schema = schemaService.getSchema( property.getItemKlass() ); if ( schema == null ) { objectMap.put( property.getFieldName(), value ); return; } List<Map<String, Object>> listProperties = new ArrayList<>(); List<Property> properties = schema.getProperties(); Collection collection = (Collection) value; collection.forEach( item -> { Map<String, Object> propertyMap = new HashMap<>(); properties.forEach( prop -> putValueToMap( prop, propertyMap, ReflectionUtils.invokeGetterMethod( prop.getFieldName(), item ) ) ); listProperties.add( propertyMap ); } ); objectMap.put( property.getFieldName(), listProperties ); } private void putValueToMap( Property property, Map<String, Object> objectMap, Object value ) { if ( value == null ) return; if ( property.isCollection() ) { Collection collection = (Collection) value; if ( collection.isEmpty() ) return; if ( BaseIdentifiableObject.class.isAssignableFrom( property.getItemKlass() ) ) { List<String> uids = IdentifiableObjectUtils.getUids( collection ); if ( uids != null && !uids.isEmpty() ) { objectMap.put( property.getFieldName(), uids ); } } else { handleNonIdentifiableCollection( property, value, objectMap ); } } else { objectMap.put( property.getFieldName(), getId( value ) ); } } private Object getPropertyValue( HibernateProxy entityProxy, EntityPersister persister, String pName ) { try { return persister.getPropertyValue( entityProxy, pName ); } catch ( Exception ex ) { // Ignore if couldn't find property reference object, maybe it was // deleted. log.debug( "Couldn't value of property: " + pName, DebugUtils.getStackTrace( ex ) ); } return null; } private boolean shouldInitializeProxy( Object value ) { if ( value == null || Hibernate.isInitialized( value ) ) { return false; } return true; } private Object getId( Object object ) { if ( BaseIdentifiableObject.class.isAssignableFrom( object.getClass() ) ) { return ((BaseIdentifiableObject) object).getUid(); } return object; } }
package org.elasticsearch.xpack.security.action.user; import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.common.Strings; import org.elasticsearch.common.ValidationException; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore; import org.elasticsearch.xpack.security.authc.esnative.ReservedRealm; import org.elasticsearch.xpack.security.user.AnonymousUser; import org.elasticsearch.xpack.security.user.SystemUser; import org.elasticsearch.xpack.security.user.User; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import org.elasticsearch.xpack.security.user.XPackUser; import org.junit.Before; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.emptyArray; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; public class TransportGetUsersActionTests extends ESTestCase { private boolean anonymousEnabled; private Settings settings; @Before public void maybeEnableAnonymous() { anonymousEnabled = randomBoolean(); if (anonymousEnabled) { settings = Settings.builder().put(AnonymousUser.ROLES_SETTING.getKey(), "superuser").build(); } else { settings = Settings.EMPTY; } } public void testAnonymousUser() { NativeUsersStore usersStore = mock(NativeUsersStore.class); when(usersStore.started()).thenReturn(true); AnonymousUser anonymousUser = new AnonymousUser(settings); ReservedRealm reservedRealm = new ReservedRealm(mock(Environment.class), settings, usersStore, anonymousUser); TransportGetUsersAction action = new TransportGetUsersAction(Settings.EMPTY, mock(ThreadPool.class), mock(ActionFilters.class), mock(IndexNameExpressionResolver.class), usersStore, mock(TransportService.class), reservedRealm); GetUsersRequest request = new GetUsersRequest(); request.usernames(anonymousUser.principal()); final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); final AtomicReference<GetUsersResponse> responseRef = new AtomicReference<>(); action.doExecute(request, new ActionListener<GetUsersResponse>() { @Override public void onResponse(GetUsersResponse response) { responseRef.set(response); } @Override public void onFailure(Exception e) { throwableRef.set(e); } }); assertThat(throwableRef.get(), is(nullValue())); assertThat(responseRef.get(), is(notNullValue())); final User[] users = responseRef.get().users(); if (anonymousEnabled) { assertThat("expected array with anonymous but got: " + Arrays.toString(users), users, arrayContaining(anonymousUser)); } else { assertThat("expected an empty array but got: " + Arrays.toString(users), users, emptyArray()); } verifyZeroInteractions(usersStore); } public void testInternalUser() { NativeUsersStore usersStore = mock(NativeUsersStore.class); TransportGetUsersAction action = new TransportGetUsersAction(Settings.EMPTY, mock(ThreadPool.class), mock(ActionFilters.class), mock(IndexNameExpressionResolver.class), usersStore, mock(TransportService.class), mock(ReservedRealm.class)); GetUsersRequest request = new GetUsersRequest(); request.usernames(randomFrom(SystemUser.INSTANCE.principal(), XPackUser.INSTANCE.principal())); final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); final AtomicReference<GetUsersResponse> responseRef = new AtomicReference<>(); action.doExecute(request, new ActionListener<GetUsersResponse>() { @Override public void onResponse(GetUsersResponse response) { responseRef.set(response); } @Override public void onFailure(Exception e) { throwableRef.set(e); } }); assertThat(throwableRef.get(), instanceOf(IllegalArgumentException.class)); assertThat(throwableRef.get().getMessage(), containsString("is internal")); assertThat(responseRef.get(), is(nullValue())); verifyZeroInteractions(usersStore); } public void testReservedUsersOnly() { NativeUsersStore usersStore = mock(NativeUsersStore.class); when(usersStore.started()).thenReturn(true); ReservedRealm reservedRealm = new ReservedRealm(mock(Environment.class), settings, usersStore, new AnonymousUser(settings)); final Collection<User> allReservedUsers = reservedRealm.users(); final int size = randomIntBetween(1, allReservedUsers.size()); final List<User> reservedUsers = randomSubsetOf(size, allReservedUsers); final List<String> names = reservedUsers.stream().map(User::principal).collect(Collectors.toList()); TransportGetUsersAction action = new TransportGetUsersAction(Settings.EMPTY, mock(ThreadPool.class), mock(ActionFilters.class), mock(IndexNameExpressionResolver.class), usersStore, mock(TransportService.class), reservedRealm); logger.error("names {}", names); GetUsersRequest request = new GetUsersRequest(); request.usernames(names.toArray(new String[names.size()])); final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); final AtomicReference<GetUsersResponse> responseRef = new AtomicReference<>(); action.doExecute(request, new ActionListener<GetUsersResponse>() { @Override public void onResponse(GetUsersResponse response) { responseRef.set(response); } @Override public void onFailure(Exception e) { throwableRef.set(e); } }); assertThat(throwableRef.get(), is(nullValue())); assertThat(responseRef.get(), is(notNullValue())); assertThat(responseRef.get().users(), arrayContaining(reservedUsers.toArray(new User[reservedUsers.size()]))); } public void testGetAllUsers() { final List<User> storeUsers = randomFrom(Collections.<User>emptyList(), Collections.singletonList(new User("joe")), Arrays.asList(new User("jane"), new User("fred")), randomUsers()); NativeUsersStore usersStore = mock(NativeUsersStore.class); when(usersStore.started()).thenReturn(true); ReservedRealm reservedRealm = new ReservedRealm(mock(Environment.class), settings, usersStore, new AnonymousUser(settings)); TransportGetUsersAction action = new TransportGetUsersAction(Settings.EMPTY, mock(ThreadPool.class), mock(ActionFilters.class), mock(IndexNameExpressionResolver.class), usersStore, mock(TransportService.class), reservedRealm); GetUsersRequest request = new GetUsersRequest(); doAnswer(new Answer() { public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); assert args.length == 2; ActionListener<List<User>> listener = (ActionListener<List<User>>) args[1]; listener.onResponse(storeUsers); return null; } }).when(usersStore).getUsers(eq(Strings.EMPTY_ARRAY), any(ActionListener.class)); final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); final AtomicReference<GetUsersResponse> responseRef = new AtomicReference<>(); action.doExecute(request, new ActionListener<GetUsersResponse>() { @Override public void onResponse(GetUsersResponse response) { responseRef.set(response); } @Override public void onFailure(Exception e) { throwableRef.set(e); } }); final List<User> expectedList = new ArrayList<>(); expectedList.addAll(reservedRealm.users()); expectedList.addAll(storeUsers); assertThat(throwableRef.get(), is(nullValue())); assertThat(responseRef.get(), is(notNullValue())); assertThat(responseRef.get().users(), arrayContaining(expectedList.toArray(new User[expectedList.size()]))); verify(usersStore, times(1)).getUsers(aryEq(Strings.EMPTY_ARRAY), any(ActionListener.class)); } public void testGetStoreOnlyUsers() { final List<User> storeUsers = randomFrom(Collections.singletonList(new User("joe")), Arrays.asList(new User("jane"), new User("fred")), randomUsers()); final String[] storeUsernames = storeUsers.stream().map(User::principal).collect(Collectors.toList()).toArray(Strings.EMPTY_ARRAY); NativeUsersStore usersStore = mock(NativeUsersStore.class); TransportGetUsersAction action = new TransportGetUsersAction(Settings.EMPTY, mock(ThreadPool.class), mock(ActionFilters.class), mock(IndexNameExpressionResolver.class), usersStore, mock(TransportService.class), mock(ReservedRealm.class)); GetUsersRequest request = new GetUsersRequest(); request.usernames(storeUsernames); if (storeUsernames.length > 1) { doAnswer(new Answer() { public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); assert args.length == 2; ActionListener<List<User>> listener = (ActionListener<List<User>>) args[1]; listener.onResponse(storeUsers); return null; } }).when(usersStore).getUsers(aryEq(storeUsernames), any(ActionListener.class)); } else { assertThat(storeUsernames.length, is(1)); doAnswer(new Answer() { public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); assert args.length == 2; ActionListener<User> listener = (ActionListener<User>) args[1]; listener.onResponse(storeUsers.get(0)); return null; } }).when(usersStore).getUser(eq(storeUsernames[0]), any(ActionListener.class)); } final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); final AtomicReference<GetUsersResponse> responseRef = new AtomicReference<>(); action.doExecute(request, new ActionListener<GetUsersResponse>() { @Override public void onResponse(GetUsersResponse response) { responseRef.set(response); } @Override public void onFailure(Exception e) { throwableRef.set(e); } }); final List<User> expectedList = new ArrayList<>(); expectedList.addAll(storeUsers); assertThat(throwableRef.get(), is(nullValue())); assertThat(responseRef.get(), is(notNullValue())); assertThat(responseRef.get().users(), arrayContaining(expectedList.toArray(new User[expectedList.size()]))); if (storeUsers.size() > 1) { verify(usersStore, times(1)).getUsers(aryEq(storeUsernames), any(ActionListener.class)); } else { verify(usersStore, times(1)).getUser(eq(storeUsernames[0]), any(ActionListener.class)); } } public void testException() { final Exception e = randomFrom(new ElasticsearchSecurityException(""), new IllegalStateException(), new ValidationException()); final List<User> storeUsers = randomFrom(Collections.singletonList(new User("joe")), Arrays.asList(new User("jane"), new User("fred")), randomUsers()); final String[] storeUsernames = storeUsers.stream().map(User::principal).collect(Collectors.toList()).toArray(Strings.EMPTY_ARRAY); NativeUsersStore usersStore = mock(NativeUsersStore.class); TransportGetUsersAction action = new TransportGetUsersAction(Settings.EMPTY, mock(ThreadPool.class), mock(ActionFilters.class), mock(IndexNameExpressionResolver.class), usersStore, mock(TransportService.class), mock(ReservedRealm.class)); GetUsersRequest request = new GetUsersRequest(); request.usernames(storeUsernames); if (storeUsernames.length > 1) { doAnswer(new Answer() { public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); assert args.length == 2; ActionListener<List<User>> listener = (ActionListener<List<User>>) args[1]; listener.onFailure(e); return null; } }).when(usersStore).getUsers(aryEq(storeUsernames), any(ActionListener.class)); } else { assertThat(storeUsernames.length, is(1)); doAnswer(new Answer() { public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); assert args.length == 2; ActionListener<User> listener = (ActionListener<User>) args[1]; listener.onFailure(e); return null; } }).when(usersStore).getUser(eq(storeUsernames[0]), any(ActionListener.class)); } final AtomicReference<Throwable> throwableRef = new AtomicReference<>(); final AtomicReference<GetUsersResponse> responseRef = new AtomicReference<>(); action.doExecute(request, new ActionListener<GetUsersResponse>() { @Override public void onResponse(GetUsersResponse response) { responseRef.set(response); } @Override public void onFailure(Exception e) { throwableRef.set(e); } }); assertThat(throwableRef.get(), is(notNullValue())); assertThat(throwableRef.get(), is(sameInstance(e))); assertThat(responseRef.get(), is(nullValue())); if (request.usernames().length == 1) { verify(usersStore, times(1)).getUser(eq(request.usernames()[0]), any(ActionListener.class)); } else { verify(usersStore, times(1)).getUsers(aryEq(storeUsernames), any(ActionListener.class)); } } private List<User> randomUsers() { int size = scaledRandomIntBetween(3, 16); List<User> users = new ArrayList<>(size); for (int i = 0; i < size; i++) { users.add(new User("user_" + i, randomAsciiOfLengthBetween(4, 12))); } return users; } }
package com.rockwellcollins.atc.agree.analysis; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import org.osate.aadl2.instance.ComponentInstance; import com.rockwellcollins.atc.agree.agree.AssumeStatement; import com.rockwellcollins.atc.agree.agree.LemmaStatement; import com.rockwellcollins.atc.agree.analysis.lustre.visitors.IdRewriteVisitor; import com.rockwellcollins.atc.agree.ast.AgreeASTBuilder; import com.rockwellcollins.atc.agree.ast.AgreeConnection; import com.rockwellcollins.atc.agree.ast.AgreeConnection.ConnectionType; import com.rockwellcollins.atc.agree.ast.AgreeNode; import com.rockwellcollins.atc.agree.ast.AgreeProgram; import com.rockwellcollins.atc.agree.ast.AgreeStatement; import com.rockwellcollins.atc.agree.ast.AgreeVar; import com.rockwellcollins.atc.agree.ast.AgreeNode.TimingModel; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.BoolExpr; import jkind.lustre.CondactExpr; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.NamedType; import jkind.lustre.Node; import jkind.lustre.NodeCallExpr; import jkind.lustre.Program; import jkind.lustre.RecordType; import jkind.lustre.TupleExpr; import jkind.lustre.Type; import jkind.lustre.TypeDef; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.VarDecl; public class LustreAstBuilder { private static List<Node> nodes; private static final String guarSuffix = "__GUARANTEE"; private static final String assumeSuffix = "__ASSUME"; private static final String lemmaSuffix = "__LEMMA"; public static Program getLustreProgram(AgreeProgram agreeProgram){ nodes = new ArrayList<>(); List<TypeDef> types = new ArrayList<>(); for(Type type : agreeProgram.globalTypes){ RecordType recType = (RecordType)type; types.add(new TypeDef(recType.id, type)); } AgreeNode flatNode = flattenAgreeNode(agreeProgram.topNode, "_TOP__"); List<Expr> assertions = new ArrayList<>(); List<VarDecl> locals = new ArrayList<>(); List<VarDecl> inputs = new ArrayList<>(); List<Equation> equations = new ArrayList<>(); List<String> properties = new ArrayList<>(); for(AgreeStatement assumption : flatNode.assumptions){ assertions.add(assumption.expr); } for(AgreeStatement assertion : flatNode.assertions){ assertions.add(assertion.expr); } int i = 0; for(AgreeStatement guarantee : flatNode.lemmas){ String guarName = guarSuffix+i++; locals.add(new AgreeVar(guarName, NamedType.BOOL, guarantee.reference, flatNode.compInst)); equations.add(new Equation(new IdExpr(guarName), guarantee.expr)); properties.add(guarName); } for(AgreeStatement guarantee : flatNode.guarantees){ String guarName = guarSuffix+i++; locals.add(new AgreeVar(guarName, NamedType.BOOL, guarantee.reference, flatNode.compInst)); equations.add(new Equation(new IdExpr(guarName), guarantee.expr)); properties.add(guarName); } for(AgreeVar var : flatNode.inputs){ inputs.add(var); } int j = 0; for(AgreeVar var : flatNode.outputs){ if(var.reference instanceof AssumeStatement || var.reference instanceof LemmaStatement){ //remove the reference so that we don't check the ungaurded //variable as an assumption inputs.add(new VarDecl(var.id, NamedType.BOOL)); //stupid hack to get the assumption properties right Expr clockExpr = new BoolExpr(true); ComponentInstance curInst = var.compInst; while(curInst != flatNode.compInst){ String compLocation = curInst.getInstanceObjectPath(); compLocation = getRelativeLocation(compLocation); compLocation.replace(".", AgreeASTBuilder.dotChar); Expr clockId = new IdExpr(compLocation+AgreeASTBuilder.clockIDSuffix); clockExpr = new BinaryExpr(clockExpr, BinaryOp.AND, clockId); curInst = curInst.getContainingComponentInstance(); } clockExpr = new BinaryExpr(clockExpr, BinaryOp.IMPLIES, new IdExpr(var.id)); AgreeVar assumeCheckVar = new AgreeVar(assumeSuffix+j++, NamedType.BOOL, var.reference, var.compInst); locals.add(assumeCheckVar); equations.add(new Equation(new IdExpr(assumeCheckVar.id), clockExpr)); properties.add(assumeCheckVar.id); }else{ inputs.add(var); } } Node main = new Node("main", inputs, null, locals, equations, properties, assertions); nodes.add(main); nodes.addAll(agreeProgram.globalLustreNodes); Program program = new Program(types, null, nodes, main.id); return program; } public static String getRelativeLocation(String location){ int dotIndex = location.indexOf("."); if(dotIndex < 0){ return ""; } return location.substring(dotIndex+1); } private static Equation getHist(IdExpr histId, Expr expr){ Expr preHist = new UnaryExpr(UnaryOp.PRE, histId); Expr preAndNow = new BinaryExpr(preHist, BinaryOp.AND, expr); return new Equation(histId, new BinaryExpr(expr, BinaryOp.ARROW, preAndNow)); } private static Node getInputLatchingNode(IdExpr clockExpr, List<VarDecl> inputs, String nodeName){ List<VarDecl> outputs = new ArrayList<>(); List<VarDecl> locals = new ArrayList<>(); List<Equation> equations = new ArrayList<>(); String clockRiseName = "__RISE"; locals.add(new VarDecl(clockRiseName, NamedType.BOOL)); IdExpr clockRiseId = new IdExpr(clockRiseName); Expr preClock = new UnaryExpr(UnaryOp.PRE, clockExpr); Expr notPreClock = new UnaryExpr(UnaryOp.NOT, preClock); Expr clockRise = new BinaryExpr(notPreClock, BinaryOp.AND, clockExpr); clockRise = new BinaryExpr(clockExpr, BinaryOp.ARROW, clockRise); equations.add(new Equation(clockRiseId, clockRise)); for(VarDecl var : inputs){ String latchName = "latched__"+var.id; IdExpr input = new IdExpr(var.id); IdExpr latchId = new IdExpr(latchName); outputs.add(new VarDecl(latchName, var.type)); Expr preLatch = new UnaryExpr(UnaryOp.PRE, latchId); equations.add(new Equation(latchId, new BinaryExpr(input, BinaryOp.ARROW, new IfThenElseExpr(clockRiseId, input, preLatch)))); } // List<VarDecl> newInputs = new ArrayList<>(); // for(AgreeVar var : inputs){ // newInputs.add(var); inputs.add(new VarDecl(clockExpr.id, NamedType.BOOL)); return new Node(nodeName, inputs, outputs, locals, equations); } private static Node getLustreNode(AgreeNode agreeNode, String nodePrefix){ List<VarDecl> inputs = new ArrayList<>(); List<VarDecl> locals = new ArrayList<>(); List<Equation> equations = new ArrayList<>(); List<Expr> assertions = new ArrayList<>(); Expr assumeConjExpr = new BoolExpr(true); int i = 0; for(AgreeStatement statement : agreeNode.assumptions){ String inputName = assumeSuffix+i++; inputs.add(new AgreeVar(inputName, NamedType.BOOL, statement.reference, agreeNode.compInst)); IdExpr assumeId = new IdExpr(inputName); assertions.add(new BinaryExpr(assumeId, BinaryOp.EQUAL, statement.expr)); assumeConjExpr = new BinaryExpr(assumeId, BinaryOp.AND, assumeConjExpr); } int j = 0; for(AgreeStatement statement : agreeNode.lemmas){ String inputName = lemmaSuffix+j++; inputs.add(new AgreeVar(inputName, NamedType.BOOL, statement.reference, agreeNode.compInst)); IdExpr lemmaId = new IdExpr(inputName); assertions.add(new BinaryExpr(lemmaId, BinaryOp.EQUAL, statement.expr)); } String assumeHistName = assumeSuffix+"__HIST"; String assumeConjName = assumeSuffix+"__CONJ"; IdExpr assumeHistId = new IdExpr(assumeHistName); IdExpr assumeConjId = new IdExpr(assumeConjName); locals.add(new VarDecl(assumeHistName, NamedType.BOOL)); locals.add(new VarDecl(assumeConjName, NamedType.BOOL)); equations.add(new Equation(assumeConjId, assumeConjExpr)); equations.add(getHist(assumeHistId, assumeConjId)); Expr guarConjExpr = new BoolExpr(true); for(AgreeStatement statement : agreeNode.guarantees){ guarConjExpr = new BinaryExpr(statement.expr, BinaryOp.AND, guarConjExpr); } for(AgreeStatement statement : agreeNode.lemmas){ guarConjExpr = new BinaryExpr(statement.expr, BinaryOp.AND, guarConjExpr); } assertions.add(new BinaryExpr(assumeHistId, BinaryOp.IMPLIES, guarConjExpr)); for(AgreeStatement statement : agreeNode.assertions){ assertions.add(statement.expr); } Expr assertExpr = new BoolExpr(true); for(Expr expr : assertions){ assertExpr = new BinaryExpr(expr, BinaryOp.AND, assertExpr); } String outputName = "__ASSERT"; List<VarDecl> outputs = new ArrayList<>(); outputs.add(new VarDecl(outputName, NamedType.BOOL)); equations.add(new Equation(new IdExpr(outputName), assertExpr)); //gather the remaining inputs for(AgreeVar var : agreeNode.inputs){ inputs.add(var); } for(AgreeVar var : agreeNode.outputs){ inputs.add(var); } return new Node(nodePrefix+agreeNode.id, inputs, outputs, locals, equations); } private static AgreeNode flattenAgreeNode(AgreeNode agreeNode, String nodePrefix) { List<AgreeVar> inputs = new ArrayList<>(); List<AgreeVar> outputs = new ArrayList<>(); List<AgreeVar> locals = new ArrayList<>(); List<AgreeStatement> assertions = new ArrayList<>(); Expr someoneTicks = null; for(AgreeNode subAgreeNode : agreeNode.subNodes){ String prefix = subAgreeNode.id+AgreeASTBuilder.dotChar; Expr clockExpr = getClockExpr(agreeNode, subAgreeNode); if(someoneTicks == null){ someoneTicks = clockExpr; }else{ someoneTicks = new BinaryExpr(someoneTicks, BinaryOp.OR, clockExpr); } AgreeNode flatNode = flattenAgreeNode(subAgreeNode, nodePrefix+subAgreeNode.id+AgreeASTBuilder.dotChar); Node lustreNode = addSubNodeLustre(agreeNode, nodePrefix, flatNode); addInputsAndOutputs(inputs, outputs, flatNode, lustreNode, prefix); addCondactCall(agreeNode, nodePrefix, inputs, assertions, flatNode, prefix, clockExpr, lustreNode); addClockHolds(agreeNode, assertions, flatNode, clockExpr); addInitConstraint(agreeNode, outputs, assertions, flatNode, prefix, clockExpr); } if(agreeNode.timing != TimingModel.SYNC){ if(someoneTicks == null){ throw new AgreeException("Somehow we generated a clock constraint without any clocks"); } assertions.add(new AgreeStatement("someone ticks", someoneTicks, null)); } addConnectionConstraints(agreeNode, assertions); //add any clock constraints assertions.addAll(agreeNode.assertions); assertions.add(new AgreeStatement("", agreeNode.clockConstraint, null)); inputs.addAll(agreeNode.inputs); outputs.addAll(agreeNode.outputs); locals.addAll(agreeNode.locals); return new AgreeNode(agreeNode.id, inputs, outputs, locals, null, agreeNode.subNodes, assertions, agreeNode.assumptions, agreeNode.guarantees, agreeNode.lemmas, new BoolExpr(true), agreeNode.initialConstraint, agreeNode.clockVar, agreeNode.reference, null, agreeNode.compInst); } private static void addConnectionConstraints(AgreeNode agreeNode, List<AgreeStatement> assertions) { for(AgreeConnection conn : agreeNode.connections){ String destName = conn.destinationNode == null ? "" : conn.destinationNode.id + AgreeASTBuilder.dotChar; destName = destName + conn.destinationVarName; String sourName = conn.sourceNode == null ? "" : conn.sourceNode.id + AgreeASTBuilder.dotChar; sourName = sourName + conn.sourceVarName; Expr connExpr = new BinaryExpr(new IdExpr(sourName), BinaryOp.EQUAL, new IdExpr(destName)); assertions.add(new AgreeStatement("", connExpr, conn.reference)); //the event connections are added seperatly in the agree ast // if(conn.type == ConnectionType.EVENT){ // Expr eventExpr = new BinaryExpr( // new IdExpr(sourName+AgreeASTBuilder.eventSuffix), // BinaryOp.EQUAL, // new IdExpr(destName+AgreeASTBuilder.eventSuffix)); // assertions.add(new AgreeStatement("", eventExpr, null)); } } private static void addInitConstraint(AgreeNode agreeNode, List<AgreeVar> outputs, List<AgreeStatement> assertions, AgreeNode subAgreeNode, String prefix, Expr clockExpr) { if(agreeNode.timing != TimingModel.SYNC){ String tickedName = subAgreeNode.id+"___TICKED"; outputs.add(new AgreeVar(tickedName, NamedType.BOOL, null, agreeNode.compInst)); Expr tickedId = new IdExpr(tickedName); Expr preTicked = new UnaryExpr(UnaryOp.PRE, tickedId); Expr tickedOrPre = new BinaryExpr(clockExpr, BinaryOp.OR, preTicked); Expr initOrTicked = new BinaryExpr(clockExpr, BinaryOp.ARROW, tickedOrPre); Expr tickedEq = new BinaryExpr(tickedId, BinaryOp.EQUAL, initOrTicked); assertions.add(new AgreeStatement("", tickedEq, null)); //we have two re-write the ids in the initial expressions IdRewriter rewriter = new IdRewriter() { @Override public IdExpr rewrite(IdExpr id) { // TODO Auto-generated method stub return new IdExpr(prefix+id.id); } }; Expr newInit = subAgreeNode.initialConstraint.accept(new IdRewriteVisitor(rewriter)); Expr initConstr = new BinaryExpr(new UnaryExpr(UnaryOp.NOT, tickedId), BinaryOp.IMPLIES, newInit); assertions.add(new AgreeStatement("", initConstr, null)); } } private static void addClockHolds(AgreeNode agreeNode, List<AgreeStatement> assertions, AgreeNode subAgreeNode, Expr clockExpr) { if(agreeNode.timing != TimingModel.SYNC){ Expr hold = new BoolExpr(true); for(AgreeVar outVar : subAgreeNode.outputs){ Expr varId = new IdExpr(subAgreeNode.id+AgreeASTBuilder.dotChar+outVar.id); Expr pre = new UnaryExpr(UnaryOp.PRE, varId); Expr eqPre = new BinaryExpr(varId, BinaryOp.EQUAL, pre); hold = new BinaryExpr(hold, BinaryOp.AND, eqPre); } Expr notClock = new UnaryExpr(UnaryOp.NOT, clockExpr); Expr notClockHold = new BinaryExpr(notClock, BinaryOp.IMPLIES, hold); notClockHold = new BinaryExpr(new BoolExpr(true), BinaryOp.ARROW, notClockHold); assertions.add(new AgreeStatement("", notClockHold, null)); } } private static void addCondactCall(AgreeNode agreeNode, String nodePrefix, List<AgreeVar> inputs, List<AgreeStatement> assertions, AgreeNode subAgreeNode, String prefix, Expr clockExpr, Node lustreNode) { List<Expr> inputIds = new ArrayList<>(); for(VarDecl var : lustreNode.inputs){ inputIds.add(new IdExpr(prefix+var.id)); } if(agreeNode.timing == TimingModel.LATCHED){ addLatchedConstraints(nodePrefix, inputs, assertions, subAgreeNode, prefix, inputIds); } Expr condactExpr = new CondactExpr(clockExpr, new NodeCallExpr(lustreNode.id, inputIds), Collections.singletonList(new BoolExpr(true))); AgreeStatement condactCall = new AgreeStatement("", condactExpr, null); assertions.add(condactCall); } private static void addInputsAndOutputs(List<AgreeVar> inputs, List<AgreeVar> outputs, AgreeNode subAgreeNode, Node lustreNode, String prefix) { int varCount = 0; for(AgreeVar var : subAgreeNode.inputs){ varCount++; AgreeVar input = new AgreeVar(prefix+var.id, var.type, var.reference, subAgreeNode.compInst); inputs.add(input); } for(AgreeVar var : subAgreeNode.outputs){ varCount++; AgreeVar output = new AgreeVar(prefix+var.id, var.type, var.reference, subAgreeNode.compInst); outputs.add(output); } //right now we do not support local variables in our translation for(AgreeVar var : subAgreeNode.locals){ varCount++; AgreeVar local = new AgreeVar(prefix+var.id, var.type, var.reference, subAgreeNode.compInst); outputs.add(local); } int i = 0; for(AgreeStatement statement : subAgreeNode.assumptions){ varCount++; AgreeVar output = new AgreeVar(prefix+assumeSuffix+i++, NamedType.BOOL, statement.reference, subAgreeNode.compInst); outputs.add(output); } int j = 0; for(AgreeStatement statement : subAgreeNode.lemmas){ varCount++; AgreeVar output = new AgreeVar(prefix+lemmaSuffix+j++, NamedType.BOOL, statement.reference, subAgreeNode.compInst); outputs.add(output); } inputs.add(subAgreeNode.clockVar); if(lustreNode.inputs.size() != varCount){ throw new AgreeException("Something went wrong during node flattening"); } } private static Node addSubNodeLustre(AgreeNode agreeNode, String nodePrefix, AgreeNode flatNode) { Node lustreNode = getLustreNode(flatNode, nodePrefix); addToNodes(lustreNode); return lustreNode; } private static void addLatchedConstraints(String nodePrefix, List<AgreeVar> inputs, List<AgreeStatement> assertions, AgreeNode subAgreeNode, String prefix, List<Expr> inputIds) { String latchNodeString = nodePrefix+subAgreeNode.id+"__LATCHED_INPUTS"; List<Expr> nonLatchedInputs = new ArrayList<>(); List<Expr> latchedInputs = new ArrayList<>(); List<VarDecl> latchedVars = new ArrayList<>(); for(AgreeVar var : subAgreeNode.inputs){ String latchedName = prefix+"latched___"+var.id; AgreeVar latchedVar = new AgreeVar(latchedName, var.type, var.reference, subAgreeNode.compInst); inputs.add(latchedVar); latchedVars.add(latchedVar); nonLatchedInputs.add(new IdExpr(prefix+var.id)); latchedInputs.add(new IdExpr(latchedName)); } //have to add the clock variable to the node call as well nonLatchedInputs.add(new IdExpr(subAgreeNode.clockVar.id)); Node latchNode = getInputLatchingNode( new IdExpr(subAgreeNode.clockVar.id), latchedVars, latchNodeString); addToNodes(latchNode); NodeCallExpr latchedNodeCall = new NodeCallExpr(latchNodeString, nonLatchedInputs); Expr latchedInputEq; if(latchedInputs.size() != 1){ latchedInputEq = new TupleExpr(latchedInputs); }else{ latchedInputEq = latchedInputs.get(0); } latchedInputEq = new BinaryExpr(latchedInputEq, BinaryOp.EQUAL, latchedNodeCall); assertions.add(new AgreeStatement("", latchedInputEq, null)); //remove the references to the non-latched inputs List<Expr> inputIdsReplace = new ArrayList<>(); for(Expr inExpr : inputIds){ boolean replaced = false; for(AgreeVar var : subAgreeNode.inputs){ if(((IdExpr)inExpr).id.equals(prefix+var.id)){ inputIdsReplace.add(new IdExpr(prefix+"latched___"+var.id)); replaced = true; break; } } if(!replaced){ inputIdsReplace.add(inExpr); } } inputIds.clear(); inputIds.addAll(inputIdsReplace); } private static Expr getClockExpr(AgreeNode agreeNode, AgreeNode subNode) { IdExpr clockId = new IdExpr(subNode.clockVar.id); switch(agreeNode.timing){ case SYNC: return new BoolExpr(true); case ASYNC: return clockId; case LATCHED: Expr preClock = new UnaryExpr(UnaryOp.PRE, clockId); Expr notClock = new UnaryExpr(UnaryOp.NOT, clockId); Expr andExpr = new BinaryExpr(preClock, BinaryOp.AND, notClock); Expr clockExpr = new BinaryExpr(new BoolExpr(false), BinaryOp.ARROW, andExpr); return clockExpr; default: throw new AgreeException("unhandled timing type: '"+agreeNode.timing+""); } } private static void addToNodes(Node node){ for(Node inList : nodes){ if(node.id.equals(inList.id)){ throw new AgreeException("AGREE Lustre AST Builder attempted to add multiple nodes of name '"+node.id+"'"); } } nodes.add(node); } }
package io.quarkus.bootstrap.resolver.maven; import io.quarkus.bootstrap.model.AppArtifact; import io.quarkus.bootstrap.resolver.maven.options.BootstrapMavenOptions; import io.quarkus.bootstrap.resolver.maven.workspace.LocalProject; import io.quarkus.bootstrap.resolver.maven.workspace.LocalWorkspace; import io.quarkus.bootstrap.resolver.maven.workspace.ModelUtils; import io.quarkus.bootstrap.util.PropertyUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.function.Supplier; import org.apache.commons.lang3.StringUtils; import org.apache.maven.cli.transfer.BatchModeMavenTransferListener; import org.apache.maven.cli.transfer.ConsoleMavenTransferListener; import org.apache.maven.cli.transfer.QuietMavenTransferListener; import org.apache.maven.model.Model; import org.apache.maven.model.building.ModelBuilder; import org.apache.maven.model.building.ModelProblemCollector; import org.apache.maven.model.building.ModelProblemCollectorRequest; import org.apache.maven.model.path.DefaultPathTranslator; import org.apache.maven.model.profile.DefaultProfileActivationContext; import org.apache.maven.model.profile.DefaultProfileSelector; import org.apache.maven.model.profile.activation.FileProfileActivator; import org.apache.maven.model.profile.activation.JdkVersionProfileActivator; import org.apache.maven.model.profile.activation.OperatingSystemProfileActivator; import org.apache.maven.model.profile.activation.PropertyProfileActivator; import org.apache.maven.repository.internal.MavenRepositorySystemUtils; import org.apache.maven.settings.Mirror; import org.apache.maven.settings.Profile; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.apache.maven.settings.SettingsUtils; import org.apache.maven.settings.building.DefaultSettingsBuilderFactory; import org.apache.maven.settings.building.DefaultSettingsBuildingRequest; import org.apache.maven.settings.building.SettingsBuildingException; import org.apache.maven.settings.building.SettingsBuildingResult; import org.apache.maven.settings.building.SettingsProblem; import org.apache.maven.settings.crypto.DefaultSettingsDecryptionRequest; import org.apache.maven.settings.crypto.SettingsDecryptionResult; import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.eclipse.aether.ConfigurationProperties; import org.eclipse.aether.DefaultRepositoryCache; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory; import org.eclipse.aether.impl.DefaultServiceLocator; import org.eclipse.aether.impl.RemoteRepositoryManager; import org.eclipse.aether.internal.impl.DefaultRemoteRepositoryManager; import org.eclipse.aether.repository.ArtifactRepository; import org.eclipse.aether.repository.Authentication; import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.repository.Proxy; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.repository.RepositoryPolicy; import org.eclipse.aether.resolution.ArtifactDescriptorException; import org.eclipse.aether.resolution.ArtifactDescriptorRequest; import org.eclipse.aether.spi.connector.RepositoryConnectorFactory; import org.eclipse.aether.spi.connector.transport.TransporterFactory; import org.eclipse.aether.transfer.TransferListener; import org.eclipse.aether.transport.wagon.WagonConfigurator; import org.eclipse.aether.transport.wagon.WagonProvider; import org.eclipse.aether.transport.wagon.WagonTransporterFactory; import org.eclipse.aether.util.repository.AuthenticationBuilder; import org.eclipse.aether.util.repository.DefaultAuthenticationSelector; import org.eclipse.aether.util.repository.DefaultMirrorSelector; import org.eclipse.aether.util.repository.DefaultProxySelector; import org.jboss.logging.Logger; public class BootstrapMavenContext { private static final Logger log = Logger.getLogger(BootstrapMavenContext.class); private static final String BASEDIR = "basedir"; private static final String DEFAULT_REMOTE_REPO_ID = "central"; private static final String DEFAULT_REMOTE_REPO_URL = "https://repo.maven.apache.org/maven2"; private static final String MAVEN_DOT_HOME = "maven.home"; private static final String MAVEN_HOME = "MAVEN_HOME"; private static final String MAVEN_PROJECTBASEDIR = "MAVEN_PROJECTBASEDIR"; private static final String MAVEN_SETTINGS = "maven.settings"; private static final String SETTINGS_XML = "settings.xml"; private static final String userHome = PropertyUtils.getUserHome(); private static final File userMavenConfigurationHome = new File(userHome, ".m2"); private boolean artifactTransferLogging; private BootstrapMavenOptions cliOptions; private File userSettings; private File globalSettings; private Boolean offline; private LocalWorkspace workspace; private LocalProject currentProject; private Settings settings; private List<org.apache.maven.model.Profile> activeSettingsProfiles; private RepositorySystem repoSystem; private RepositorySystemSession repoSession; private List<RemoteRepository> remoteRepos; private RemoteRepositoryManager remoteRepoManager; private String localRepo; private Path currentPom; private Boolean currentProjectExists; private DefaultServiceLocator serviceLocator; private String alternatePomName; private Path rootProjectDir; public static BootstrapMavenContextConfig<?> config() { return new BootstrapMavenContextConfig<>(); } public BootstrapMavenContext() throws BootstrapMavenException { this(new BootstrapMavenContextConfig<>()); } public BootstrapMavenContext(BootstrapMavenContextConfig<?> config) throws BootstrapMavenException { /* * WARNING: this constructor calls instance method as part of the initialization. * This means the values that are available in the config should be set before * the instance method invocations. */ this.alternatePomName = config.alternatePomName; this.artifactTransferLogging = config.artifactTransferLogging; this.localRepo = config.localRepo; this.offline = config.offline; this.repoSystem = config.repoSystem; this.repoSession = config.repoSession; this.remoteRepos = config.remoteRepos; this.remoteRepoManager = config.remoteRepoManager; this.cliOptions = config.cliOptions; this.rootProjectDir = config.rootProjectDir; if (config.currentProject != null) { this.currentProject = config.currentProject; this.currentPom = currentProject.getRawModel().getPomFile().toPath(); this.workspace = config.currentProject.getWorkspace(); } else if (config.workspaceDiscovery) { currentProject = resolveCurrentProject(); this.workspace = currentProject == null ? null : currentProject.getWorkspace(); } userSettings = config.userSettings; } public AppArtifact getCurrentProjectArtifact(String extension) throws BootstrapMavenException { if (currentProject != null) { return currentProject.getAppArtifact(extension); } final Model model = loadCurrentProjectModel(); if (model == null) { return null; } return new AppArtifact(ModelUtils.getGroupId(model), model.getArtifactId(), "", extension, ModelUtils.getVersion(model)); } public LocalProject getCurrentProject() { return currentProject; } public LocalWorkspace getWorkspace() { return workspace; } public BootstrapMavenOptions getCliOptions() { return cliOptions == null ? cliOptions = BootstrapMavenOptions.newInstance() : cliOptions; } public File getUserSettings() { return userSettings == null ? userSettings = resolveSettingsFile( getCliOptions().getOptionValue(BootstrapMavenOptions.ALTERNATE_USER_SETTINGS), () -> { final String quarkusMavenSettings = getProperty(MAVEN_SETTINGS); return quarkusMavenSettings == null ? new File(userMavenConfigurationHome, SETTINGS_XML) : new File(quarkusMavenSettings); }) : userSettings; } private String getProperty(String name) { String value = PropertyUtils.getProperty(name); if (value != null) { return value; } final Properties props = getCliOptions().getSystemProperties(); return props == null ? null : props.getProperty(name); } public File getGlobalSettings() { return globalSettings == null ? globalSettings = resolveSettingsFile( getCliOptions().getOptionValue(BootstrapMavenOptions.ALTERNATE_GLOBAL_SETTINGS), () -> { String mavenHome = getProperty(MAVEN_DOT_HOME); if (mavenHome == null) { mavenHome = System.getenv(MAVEN_HOME); if (mavenHome == null) { mavenHome = ""; } } return new File(mavenHome, "conf/settings.xml"); }) : globalSettings; } public boolean isOffline() throws BootstrapMavenException { return offline == null ? offline = (getCliOptions().hasOption(BootstrapMavenOptions.OFFLINE) || getEffectiveSettings().isOffline()) : offline; } public RepositorySystem getRepositorySystem() throws BootstrapMavenException { return repoSystem == null ? repoSystem = newRepositorySystem() : repoSystem; } public RepositorySystemSession getRepositorySystemSession() throws BootstrapMavenException { return repoSession == null ? repoSession = newRepositorySystemSession() : repoSession; } public List<RemoteRepository> getRemoteRepositories() throws BootstrapMavenException { return remoteRepos == null ? remoteRepos = resolveRemoteRepos() : remoteRepos; } public Settings getEffectiveSettings() throws BootstrapMavenException { if (settings != null) { return settings; } final DefaultSettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest() .setSystemProperties(System.getProperties()) .setUserSettingsFile(getUserSettings()) .setGlobalSettingsFile(getGlobalSettings()); final Properties cmdLineProps = getCliOptions().getSystemProperties(); if (cmdLineProps != null) { settingsRequest.setUserProperties(cmdLineProps); } final Settings effectiveSettings; try { final SettingsBuildingResult result = new DefaultSettingsBuilderFactory() .newInstance().build(settingsRequest); final List<SettingsProblem> problems = result.getProblems(); if (!problems.isEmpty()) { for (SettingsProblem problem : problems) { switch (problem.getSeverity()) { case ERROR: case FATAL: throw new BootstrapMavenException("Settings problem encountered at " + problem.getLocation(), problem.getException()); default: log.warn("Settings problem encountered at " + problem.getLocation(), problem.getException()); } } } effectiveSettings = result.getEffectiveSettings(); } catch (SettingsBuildingException e) { throw new BootstrapMavenException("Failed to initialize Maven repository settings", e); } return settings = effectiveSettings; } public String getLocalRepo() throws BootstrapMavenException { return localRepo == null ? localRepo = resolveLocalRepo(getEffectiveSettings()) : localRepo; } private LocalProject resolveCurrentProject() throws BootstrapMavenException { try { return LocalProject.loadWorkspace(this); } catch (Exception e) { throw new BootstrapMavenException("Failed to load current project at " + getCurrentProjectPomOrNull(), e); } } private String resolveLocalRepo(Settings settings) { String localRepo = System.getenv("QUARKUS_LOCAL_REPO"); if (localRepo != null) { return localRepo; } localRepo = getProperty("maven.repo.local"); if (localRepo != null) { return localRepo; } localRepo = settings.getLocalRepository(); return localRepo == null ? new File(userMavenConfigurationHome, "repository").getAbsolutePath() : localRepo; } private File resolveSettingsFile(String settingsArg, Supplier<File> supplier) { File userSettings; if (settingsArg != null) { userSettings = new File(settingsArg); if (userSettings.exists()) { return userSettings; } if (userSettings.isAbsolute()) { return null; } // in case the settings path is a relative one we check whether the pom path is also a relative one // in which case we can resolve the settings path relative to the project directory // otherwise, we don't have a clue what the settings path is relative to String alternatePomDir = getCliOptions().getOptionValue(BootstrapMavenOptions.ALTERNATE_POM_FILE); if (alternatePomDir != null) { File tmp = new File(alternatePomDir); if (tmp.isAbsolute()) { alternatePomDir = null; } else { if (!tmp.isDirectory()) { tmp = tmp.getParentFile(); } alternatePomDir = tmp.toString(); } } // Root project base dir userSettings = resolveSettingsFile(settingsArg, alternatePomDir, System.getenv("MAVEN_PROJECTBASEDIR")); if (userSettings != null) { return userSettings; } // current module project base dir userSettings = resolveSettingsFile(settingsArg, alternatePomDir, PropertyUtils.getProperty(BASEDIR)); if (userSettings != null) { return userSettings; } userSettings = new File(PropertyUtils.getUserHome(), settingsArg); if (userSettings.exists()) { return userSettings; } } userSettings = supplier.get(); return userSettings.exists() ? userSettings : null; } private File resolveSettingsFile(String settingsArg, String alternatePomDir, String projectBaseDir) { if (projectBaseDir == null) { return null; } File userSettings; if (alternatePomDir != null && projectBaseDir.endsWith(alternatePomDir)) { userSettings = new File(projectBaseDir.substring(0, projectBaseDir.length() - alternatePomDir.length()), settingsArg); if (userSettings.exists()) { return userSettings; } } userSettings = new File(projectBaseDir, settingsArg); if (userSettings.exists()) { return userSettings; } return null; } private DefaultRepositorySystemSession newRepositorySystemSession() throws BootstrapMavenException { final DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); final Settings settings = getEffectiveSettings(); final List<Mirror> mirrors = settings.getMirrors(); if (mirrors != null && !mirrors.isEmpty()) { final DefaultMirrorSelector ms = new DefaultMirrorSelector(); for (Mirror m : mirrors) { ms.add(m.getId(), m.getUrl(), m.getLayout(), false, m.getMirrorOf(), m.getMirrorOfLayouts()); } session.setMirrorSelector(ms); } final String localRepoPath = getLocalRepo(); session.setLocalRepositoryManager( getRepositorySystem().newLocalRepositoryManager(session, new LocalRepository(localRepoPath))); session.setOffline(isOffline()); final BootstrapMavenOptions mvnArgs = getCliOptions(); if (!mvnArgs.isEmpty()) { if (mvnArgs.hasOption(BootstrapMavenOptions.SUPRESS_SNAPSHOT_UPDATES)) { session.setUpdatePolicy(RepositoryPolicy.UPDATE_POLICY_NEVER); } else if (mvnArgs.hasOption(BootstrapMavenOptions.UPDATE_SNAPSHOTS)) { session.setUpdatePolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS); } if (mvnArgs.hasOption(BootstrapMavenOptions.CHECKSUM_FAILURE_POLICY)) { session.setChecksumPolicy(RepositoryPolicy.CHECKSUM_POLICY_FAIL); } else if (mvnArgs.hasOption(BootstrapMavenOptions.CHECKSUM_WARNING_POLICY)) { session.setChecksumPolicy(RepositoryPolicy.CHECKSUM_POLICY_WARN); } } final DefaultSettingsDecryptionRequest decrypt = new DefaultSettingsDecryptionRequest(); decrypt.setProxies(settings.getProxies()); decrypt.setServers(settings.getServers()); final SettingsDecryptionResult decrypted = new SettingsDecrypterImpl().decrypt(decrypt); if (!decrypted.getProblems().isEmpty() && log.isDebugEnabled()) { // this is how maven handles these for (SettingsProblem p : decrypted.getProblems()) { log.debug(p.getMessage(), p.getException()); } } final DefaultProxySelector proxySelector = new DefaultProxySelector(); for (org.apache.maven.settings.Proxy p : decrypted.getProxies()) { if (p.isActive()) { proxySelector.add(toAetherProxy(p), p.getNonProxyHosts()); } } session.setProxySelector(proxySelector); final Map<Object, Object> configProps = new LinkedHashMap<>(session.getConfigProperties()); configProps.put(ConfigurationProperties.USER_AGENT, getUserAgent()); configProps.put(ConfigurationProperties.INTERACTIVE, settings.isInteractiveMode()); final DefaultAuthenticationSelector authSelector = new DefaultAuthenticationSelector(); for (Server server : decrypted.getServers()) { AuthenticationBuilder authBuilder = new AuthenticationBuilder(); authBuilder.addUsername(server.getUsername()).addPassword(server.getPassword()); authBuilder.addPrivateKey(server.getPrivateKey(), server.getPassphrase()); authSelector.add(server.getId(), authBuilder.build()); if (server.getConfiguration() != null) { Xpp3Dom dom = (Xpp3Dom) server.getConfiguration(); for (int i = dom.getChildCount() - 1; i >= 0; i Xpp3Dom child = dom.getChild(i); if ("wagonProvider".equals(child.getName())) { dom.removeChild(i); } } XmlPlexusConfiguration config = new XmlPlexusConfiguration(dom); configProps.put("aether.connector.wagon.config." + server.getId(), config); } configProps.put("aether.connector.perms.fileMode." + server.getId(), server.getFilePermissions()); configProps.put("aether.connector.perms.dirMode." + server.getId(), server.getDirectoryPermissions()); } session.setAuthenticationSelector(authSelector); session.setConfigProperties(configProps); if (session.getCache() == null) { session.setCache(new DefaultRepositoryCache()); } if (workspace != null) { session.setWorkspaceReader(workspace); } if (session.getTransferListener() == null && artifactTransferLogging) { TransferListener transferListener; if (mvnArgs.hasOption(BootstrapMavenOptions.NO_TRANSFER_PROGRESS)) { transferListener = new QuietMavenTransferListener(); } else if (mvnArgs.hasOption(BootstrapMavenOptions.BATCH_MODE)) { transferListener = new BatchModeMavenTransferListener(System.out); } else { transferListener = new ConsoleMavenTransferListener(System.out, true); } session.setTransferListener(transferListener); } return session; } private List<RemoteRepository> resolveRemoteRepos() throws BootstrapMavenException { final List<RemoteRepository> rawRepos = new ArrayList<>(); getActiveSettingsProfiles().forEach(p -> addProfileRepos(p, rawRepos)); // central must be there if (rawRepos.isEmpty() || !includesDefaultRepo(rawRepos)) { rawRepos.add(newDefaultRepository()); } final List<RemoteRepository> repos = getRepositorySystem().newResolutionRepositories(getRepositorySystemSession(), rawRepos); return workspace == null ? repos : resolveCurrentProjectRepos(repos); } public static RemoteRepository newDefaultRepository() { return new RemoteRepository.Builder(DEFAULT_REMOTE_REPO_ID, "default", DEFAULT_REMOTE_REPO_URL) .setReleasePolicy(new RepositoryPolicy(true, RepositoryPolicy.UPDATE_POLICY_DAILY, RepositoryPolicy.CHECKSUM_POLICY_WARN)) .setSnapshotPolicy(new RepositoryPolicy(false, RepositoryPolicy.UPDATE_POLICY_DAILY, RepositoryPolicy.CHECKSUM_POLICY_WARN)) .build(); } private Model loadCurrentProjectModel() throws BootstrapMavenException { final Path pom = getCurrentProjectPomOrNull(); if (pom == null) { return null; } try { return ModelUtils.readModel(pom); } catch (IOException e) { throw new BootstrapMavenException("Failed to parse " + pom, e); } } private List<RemoteRepository> resolveCurrentProjectRepos(List<RemoteRepository> repos) throws BootstrapMavenException { final Model model = loadCurrentProjectModel(); if (model == null) { return repos; } final Artifact projectArtifact = new DefaultArtifact(ModelUtils.getGroupId(model), model.getArtifactId(), "", "pom", ModelUtils.getVersion(model)); final List<RemoteRepository> rawRepos; try { rawRepos = getRepositorySystem() .readArtifactDescriptor(getRepositorySystemSession(), new ArtifactDescriptorRequest() .setArtifact(projectArtifact) .setRepositories(repos)) .getRepositories(); } catch (ArtifactDescriptorException e) { throw new BootstrapMavenException("Failed to read artifact descriptor for " + projectArtifact, e); } return getRepositorySystem().newResolutionRepositories(getRepositorySystemSession(), rawRepos); } public List<org.apache.maven.model.Profile> getActiveSettingsProfiles() throws BootstrapMavenException { if (activeSettingsProfiles != null) { return activeSettingsProfiles; } final Settings settings = getEffectiveSettings(); final int profilesTotal = settings.getProfiles().size(); if (profilesTotal == 0) { return Collections.emptyList(); } List<org.apache.maven.model.Profile> modelProfiles = new ArrayList<>(profilesTotal); for (Profile profile : settings.getProfiles()) { modelProfiles.add(SettingsUtils.convertFromSettingsProfile(profile)); } final BootstrapMavenOptions mvnArgs = getCliOptions(); List<String> activeProfiles = mvnArgs.getActiveProfileIds(); final List<String> inactiveProfiles = mvnArgs.getInactiveProfileIds(); final Path currentPom = getCurrentProjectPomOrNull(); final DefaultProfileActivationContext context = new DefaultProfileActivationContext() .setActiveProfileIds(activeProfiles) .setInactiveProfileIds(inactiveProfiles) .setSystemProperties(System.getProperties()) .setProjectDirectory( currentPom == null ? getCurrentProjectBaseDir().toFile() : currentPom.getParent().toFile()); final DefaultProfileSelector profileSelector = new DefaultProfileSelector() .addProfileActivator(new PropertyProfileActivator()) .addProfileActivator(new JdkVersionProfileActivator()) .addProfileActivator(new OperatingSystemProfileActivator()) .addProfileActivator(new FileProfileActivator().setPathTranslator(new DefaultPathTranslator())); modelProfiles = profileSelector.getActiveProfiles(modelProfiles, context, new ModelProblemCollector() { public void add(ModelProblemCollectorRequest req) { log.error("Failed to activate a Maven profile: " + req.getMessage()); } }); activeProfiles = settings.getActiveProfiles(); if (!activeProfiles.isEmpty()) { for (String profileName : activeProfiles) { final Profile profile = getProfile(profileName, settings); if (profile != null) { modelProfiles.add(SettingsUtils.convertFromSettingsProfile(profile)); } } } return activeSettingsProfiles = modelProfiles; } private static Profile getProfile(String name, Settings settings) throws BootstrapMavenException { final Profile profile = settings.getProfilesAsMap().get(name); if (profile == null) { unrecognizedProfile(name, true); } return profile; } private static void unrecognizedProfile(String name, boolean activate) { final StringBuilder buf = new StringBuilder(); buf.append("The requested Maven profile \"").append(name).append("\" could not be "); if (!activate) { buf.append("de"); } buf.append("activated because it does not exist."); log.warn(buf.toString()); } private static boolean includesDefaultRepo(List<RemoteRepository> repositories) { for (ArtifactRepository repository : repositories) { if (repository.getId().equals(DEFAULT_REMOTE_REPO_ID)) { return true; } } return false; } private static void addProfileRepos(final org.apache.maven.model.Profile profile, final List<RemoteRepository> all) { final List<org.apache.maven.model.Repository> repositories = profile.getRepositories(); for (org.apache.maven.model.Repository repo : repositories) { final RemoteRepository.Builder repoBuilder = new RemoteRepository.Builder(repo.getId(), repo.getLayout(), repo.getUrl()); org.apache.maven.model.RepositoryPolicy policy = repo.getReleases(); if (policy != null) { repoBuilder.setReleasePolicy(toAetherRepoPolicy(policy)); } policy = repo.getSnapshots(); if (policy != null) { repoBuilder.setSnapshotPolicy(toAetherRepoPolicy(policy)); } all.add(repoBuilder.build()); } } private static RepositoryPolicy toAetherRepoPolicy(org.apache.maven.model.RepositoryPolicy modelPolicy) { return new RepositoryPolicy(modelPolicy.isEnabled(), StringUtils.isEmpty(modelPolicy.getUpdatePolicy()) ? RepositoryPolicy.UPDATE_POLICY_DAILY : modelPolicy.getUpdatePolicy(), StringUtils.isEmpty(modelPolicy.getChecksumPolicy()) ? RepositoryPolicy.CHECKSUM_POLICY_WARN : modelPolicy.getChecksumPolicy()); } /** * Convert a {@link org.apache.maven.settings.Proxy} to a {@link Proxy}. * * @param proxy Maven proxy settings, may be {@code null}. * @return Aether repository proxy or {@code null} if given {@link org.apache.maven.settings.Proxy} is {@code null}. */ private static Proxy toAetherProxy(org.apache.maven.settings.Proxy proxy) { if (proxy == null) { return null; } Authentication auth = null; if (proxy.getUsername() != null) { auth = new AuthenticationBuilder() .addUsername(proxy.getUsername()) .addPassword(proxy.getPassword()) .build(); } return new Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), auth); } private RepositorySystem newRepositorySystem() throws BootstrapMavenException { final DefaultServiceLocator locator = getServiceLocator(); if (!isOffline()) { locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class); locator.addService(TransporterFactory.class, WagonTransporterFactory.class); locator.setServices(WagonConfigurator.class, new BootstrapWagonConfigurator()); locator.setServices(WagonProvider.class, new BootstrapWagonProvider()); } locator.setServices(ModelBuilder.class, new MavenModelBuilder(workspace, getCliOptions(), workspace == null ? Collections.emptyList() : getActiveSettingsProfiles())); locator.setErrorHandler(new DefaultServiceLocator.ErrorHandler() { @Override public void serviceCreationFailed(Class<?> type, Class<?> impl, Throwable exception) { log.error("Failed to initialize " + impl.getName() + " as a service implementing " + type.getName(), exception); } }); return locator.getService(RepositorySystem.class); } public RemoteRepositoryManager getRemoteRepositoryManager() { if (remoteRepoManager != null) { return remoteRepoManager; } final DefaultRemoteRepositoryManager remoteRepoManager = new DefaultRemoteRepositoryManager(); remoteRepoManager.initService(getServiceLocator()); return this.remoteRepoManager = remoteRepoManager; } private DefaultServiceLocator getServiceLocator() { return serviceLocator == null ? serviceLocator = MavenRepositorySystemUtils.newServiceLocator() : serviceLocator; } private static String getUserAgent() { return "Apache-Maven/" + getMavenVersion() + " (Java " + PropertyUtils.getProperty("java.version") + "; " + PropertyUtils.getProperty("os.name") + " " + PropertyUtils.getProperty("os.version") + ")"; } private static String getMavenVersion() { final String mvnVersion = PropertyUtils.getProperty("maven.version"); if (mvnVersion != null) { return mvnVersion; } final Properties props = new Properties(); try (InputStream is = BootstrapMavenContext.class.getResourceAsStream( "/META-INF/maven/org.apache.maven/maven-core/pom.properties")) { if (is != null) { props.load(is); } } catch (IOException e) { log.debug("Failed to read Maven version", e); } return props.getProperty("version", "unknown-version"); } public boolean isCurrentProjectExists() { return currentProjectExists == null ? currentProjectExists = getCurrentProjectPomOrNull() != null : currentProjectExists; } public Path getCurrentProjectPomOrNull() { if (currentPom != null || currentProjectExists != null && !currentProjectExists) { return currentPom; } final Path pom = resolveCurrentPom(); return currentPom = (currentProjectExists = pom != null) ? pom : null; } private Path resolveCurrentPom() { Path alternatePom = null; // explicitly set absolute path has a priority if (alternatePomName != null) { alternatePom = Paths.get(alternatePomName); if (alternatePom.isAbsolute()) { return pomXmlOrNull(alternatePom); } } if (alternatePom == null) { // check whether an alternate pom was provided as a CLI arg final String cliPomName = getCliOptions().getOptionValue(BootstrapMavenOptions.ALTERNATE_POM_FILE); if (cliPomName != null) { alternatePom = Paths.get(cliPomName); } } final String basedirProp = PropertyUtils.getProperty(BASEDIR); if (basedirProp != null) { // this is the actual current project dir return getPomForDirOrNull(Paths.get(basedirProp), alternatePom); } // we are not in the context of a Maven build if (alternatePom != null && alternatePom.isAbsolute()) { return pomXmlOrNull(alternatePom); } // trying the current dir as the basedir final Path basedir = Paths.get("").normalize().toAbsolutePath(); if (alternatePom != null) { return pomXmlOrNull(basedir.resolve(alternatePom)); } final Path pom = basedir.resolve("pom.xml"); return Files.exists(pom) ? pom : null; } static Path getPomForDirOrNull(final Path basedir, Path alternatePom) { // if the basedir matches the parent of the alternate pom, it's the alternate pom if (alternatePom != null && alternatePom.isAbsolute() && alternatePom.getParent().equals(basedir)) { return alternatePom; } // even if the alternate pom has been specified we try the default pom.xml first // since unlike Maven CLI we don't know which project originated the build Path pom = basedir.resolve("pom.xml"); if (Files.exists(pom)) { return pom; } // if alternate pom path has a single element we can try it // if it has more, it won't match the basedir if (alternatePom != null && !alternatePom.isAbsolute() && alternatePom.getNameCount() == 1) { pom = basedir.resolve(alternatePom); if (Files.exists(pom)) { return pom; } } // give up return null; } private static Path pomXmlOrNull(Path path) { if (Files.isDirectory(path)) { path = path.resolve("pom.xml"); } return Files.exists(path) ? path : null; } public Path getCurrentProjectBaseDir() { if (currentProject != null) { return currentProject.getDir(); } final String basedirProp = PropertyUtils.getProperty(BASEDIR); return basedirProp == null ? Paths.get("").normalize().toAbsolutePath() : Paths.get(basedirProp); } public Path getRootProjectBaseDir() { // originally we checked for MAVEN_PROJECTBASEDIR which is set by the mvn script // and points to the first parent containing '.mvn' dir but it's not consistent // with how Maven discovers the workspace and also created issues testing the Quarkus platform // due to its specific FS layout return rootProjectDir; } }
package io.subutai.core.hubmanager.impl.tunnel; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.http.HttpStatus; import io.subutai.common.command.CommandException; import io.subutai.common.command.CommandResult; import io.subutai.common.command.RequestBuilder; import io.subutai.common.peer.ResourceHost; import io.subutai.core.hubmanager.api.RestClient; import io.subutai.core.hubmanager.api.RestResult; import io.subutai.hub.share.common.util.DtoConverter; import io.subutai.hub.share.dto.CommonDto; import io.subutai.hub.share.dto.TunnelInfoDto; import static io.subutai.hub.share.dto.TunnelInfoDto.TunnelStatus.ERROR; public class TunnelHelper { private static final Logger LOG = LoggerFactory.getLogger( TunnelHelper.class ); private static final String DELETE_TUNNEL_COMMAND = "subutai tunnel del %s"; private static final String GET_OPENED_TUNNELS_FOR_IP_COMMAND = "subutai tunnel list | grep %s | awk '{print $2}'"; private TunnelHelper() { throw new IllegalAccessError( "Utility class" ); } static void sendError( String link, String errorLog, RestClient restClient ) { TunnelInfoDto tunnelInfoDto = new TunnelInfoDto(); tunnelInfoDto.setTunnelStatus( ERROR ); tunnelInfoDto.setErrorLogs( errorLog ); updateTunnelStatus( link, tunnelInfoDto, restClient ); } static RestResult<Object> updateTunnelStatus( String link, TunnelInfoDto tunnelInfoDto, RestClient restClient ) { try { byte[] body = DtoConverter.serialize( tunnelInfoDto ); CommonDto commonDto = new CommonDto( body ); return restClient.put( link, commonDto, Object.class ); } catch ( Exception e ) { String mgs = "Could not sent tunnel peer data to hub."; LOG.error( mgs, e.getMessage() ); return null; } } static TunnelInfoDto getPeerTunnelState( String link, RestClient restClient ) { try { RestResult<TunnelInfoDto> restResult = restClient.get( link, TunnelInfoDto.class ); LOG.debug( "Response: HTTP {} - {}", restResult.getStatus(), restResult.getReasonPhrase() ); if ( restResult.getStatus() != HttpStatus.SC_OK ) { LOG.error( "Error to get tunnel data from Hub: HTTP {} - {}", restResult.getStatus(), restResult.getError() ); return null; } return restResult.getEntity(); } catch ( Exception e ) { sendError( link, e.getMessage(), restClient ); LOG.error( e.getMessage() ); return null; } } public static TunnelInfoDto parseResult( String result, TunnelInfoDto tunnelInfoDto ) { result = result.replaceAll( "\n", "" ); result = result.replaceAll( "\t", "_" ); String[] ipport = result.split( "_" ); result = ipport[0]; ipport = result.split( ":" ); tunnelInfoDto.setOpenedIp( String.valueOf( ipport[0] ) ); tunnelInfoDto.setOpenedPort( String.valueOf( ipport[1] ) ); return tunnelInfoDto; } public static void deleteAllTunnelsForIp( final Set<ResourceHost> resourceHosts, final String ip ) { for ( ResourceHost resourceHost : resourceHosts ) { try { CommandResult result = resourceHost .execute( new RequestBuilder( String.format( GET_OPENED_TUNNELS_FOR_IP_COMMAND, ip ) ) ); if ( result.hasSucceeded() ) { String[] data = result.getStdOut().split( "\n" ); for ( String tunnel : data ) { resourceHost.execute( new RequestBuilder( String.format( DELETE_TUNNEL_COMMAND, tunnel ) ) ); } } } catch ( CommandException e ) { LOG.error( e.getMessage() ); } } } }
package org.safehaus.subutai.core.peer.impl; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.safehaus.subutai.common.command.CommandCallback; import org.safehaus.subutai.common.command.CommandException; import org.safehaus.subutai.common.command.CommandResult; import org.safehaus.subutai.common.command.RequestBuilder; import org.safehaus.subutai.common.host.ContainerHostState; import org.safehaus.subutai.common.host.HostInfo; import org.safehaus.subutai.common.metric.ProcessResourceUsage; import org.safehaus.subutai.common.metric.ResourceHostMetric; import org.safehaus.subutai.common.peer.ContainerHost; import org.safehaus.subutai.common.peer.ContainersDestructionResult; import org.safehaus.subutai.common.peer.Host; import org.safehaus.subutai.common.peer.HostInfoModel; import org.safehaus.subutai.common.peer.PeerException; import org.safehaus.subutai.common.peer.PeerInfo; import org.safehaus.subutai.common.protocol.Criteria; import org.safehaus.subutai.common.protocol.Template; import org.safehaus.subutai.common.quota.CpuQuotaInfo; import org.safehaus.subutai.common.quota.DiskPartition; import org.safehaus.subutai.common.quota.DiskQuota; import org.safehaus.subutai.common.quota.MemoryQuotaInfo; import org.safehaus.subutai.common.quota.PeerQuotaInfo; import org.safehaus.subutai.common.quota.QuotaException; import org.safehaus.subutai.common.quota.QuotaInfo; import org.safehaus.subutai.common.quota.QuotaType; import org.safehaus.subutai.common.settings.Common; import org.safehaus.subutai.common.util.CollectionUtil; import org.safehaus.subutai.common.util.StringUtil; import org.safehaus.subutai.common.util.UUIDUtil; import org.safehaus.subutai.core.executor.api.CommandExecutor; import org.safehaus.subutai.core.hostregistry.api.ContainerHostInfo; import org.safehaus.subutai.core.hostregistry.api.HostDisconnectedException; import org.safehaus.subutai.core.hostregistry.api.HostListener; import org.safehaus.subutai.core.hostregistry.api.HostRegistry; import org.safehaus.subutai.core.hostregistry.api.ResourceHostInfo; import org.safehaus.subutai.core.lxc.quota.api.QuotaManager; import org.safehaus.subutai.core.metric.api.Monitor; import org.safehaus.subutai.core.metric.api.MonitorException; import org.safehaus.subutai.core.peer.api.ContainerGroup; import org.safehaus.subutai.core.peer.api.ContainerGroupNotFoundException; import org.safehaus.subutai.core.peer.api.HostNotFoundException; import org.safehaus.subutai.core.peer.api.LocalPeer; import org.safehaus.subutai.core.peer.api.ManagementHost; import org.safehaus.subutai.core.peer.api.Payload; import org.safehaus.subutai.core.peer.api.PeerManager; import org.safehaus.subutai.core.peer.api.RequestListener; import org.safehaus.subutai.core.peer.api.ResourceHost; import org.safehaus.subutai.core.peer.api.ResourceHostException; import org.safehaus.subutai.core.peer.impl.container.ContainersDestructionResultImpl; import org.safehaus.subutai.core.peer.impl.container.CreateContainerWrapperTask; import org.safehaus.subutai.core.peer.impl.container.DestroyContainerWrapperTask; import org.safehaus.subutai.core.peer.impl.dao.ContainerGroupDataService; import org.safehaus.subutai.core.peer.impl.dao.ContainerHostDataService; import org.safehaus.subutai.core.peer.impl.dao.ManagementHostDataService; import org.safehaus.subutai.core.peer.impl.dao.ResourceHostDataService; import org.safehaus.subutai.core.peer.impl.entity.AbstractSubutaiHost; import org.safehaus.subutai.core.peer.impl.entity.ContainerGroupEntity; import org.safehaus.subutai.core.peer.impl.entity.ContainerHostEntity; import org.safehaus.subutai.core.peer.impl.entity.ManagementHostEntity; import org.safehaus.subutai.core.peer.impl.entity.ResourceHostEntity; import org.safehaus.subutai.core.registry.api.RegistryException; import org.safehaus.subutai.core.registry.api.TemplateRegistry; import org.safehaus.subutai.core.strategy.api.StrategyException; import org.safehaus.subutai.core.strategy.api.StrategyManager; import org.safehaus.subutai.core.strategy.api.StrategyNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; /** * Local peer implementation */ public class LocalPeerImpl implements LocalPeer, HostListener { private static final Logger LOG = LoggerFactory.getLogger( LocalPeerImpl.class ); private static final long HOST_INACTIVE_TIME = 5 * 1000 * 60; // 5 min private PeerManager peerManager; private TemplateRegistry templateRegistry; private ManagementHost managementHost; private Set<ResourceHost> resourceHosts = Sets.newHashSet(); private CommandExecutor commandExecutor; private StrategyManager strategyManager; private QuotaManager quotaManager; private Monitor monitor; private ManagementHostDataService managementHostDataService; private ResourceHostDataService resourceHostDataService; private ContainerHostDataService containerHostDataService; private ContainerGroupDataService containerGroupDataService; private HostRegistry hostRegistry; private Set<RequestListener> requestListeners; public LocalPeerImpl( PeerManager peerManager, TemplateRegistry templateRegistry, QuotaManager quotaManager, StrategyManager strategyManager, Set<RequestListener> requestListeners, CommandExecutor commandExecutor, HostRegistry hostRegistry, Monitor monitor ) { this.strategyManager = strategyManager; this.peerManager = peerManager; this.templateRegistry = templateRegistry; this.quotaManager = quotaManager; this.monitor = monitor; this.requestListeners = requestListeners; this.commandExecutor = commandExecutor; this.hostRegistry = hostRegistry; } public void init() { managementHostDataService = new ManagementHostDataService( peerManager.getEntityManagerFactory() ); Collection allManagementHostEntity = managementHostDataService.getAll(); if ( allManagementHostEntity != null && allManagementHostEntity.size() > 0 ) { managementHost = ( ManagementHost ) allManagementHostEntity.iterator().next(); ( ( AbstractSubutaiHost ) managementHost ).setPeer( this ); managementHost.init(); } resourceHostDataService = new ResourceHostDataService( peerManager.getEntityManagerFactory() ); resourceHosts = Sets.newHashSet(); synchronized ( resourceHosts ) { resourceHosts.addAll( resourceHostDataService.getAll() ); } containerHostDataService = new ContainerHostDataService( peerManager.getEntityManagerFactory() ); containerGroupDataService = new ContainerGroupDataService( peerManager.getEntityManagerFactory() ); setResourceHostTransientFields( getResourceHosts() ); for ( ResourceHost resourceHost : getResourceHosts() ) { setContainersTransientFields( resourceHost.getContainerHosts() ); } hostRegistry.addHostListener( this ); } private void setResourceHostTransientFields( Set<ResourceHost> resourceHosts ) { for ( ResourceHost resourceHost : resourceHosts ) { ( ( AbstractSubutaiHost ) resourceHost ).setPeer( this ); ( ( ResourceHostEntity ) resourceHost ).setRegistry( templateRegistry ); ( ( ResourceHostEntity ) resourceHost ).setMonitor( monitor ); ( ( ResourceHostEntity ) resourceHost ).setHostRegistry( hostRegistry ); } } public void shutdown() { hostRegistry.removeHostListener( this ); } @Override public UUID getId() { return peerManager.getLocalPeerInfo().getId(); } @Override public String getName() { return peerManager.getLocalPeerInfo().getName(); } @Override public UUID getOwnerId() { return peerManager.getLocalPeerInfo().getOwnerId(); } @Override public PeerInfo getPeerInfo() { return peerManager.getLocalPeerInfo(); } @Override public ContainerHostState getContainerHostState( final ContainerHost host ) throws PeerException { Host ahost = bindHost( host.getId() ); if ( ahost instanceof ContainerHost ) { ContainerHost containerHost = ( ContainerHost ) ahost; return containerHost.getState(); } else { throw new UnsupportedOperationException(); } } @Override public ContainerHost createContainer( final ResourceHost resourceHost, final Template template, final String containerName ) throws PeerException { Preconditions.checkNotNull( resourceHost, "Invalid resource host" ); Preconditions.checkNotNull( template, "Invalid template" ); Preconditions.checkArgument( !Strings.isNullOrEmpty( containerName ), "Invalid container name" ); getResourceHostByName( resourceHost.getHostname() ); if ( templateRegistry.getTemplate( template.getTemplateName() ) == null ) { throw new PeerException( String.format( "Template %s not registered", template.getTemplateName() ) ); } try { return resourceHost.createContainer( template.getTemplateName(), containerName, 180 ); } catch ( ResourceHostException e ) { LOG.error( "Failed to create container", e ); throw new PeerException( e ); } } //TODO wrap all parameters into request object public Set<HostInfoModel> createContainers( final UUID environmentId, final UUID initiatorPeerId, final UUID ownerId, final List<Template> templates, final int numberOfContainers, final String strategyId, final List<Criteria> criteria ) throws PeerException { Preconditions.checkNotNull( environmentId, "Invalid environment id" ); Preconditions.checkNotNull( initiatorPeerId, "Invalid initiator peer id" ); Preconditions.checkNotNull( ownerId, "Invalid owner id" ); Preconditions.checkArgument( !CollectionUtil.isCollectionEmpty( templates ), "Invalid template set" ); Preconditions.checkArgument( numberOfContainers > 0, "Invalid number of containers" ); Preconditions.checkArgument( !Strings.isNullOrEmpty( strategyId ), "Invalid strategy id" ); final int waitContainerTimeoutSec = 180; //check if strategy exists try { strategyManager.findStrategyById( strategyId ); } catch ( StrategyNotFoundException e ) { throw new PeerException( e ); } //try to register remote templates with local registry try { for ( Template t : templates ) { if ( t.isRemote() ) { tryToRegister( t ); } } } catch ( RegistryException e ) { throw new PeerException( e ); } List<ResourceHostMetric> serverMetricMap = new ArrayList<>(); for ( ResourceHost resourceHost : getResourceHosts() ) { //take connected resource hosts for container creation //and prepare needed templates if ( resourceHost.isConnected() ) { try { serverMetricMap.add( resourceHost.getHostMetric() ); resourceHost.prepareTemplates( templates ); } catch ( ResourceHostException e ) { throw new PeerException( e ); } } } //calculate placement strategy Map<ResourceHostMetric, Integer> slots; try { slots = strategyManager .getPlacementDistribution( serverMetricMap, numberOfContainers, strategyId, criteria ); } catch ( StrategyException e ) { throw new PeerException( e ); } //distribute new containers' names across selected resource hosts Map<ResourceHost, Set<String>> containerDistribution = Maps.newHashMap(); String templateName = templates.get( templates.size() - 1 ).getTemplateName(); for ( Map.Entry<ResourceHostMetric, Integer> e : slots.entrySet() ) { Set<String> hostCloneNames = new HashSet<>(); for ( int i = 0; i < e.getValue(); i++ ) { String newContainerName = StringUtil .trimToSize( String.format( "%s%s", templateName, UUID.randomUUID() ).replace( "-", "" ), Common.MAX_CONTAINER_NAME_LEN ); hostCloneNames.add( newContainerName ); } ResourceHost resourceHost = getResourceHostByName( e.getKey().getHost() ); containerDistribution.put( resourceHost, hostCloneNames ); } List<Future<ContainerHost>> taskFutures = Lists.newArrayList(); ExecutorService executorService = Executors.newFixedThreadPool( numberOfContainers ); //create containers in parallel on each resource host for ( Map.Entry<ResourceHost, Set<String>> resourceHostDistribution : containerDistribution.entrySet() ) { ResourceHostEntity resourceHostEntity = ( ResourceHostEntity ) resourceHostDistribution.getKey(); for ( String hostname : resourceHostDistribution.getValue() ) { taskFutures.add( executorService.submit( new CreateContainerWrapperTask( resourceHostEntity, templateName, hostname, waitContainerTimeoutSec ) ) ); } } Set<HostInfoModel> result = Sets.newHashSet(); Set<ContainerHost> newContainers = Sets.newHashSet(); //wait for succeeded containers for ( Future<ContainerHost> future : taskFutures ) { try { ContainerHost containerHost = future.get(); newContainers.add( new ContainerHostEntity( getId().toString(), hostRegistry.getContainerHostInfoById( containerHost.getId() ) ) ); result.add( new HostInfoModel( containerHost ) ); } catch ( ExecutionException | InterruptedException | HostDisconnectedException e ) { LOG.error( "Error creating containers", e ); } } executorService.shutdown(); if ( !CollectionUtil.isCollectionEmpty( newContainers ) ) { ContainerGroupEntity containerGroup; try { //update existing container group to include new containers containerGroup = ( ContainerGroupEntity ) findContainerGroupByEnvironmentId( environmentId ); Set<UUID> containerIds = Sets.newHashSet( containerGroup.getContainerIds() ); for ( ContainerHost containerHost : newContainers ) { containerIds.add( containerHost.getId() ); } containerGroup.setContainerIds2( containerIds ); containerGroupDataService.update( containerGroup ); } catch ( ContainerGroupNotFoundException e ) { //create container group for new containers containerGroup = new ContainerGroupEntity( environmentId, initiatorPeerId, ownerId, templateName, newContainers ); containerGroupDataService.persist( containerGroup ); } } return result; } @Override public ContainerGroup findContainerGroupByContainerId( final UUID containerId ) throws ContainerGroupNotFoundException { Preconditions.checkNotNull( containerId, "Invalid container id" ); List<ContainerGroupEntity> containerGroups = ( List<ContainerGroupEntity> ) containerGroupDataService.getAll(); for ( ContainerGroupEntity containerGroup : containerGroups ) { for ( UUID containerHostId : containerGroup.getContainerIds() ) { if ( containerId.equals( containerHostId ) ) { return containerGroup; } } } throw new ContainerGroupNotFoundException(); } @Override public ContainerGroup findContainerGroupByEnvironmentId( final UUID environmentId ) throws ContainerGroupNotFoundException { Preconditions.checkNotNull( environmentId, "Invalid container id" ); List<ContainerGroupEntity> containerGroups = ( List<ContainerGroupEntity> ) containerGroupDataService.getAll(); for ( ContainerGroupEntity containerGroup : containerGroups ) { if ( environmentId.equals( containerGroup.getEnvironmentId() ) ) { return containerGroup; } } throw new ContainerGroupNotFoundException(); } @Override public Set<ContainerGroup> findContainerGroupsByOwnerId( final UUID ownerId ) { Preconditions.checkNotNull( ownerId, "Invalid owner id" ); Set<ContainerGroup> result = Sets.newHashSet(); List<ContainerGroupEntity> containerGroups = ( List<ContainerGroupEntity> ) containerGroupDataService.getAll(); for ( ContainerGroupEntity containerGroup : containerGroups ) { if ( ownerId.equals( containerGroup.getOwnerId() ) ) { result.add( containerGroup ); } } return result; } private void tryToRegister( final Template template ) throws RegistryException { if ( templateRegistry.getTemplate( template.getTemplateName() ) == null ) { templateRegistry.registerTemplate( template ); } } @Override public ContainerHost getContainerHostByName( String hostname ) throws HostNotFoundException { Preconditions.checkArgument( !Strings.isNullOrEmpty( hostname ), "Invalid container hostname" ); for ( ResourceHost resourceHost : getResourceHosts() ) { try { return resourceHost.getContainerHostByName( hostname ); } catch ( HostNotFoundException e ) { //ignore } } throw new HostNotFoundException( String.format( "Container host not found by name %s", hostname ) ); } @Override public ContainerHost getContainerHostById( final UUID hostId ) throws HostNotFoundException { Preconditions.checkNotNull( hostId, "Invalid container id" ); for ( ResourceHost resourceHost : getResourceHosts() ) { try { return resourceHost.getContainerHostById( hostId ); } catch ( HostNotFoundException e ) { //ignore } } throw new HostNotFoundException( String.format( "Container host not found by id %s", hostId ) ); } @Override public ResourceHost getResourceHostByName( String hostname ) throws HostNotFoundException { Preconditions.checkArgument( !Strings.isNullOrEmpty( hostname ), "Invalid resource host hostname" ); for ( ResourceHost resourceHost : getResourceHosts() ) { if ( resourceHost.getHostname().equalsIgnoreCase( hostname ) ) { return resourceHost; } } throw new HostNotFoundException( String.format( "Resource host not found by hostname %s", hostname ) ); } @Override public ResourceHost getResourceHostById( final UUID hostId ) throws HostNotFoundException { Preconditions.checkNotNull( hostId, "Invalid resource host id" ); for ( ResourceHost resourceHost : getResourceHosts() ) { if ( resourceHost.getId().equals( hostId ) ) { return resourceHost; } } throw new HostNotFoundException( String.format( "Resource host not found by id %s", hostId ) ); } @Override public ResourceHost getResourceHostByContainerName( final String containerName ) throws HostNotFoundException { Preconditions.checkArgument( !Strings.isNullOrEmpty( containerName ), "Invalid container name" ); ContainerHost c = getContainerHostByName( containerName ); ContainerHostEntity containerHostEntity = ( ContainerHostEntity ) c; return containerHostEntity.getParent(); } @Override public ResourceHost getResourceHostByContainerId( final UUID hostId ) throws HostNotFoundException { Preconditions.checkNotNull( hostId, "Invalid container id" ); ContainerHost c = getContainerHostById( hostId ); ContainerHostEntity containerHostEntity = ( ContainerHostEntity ) c; return containerHostEntity.getParent(); } @Override public Host bindHost( String id ) throws HostNotFoundException { Preconditions.checkArgument( UUIDUtil.isStringAUuid( id ), "Invalid host id" ); UUID hostId = UUID.fromString( id ); if ( getManagementHost().getId().equals( hostId ) ) { return getManagementHost(); } for ( ResourceHost resourceHost : getResourceHosts() ) { if ( resourceHost.getId().equals( hostId ) ) { return resourceHost; } else { try { return resourceHost.getContainerHostById( hostId ); } catch ( HostNotFoundException e ) { //ignore } } } throw new HostNotFoundException( String.format( "Host by id %s is not registered", id ) ); } @Override public Host bindHost( UUID id ) throws HostNotFoundException { Preconditions.checkNotNull( id, "Invalid host id" ); return bindHost( id.toString() ); } @Override public void startContainer( final ContainerHost host ) throws PeerException { Preconditions.checkNotNull( host, "Container host is null" ); ContainerHostEntity containerHost = ( ContainerHostEntity ) bindHost( host.getId() ); ResourceHost resourceHost = containerHost.getParent(); try { resourceHost.startContainerHost( containerHost ); } catch ( ResourceHostException e ) { // containerHost.setState( ContainerState.UNKNOWN ); throw new PeerException( String.format( "Could not start LXC container [%s]", e.toString() ) ); } catch ( Exception e ) { throw new PeerException( String.format( "Could not stop LXC container [%s]", e.toString() ) ); } } @Override public void stopContainer( final ContainerHost host ) throws PeerException { Preconditions.checkNotNull( host, "Container host is null" ); ContainerHostEntity containerHost = ( ContainerHostEntity ) bindHost( host.getHostId() ); ResourceHost resourceHost = containerHost.getParent(); try { resourceHost.stopContainerHost( containerHost ); } catch ( Exception e ) { throw new PeerException( String.format( "Could not stop LXC container [%s]", e.toString() ) ); } } @Override public void destroyContainer( final ContainerHost host ) throws PeerException { Preconditions.checkNotNull( host, "Container host is null" ); try { ContainerHostEntity entity = ( ContainerHostEntity ) bindHost( host.getId() ); ResourceHost resourceHost = entity.getParent(); resourceHost.destroyContainerHost( host ); containerHostDataService.remove( host.getHostId() ); ( ( ResourceHostEntity ) entity.getParent() ).removeContainerHost( entity ); //update container group ContainerGroupEntity containerGroup = ( ContainerGroupEntity ) findContainerGroupByContainerId( host.getId() ); Set<UUID> containerIds = containerGroup.getContainerIds(); containerIds.remove( host.getId() ); if ( containerIds.isEmpty() ) { containerGroupDataService.remove( containerGroup.getEnvironmentId().toString() ); } else { containerGroup.setContainerIds2( containerIds ); containerGroupDataService.update( containerGroup ); } } catch ( ResourceHostException e ) { String errMsg = String.format( "Could not destroy container [%s]", host.getHostname() ); LOG.error( errMsg, e ); throw new PeerException( errMsg, e.toString() ); } catch ( ContainerGroupNotFoundException e ) { LOG.error( "Could not find container group", e ); } } @Override public boolean isConnected( final Host host ) { Preconditions.checkNotNull( host, "Container host is null" ); try { HostInfo hostInfo = hostRegistry.getHostInfoById( host.getId() ); if ( hostInfo instanceof ContainerHostInfo ) { return ContainerHostState.RUNNING.equals( ( ( ContainerHostInfo ) hostInfo ).getStatus() ); } Host h = bindHost( host.getId() ); return !isTimedOut( h.getLastHeartbeat(), HOST_INACTIVE_TIME ); } catch ( PeerException | HostDisconnectedException e ) { return false; } } private boolean isTimedOut( long lastHeartbeat, long timeoutInMillis ) { return ( System.currentTimeMillis() - lastHeartbeat ) > timeoutInMillis; } @Override public PeerQuotaInfo getQuota( ContainerHost host, final QuotaType quota ) throws PeerException { try { Host c = bindHost( host.getHostId() ); return quotaManager.getQuota( c.getHostname(), quota ); } catch ( QuotaException e ) { throw new PeerException( e ); } } @Override public QuotaInfo getQuotaInfo( ContainerHost host, final QuotaType quota ) throws PeerException { try { Host c = bindHost( host.getHostId() ); return quotaManager.getQuotaInfo( c.getId(), quota ); } catch ( QuotaException e ) { throw new PeerException( e ); } } @Override public void setQuota( ContainerHost host, final QuotaInfo quota ) throws PeerException { try { Host c = bindHost( host.getHostId() ); quotaManager.setQuota( c.getHostname(), quota ); } catch ( QuotaException e ) { throw new PeerException( e ); } } @Override public ManagementHost getManagementHost() throws HostNotFoundException { if ( managementHost == null ) { throw new HostNotFoundException( "Management host not found." ); } return managementHost; } @Override public Set<ResourceHost> getResourceHosts() { synchronized ( resourceHosts ) { return Sets.newConcurrentHashSet( resourceHosts ); } } public void addResourceHost( final ResourceHost host ) { Preconditions.checkNotNull( host, "Resource host could not be null." ); synchronized ( resourceHosts ) { resourceHosts.add( host ); } } @Override public CommandResult execute( final RequestBuilder requestBuilder, final Host host ) throws CommandException { return execute( requestBuilder, host, null ); } @Override public CommandResult execute( final RequestBuilder requestBuilder, final Host aHost, final CommandCallback callback ) throws CommandException { Preconditions.checkNotNull( requestBuilder, "Invalid request" ); Preconditions.checkNotNull( aHost, "Invalid host" ); Host host; try { host = bindHost( aHost.getId() ); } catch ( PeerException e ) { throw new CommandException( "Host is not registered" ); } if ( !host.isConnected() ) { throw new CommandException( "Host is not connected" ); } CommandResult result; if ( callback == null ) { result = commandExecutor.execute( host.getId(), requestBuilder ); } else { result = commandExecutor.execute( host.getId(), requestBuilder, callback ); } return result; } @Override public void executeAsync( final RequestBuilder requestBuilder, final Host aHost, final CommandCallback callback ) throws CommandException { Preconditions.checkNotNull( requestBuilder, "Invalid request" ); Preconditions.checkNotNull( aHost, "Invalid host" ); Host host; try { host = bindHost( aHost.getId() ); } catch ( PeerException e ) { throw new CommandException( "Host not register." ); } if ( !host.isConnected() ) { throw new CommandException( "Host disconnected." ); } if ( callback == null ) { commandExecutor.executeAsync( host.getId(), requestBuilder ); } else { commandExecutor.executeAsync( host.getId(), requestBuilder, callback ); } } @Override public void executeAsync( final RequestBuilder requestBuilder, final Host host ) throws CommandException { executeAsync( requestBuilder, host, null ); } @Override public boolean isLocal() { return true; } public void cleanDb() { if ( managementHost != null && managementHost.getId() != null ) { // peerDAO.deleteInfo( SOURCE_MANAGEMENT_HOST, managementHost.getId().toString() ); managementHostDataService.remove( managementHost.getHostId() ); managementHost = null; } for ( ResourceHost resourceHost : getResourceHosts() ) { for ( ContainerHost containerHost : resourceHost.getContainerHosts() ) { containerHostDataService.remove( containerHost.getHostId() ); ( ( ResourceHostEntity ) resourceHost ).removeContainerHost( containerHost ); } resourceHostDataService.remove( resourceHost.getHostId() ); // peerDAO.deleteInfo( SOURCE_RESOURCE_HOST, resourceHost.getId().toString() ); } synchronized ( resourceHosts ) { resourceHosts.clear(); } } @Override public Template getTemplate( final String templateName ) { Preconditions.checkArgument( !Strings.isNullOrEmpty( templateName ), "Invalid template name" ); return templateRegistry.getTemplate( templateName ); } @Override public boolean isOnline() throws PeerException { return true; } @Override public <T, V> V sendRequest( final T request, final String recipient, final int requestTimeout, final Class<V> responseType, final int responseTimeout, Map<String, String> headers ) throws PeerException { Preconditions.checkNotNull( responseType, "Invalid response type" ); return sendRequestInternal( request, recipient, responseType ); } @Override public <T> void sendRequest( final T request, final String recipient, final int requestTimeout, Map<String, String> headers ) throws PeerException { sendRequestInternal( request, recipient, null ); } private <T, V> V sendRequestInternal( final T request, final String recipient, final Class<V> responseType ) throws PeerException { Preconditions.checkNotNull( request, "Invalid request" ); Preconditions.checkArgument( !Strings.isNullOrEmpty( recipient ), "Invalid recipient" ); for ( RequestListener requestListener : requestListeners ) { if ( recipient.equalsIgnoreCase( requestListener.getRecipient() ) ) { try { Object response = requestListener.onRequest( new Payload( request, getId() ) ); if ( response != null && responseType != null ) { return responseType.cast( response ); } } catch ( Exception e ) { throw new PeerException( e ); } } } return null; } @Override public void onHeartbeat( final ResourceHostInfo resourceHostInfo ) { if ( resourceHostInfo.getHostname().equals( "management" ) ) { if ( managementHost == null ) { managementHost = new ManagementHostEntity( getId().toString(), resourceHostInfo ); try { managementHost.init(); } catch ( Exception e ) { LOG.error( e.toString() ); } managementHostDataService.persist( ( ManagementHostEntity ) managementHost ); ( ( AbstractSubutaiHost ) managementHost ).setPeer( this ); } ( ( AbstractSubutaiHost ) managementHost ).updateHostInfo( resourceHostInfo ); } else { ResourceHost host; try { host = getResourceHostByName( resourceHostInfo.getHostname() ); saveResourceHostContainers( host, resourceHostInfo.getContainers() ); } catch ( HostNotFoundException e ) { host = new ResourceHostEntity( getId().toString(), resourceHostInfo ); host.init(); resourceHostDataService.persist( ( ResourceHostEntity ) host ); addResourceHost( host ); setResourceHostTransientFields( Sets.newHashSet( host ) ); saveResourceHostContainers( host, resourceHostInfo.getContainers() ); } ( ( AbstractSubutaiHost ) host ).updateHostInfo( resourceHostInfo ); } } private void saveResourceHostContainers( ResourceHost resourceHost, Set<ContainerHostInfo> containerHostInfos ) { for ( ContainerHostInfo containerHostInfo : containerHostInfos ) { if ( containerHostInfo.getInterfaces().size() == 0 ) { continue; } Host containerHost; try { containerHost = bindHost( containerHostInfo.getId() ); } catch ( HostNotFoundException hnfe ) { containerHost = new ContainerHostEntity( getId().toString(), containerHostInfo ); setContainersTransientFields( Sets.newHashSet( ( ContainerHost ) containerHost ) ); // ( ( AbstractSubutaiHost ) containerHost ).setPeer( this ); // ( ( ContainerHostEntity ) containerHost ).setDataService( containerHostDataService ); ( ( ResourceHostEntity ) resourceHost ).addContainerHost( ( ContainerHostEntity ) containerHost ); containerHostDataService.persist( ( ContainerHostEntity ) containerHost ); } ( ( ContainerHostEntity ) containerHost ).updateHostInfo( containerHostInfo ); } } private void setContainersTransientFields( final Set<ContainerHost> containerHosts ) { for ( ContainerHost containerHost : containerHosts ) { ( ( AbstractSubutaiHost ) containerHost ).setPeer( this ); ( ( ContainerHostEntity ) containerHost ).setDataService( containerHostDataService ); ( ( ContainerHostEntity ) containerHost ).setLocalPeer( this ); } } @Override public ProcessResourceUsage getProcessResourceUsage( final ContainerHost host, final int processPid ) throws PeerException { Preconditions.checkNotNull( host, "Invalid container host" ); Preconditions.checkArgument( processPid > 0, "Process pid must be greater than 0" ); try { Host c = bindHost( host.getId() ); return monitor.getProcessResourceUsage( ( ContainerHost ) c, processPid ); } catch ( MonitorException e ) { throw new PeerException( e ); } } @Override public int getRamQuota( final ContainerHost host ) throws PeerException { Preconditions.checkNotNull( host, "Invalid container host" ); try { return quotaManager.getRamQuota( host.getId() ); } catch ( QuotaException e ) { throw new PeerException( e ); } } @Override public MemoryQuotaInfo getRamQuotaInfo( final ContainerHost host ) throws PeerException { Preconditions.checkNotNull( host, "Invalid container host" ); try { return quotaManager.getRamQuotaInfo( host.getId() ); } catch ( QuotaException e ) { throw new PeerException( e ); } } @Override public void setRamQuota( final ContainerHost host, final int ramInMb ) throws PeerException { Preconditions.checkNotNull( host, "Invalid container host" ); Preconditions.checkArgument( ramInMb > 0, "Ram quota value must be greater than 0" ); try { quotaManager.setRamQuota( host.getId(), ramInMb ); } catch ( QuotaException e ) { throw new PeerException( e ); } } @Override public int getCpuQuota( final ContainerHost host ) throws PeerException { Preconditions.checkNotNull( host, "Invalid container host" ); try { return quotaManager.getCpuQuota( host.getId() ); } catch ( QuotaException e ) { throw new PeerException( e ); } } @Override public CpuQuotaInfo getCpuQuotaInfo( final ContainerHost host ) throws PeerException { Preconditions.checkNotNull( host, "Invalid container host" ); try { return quotaManager.getCpuQuotaInfo( host.getId() ); } catch ( QuotaException e ) { throw new PeerException( e ); } } @Override public void setCpuQuota( final ContainerHost host, final int cpuPercent ) throws PeerException { Preconditions.checkNotNull( host, "Invalid container host" ); Preconditions.checkArgument( cpuPercent > 0, "Cpu quota value must be greater than 0" ); try { quotaManager.setCpuQuota( host.getId(), cpuPercent ); } catch ( QuotaException e ) { throw new PeerException( e ); } } @Override public Set<Integer> getCpuSet( final ContainerHost host ) throws PeerException { Preconditions.checkNotNull( host, "Invalid container host" ); try { return quotaManager.getCpuSet( host.getId() ); } catch ( QuotaException e ) { throw new PeerException( e ); } } @Override public void setCpuSet( final ContainerHost host, final Set<Integer> cpuSet ) throws PeerException { Preconditions.checkNotNull( host, "Invalid container host" ); Preconditions.checkArgument( !CollectionUtil.isCollectionEmpty( cpuSet ), "Empty cpu set" ); try { quotaManager.setCpuSet( host.getId(), cpuSet ); } catch ( QuotaException e ) { throw new PeerException( e ); } } @Override public DiskQuota getDiskQuota( final ContainerHost host, final DiskPartition diskPartition ) throws PeerException { Preconditions.checkNotNull( host, "Invalid container host" ); Preconditions.checkNotNull( diskPartition, "Invalid disk partition" ); try { return quotaManager.getDiskQuota( host.getId(), diskPartition ); } catch ( QuotaException e ) { throw new PeerException( e ); } } @Override public void setDiskQuota( final ContainerHost host, final DiskQuota diskQuota ) throws PeerException { Preconditions.checkNotNull( host, "Invalid container host" ); Preconditions.checkNotNull( diskQuota, "Invalid disk quota" ); try { quotaManager.setDiskQuota( host.getId(), diskQuota ); } catch ( QuotaException e ) { throw new PeerException( e ); } } @Override public int getAvailableRamQuota( final ContainerHost host ) throws PeerException { Preconditions.checkNotNull( host, "Invalid container host" ); try { return quotaManager.getAvailableRamQuota( host.getId() ); } catch ( QuotaException e ) { throw new PeerException( e ); } } @Override public int getAvailableCpuQuota( final ContainerHost host ) throws PeerException { Preconditions.checkNotNull( host, "Invalid container host" ); try { return quotaManager.getAvailableCpuQuota( host.getId() ); } catch ( QuotaException e ) { throw new PeerException( e ); } } @Override public DiskQuota getAvailableDiskQuota( final ContainerHost host, final DiskPartition diskPartition ) throws PeerException { Preconditions.checkNotNull( host, "Invalid container host" ); Preconditions.checkNotNull( diskPartition, "Invalid disk partition" ); try { return quotaManager.getAvailableDiskQuota( host.getId(), diskPartition ); } catch ( QuotaException e ) { throw new PeerException( e ); } } @Override public ContainersDestructionResult destroyEnvironmentContainers( final UUID environmentId ) throws PeerException { Preconditions.checkNotNull( environmentId, "Invalid environment id" ); Set<Exception> errors = Sets.newHashSet(); Set<UUID> destroyedContainersIds = Sets.newHashSet(); try { ContainerGroup containerGroup = findContainerGroupByEnvironmentId( environmentId ); Set<ContainerHost> containerHosts = Sets.newHashSet(); for ( UUID containerId : containerGroup.getContainerIds() ) { try { containerHosts.add( getContainerHostById( containerId ) ); } catch ( HostNotFoundException e ) { errors.add( e ); } } if ( !containerHosts.isEmpty() ) { List<Future<UUID>> taskFutures = Lists.newArrayList(); ExecutorService executorService = Executors.newFixedThreadPool( containerHosts.size() ); for ( ContainerHost containerHost : containerHosts ) { taskFutures.add( executorService.submit( new DestroyContainerWrapperTask( this, containerHost ) ) ); } for ( Future<UUID> taskFuture : taskFutures ) { try { destroyedContainersIds.add( taskFuture.get() ); } catch ( ExecutionException | InterruptedException e ) { errors.add( e ); } } executorService.shutdown(); } String exception = null; if ( !errors.isEmpty() ) { exception = String.format( "There were errors while destroying containers: %s", errors ); } return new ContainersDestructionResultImpl( destroyedContainersIds, exception ); } catch ( ContainerGroupNotFoundException e ) { throw new PeerException( e ); } } @Override public boolean equals( final Object o ) { if ( this == o ) { return true; } if ( !( o instanceof LocalPeerImpl ) ) { return false; } final LocalPeerImpl that = ( LocalPeerImpl ) o; return getId().equals( that.getId() ); } @Override public int hashCode() { return getId().hashCode(); } }
package mutation; import controller.GenomeGraph; import genome.Strand; import genome.StrandEdge; import java.util.ArrayList; import java.util.HashMap; /** * The Class AllMutations. * * @author Jeffrey Helgers. * This class computes all the mutations in the given dataset. */ public class Mutations { /** * The genome graph. */ private GenomeGraph genomeGraph; /** * Constructor to create. * * @param graph The genome graph. */ public Mutations(GenomeGraph graph) { this.genomeGraph = graph; } /** * Compute all the mutations in the graph. * From all the start Strands. */ public void computeAllMutations() { HashMap<Integer, Strand> strands = genomeGraph.getStrandNodes(); for (Strand strand : strands.values()) { mutationsOnStrand(strand, strands); } } /** * Check if there is a SNP mutation starting from the start strand. * @param start The start strand. * @param strands All the strands. */ private void findSNP(Strand start, ArrayList<Strand> strands) { for (int i = 0; i < start.getEdges().size() - 1; i++) { Strand firstEdgeEnd = strands.get(start.getEdges().get(i).getEnd()); if (firstEdgeEnd.getSequence().length() == 1) { for (int j = i + 1; j < start.getEdges().size(); i++) { Strand secondEdgeEnd = strands.get(start.getEdges().get(j).getEnd()); if (secondEdgeEnd.getSequence().length() == 1) { for (StrandEdge edge1 : firstEdgeEnd.getEdges()) { for (StrandEdge edge2 : secondEdgeEnd.getEdges()) { if (edge1.getEnd() == edge2.getEnd()) { start.addMutation(new MutationSNP( MutationType.SNP, firstEdgeEnd.getGenomes(), secondEdgeEnd.getGenomes(), start, strands.get(edge1.getEnd()), firstEdgeEnd, secondEdgeEnd)); } } } } } } } } /** * Compute mutations that can appear form a start Strand. * When there is only one edge, there can't be a mutation. * @param start The start Strand. * @param strands All the Strands in the graph. */ private void mutationsOnStrand(Strand start, HashMap<Integer, Strand> strands) { if (start.getEdges().size() > 1) { for (int i = 0; i < start.getEdges().size() - 1; i++) { Strand next1 = strands.get(start.getEdges().get(i).getEnd()); for (int j = i + 1; j < start.getEdges().size(); j++) { Strand next2 = strands.get(start.getEdges().get(j).getEnd()); checkMutation(start, next1, next2); } } } } /** * Checks if there is a mutation from the start Strand using these two edges. * @param start The start Strand. * @param next1 The Strand on the first edge. * @param next2 The Strand on the second edge. * @param strands All the strands. */ private void checkMutation(Strand start, Strand next1, Strand next2) { for (StrandEdge edge1 : next1.getEdges()) { if (edge1.getEnd() == next2.getId()) { ArrayList<String> genomesInBothStrands = new ArrayList<>(start.getGenomes()); genomesInBothStrands.retainAll(next2.getGenomes()); ArrayList<String> genomesInOriginal = new ArrayList<>(next1.getGenomes()); genomesInOriginal.retainAll(genomesInBothStrands); genomesInBothStrands.removeAll(genomesInOriginal); MutationIndel indel = new MutationIndel(MutationType.DELETION, genomesInOriginal, genomesInBothStrands, start, next2, new ArrayList<Strand>()); start.addMutation(indel); return; } } for (StrandEdge edge2 : next2.getEdges()) { if (edge2.getEnd() == next1.getId()) { ArrayList<String> genomesInBothStrands = new ArrayList<>(start.getGenomes()); genomesInBothStrands.retainAll(next2.getGenomes()); ArrayList<String> genomesInMutation = new ArrayList<>(next1.getGenomes()); genomesInMutation.retainAll(genomesInBothStrands); genomesInBothStrands.removeAll(genomesInMutation); MutationIndel indel = new MutationIndel(MutationType.INSERTION, genomesInBothStrands, genomesInMutation, start, next1, new ArrayList<Strand>()); start.addMutation(indel); return; } } } }
package org.eclipse.xtext.parser.terminalrules; import org.eclipse.xtext.GrammarUtil; import org.eclipse.xtext.conversion.IValueConverter; import org.eclipse.xtext.conversion.ValueConverter; import org.eclipse.xtext.conversion.impl.AbstractDeclarativeValueConverterService; import org.eclipse.xtext.conversion.impl.AbstractNullSafeConverter; import org.eclipse.xtext.parsetree.AbstractNode; import org.eclipse.xtext.util.Strings; /** * @author Sebastian Zarnekow - Initial contribution and API */ public class TerminalRuleTestLanguageConverters extends AbstractDeclarativeValueConverterService { @ValueConverter(rule = "ID") public IValueConverter<String> ID() { return new AbstractNullSafeConverter<String>() { @Override protected String internalToValue(String string, AbstractNode node) { return string.startsWith("^") ? string.substring(1) : string; } @Override protected String internalToString(String value) { if (GrammarUtil.getAllKeywords(getGrammar()).contains(value)) { return "^"+value; } return value; } }; } @ValueConverter(rule = "STRING") public IValueConverter<String> STRING() { return new AbstractNullSafeConverter<String>() { @Override protected String internalToValue(String string, AbstractNode node) { return Strings.convertFromJavaString(string.substring(1, string.length() - 1)); } @Override protected String internalToString(String value) { return '"' + Strings.convertToJavaString(value) + '"'; } }; } }
package cn.com.sunjiesh.thirdservice.wechat.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.qq.weixin.mp.aes.AesException; import cn.com.sunjiesh.thirdservice.wechat.service.CustomMessageReceiveService; import cn.com.sunjiesh.wechat.handler.WechatValidHandler; import cn.com.sunjiesh.xcutils.common.base.ServiceException; /** * Wechat * @author Tom * */ @RestController @RequestMapping("/wechat") public class WechatController { private static final Logger LOGGER = LoggerFactory.getLogger(WechatController.class); @Autowired private CustomMessageReceiveService messageReceiveService; @RequestMapping(value = "/receive.do", method = RequestMethod.GET) public String valid(@RequestParam("timestamp") String timestamp, @RequestParam("echostr") String echoStr, @RequestParam("nonce") String nonce, @RequestParam("signature") String signature){ LOGGER.debug("Receive a get requeset"); // tokentimestampnonce String responseStr = WechatValidHandler.valid(timestamp, echoStr, nonce, signature); return responseStr; } @RequestMapping(value = "/receive.do", method = RequestMethod.POST) @ResponseBody public String receive(@RequestHeader("Content-Type") String contentType, HttpServletRequest request, @RequestBody String requestBody) { try { LOGGER.debug("Receive a post requeset"); Map<String,String> queryParams=new HashMap<String,String>(); String requestQueryString=request.getQueryString(); LOGGER.debug("requestQueryString="+requestQueryString); if(!StringUtils.isEmpty(requestQueryString)){ String[] queryStringArr=requestQueryString.split("&"); for(String queryString:queryStringArr){ if(queryString.contains("=")){ String[] paramKeyAndValue=queryString.split("="); String paramKey=paramKeyAndValue[0]; String paramValue=paramKeyAndValue[1]; queryParams.put(paramKey, paramValue); } } } LOGGER.debug("requestPart=" + requestBody); LOGGER.debug("contentType=" + contentType); String respXml = messageReceiveService.messageReceive(requestBody,queryParams); LOGGER.debug("respXml="+respXml); // super.responseXml(response,respXml); return respXml; } catch (ServiceException | AesException e) { e.printStackTrace(); LOGGER.error("", e); } catch (Exception e) { e.printStackTrace(); LOGGER.error("", e); } return ""; } }
package org.eclipse.birt.report.designer.internal.ui.dialogs; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.data.ui.dataset.DataSetUIUtil; import org.eclipse.birt.report.designer.internal.ui.swt.custom.AutoResizeTableLayout; import org.eclipse.birt.report.designer.internal.ui.util.DataUtil; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.dialogs.BaseDialog; import org.eclipse.birt.report.designer.ui.views.attributes.providers.LinkedDataSetAdapter; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.model.api.CachedMetaDataHandle; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.ResultSetColumnHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn; import org.eclipse.birt.report.model.api.metadata.IChoice; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTableViewer; import org.eclipse.jface.viewers.CheckboxTreeViewer; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.TreeViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; 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.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TreeItem; /** * DataSetBindingSelector */ public class DataSetBindingSelector extends BaseDialog { public static final String NONE = Messages.getString( "BindingPage.None" ); //$NON-NLS-1$ private CheckboxTableViewer columnTableViewer; private CheckboxTreeViewer columnTreeViewer; private Composite contentPane; private Combo dataSetCombo; private String dataSetName; private DataSetHandle datasetHandle; private String[] columns; private boolean validateEmptyResults = false; private List<DataSetHandle> datasets; private Object[] result; private static final IChoice[] DATA_TYPE_CHOICES = DEUtil.getMetaDataDictionary( ) .getStructure( ComputedColumn.COMPUTED_COLUMN_STRUCT ) .getMember( ComputedColumn.DATA_TYPE_MEMBER ) .getAllowedChoices( ) .getChoices( ); /** * DataSetColumnProvider */ private static class DataSetColumnProvider extends LabelProvider implements ITableLabelProvider, IStructuredContentProvider { public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { } public Object[] getElements( Object inputElement ) { if ( inputElement instanceof Iterator ) { Iterator iter = (Iterator) inputElement; List list = new ArrayList( ); while ( iter.hasNext( ) ) list.add( iter.next( ) ); return list.toArray( ); } return new Object[0]; } public Image getColumnImage( Object element, int columnIndex ) { return null; } public String getColumnText( Object element, int columnIndex ) { ResultSetColumnHandle column = (ResultSetColumnHandle) element; if ( columnIndex == 1 ) { return column.getColumnName( ); } if ( columnIndex == 2 ) { return getDataTypeDisplayName( column.getDataType( ) ); } return null; } } /** * GroupedColumnProvider */ private static class GroupedColumnProvider implements ITreeContentProvider { public void dispose( ) { } public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { } public Object[] getElements( Object inputElement ) { if ( inputElement instanceof Map ) { return ( (Map) inputElement ).entrySet( ).toArray( ); } return new Object[0]; } public Object[] getChildren( Object parentElement ) { if ( parentElement instanceof Entry ) { return ( (List) ( (Entry) parentElement ).getValue( ) ).toArray( ); } return new Object[0]; } public Object getParent( Object element ) { return null; } public boolean hasChildren( Object element ) { Object[] cc = getChildren( element ); return cc != null && cc.length > 0; } } /** * GroupedColumnNameProvider */ private static class GroupedColumnNameProvider extends ColumnLabelProvider { @Override public String getText( Object element ) { if ( element instanceof Entry ) { return (String) ( (Entry) element ).getKey( ); } else if ( element instanceof ResultSetColumnHandle ) { ResultSetColumnHandle column = (ResultSetColumnHandle) element; return column.getColumnName( ); } return ""; //$NON-NLS-1$ } } /** * GroupedColumnTypeProvider */ private static class GroupedColumnTypeProvider extends ColumnLabelProvider { @Override public String getText( Object element ) { if ( element instanceof ResultSetColumnHandle ) { ResultSetColumnHandle column = (ResultSetColumnHandle) element; return getDataTypeDisplayName( column.getDataType( ) ); } return ""; //$NON-NLS-1$ } } public DataSetBindingSelector( Shell parentShell, String title ) { super( parentShell, title ); } public Control createDialogArea( Composite parent ) { UIUtil.bindHelp( parent, IHelpContextIds.SELECT_DATASET_BINDING_COLUMN ); Composite area = (Composite) super.createDialogArea( parent ); Composite contents = new Composite( area, SWT.NONE ); contents.setLayoutData( new GridData( GridData.FILL_BOTH ) ); GridLayout layout = new GridLayout( ); layout.numColumns = 2; contents.setLayout( layout ); createDataSetContents( contents ); contentPane = new Composite( contents, SWT.None ); contentPane.setLayoutData( new GridData( GridData.FILL_BOTH ) ); contentPane.setLayout( new GridLayout( ) ); columnTableViewer = null; columnTreeViewer = null; Object input = populateInput( ); if ( input instanceof Map ) { createColumnBindingTreeContents( contentPane, input ); } else { createColumnBindingTableContents( contentPane, input ); } return area; } protected Control createContents( Composite parent ) { Control control = super.createContents( parent ); enableOKButton( ); return control; } protected void createColumnBindingTableContents( Composite parent, Object input ) { columnTableViewer = CheckboxTableViewer.newCheckList( parent, SWT.CHECK | SWT.BORDER | SWT.FULL_SELECTION ); GridData data = new GridData( GridData.FILL_BOTH ); data.widthHint = 450; data.heightHint = 200; data.horizontalSpan = 2; data.verticalIndent = 5; columnTableViewer.getTable( ).setLayoutData( data ); columnTableViewer.getTable( ).setHeaderVisible( true ); columnTableViewer.getTable( ).setLinesVisible( true ); new TableColumn( columnTableViewer.getTable( ), SWT.NONE ).setText( "" ); //$NON-NLS-1$ new TableColumn( columnTableViewer.getTable( ), SWT.NONE ).setText( Messages.getString( "DataSetColumnBindingsFormHandleProvider.Column.Name" ) );//$NON-NLS-1$ new TableColumn( columnTableViewer.getTable( ), SWT.NONE ).setText( Messages.getString( "DataSetColumnBindingsFormHandleProvider.Column.DataType" ) ); //$NON-NLS-1$ TableLayout layout = new AutoResizeTableLayout( columnTableViewer.getTable( ) ); layout.addColumnData( new ColumnWeightData( 6, true ) ); layout.addColumnData( new ColumnWeightData( 47, true ) ); layout.addColumnData( new ColumnWeightData( 47, true ) ); columnTableViewer.getTable( ).setLayout( layout ); columnTableViewer.addSelectionChangedListener( new ISelectionChangedListener( ) { public void selectionChanged( SelectionChangedEvent event ) { enableOKButton( ); } } ); DataSetColumnProvider provider = new DataSetColumnProvider( ); columnTableViewer.setLabelProvider( provider ); columnTableViewer.setContentProvider( provider ); Composite buttonContainer = new Composite( parent, SWT.NONE ); data = new GridData( GridData.FILL_HORIZONTAL ); data.horizontalSpan = 2; buttonContainer.setLayoutData( data ); GridLayout gdLayout = new GridLayout( ); gdLayout.numColumns = 2; gdLayout.marginWidth = gdLayout.marginHeight = 0; buttonContainer.setLayout( gdLayout ); Button selectAllButton = new Button( buttonContainer, SWT.PUSH ); selectAllButton.setText( Messages.getString( "DataSetBindingSelector.Button.SelectAll" ) ); //$NON-NLS-1$ selectAllButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { columnTableViewer.setAllChecked( true ); enableOKButton( ); } } ); Button deselectAllButton = new Button( buttonContainer, SWT.PUSH ); deselectAllButton.setText( Messages.getString( "DataSetBindingSelector.Button.DeselectAll" ) ); //$NON-NLS-1$ deselectAllButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { columnTableViewer.setAllChecked( false ); enableOKButton( ); } } ); handleDataSetComboSelectedEvent( input ); if ( columns != null ) { int count = columnTableViewer.getTable( ).getItemCount( ); List columnList = Arrays.asList( columns ); for ( int i = 0; i < count; i++ ) { ResultSetColumnHandle column = (ResultSetColumnHandle) columnTableViewer.getElementAt( i ); if ( columnList.contains( column.getColumnName( ) ) ) { columnTableViewer.setChecked( column, true ); } } } } protected void createColumnBindingTreeContents( Composite parent, Object input ) { columnTreeViewer = new CheckboxTreeViewer( parent, SWT.CHECK | SWT.BORDER | SWT.FULL_SELECTION ); GridData data = new GridData( GridData.FILL_BOTH ); data.widthHint = 450; data.heightHint = 200; data.horizontalSpan = 2; data.verticalIndent = 5; columnTreeViewer.getTree( ).setLayoutData( data ); columnTreeViewer.getTree( ).setHeaderVisible( true ); columnTreeViewer.getTree( ).setLinesVisible( true ); TreeViewerColumn tvc1 = new TreeViewerColumn( columnTreeViewer, SWT.NONE ); tvc1.getColumn( ) .setText( Messages.getString( "DataSetColumnBindingsFormHandleProvider.Column.Name" ) );//$NON-NLS-1$ tvc1.getColumn( ).setWidth( 230 ); tvc1.setLabelProvider( new GroupedColumnNameProvider( ) ); TreeViewerColumn tvc2 = new TreeViewerColumn( columnTreeViewer, SWT.NONE ); tvc2.getColumn( ) .setText( Messages.getString( "DataSetColumnBindingsFormHandleProvider.Column.DataType" ) ); //$NON-NLS-1$ tvc2.getColumn( ).setWidth( 100 ); tvc2.setLabelProvider( new GroupedColumnTypeProvider( ) ); columnTreeViewer.addSelectionChangedListener( new ISelectionChangedListener( ) { public void selectionChanged( SelectionChangedEvent event ) { enableOKButton( ); } } ); columnTreeViewer.addCheckStateListener( new ICheckStateListener( ) { public void checkStateChanged( CheckStateChangedEvent event ) { Object element = event.getElement( ); if ( element instanceof Entry ) { columnTreeViewer.setGrayed( element, false ); columnTreeViewer.setSubtreeChecked( element, event.getChecked( ) ); } else { Map<String, List> input = (Map<String, List>) columnTreeViewer.getInput( ); for ( Entry<String, List> ent : input.entrySet( ) ) { List children = ent.getValue( ); if ( children.contains( element ) ) { Object parent = ent; boolean allChecked = event.getChecked( ); boolean graySet = false; for ( Object cc : children ) { if ( columnTreeViewer.getChecked( cc ) != allChecked ) { columnTreeViewer.setGrayed( parent, true ); columnTreeViewer.setChecked( parent, true ); graySet = true; break; } } if ( !graySet ) { columnTreeViewer.setGrayed( parent, false ); columnTreeViewer.setChecked( parent, allChecked ); } break; } } } enableOKButton( ); } } ); columnTreeViewer.setContentProvider( new GroupedColumnProvider( ) ); Composite buttonContainer = new Composite( parent, SWT.NONE ); data = new GridData( GridData.FILL_HORIZONTAL ); data.horizontalSpan = 2; buttonContainer.setLayoutData( data ); GridLayout gdLayout = new GridLayout( ); gdLayout.numColumns = 2; gdLayout.marginWidth = gdLayout.marginHeight = 0; buttonContainer.setLayout( gdLayout ); Button selectAllButton = new Button( buttonContainer, SWT.PUSH ); selectAllButton.setText( Messages.getString( "DataSetBindingSelector.Button.SelectAll" ) ); //$NON-NLS-1$ selectAllButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { TreeItem[] items = columnTreeViewer.getTree( ).getItems( ); for ( TreeItem ti : items ) { columnTreeViewer.setGrayed( ti.getData( ), false ); columnTreeViewer.setSubtreeChecked( ti.getData( ), true ); } enableOKButton( ); } } ); Button deselectAllButton = new Button( buttonContainer, SWT.PUSH ); deselectAllButton.setText( Messages.getString( "DataSetBindingSelector.Button.DeselectAll" ) ); //$NON-NLS-1$ deselectAllButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { TreeItem[] items = columnTreeViewer.getTree( ).getItems( ); for ( TreeItem ti : items ) { columnTreeViewer.setGrayed( ti.getData( ), false ); columnTreeViewer.setSubtreeChecked( ti.getData( ), false ); } enableOKButton( ); } } ); handleDataSetComboSelectedEvent( input ); if ( columns != null ) { Set<String> columnSet = new HashSet<String>( Arrays.asList( columns ) ); TreeItem[] items = columnTreeViewer.getTree( ).getItems( ); for ( TreeItem ti : items ) { TreeItem[] ccs = ti.getItems( ); int count = 0; for ( TreeItem cc : ccs ) { ResultSetColumnHandle column = (ResultSetColumnHandle) cc.getData( ); if ( columnSet.contains( column.getColumnName( ) ) ) { columnTreeViewer.setChecked( column, true ); count++; } } if ( count == ccs.length ) { columnTreeViewer.setChecked( ti.getData( ), true ); } } } } protected void createDataSetContents( Composite parent ) { if ( dataSetName != null ) { Label lb = new Label( parent, SWT.NONE ); lb.setText( Messages.getString( "DataSetBindingSelector.Label.SelectBindingColumns" ) ); //$NON-NLS-1$ GridData data = new GridData( GridData.FILL_HORIZONTAL ); data.horizontalSpan = 2; lb.setLayoutData( data ); } else { Label dateSetLabel = new Label( parent, SWT.NONE ); dateSetLabel.setText( Messages.getString( "DataSetBindingSelector.Combo.DataSet" ) ); //$NON-NLS-1$ dataSetCombo = new Combo( parent, SWT.BORDER | SWT.READ_ONLY ); datasets = UIUtil.getVisibleDataSetHandles( SessionHandleAdapter.getInstance( ) .getModule( ) ); dataSetCombo.setItems( getDataSetComboList( ) ); dataSetCombo.select( 0 ); GridData data = new GridData( GridData.FILL_HORIZONTAL ); dataSetCombo.setLayoutData( data ); dataSetCombo.setVisibleItemCount( 30 ); dataSetCombo.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { Object input = populateInput( ); if ( input instanceof Map ) { if ( columnTreeViewer == null ) { disposeChildren( contentPane ); columnTableViewer = null; createColumnBindingTreeContents( contentPane, input ); } } else { if ( columnTableViewer == null ) { disposeChildren( contentPane ); columnTreeViewer = null; createColumnBindingTableContents( contentPane, input ); } } handleDataSetComboSelectedEvent( input ); } } ); } } private void disposeChildren( Composite parent ) { Control[] cc = parent.getChildren( ); if ( cc != null ) { for ( Control c : cc ) { c.dispose( ); } } } private String[] getDataSetComboList( ) { String[] comboList = new String[datasets.size( ) + 1]; comboList[0] = NONE; for ( int i = 0; i < datasets.size( ); i++ ) { comboList[i + 1] = datasets.get( i ).getQualifiedName( ); if ( SessionHandleAdapter.getInstance( ) .getModule( ) .findDataSet( comboList[i + 1] ) != datasets.get( i ) ) { comboList[i + 1] += Messages.getString( "BindingGroupDescriptorProvider.Flag.DataModel" ); } } return comboList; } private DataSetHandle getSelectedDataSet( ) { if ( dataSetCombo.getSelectionIndex( ) > 0 ) { return (DataSetHandle) datasets.get( dataSetCombo.getSelectionIndex( ) - 1 ); } return null; } private Object populateInput( ) { Object input = null; DataSetHandle handle = null; if ( datasetHandle != null ) { handle = datasetHandle; LinkedDataSetAdapter adapter = new LinkedDataSetAdapter( ); for ( Iterator iterator = adapter.getVisibleLinkedDataSetsDataSetHandles( SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) ) .iterator( ); iterator.hasNext( ); ) { DataSetHandle dataSetHandle = (DataSetHandle) iterator.next( ); if ( dataSetHandle.getQualifiedName( ).equals( dataSetName ) ) { // if dataet is linkeddatamodel, reset the handle to get // grouped view. handle = null; break; } } } else if ( dataSetName != null ) { handle = DataUtil.findDataSet( dataSetName ); } else { handle = getSelectedDataSet( ); } if ( handle != null ) { try { CachedMetaDataHandle cmdh = DataSetUIUtil.getCachedMetaDataHandle( handle ); input = cmdh.getResultSet( ).iterator( ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); } } else { input = new LinkedDataSetAdapter( ).getGroupedResultSetColumns( dataSetName ); } return input; } protected void handleDataSetComboSelectedEvent( Object input ) { if ( input instanceof Iterator ) { columnTableViewer.setInput( input ); } else if ( input instanceof Map ) { columnTreeViewer.setInput( input ); columnTreeViewer.expandAll( ); } else { if ( columnTableViewer != null ) { columnTableViewer.setInput( null ); } if ( columnTreeViewer != null ) { columnTreeViewer.setInput( null ); } } } protected void okPressed( ) { result = new Object[3]; if ( dataSetName != null || dataSetCombo.getSelectionIndex( ) > 0 ) { if ( dataSetName == null ) { result[0] = getSelectedDataSet( ); } else { result[0] = datasetHandle; } if ( columnTableViewer != null ) { if ( columnTableViewer.getCheckedElements( ) != null ) { result[1] = columnTableViewer.getCheckedElements( ); List<String> list = new ArrayList<String>( ); for ( int i = 0; i < columnTableViewer.getTable( ) .getItemCount( ); i++ ) { ResultSetColumnHandle column = (ResultSetColumnHandle) columnTableViewer.getElementAt( i ); if ( !columnTableViewer.getChecked( column ) ) { list.add( column.getColumnName( ) ); } } result[2] = list.toArray( ); } else { result[1] = null; List<String> list = new ArrayList<String>( ); for ( int i = 0; i < columnTableViewer.getTable( ) .getItemCount( ); i++ ) { ResultSetColumnHandle column = (ResultSetColumnHandle) columnTableViewer.getElementAt( i ); if ( !columnTableViewer.getChecked( column ) ) { list.add( column.getColumnName( ) ); } } if ( list.isEmpty( ) ) result[2] = null; else result[2] = list.toArray( ); } } else { if ( columnTreeViewer.getCheckedElements( ) != null ) { Object[] selection = columnTreeViewer.getCheckedElements( ); List<ResultSetColumnHandle> cols = new ArrayList<ResultSetColumnHandle>( ); for ( Object obj : selection ) { if ( obj instanceof ResultSetColumnHandle ) { cols.add( (ResultSetColumnHandle) obj ); } } result[1] = cols.toArray( ); List<String> list = new ArrayList<String>( ); for ( int i = 0; i < columnTreeViewer.getTree( ) .getItemCount( ); i++ ) { TreeItem ti = columnTreeViewer.getTree( ).getItem( i ); for ( int j = 0; j < ti.getItemCount( ); j++ ) { TreeItem sti = ti.getItem( j ); if ( !sti.getChecked( ) ) { list.add( ( (ResultSetColumnHandle) sti.getData( ) ).getColumnName( ) ); } } } result[2] = list.toArray( ); } else { result[1] = null; List<String> list = new ArrayList<String>( ); for ( int i = 0; i < columnTreeViewer.getTree( ) .getItemCount( ); i++ ) { TreeItem ti = columnTreeViewer.getTree( ).getItem( i ); for ( int j = 0; j < ti.getItemCount( ); j++ ) { TreeItem sti = ti.getItem( j ); if ( !sti.getChecked( ) ) { list.add( ( (ResultSetColumnHandle) sti.getData( ) ).getColumnName( ) ); } } } if ( list.isEmpty( ) ) result[2] = null; else result[2] = list.toArray( ); } } } else { result[0] = null; result[1] = null; result[2] = null; } super.okPressed( ); } public Object getResult( ) { return result; } public void setDataSet( String dataSetName ) { setDataSet( dataSetName, true ); } public void setDataSet( String dataSetName, boolean isDataSet ) { this.dataSetName = dataSetName; if ( isDataSet ) { datasetHandle = SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) .findDataSet( dataSetName ); } else { LinkedDataSetAdapter adapter = new LinkedDataSetAdapter( ); for ( Iterator iterator = adapter.getVisibleLinkedDataSetsDataSetHandles( SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) ) .iterator( ); iterator.hasNext( ); ) { DataSetHandle dataSetHandle = (DataSetHandle) iterator.next( ); if ( dataSetHandle.getQualifiedName( ).equals( dataSetName ) ) { this.datasetHandle = dataSetHandle; break; } } } } private static String getDataTypeDisplayName( String dataType ) { for ( int i = 0; i < DATA_TYPE_CHOICES.length; i++ ) { IChoice choice = DATA_TYPE_CHOICES[i]; if ( choice.getName( ).equals( dataType ) ) { return choice.getDisplayName( ); } } return dataType; } private void enableOKButton( ) { if ( getOkButton( ) != null && !getOkButton( ).isDisposed( ) ) { if ( validateEmptyResults ) { if ( columnTableViewer != null ) { getOkButton( ).setEnabled( columnTableViewer.getCheckedElements( ).length > 0 ); } else { getOkButton( ).setEnabled( columnTreeViewer.getCheckedElements( ).length > 0 ); } } } } public void setColumns( String[] columns ) { this.columns = columns; } public void setValidateEmptyResults( boolean validateEmptyResults ) { this.validateEmptyResults = validateEmptyResults; } public DataSetHandle getDatasetHandle( ) { return datasetHandle; } public void setDatasetHandle( DataSetHandle datasetHandle ) { if ( datasetHandle != null ) { this.datasetHandle = datasetHandle; this.dataSetName = datasetHandle.getQualifiedName( ); } } }
import org.json.simple.JSONArray; import org.json.simple.JSONObject; import spark.Request; import spark.Response; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.logging.FileHandler; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import static spark.Spark.*; public class SparkServer { private static final Logger logger = Logger.getLogger(SparkServer.class.getName()); static boolean BANKMODE = true; static Transaction transaction = null; static int i = 1; static int j = 1; static Map<Integer, Account> accountMap; static Bank bank; public static void main(String[] args) { Runtime.getRuntime().addShutdownHook(new ShutdownThread()); bank = new Bank().withBankName("OpenBank"); logger.info("Bank: " + bank.toString()); apiLogSetup(); accountMapSetup();
package org.epics.pvmanager.graphene; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.epics.graphene.*; import org.epics.pvmanager.QueueCollector; import org.epics.pvmanager.ReadFunction; import org.epics.util.array.ArrayDouble; import org.epics.vtype.VImage; import org.epics.vtype.VNumber; import org.epics.vtype.VNumberArray; import org.epics.vtype.VTable; import org.epics.vtype.VType; import org.epics.vtype.ValueUtil; /** * * @author carcassi */ class IntensityGraph2DFunction implements ReadFunction<Graph2DResult> { private ReadFunction<VNumberArray> arrayData; private IntensityGraph2DRenderer renderer = new IntensityGraph2DRenderer(300, 200); private Graph2DResult previousImage; private final QueueCollector<IntensityGraph2DRendererUpdate> rendererUpdateQueue = new QueueCollector<>(100); public IntensityGraph2DFunction(ReadFunction<?> arrayData) { this.arrayData = new CheckedReadFunction<VNumberArray>(arrayData, "Data", VNumberArray.class); } public QueueCollector<IntensityGraph2DRendererUpdate> getUpdateQueue() { return rendererUpdateQueue; } @Override public Graph2DResult readValue() { VNumberArray data = arrayData.readValue(); // Data must be available if (data == null) { return null; } // TODO: check array is one dimensional Cell2DDataset dataset = null; if (data.getSizes().size() == 1) { dataset = Cell2DDatasets.datasetFrom(data.getData(), data.getDimensionDisplay().get(0).getCellBoundaries(), new ArrayDouble(0, 1)); } else if (data.getSizes().size() == 2) { dataset = Cell2DDatasets.datasetFrom(data.getData(), data.getDimensionDisplay().get(1).getCellBoundaries(), data.getDimensionDisplay().get(0).getCellBoundaries()); } else { throw new IllegalArgumentException("Array is 3D or more"); } // Process all renderer updates for (IntensityGraph2DRendererUpdate rendererUpdate : getUpdateQueue().readValue()) { renderer.update(rendererUpdate); } // If no size is set, don't calculate anything if (renderer.getImageHeight() == 0 && renderer.getImageWidth() == 0) return null; BufferedImage image = new BufferedImage(renderer.getImageWidth(), renderer.getImageHeight(), BufferedImage.TYPE_3BYTE_BGR); GraphBuffer buffer = new GraphBuffer(image); renderer.draw(buffer, dataset); return new Graph2DResult(null, ValueUtil.toVImage(image), new GraphDataRange(renderer.getXPlotRange(), dataset.getXRange(), renderer.getXAggregatedRange()), new GraphDataRange(renderer.getYPlotRange(), dataset.getStatistics(), renderer.getYAggregatedRange()), -1); } }
package org.kuali.coeus.s2sgen.impl.generate.support; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.*; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.DegreeTypeDataType; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.FieldOfTrainingDataType; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.InstitutionalEnvironment.InstitutionalEnvironmentCommitmenttoTraining; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.Sponsors; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.OtherResearchTrainingPlan; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.OtherResearchTrainingPlan.*; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.OtherResearchTrainingPlan.InclusionOfChildren; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.OtherResearchTrainingPlan.InclusionOfWomenAndMinorities; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.Budget; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.Budget.FederalStipendRequested; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.Budget.InstitutionalBaseSalary; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.Budget.SupplementationFromOtherSources; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.ResearchTrainingPlan; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.FellowshipApplicant.BackgroundandGoals; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.ResearchTrainingPlan.ProgressReportPublicationList; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.Introduction.IntroductionToApplication; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.OtherResearchTrainingPlan.ProtectionOfHumanSubjects; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.AdditionalInformation; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.AdditionalInformation.ConcurrentSupportDescription; import gov.grants.apply.forms.phsFellowshipSupplemental31V31.PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.AdditionalInformation.CurrentPriorNRSASupport; import gov.grants.apply.forms.phsFellowshipSupplementalV10.CitizenshipDataType; import gov.grants.apply.system.attachmentsV10.AttachedFileDataType; import gov.grants.apply.system.attachmentsV10.AttachmentGroupMin0Max100DataType; import gov.grants.apply.system.globalLibraryV20.YesNoDataType; import gov.grants.apply.system.globalLibraryV20.YesNoDataType.Enum; import org.apache.commons.lang3.StringUtils; import org.apache.xmlbeans.XmlObject; import org.kuali.coeus.common.api.person.attr.CitizenshipType; import org.kuali.coeus.common.api.ynq.YnqConstant; import org.kuali.coeus.common.budget.api.nonpersonnel.BudgetLineItemContract; import org.kuali.coeus.common.budget.api.period.BudgetPeriodContract; import org.kuali.coeus.common.questionnaire.api.answer.AnswerContract; import org.kuali.coeus.common.questionnaire.api.answer.AnswerHeaderContract; import org.kuali.coeus.common.questionnaire.api.core.QuestionnaireContract; import org.kuali.coeus.common.questionnaire.api.core.QuestionnaireQuestionContract; import org.kuali.coeus.common.questionnaire.api.question.QuestionContract; import org.kuali.coeus.propdev.api.attachment.NarrativeContract; import org.kuali.coeus.propdev.api.budget.ProposalDevelopmentBudgetExtContract; import org.kuali.coeus.propdev.api.core.DevelopmentProposalContract; import org.kuali.coeus.propdev.api.core.ProposalDevelopmentDocumentContract; import org.kuali.coeus.propdev.api.person.ProposalPersonContract; import org.kuali.coeus.propdev.api.specialreview.ProposalSpecialReviewContract; import org.kuali.coeus.s2sgen.api.core.ConfigurationConstants; import org.kuali.coeus.s2sgen.impl.generate.FormGenerator; import org.kuali.coeus.s2sgen.impl.generate.FormVersion; import org.kuali.coeus.s2sgen.impl.util.FieldValueConstants; import org.kuali.coeus.sys.api.model.ScaleTwoDecimal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; @FormGenerator("PHS398FellowshipSupplementalV3_1Generator") public class PHS398FellowshipSupplementalV3_1Generator extends PHS398FellowshipSupplementalBaseGenerator { private static final Logger LOG = LoggerFactory.getLogger(PHS398FellowshipSupplementalV3_1Generator.class); private static final int HUMAN = 1; private static final int VERT = 4; private static final int CLINICAL = 2; private static final int PHASE3CLINICAL = 3; private static final int STEMCELLS = 5; private static final int KIRST_START_KNOWN = 43; private static final int KIRST_END_KNOWN = 49; private static final int KIRST_START_DT = 44; private static final int KIRST_END_DT = 45; private static final int KIRST_GRANT_KNOWN = 46; private static final int KIRST_GRANT_NUM = 27; private static final int PRE_OR_POST = 32; private static final int IND_OR_INST = 33; private static final int STEMCELLLINES = 7; private static final int CELLLINEIND = 6; private static final int DEGREE_TYPE_SOUGHT = 99; private static final int DEG_EXP_COMP_DATE = 35; private static final int NRSA_SUPPORT = 24; private static final int BROAD_TRAINING = 23; private static final int OTHER_MASTERS = 16; private static final int OTHER_DOCT = 17; private static final int OTHER_DDOT = 18; private static final int OTHER_VDOT = 19; private static final int OTHER_DBOTH = 100; private static final int OTHER_MDOT = 21; private static final int SUBMITTED_DIFF_INST = 28; private static final int SENIOR_FELL = 36; private static final int OTHER_SUPP_SOURCE = 37; private static final int SUPP_FUNDING_AMT = 38; private static final int SUPP_MONTHS = 51; private static final int SUPP_SOURCE = 41; private static final int SUPP_TYPE = 40; private static final int BASE_SALARY = 47; private static final int ACAD_PERIOD = 48; private static final int SALARY_MONTHS = 50; private static final String APPENDIX = "96"; private static final String SPONSOR_COSPONSOR = "134"; protected static final String LETTER_COLLAB_CONTRIB_CONSULT = "157"; protected static final String PHS_FELLOW_INSTITUTION_ENVIRON_COMMITMENT = "158"; protected static final String DATA_SAFETY_MONITORING_PLAN = "159"; protected static final String PHS_FELLOW_AUTH_KEY_BIO_CHEM_RESOURCES = "160"; protected static final int WILL_VERTEBRATE_ANIMALS_BE_USED = 145; protected static final int ARE_VERTEBRATE_ANIMALS_EUTHANISED = 146; protected static final String INCLUSION_OF_CHILDREN = "107"; protected static final String INTRODUCTION_TO_APPLICATION = "97"; protected static final String SPECIFIC_AIMS = "98"; protected static final String RESEARCH_STRATEGY = "127"; protected static final String RESPECTIVE_CONTRIBUTIONS = "88"; protected static final String SELECTION_OF_SPONSOR_AND_INSTITUTION = "89"; protected static final String PROGRESS_REPORT_PUBLICATION_LIST = "103"; protected static final String RESPONSIBLE_CONDUCT_OF_RESEARCH = "90"; protected static final String PROTECTION_OF_HUMAN_SUBJECTS = "104"; protected static final String INCLUSION_OF_WOMEN_AND_MINORITIES = "105"; protected static final String CONCURRENT_SUPPORT = "91"; protected static final String VERTEBRATE_ANIMALS = "108"; protected static final String SELECT_AGENT_RESEARCH = "109"; protected static final String RESOURCE_SHARING_PLANS = "110"; // Is method consistent with American Veterinary Medical Association (AVMA) guidelines? protected static final int CONSISTENT_AVMA_GUIDELINES = 147; // If NO to AVMA Guidelines, describe method and provide scientific justification in 1000 characters or less protected static final int NO_AVMA_METHOD_SCIENTIFIC_JUSTIFICATION = 148; protected static final int FIELD_OF_TRAINING = 200; protected static final String FELLOWSHIP_BACKGROUND_AND_GOALS = "156"; private static final String ANSWER_YES = "Yes"; private static final String ANSWER_NO = "No"; public static final String TEMPORARY_VISA_ALSO_APPLIED_FOR_PERMANENT_RESIDENT_STATUS = "Temporary Visa also applied for permanent resident status"; @Value("http://apply.grants.gov/forms/PHS_Fellowship_Supplemental_3_1-V3.1") private String namespace; @Value("PHS_Fellowship_Supplemental_3_1") private String formName; @Value("classpath:org/kuali/coeus/s2sgen/impl/generate/support/stylesheet/PHS_FellowshipSupplemental-V3.1.xsl") private Resource stylesheet; @Value("gov.grants.apply.forms.phsFellowshipSupplemental31V31") private String packageName; @Value("211") private int sortIndex; protected PHSFellowshipSupplemental31Document getPHSFellowshipSupplemental31() { PHSFellowshipSupplemental31Document phsFellowshipSupplementalDocument = PHSFellowshipSupplemental31Document.Factory .newInstance(); PHSFellowshipSupplemental31 phsFellowshipSupplemental = phsFellowshipSupplementalDocument .addNewPHSFellowshipSupplemental31(); ResearchTrainingPlan researchTrainingPlan = phsFellowshipSupplemental.addNewResearchTrainingPlan(); setNarrativeDataForResearchTrainingPlan(phsFellowshipSupplemental, researchTrainingPlan); setOtherResearchTrainingPlanVertebrate(phsFellowshipSupplemental); phsFellowshipSupplemental.setFormVersion(FormVersion.v3_1.getVersion()); final AttachmentGroupMin0Max100DataType appendix = getAppendix(); if(appendix != null) { phsFellowshipSupplemental.setAppendix(appendix); } setQuestionnaireData(phsFellowshipSupplemental); return phsFellowshipSupplementalDocument; } private void setOtherResearchTrainingPlanVertebrate(PHSFellowshipSupplemental31 phsFellowshipSupplemental) { OtherResearchTrainingPlan otherResearchTrainingPlan = phsFellowshipSupplemental.getOtherResearchTrainingPlan(); if(otherResearchTrainingPlan == null) { otherResearchTrainingPlan = phsFellowshipSupplemental.addNewOtherResearchTrainingPlan(); } List<? extends AnswerHeaderContract> answers = findQuestionnaireWithAnswers(pdDoc.getDevelopmentProposal()); for (AnswerHeaderContract answerHeader : answers) { QuestionnaireContract questionnaire = questionAnswerService.findQuestionnaireById(answerHeader.getQuestionnaireId()); List<? extends QuestionnaireQuestionContract> questionnaireQuestions = questionnaire.getQuestionnaireQuestions(); for (QuestionnaireQuestionContract questionnaireQuestion : questionnaireQuestions) { AnswerContract answerBO = getAnswer(questionnaireQuestion, answerHeader); String answer = answerBO != null ? answerBO.getAnswer() : null; QuestionContract question = questionnaireQuestion.getQuestion(); Integer questionId = question.getQuestionSeqId(); if (answer != null) { switch (questionId) { case VERT: // will the inclusion of vertebrate animals use be indefinite otherResearchTrainingPlan.setVertebrateAnimalsIndefinite(getYesNoEnum(answer)); break; case ARE_VERTEBRATE_ANIMALS_EUTHANISED: // Are vertebrate animals euthanized otherResearchTrainingPlan.setAreAnimalsEuthanized(getYesNoEnum(answer)); break; case CONSISTENT_AVMA_GUIDELINES: otherResearchTrainingPlan.setAVMAConsistentIndicator(getYesNoEnum(answer)); break; case NO_AVMA_METHOD_SCIENTIFIC_JUSTIFICATION: otherResearchTrainingPlan.setEuthanasiaMethodDescription(answer); break; } } } } AttachedFileDataType attachedFileDataType; for (NarrativeContract narrative : pdDoc.getDevelopmentProposal().getNarratives()) { final String code = narrative.getNarrativeType().getCode(); if (code != null) { if(code.equalsIgnoreCase(VERTEBRATE_ANIMALS)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { VertebrateAnimals vertebrateAnimals = VertebrateAnimals.Factory.newInstance(); vertebrateAnimals.setAttFile(attachedFileDataType); if (otherResearchTrainingPlan == null) { otherResearchTrainingPlan = phsFellowshipSupplemental.addNewOtherResearchTrainingPlan(); } otherResearchTrainingPlan.setVertebrateAnimals(vertebrateAnimals); } } else if(code.equalsIgnoreCase(SELECT_AGENT_RESEARCH)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { SelectAgentResearch selectAgentResearch = SelectAgentResearch.Factory.newInstance(); selectAgentResearch.setAttFile(attachedFileDataType); if (otherResearchTrainingPlan == null) { otherResearchTrainingPlan = phsFellowshipSupplemental.addNewOtherResearchTrainingPlan(); } otherResearchTrainingPlan.setSelectAgentResearch(selectAgentResearch); } } else if(code.equalsIgnoreCase(RESOURCE_SHARING_PLANS)) { ResourceSharingPlan resourceSharingPlan = ResourceSharingPlan.Factory.newInstance(); attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { resourceSharingPlan.setAttFile(attachedFileDataType); if (otherResearchTrainingPlan == null) { otherResearchTrainingPlan = phsFellowshipSupplemental.addNewOtherResearchTrainingPlan(); } otherResearchTrainingPlan.setResourceSharingPlan(resourceSharingPlan); } } else if(code.equalsIgnoreCase(PHS_FELLOW_AUTH_KEY_BIO_CHEM_RESOURCES)) { KeyBiologicalAndOrChemicalResources keyBiologicalAndOrChemicalResources = KeyBiologicalAndOrChemicalResources.Factory.newInstance(); attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { keyBiologicalAndOrChemicalResources.setAttFile(attachedFileDataType); if (otherResearchTrainingPlan == null) { otherResearchTrainingPlan = phsFellowshipSupplemental.addNewOtherResearchTrainingPlan(); } otherResearchTrainingPlan.setKeyBiologicalAndOrChemicalResources(keyBiologicalAndOrChemicalResources); } } } } } private void setQuestionnaireData(PHSFellowshipSupplemental31 phsFellowshipSupplemental) { Map<Integer, String> hmBudgetQuestions = new HashMap<>(); List<? extends AnswerHeaderContract> answers = findQuestionnaireWithAnswers(pdDoc.getDevelopmentProposal()); OtherResearchTrainingPlan otherResearchTrainingPlan = phsFellowshipSupplemental.getOtherResearchTrainingPlan(); if(otherResearchTrainingPlan == null) { otherResearchTrainingPlan = phsFellowshipSupplemental.addNewOtherResearchTrainingPlan(); } setHumanSubjectInvolvedAndVertebrateAnimalUsed(otherResearchTrainingPlan); AdditionalInformation additionalInfoType = phsFellowshipSupplemental.addNewAdditionalInformation(); AdditionalInformation.GraduateDegreeSought graduateDegreeSought = AdditionalInformation.GraduateDegreeSought.Factory.newInstance(); AdditionalInformation.StemCells stemCellstype = AdditionalInformation.StemCells.Factory.newInstance(); List<KirschsteinBean> cvKirsch = new ArrayList<>(); for (AnswerHeaderContract answerHeader : answers) { QuestionnaireContract questionnaire = questionAnswerService.findQuestionnaireById(answerHeader.getQuestionnaireId()); List<? extends QuestionnaireQuestionContract> questionnaireQuestions = questionnaire.getQuestionnaireQuestions(); for (QuestionnaireQuestionContract questionnaireQuestion : questionnaireQuestions) { AnswerContract answerBO = getAnswer(questionnaireQuestion, answerHeader); String answer = answerBO != null ? answerBO.getAnswer() : null; QuestionContract question = questionnaireQuestion.getQuestion(); Integer questionNumber = questionnaireQuestion.getQuestionNumber(); Integer parentQuestionNumber = questionnaireQuestion.getParentQuestionNumber(); Integer questionId = question.getQuestionSeqId(); if (answer != null) { switch (questionId) { case HUMAN: otherResearchTrainingPlan.setHumanSubjectsIndefinite(getYesNoEnum(answer)); break; case CLINICAL: // clinical trial otherResearchTrainingPlan.setClinicalTrial(getYesNoEnum(answer)); break; case PHASE3CLINICAL: // phase 3 clinical trial otherResearchTrainingPlan.setPhase3ClinicalTrial(getYesNoEnum(answer)); break; case STEMCELLS: // stem cells used stemCellstype.setIsHumanStemCellsInvolved(getYesNoEnum(answer)); break; case CELLLINEIND: // stem cell line indicator stemCellstype.setStemCellsIndicator(answer .equals(YnqConstant.NO.code()) ? YesNoDataType.Y_YES : YesNoDataType.N_NO); break; case STEMCELLLINES: List<? extends AnswerContract> answerList = getAnswers(questionnaireQuestion,answerHeader); for (AnswerContract questionnaireAnswerBO: answerList) { String questionnaireSubAnswer = questionnaireAnswerBO.getAnswer(); if(questionnaireSubAnswer!=null){ stemCellstype.addCellLines(questionnaireAnswerBO.getAnswer()); } } break; case DEGREE_TYPE_SOUGHT: graduateDegreeSought.setDegreeType(DegreeTypeDataType.Enum.forString(answer)); break; case DEG_EXP_COMP_DATE: graduateDegreeSought.setDegreeDate(answer.substring(6, 10) + STRING_SEPRATOR + answer.substring(0, 2)); break; case OTHER_MASTERS: graduateDegreeSought.setOtherDegreeTypeText(answer); break; case OTHER_DDOT: graduateDegreeSought.setDegreeType(DegreeTypeDataType.DDOT_OTHER_DOCTOR_OF_MEDICAL_DENTISTRY); graduateDegreeSought.setOtherDegreeTypeText(answer); break; case OTHER_VDOT: graduateDegreeSought.setDegreeType(DegreeTypeDataType.VDOT_OTHER_DOCTOR_OF_VETERINARY_MEDICINE); graduateDegreeSought.setOtherDegreeTypeText(answer); break; case OTHER_MDOT: graduateDegreeSought.setDegreeType(DegreeTypeDataType.MDOT_OTHER_DOCTOR_OF_MEDICINE); graduateDegreeSought.setOtherDegreeTypeText(answer); break; case OTHER_DBOTH: if (graduateDegreeSought.getDegreeType().equals(DegreeTypeDataType.OTH_OTHER)) { graduateDegreeSought.setOtherDegreeTypeText(answer); } break; case OTHER_DOCT: graduateDegreeSought.setDegreeType(DegreeTypeDataType.DOTH_OTHER_DOCTORATE); graduateDegreeSought.setOtherDegreeTypeText(answer); break; case BROAD_TRAINING: case FIELD_OF_TRAINING: if (!answer.toUpperCase().equals("SUB CATEGORY NOT FOUND")) { final FieldOfTrainingDataType.Enum fieldOfTraining = FieldOfTrainingDataType.Enum.forString(answer); additionalInfoType.setFieldOfTraining(fieldOfTraining); } break; case NRSA_SUPPORT: additionalInfoType.setCurrentPriorNRSASupportIndicator(getYesNoEnum(answer)); break; case KIRST_START_KNOWN: case KIRST_END_KNOWN: case KIRST_START_DT: case KIRST_END_DT: case KIRST_GRANT_KNOWN: case KIRST_GRANT_NUM: case PRE_OR_POST: case IND_OR_INST: if (questionId == KIRST_START_KNOWN) { if (answer.equals("N")) { answer = FieldValueConstants.VALUE_UNKNOWN; questionId = KIRST_START_DT; } else break; } if (questionId == KIRST_END_KNOWN) { if (answer.equals("N")) { answer = FieldValueConstants.VALUE_UNKNOWN; questionId = KIRST_END_DT; } else break; } if (questionId == KIRST_GRANT_KNOWN) { if (answer.equals("N")) { answer = FieldValueConstants.VALUE_UNKNOWN; questionId = KIRST_GRANT_NUM; } else break; } KirschsteinBean cbKirschstein = new KirschsteinBean(); cbKirschstein.setAnswer(answer); cbKirschstein.setQuestionId(questionId); cbKirschstein.setQuestionNumber(questionNumber); cbKirschstein.setParentQuestionNumber(parentQuestionNumber); cvKirsch.add(cbKirschstein); break; case SUBMITTED_DIFF_INST: additionalInfoType.setChangeOfInstitution(getYesNoEnum(answer)); break; case 29: additionalInfoType.setFormerInstitution(answer); break; case SENIOR_FELL: hmBudgetQuestions.put(SENIOR_FELL, answer); break; case OTHER_SUPP_SOURCE: hmBudgetQuestions.put(OTHER_SUPP_SOURCE, answer); break; case SUPP_SOURCE: hmBudgetQuestions.put(SUPP_SOURCE, answer); break; case SUPP_FUNDING_AMT: hmBudgetQuestions.put(SUPP_FUNDING_AMT, answer); break; case SUPP_MONTHS: hmBudgetQuestions.put(SUPP_MONTHS, answer); break; case SUPP_TYPE: hmBudgetQuestions.put(SUPP_TYPE, answer); break; case SALARY_MONTHS: hmBudgetQuestions.put(SALARY_MONTHS, answer); break; case ACAD_PERIOD: hmBudgetQuestions.put(ACAD_PERIOD, answer); break; case BASE_SALARY: hmBudgetQuestions.put(BASE_SALARY, answer); break; default: break; } } else if (answer == null ) { switch (questionId) { case HUMAN: otherResearchTrainingPlan.setHumanSubjectsIndefinite(null); otherResearchTrainingPlan.setHumanSubjectsInvolved(null); break; case VERT: otherResearchTrainingPlan.setVertebrateAnimalsIndefinite(null); otherResearchTrainingPlan.setVertebrateAnimalsUsed(null); break; case CLINICAL: otherResearchTrainingPlan.setClinicalTrial(null); break; case PHASE3CLINICAL: if(otherResearchTrainingPlan.getClinicalTrial() == (YesNoDataType.Y_YES)) { otherResearchTrainingPlan.setPhase3ClinicalTrial(null); } break; case FIELD_OF_TRAINING: additionalInfoType.setFieldOfTraining(null); break; case STEMCELLS: stemCellstype.setIsHumanStemCellsInvolved(null); break; case NRSA_SUPPORT: additionalInfoType.setCurrentPriorNRSASupportIndicator(null); break; default: break; } } } } if (stemCellstype != null) additionalInfoType.setStemCells(stemCellstype); if (graduateDegreeSought.getDegreeType() != null) additionalInfoType.setGraduateDegreeSought(graduateDegreeSought); List<KirschsteinBean> cvType = new ArrayList<>(); List<KirschsteinBean> cvStart = new ArrayList<>(); List<KirschsteinBean> cvEnd = new ArrayList<>(); List<KirschsteinBean> cvLevel = new ArrayList<>(); List<KirschsteinBean> cvGrant = new ArrayList<>(); KirschsteinBean kbBean1 = null; KirschsteinBean kbBean2 = null; KirschsteinBean kbBean3 = null; KirschsteinBean kbBean4 = null; KirschsteinBean kbBean5 = null; if (additionalInfoType.getCurrentPriorNRSASupportIndicator() != null) { if (additionalInfoType.getCurrentPriorNRSASupportIndicator().equals(YesNoDataType.Y_YES)) { KirschsteinBean kbBean; Collections.sort(cvKirsch, BY_QUESTION_NUMBER); for (KirschsteinBean aCvKirsch : cvKirsch) { kbBean = aCvKirsch; switch (kbBean.getQuestionId()) { case PRE_OR_POST: cvLevel.add(kbBean); break; case IND_OR_INST: cvType.add(kbBean); break; case KIRST_START_DT: cvStart.add(kbBean); break; case KIRST_END_DT: cvEnd.add(kbBean); break; case KIRST_GRANT_NUM: cvGrant.add(kbBean); break; } } } List<CurrentPriorNRSASupport> currentPriorNRSASupportList = new ArrayList<>(); int numberRepeats = cvLevel.size(); if (numberRepeats > 0) { for (int j = 0; j < numberRepeats; j++) { kbBean1 = cvLevel.get(j); if(cvType.size() - 1 >= j) { kbBean2 = cvType.get(j); } if(cvStart.size() - 1 >= j) { kbBean3 = cvStart.get(j); } if(cvEnd.size() - 1 >= j) { kbBean4 = cvEnd.get(j); } if(cvGrant.size() - 1 >= j) { kbBean5 = cvGrant.get(j); } CurrentPriorNRSASupport nrsaSupportType = CurrentPriorNRSASupport.Factory.newInstance(); if (kbBean1 != null) { nrsaSupportType.setLevel(CurrentPriorNRSASupport.Level.Enum.forString(kbBean1.getAnswer())); } if(kbBean2 != null) { nrsaSupportType.setType(CurrentPriorNRSASupport.Type.Enum.forString(kbBean2.getAnswer())); } if (kbBean3 != null && !kbBean3.getAnswer().equals(FieldValueConstants.VALUE_UNKNOWN)) { nrsaSupportType.setStartDate(s2SDateTimeService.convertDateStringToCalendar(kbBean3.getAnswer())); } if (kbBean4 != null && !kbBean4.getAnswer().equals(FieldValueConstants.VALUE_UNKNOWN)) { nrsaSupportType.setEndDate(s2SDateTimeService.convertDateStringToCalendar(kbBean4.getAnswer())); } if (kbBean5 != null) { nrsaSupportType.setGrantNumber(kbBean5.getAnswer()); } currentPriorNRSASupportList.add(nrsaSupportType); } } additionalInfoType.setCurrentPriorNRSASupportArray(currentPriorNRSASupportList.toArray(new CurrentPriorNRSASupport[0])); } phsFellowshipSupplemental.setBudget(createBudgetElements(hmBudgetQuestions)); setAdditionalInformation(additionalInfoType); } protected Budget createBudgetElements(Map<Integer, String> budgetMap) { Budget budget = Budget.Factory.newInstance(); budget.setTuitionAndFeesRequested(YesNoDataType.N_NO); getInstitutionalBaseSalary(budget, budgetMap); getFederalStipendRequested(budget); getSupplementationFromOtherSources(budget, budgetMap); setTuitionRequestedYears(budget); return budget; } protected List<AnswerContract> getAnswers(QuestionnaireQuestionContract questionnaireQuestion, AnswerHeaderContract answerHeader) { List<AnswerContract> returnAnswers = new ArrayList<>(); if (answerHeader != null) { List<? extends AnswerContract> answers = answerHeader.getAnswers(); for (AnswerContract answer : answers) { if (answer.getQuestionnaireQuestionsId().equals(questionnaireQuestion.getId())) { returnAnswers.add(answer); } } } return returnAnswers; } /** * This method is to return YesNoDataType enum */ protected Enum getYesNoEnum(String answer) { return answer.equals("Y") ? YesNoDataType.Y_YES : YesNoDataType.N_NO; } /* * This method is used to get TuitionRequestedYears data to Budget XMLObject from List of BudgetLineItem based on CostElement * value of TUITION_COST_ELEMENTS */ protected void setTuitionRequestedYears(Budget budget) { ProposalDevelopmentBudgetExtContract pBudget = s2SCommonBudgetService.getBudget(pdDoc.getDevelopmentProposal()); if (pBudget == null) { return; } ScaleTwoDecimal tuitionTotal = ScaleTwoDecimal.ZERO; for (BudgetPeriodContract budgetPeriod : pBudget.getBudgetPeriods()) { ScaleTwoDecimal tuition = ScaleTwoDecimal.ZERO; for (BudgetLineItemContract budgetLineItem : budgetPeriod.getBudgetLineItems()) { if (getCostElementsByParam(ConfigurationConstants.TUITION_COST_ELEMENTS).contains(budgetLineItem.getCostElementBO().getCostElement())) { tuition = tuition.add(budgetLineItem.getLineItemCost()); } } tuitionTotal = tuitionTotal.add(tuition); switch (budgetPeriod.getBudgetPeriod()) { case 1: budget.setTuitionRequestedYear1(tuition.bigDecimalValue()); break; case 2: budget.setTuitionRequestedYear2(tuition.bigDecimalValue()); break; case 3: budget.setTuitionRequestedYear3(tuition.bigDecimalValue()); break; case 4: budget.setTuitionRequestedYear4(tuition.bigDecimalValue()); break; case 5: budget.setTuitionRequestedYear5(tuition.bigDecimalValue()); break; case 6: budget.setTuitionRequestedYear6(tuition.bigDecimalValue()); break; default: break; } } budget.setTuitionRequestedTotal(tuitionTotal.bigDecimalValue()); if (!tuitionTotal.equals(ScaleTwoDecimal.ZERO)) { budget.setTuitionAndFeesRequested(YesNoDataType.Y_YES); } } /* * This method is used to set data to SupplementationFromOtherSources XMLObject from budgetMap data for Budget */ protected void getSupplementationFromOtherSources(Budget budget, Map<Integer, String> hmBudgetQuestions) { if (!hmBudgetQuestions.isEmpty()) { if (hmBudgetQuestions.get(OTHER_SUPP_SOURCE) != null) { if (hmBudgetQuestions.get(OTHER_SUPP_SOURCE).toString().toUpperCase().equals("Y")) { SupplementationFromOtherSources supplementationFromOtherSources = budget .addNewSupplementationFromOtherSources(); if (hmBudgetQuestions.get(SUPP_SOURCE) != null) { supplementationFromOtherSources.setSource(hmBudgetQuestions.get(SUPP_SOURCE).toString()); supplementationFromOtherSources.setAmount(new BigDecimal(hmBudgetQuestions.get(SUPP_FUNDING_AMT).toString())); try { supplementationFromOtherSources.setNumberOfMonths(new BigDecimal(hmBudgetQuestions.get(SUPP_MONTHS).toString())); }catch (Exception ex) {} supplementationFromOtherSources.setType(hmBudgetQuestions.get(SUPP_TYPE).toString()); } } } } } /* * This method is used to get FederalStipendRequested XMLObject and set additional information data to it. */ protected void getFederalStipendRequested(Budget budget) { FederalStipendRequested federalStipendRequested = FederalStipendRequested.Factory.newInstance(); ProposalDevelopmentBudgetExtContract pBudget = s2SCommonBudgetService.getBudget(pdDoc.getDevelopmentProposal()); if (pBudget != null) { ScaleTwoDecimal sumOfLineItemCost = ScaleTwoDecimal.ZERO; ScaleTwoDecimal numberOfMonths = ScaleTwoDecimal.ZERO; for (BudgetPeriodContract budgetPeriod : pBudget.getBudgetPeriods()) { if (budgetPeriod.getBudgetPeriod() == 1) { for (BudgetLineItemContract budgetLineItem : budgetPeriod.getBudgetLineItems()) { if (getCostElementsByParam(ConfigurationConstants.STIPEND_COST_ELEMENTS).contains( budgetLineItem.getCostElementBO().getCostElement())) { sumOfLineItemCost = sumOfLineItemCost.add(budgetLineItem.getLineItemCost()); numberOfMonths = numberOfMonths.add(getNumberOfMonths(budgetLineItem.getStartDate(), budgetLineItem .getEndDate())); } } } } federalStipendRequested.setAmount(sumOfLineItemCost.bigDecimalValue()); federalStipendRequested.setNumberOfMonths(numberOfMonths.bigDecimalValue()); budget.setFederalStipendRequested(federalStipendRequested); } } /* * This method is used to set data to InstitutionalBaseSalary XMLObject from budgetMap data for Budget */ protected void getInstitutionalBaseSalary(Budget budget, Map<Integer, String> budgetMap) { InstitutionalBaseSalary institutionalBaseSalary = InstitutionalBaseSalary.Factory.newInstance(); if (budgetMap.get(SENIOR_FELL) != null && budgetMap.get(SENIOR_FELL).toString().equals(YnqConstant.YES.code())) { if (budgetMap.get(BASE_SALARY) != null) { institutionalBaseSalary.setAmount(new BigDecimal(budgetMap.get(BASE_SALARY).toString())); } if (budgetMap.get(ACAD_PERIOD) != null) { institutionalBaseSalary.setAcademicPeriod(PHSFellowshipSupplemental31Document.PHSFellowshipSupplemental31.Budget.InstitutionalBaseSalary.AcademicPeriod.Enum.forString(budgetMap.get(ACAD_PERIOD).toString())); } if (budgetMap.get(SALARY_MONTHS) != null) { institutionalBaseSalary.setNumberOfMonths(new BigDecimal(budgetMap.get(SALARY_MONTHS).toString())); } budget.setInstitutionalBaseSalary(institutionalBaseSalary); } } /** * This method is used to set Narrative Data to ResearchTrainingPlan XMLObject based on NarrativeTypeCode. * * @param researchTrainingPlan */ protected void setNarrativeDataForResearchTrainingPlan(PHSFellowshipSupplemental31 phsFellowshipSupplemental, ResearchTrainingPlan researchTrainingPlan) { AttachedFileDataType attachedFileDataType; Sponsors sponsors = phsFellowshipSupplemental.addNewSponsors(); OtherResearchTrainingPlan otherResearchTrainingPlan = null; PHSFellowshipSupplemental31.InstitutionalEnvironment institutionalEnvironment = phsFellowshipSupplemental.addNewInstitutionalEnvironment(); PHSFellowshipSupplemental31.FellowshipApplicant fellowshipApplicant = phsFellowshipSupplemental.addNewFellowshipApplicant(); PHSFellowshipSupplemental31.Introduction introduction = phsFellowshipSupplemental.addNewIntroduction(); for (NarrativeContract narrative : pdDoc.getDevelopmentProposal().getNarratives()) { final String code = narrative.getNarrativeType().getCode(); if (code != null ) { if (code.equalsIgnoreCase(INTRODUCTION_TO_APPLICATION)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { IntroductionToApplication introductionToApplication = IntroductionToApplication.Factory.newInstance(); introductionToApplication.setAttFile(attachedFileDataType); introduction.setIntroductionToApplication(introductionToApplication); } } else if (code.equalsIgnoreCase(FELLOWSHIP_BACKGROUND_AND_GOALS)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { BackgroundandGoals backgroundandGoals = BackgroundandGoals.Factory.newInstance(); backgroundandGoals.setAttFile(attachedFileDataType); fellowshipApplicant.setBackgroundandGoals(backgroundandGoals); } } else if (code.equalsIgnoreCase(SPECIFIC_AIMS)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { ResearchTrainingPlan.SpecificAims specificAims = ResearchTrainingPlan.SpecificAims.Factory.newInstance(); specificAims.setAttFile(attachedFileDataType); researchTrainingPlan.setSpecificAims(specificAims); } } else if (code.equalsIgnoreCase(RESEARCH_STRATEGY)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { ResearchTrainingPlan.ResearchStrategy researchStrategy = ResearchTrainingPlan.ResearchStrategy.Factory.newInstance(); researchStrategy.setAttFile(attachedFileDataType); researchTrainingPlan.setResearchStrategy(researchStrategy); } } else if (code.equalsIgnoreCase(RESPECTIVE_CONTRIBUTIONS)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { ResearchTrainingPlan.RespectiveContribution respectiveContribution = ResearchTrainingPlan.RespectiveContribution.Factory.newInstance(); respectiveContribution.setAttFile(attachedFileDataType); researchTrainingPlan.setRespectiveContribution(respectiveContribution); } } else if (code.equalsIgnoreCase(SELECTION_OF_SPONSOR_AND_INSTITUTION)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { ResearchTrainingPlan.SponsorandInstitution sponsorAndInstitution = ResearchTrainingPlan.SponsorandInstitution.Factory .newInstance(); sponsorAndInstitution.setAttFile(attachedFileDataType); researchTrainingPlan.setSponsorandInstitution(sponsorAndInstitution); } } else if (code.equalsIgnoreCase(PROGRESS_REPORT_PUBLICATION_LIST)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { ResearchTrainingPlan.ProgressReportPublicationList progressReportPublicationList = ProgressReportPublicationList.Factory .newInstance(); progressReportPublicationList.setAttFile(attachedFileDataType); researchTrainingPlan.setProgressReportPublicationList(progressReportPublicationList); } } else if (code.equalsIgnoreCase(RESPONSIBLE_CONDUCT_OF_RESEARCH)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { ResearchTrainingPlan.TrainingInResponsibleConductOfResearch responsibleConductOfResearch = ResearchTrainingPlan.TrainingInResponsibleConductOfResearch.Factory .newInstance(); responsibleConductOfResearch.setAttFile(attachedFileDataType); researchTrainingPlan.setTrainingInResponsibleConductOfResearch(responsibleConductOfResearch); } } // -- Sponsor(s), Collaborator(s), and Consultant(s) Section else if (code.equalsIgnoreCase(SPONSOR_COSPONSOR)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { Sponsors.SponsorAndCoSponsorStatements sponsorCosponsorInfo = sponsors.addNewSponsorAndCoSponsorStatements(); sponsorCosponsorInfo.setAttFile(attachedFileDataType); } } else if (code.equalsIgnoreCase(LETTER_COLLAB_CONTRIB_CONSULT)){ attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { Sponsors.LettersOfSupport lettersOfSupport = Sponsors.LettersOfSupport.Factory.newInstance(); lettersOfSupport.setAttFile(attachedFileDataType); sponsors.setLettersOfSupport(lettersOfSupport); } } // Institutional Environment and Commitment to Training Section else if (code.equalsIgnoreCase(PHS_FELLOW_INSTITUTION_ENVIRON_COMMITMENT)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { InstitutionalEnvironmentCommitmenttoTraining institutionalEnvironmentCommitmenttoTraining = InstitutionalEnvironmentCommitmenttoTraining.Factory.newInstance(); institutionalEnvironmentCommitmenttoTraining.setAttFile(attachedFileDataType); institutionalEnvironment.setInstitutionalEnvironmentCommitmenttoTraining(institutionalEnvironmentCommitmenttoTraining); } } // Other research training plan section else if (code.equalsIgnoreCase(PROTECTION_OF_HUMAN_SUBJECTS)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { ProtectionOfHumanSubjects protectionOfHumanSubjects = ProtectionOfHumanSubjects.Factory.newInstance(); protectionOfHumanSubjects.setAttFile(attachedFileDataType); if (otherResearchTrainingPlan == null) { otherResearchTrainingPlan = phsFellowshipSupplemental.addNewOtherResearchTrainingPlan(); } otherResearchTrainingPlan.setProtectionOfHumanSubjects(protectionOfHumanSubjects); } } else if (code.equalsIgnoreCase(DATA_SAFETY_MONITORING_PLAN)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { DataSafetyMonitoringPlan dataSafetyMonitoringPlan = DataSafetyMonitoringPlan.Factory.newInstance(); dataSafetyMonitoringPlan.setAttFile(attachedFileDataType); if (otherResearchTrainingPlan == null) { otherResearchTrainingPlan = phsFellowshipSupplemental.addNewOtherResearchTrainingPlan(); } otherResearchTrainingPlan.setDataSafetyMonitoringPlan(dataSafetyMonitoringPlan); } } else if (code.equalsIgnoreCase(INCLUSION_OF_WOMEN_AND_MINORITIES)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { InclusionOfWomenAndMinorities inclusionOfWomenAndMinorities = InclusionOfWomenAndMinorities.Factory .newInstance(); inclusionOfWomenAndMinorities.setAttFile(attachedFileDataType); if (otherResearchTrainingPlan == null) { otherResearchTrainingPlan = phsFellowshipSupplemental.addNewOtherResearchTrainingPlan(); } otherResearchTrainingPlan.setInclusionOfWomenAndMinorities(inclusionOfWomenAndMinorities); } } else if (code.equalsIgnoreCase(INCLUSION_OF_CHILDREN)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { InclusionOfChildren inclusionOfChildren = InclusionOfChildren.Factory.newInstance(); inclusionOfChildren.setAttFile(attachedFileDataType); if (otherResearchTrainingPlan == null) { otherResearchTrainingPlan = phsFellowshipSupplemental.addNewOtherResearchTrainingPlan(); } otherResearchTrainingPlan.setInclusionOfChildren(inclusionOfChildren); } } } } } /** * This method is used to set HumanSubjectInvoved and VertebrateAnimalUsed XMLObject Data. * * @param researchTrainingPlan */ protected void setHumanSubjectInvolvedAndVertebrateAnimalUsed(OtherResearchTrainingPlan researchTrainingPlan) { researchTrainingPlan.setHumanSubjectsInvolved(YesNoDataType.N_NO); researchTrainingPlan.setVertebrateAnimalsUsed(YesNoDataType.N_NO); for (ProposalSpecialReviewContract propSpecialReview : pdDoc.getDevelopmentProposal().getPropSpecialReviews()) { switch (Integer.parseInt(propSpecialReview.getSpecialReviewType().getCode())) { case 1: researchTrainingPlan.setHumanSubjectsInvolved(YesNoDataType.Y_YES); break; case 2: researchTrainingPlan.setVertebrateAnimalsUsed(YesNoDataType.Y_YES); break; default: break; } } } private List<? extends AnswerHeaderContract> findQuestionnaireWithAnswers(DevelopmentProposalContract developmentProposal) { return getPropDevQuestionAnswerService().getQuestionnaireAnswerHeaders(developmentProposal.getProposalNumber(), "http://apply.grants.gov/forms/PHS_Fellowship_Supplemental_3_1-V3.1", "PHS_Fellowship_Supplemental_3_1"); } private AnswerContract getAnswer(QuestionnaireQuestionContract questionnaireQuestion, AnswerHeaderContract answerHeader) { List<? extends AnswerContract> answers = answerHeader.getAnswers(); for (AnswerContract answer : answers) { if (answer.getQuestionnaireQuestionsId().equals(questionnaireQuestion.getId())) { return answer; } } return null; } /* * This method is used to set additional information data to AdditionalInformation XMLObject from DevelopmentProposal, * ProposalYnq */ private void setAdditionalInformation(AdditionalInformation additionalInformation) { setCitizenshipAndAlternatePhoneNumber(additionalInformation); setAdditionalInformationConcurrentSupport(additionalInformation); } private void setCitizenshipAndAlternatePhoneNumber(AdditionalInformation additionalInformation) { ProposalPersonContract principalInvestigator = s2SProposalPersonService.getPrincipalInvestigator(pdDoc); for (ProposalPersonContract proposalPerson : pdDoc.getDevelopmentProposal().getProposalPersons()) { if (proposalPerson.isInvestigator()) { CitizenshipType citizenShip = s2SProposalPersonService.getCitizenship(proposalPerson); if(citizenShip!=null && StringUtils.isNotBlank(citizenShip.getCitizenShip())){ if (citizenShip.getCitizenShip().trim().equals(CitizenshipDataType.NON_U_S_CITIZEN_WITH_TEMPORARY_VISA.toString())) { additionalInformation.setUSCitizen(YesNoDataType.N_NO); additionalInformation.setNonUSCitizen(NonUSCitizenDataType.WITH_A_TEMPORARY_U_S_VISA); } else if (citizenShip.getCitizenShip().trim().equals(CitizenshipDataType.PERMANENT_RESIDENT_OF_U_S.toString())) { additionalInformation.setUSCitizen(YesNoDataType.N_NO); additionalInformation.setNonUSCitizen(NonUSCitizenDataType.WITH_A_PERMANENT_U_S_RESIDENT_VISA); } else if (citizenShip.getCitizenShip().trim().equals( CitizenshipDataType.U_S_CITIZEN_OR_NONCITIZEN_NATIONAL.toString())) { additionalInformation.setUSCitizen(YesNoDataType.Y_YES); } else if (citizenShip.getCitizenShip().trim().equals( TEMPORARY_VISA_ALSO_APPLIED_FOR_PERMANENT_RESIDENT_STATUS)) { additionalInformation.setUSCitizen(YesNoDataType.N_NO); additionalInformation.setNonUSCitizen(NonUSCitizenDataType.WITH_A_TEMPORARY_U_S_VISA); additionalInformation.setPermanentResidentByAwardIndicator(YesNoDataType.Y_YES); } } } } if (principalInvestigator != null && principalInvestigator.getMobilePhoneNumber() != null) { additionalInformation.setAlernatePhoneNumber(principalInvestigator.getMobilePhoneNumber()); } } private void setAdditionalInformationConcurrentSupport(AdditionalInformation additionalInformation) { additionalInformation.setConcurrentSupport(YesNoDataType.N_NO); AttachedFileDataType attachedFileDataType; for (NarrativeContract narrative : pdDoc.getDevelopmentProposal().getNarratives()) { final String code = narrative.getNarrativeType().getCode(); if (code != null) { if(code.equalsIgnoreCase(CONCURRENT_SUPPORT)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { ConcurrentSupportDescription concurrentSupportDescription = ConcurrentSupportDescription.Factory .newInstance(); concurrentSupportDescription.setAttFile(attachedFileDataType); additionalInformation.setConcurrentSupport(YesNoDataType.Y_YES); additionalInformation.setConcurrentSupportDescription(concurrentSupportDescription); } } } } } private AttachmentGroupMin0Max100DataType getAppendix() { AttachmentGroupMin0Max100DataType attachmentGroupType = null; List<AttachedFileDataType> attachedFileDataTypeList = new ArrayList<>(); AttachedFileDataType attachedFileDataType; for (NarrativeContract narrative : pdDoc.getDevelopmentProposal().getNarratives()) { final String code = narrative.getNarrativeType().getCode(); if (code != null && code.equalsIgnoreCase(APPENDIX)) { attachedFileDataType = getAttachedFileType(narrative); if (attachedFileDataType != null) { attachedFileDataTypeList.add(attachedFileDataType); } } } if(attachedFileDataTypeList.size() != 0) { attachmentGroupType = AttachmentGroupMin0Max100DataType.Factory.newInstance(); attachmentGroupType.setAttachedFileArray(attachedFileDataTypeList.toArray(new AttachedFileDataType[attachedFileDataTypeList .size()])); } return attachmentGroupType; } /* * * This method computes the number of months between any 2 given {@link Date} objects * * @param dateStart starting date. @param dateEnd end date. * * @return number of months between the start date and end date. */ private ScaleTwoDecimal getNumberOfMonths(Date dateStart, Date dateEnd) { BigDecimal monthCount = ScaleTwoDecimal.ZERO.bigDecimalValue(); int fullMonthCount = 0; Calendar startDate = Calendar.getInstance(); Calendar endDate = Calendar.getInstance(); startDate.setTime(dateStart); endDate.setTime(dateEnd); startDate.clear(Calendar.HOUR); startDate.clear(Calendar.MINUTE); startDate.clear(Calendar.SECOND); startDate.clear(Calendar.MILLISECOND); endDate.clear(Calendar.HOUR); endDate.clear(Calendar.MINUTE); endDate.clear(Calendar.SECOND); endDate.clear(Calendar.MILLISECOND); if (startDate.after(endDate)) { return ScaleTwoDecimal.ZERO; } int startMonthDays = startDate.getActualMaximum(Calendar.DATE) - startDate.get(Calendar.DATE); startMonthDays++; int startMonthMaxDays = startDate.getActualMaximum(Calendar.DATE); BigDecimal startMonthFraction = new ScaleTwoDecimal(startMonthDays).bigDecimalValue().divide(new ScaleTwoDecimal(startMonthMaxDays).bigDecimalValue(), RoundingMode.HALF_UP); int endMonthDays = endDate.get(Calendar.DATE); int endMonthMaxDays = endDate.getActualMaximum(Calendar.DATE); BigDecimal endMonthFraction = new ScaleTwoDecimal(endMonthDays).bigDecimalValue().divide(new ScaleTwoDecimal(endMonthMaxDays).bigDecimalValue(), RoundingMode.HALF_UP); startDate.set(Calendar.DATE, 1); endDate.set(Calendar.DATE, 1); while (startDate.getTimeInMillis() < endDate.getTimeInMillis()) { startDate.set(Calendar.MONTH, startDate.get(Calendar.MONTH) + 1); fullMonthCount++; } fullMonthCount = fullMonthCount - 1; monthCount = monthCount.add(new ScaleTwoDecimal(fullMonthCount).bigDecimalValue()).add(startMonthFraction).add(endMonthFraction); return new ScaleTwoDecimal(monthCount); } /** * This method creates {@link XmlObject} of type {@link PHSFellowshipSupplemental31Document} by populating data from the given * {@link ProposalDevelopmentDocumentContract} * * @param proposalDevelopmentDocument for which the {@link XmlObject} needs to be created * @return {@link XmlObject} which is generated using the given {@link ProposalDevelopmentDocumentContract} */ public XmlObject getFormObject(ProposalDevelopmentDocumentContract proposalDevelopmentDocument) { this.pdDoc = proposalDevelopmentDocument; return getPHSFellowshipSupplemental31(); } @Override public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } @Override public String getFormName() { return formName; } public void setFormName(String formName) { this.formName = formName; } @Override public Resource getStylesheet() { return stylesheet; } public void setStylesheet(Resource stylesheet) { this.stylesheet = stylesheet; } @Override public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } @Override public int getSortIndex() { return sortIndex; } public void setSortIndex(int sortIndex) { this.sortIndex = sortIndex; } }
package orc.ast.simple.type; import java.lang.reflect.TypeVariable; import java.util.LinkedList; import java.util.List; import orc.env.Env; import orc.error.OrcError; import orc.error.compiletime.typing.ArgumentArityException; import orc.error.compiletime.typing.SubtypeFailureException; import orc.error.compiletime.typing.TypeException; import orc.error.compiletime.typing.UncallableTypeException; import orc.type.java.ClassTycon; /** * A syntactic type which refers to a Java class (which we will treat as an Orc type). * @author quark, dkitchin */ public class ClassnameType extends Type { public String classname; public ClassnameType(String classname) { this.classname = classname; } @Override public orc.type.Type convert(Env<String> env) throws TypeException { return new orc.type.ClassnameType(classname); // FIXME: the following breaks conversion between orc.ast.oil and orc.ast.oil.xml. // See comments in issue 26. /* Class cls; try { cls = Class.forName(classname); } catch (ClassNotFoundException e) { throw new TypeException("Failed to load class " + classname + " as a type."); } return orc.type.Type.fromJavaClass(cls); */ } public String toString() { return classname; } }
package org.hisp.dhis.analytics.table; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hisp.dhis.analytics.AnalyticsTableGenerator; import org.hisp.dhis.analytics.AnalyticsTableHook; import org.hisp.dhis.analytics.AnalyticsTableHookService; import org.hisp.dhis.analytics.AnalyticsTablePhase; import org.hisp.dhis.analytics.AnalyticsTableService; import org.hisp.dhis.analytics.AnalyticsTableType; import org.hisp.dhis.analytics.AnalyticsTableUpdateParams; import org.hisp.dhis.commons.collection.CollectionUtils; import org.hisp.dhis.message.MessageService; import org.hisp.dhis.resourcetable.ResourceTableService; import org.hisp.dhis.scheduling.JobConfiguration; import org.hisp.dhis.setting.SettingKey; import org.hisp.dhis.setting.SystemSettingManager; import org.hisp.dhis.system.notification.Notifier; import org.hisp.dhis.system.util.Clock; import org.hisp.dhis.system.util.DateUtils; import org.springframework.beans.factory.annotation.Autowired; import java.util.Date; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static org.hisp.dhis.system.notification.NotificationLevel.ERROR; import static org.hisp.dhis.system.notification.NotificationLevel.INFO; /** * @author Lars Helge Overland */ public class DefaultAnalyticsTableGenerator implements AnalyticsTableGenerator { private static final Log log = LogFactory.getLog( DefaultAnalyticsTableGenerator.class ); @Autowired private List<AnalyticsTableService> analyticsTableServices; @Autowired private ResourceTableService resourceTableService; @Autowired private MessageService messageService; @Autowired private AnalyticsTableHookService tableHookService; @Autowired private SystemSettingManager systemSettingManager; @Autowired private Notifier notifier; // Implementation @Override public void generateTables( AnalyticsTableUpdateParams params ) { final Date startTime = new Date(); final Clock clock = new Clock( log ).startClock(); final JobConfiguration jobId = params.getJobId(); final Set<AnalyticsTableType> skipTypes = CollectionUtils.emptyIfNull( params.getSkipTableTypes() ); final Set<AnalyticsTableType> availableTypes = analyticsTableServices.stream() .map( AnalyticsTableService::getAnalyticsTableType ) .collect( Collectors.toSet() ); log.info( String.format( "Found %d analytics table types: %s", availableTypes.size(), availableTypes ) ); log.info( String.format( "Skip %d analytics table types: %s", skipTypes.size(), skipTypes ) ); try { notifier.clear( jobId ).notify( jobId, "Analytics table update process started" ); if ( !params.isSkipResourceTables() ) { notifier.notify( jobId, "Updating resource tables" ); generateResourceTables(); } for ( AnalyticsTableService service : analyticsTableServices ) { AnalyticsTableType tableType = service.getAnalyticsTableType(); if ( !skipTypes.contains( tableType ) ) { notifier.notify( jobId, "Updating tables: " + tableType ); service.update( params ); } } clock.logTime( "Analytics tables updated" ); notifier.notify( jobId, INFO, "Analytics tables updated: " + clock.time(), true ); } catch ( RuntimeException ex ) { notifier.notify( jobId, ERROR, "Process failed: " + ex.getMessage(), true ); messageService.sendSystemErrorNotification( "Analytics table process failed", ex ); throw ex; } systemSettingManager.saveSystemSetting( SettingKey.LAST_SUCCESSFUL_ANALYTICS_TABLES_UPDATE, startTime ); systemSettingManager.saveSystemSetting( SettingKey.LAST_SUCCESSFUL_ANALYTICS_TABLES_RUNTIME, DateUtils.getPrettyInterval( clock.getSplitTime() ) ); } @Override public void dropTables() { for ( AnalyticsTableService service : analyticsTableServices ) { service.dropTables(); } } @Override public void generateResourceTables( JobConfiguration jobId ) { final Clock clock = new Clock().startClock(); notifier.notify( jobId, "Generating resource tables" ); try { generateResourceTables(); notifier.notify( jobId, INFO, "Resource tables generated: " + clock.time(), true ); } catch ( RuntimeException ex ) { notifier.notify( jobId, ERROR, "Process failed: " + ex.getMessage(), true ); messageService.sendSystemErrorNotification( "Resource table process failed", ex ); throw ex; } } // Supportive methods private void generateResourceTables() { final Date startTime = new Date(); resourceTableService.dropAllSqlViews(); resourceTableService.generateOrganisationUnitStructures(); resourceTableService.generateDataSetOrganisationUnitCategoryTable(); resourceTableService.generateCategoryOptionComboNames(); resourceTableService.generateDataElementGroupSetTable(); resourceTableService.generateIndicatorGroupSetTable(); resourceTableService.generateOrganisationUnitGroupSetTable(); resourceTableService.generateCategoryTable(); resourceTableService.generateDataElementTable(); resourceTableService.generatePeriodTable(); resourceTableService.generateDatePeriodTable(); resourceTableService.generateDataElementCategoryOptionComboTable(); resourceTableService.createAllSqlViews(); systemSettingManager.saveSystemSetting( SettingKey.LAST_SUCCESSFUL_RESOURCE_TABLES_UPDATE, startTime ); } }
package org.eclipse.collections.codegenerator.maven; import java.net.URL; import java.net.URLClassLoader; import java.util.Arrays; import java.util.List; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.eclipse.collections.codegenerator.EclipseCollectionsCodeGenerator; /** * @goal generate * @phase generate-sources * @requiresDependencyResolution compile */ public class GenerateMojo extends AbstractMojo { /** * Skips code generation if true. * * @parameter property="skipCodeGen" */ private boolean skipCodeGen; /** * @parameter default-value="${project.build.directory}/generated-sources" * @required */ private String templateDirectory; /** * The Maven project to act upon. * * @parameter property="project" * @required */ private MavenProject project; public void execute() throws MojoExecutionException, MojoFailureException { if (this.skipCodeGen) { this.getLog().info("Skipping code generation in " + this.project.getArtifactId()); } else { this.getLog().info("Generating sources to " + this.project.getArtifactId()); } List<URL> urls = Arrays.asList(((URLClassLoader) GenerateMojo.class.getClassLoader()).getURLs()); final boolean[] error = new boolean[1]; EclipseCollectionsCodeGenerator.ErrorListener errorListener = new EclipseCollectionsCodeGenerator.ErrorListener() { public void error(String string) { GenerateMojo.this.getLog().error(string); error[0] = true; } }; EclipseCollectionsCodeGenerator gsCollectionsCodeGenerator = new EclipseCollectionsCodeGenerator(this.templateDirectory, this.project.getBasedir(), urls, errorListener); if (!this.skipCodeGen) { int numFilesWritten = gsCollectionsCodeGenerator.generateFiles(); this.getLog().info("Generated " + numFilesWritten + " files"); } if (error[0]) { throw new MojoExecutionException("Error(s) during code generation."); } if (gsCollectionsCodeGenerator.isTest()) { this.project.addTestCompileSourceRoot(EclipseCollectionsCodeGenerator.GENERATED_TEST_SOURCES_LOCATION); } else { this.project.addCompileSourceRoot(EclipseCollectionsCodeGenerator.GENERATED_SOURCES_LOCATION); } } }
package org.elasticsearch.shield.authc.ldap.support; import com.unboundid.ldap.listener.InMemoryDirectoryServer; import com.unboundid.ldap.sdk.LDAPConnection; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.shield.authc.RealmConfig; import org.elasticsearch.shield.authc.support.SecuredString; import org.elasticsearch.shield.ssl.ClientSSLService; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; /** * Tests that the server sets properly load balance connections without throwing exceptions */ public class SessionFactoryLoadBalancingTests extends LdapTestCase { public void testRoundRobin() throws Exception { TestSessionFactory testSessionFactory = createSessionFactory(LdapLoadBalancing.ROUND_ROBIN); final int numberOfIterations = randomIntBetween(1, 5); for (int iteration = 0; iteration < numberOfIterations; iteration++) { for (int i = 0; i < numberOfLdapServers; i++) { LDAPConnection connection = null; try { connection = testSessionFactory.getServerSet().getConnection(); assertThat(connection.getConnectedPort(), is(ldapServers[i].getListenPort())); } finally { if (connection != null) { connection.close(); } } } } } public void testRoundRobinWithFailures() throws Exception { assumeTrue("at least one ldap server should be present for this test", ldapServers.length > 1); logger.debug("using [{}] ldap servers, urls {}", ldapServers.length, ldapUrls()); TestSessionFactory testSessionFactory = createSessionFactory(LdapLoadBalancing.ROUND_ROBIN); // create a list of ports List<Integer> ports = new ArrayList<>(numberOfLdapServers); for (int i = 0; i < ldapServers.length; i++) { ports.add(ldapServers[i].getListenPort()); } logger.debug("list of all ports {}", ports); final int numberToKill = randomIntBetween(1, numberOfLdapServers - 1); logger.debug("killing [{}] servers", numberToKill); // get a subset to kil final List<InMemoryDirectoryServer> ldapServersToKill = randomSubsetOf(numberToKill, ldapServers); final List<InMemoryDirectoryServer> ldapServersList = Arrays.asList(ldapServers); for (InMemoryDirectoryServer ldapServerToKill : ldapServersToKill) { final int index = ldapServersList.indexOf(ldapServerToKill); assertThat(index, greaterThanOrEqualTo(0)); final Integer port = Integer.valueOf(ldapServers[index].getListenPort()); logger.debug("shutting down server index [{}] listening on [{}]", index, port); assertTrue(ports.remove(port)); ldapServers[index].shutDown(true); assertThat(ldapServers[index].getListenPort(), is(-1)); } final int numberOfIterations = randomIntBetween(1, 5); for (int iteration = 0; iteration < numberOfIterations; iteration++) { logger.debug("iteration [{}]", iteration); for (Integer port : ports) { LDAPConnection connection = null; try { logger.debug("attempting connection with expected port [{}]", port); connection = testSessionFactory.getServerSet().getConnection(); assertThat(connection.getConnectedPort(), is(port)); } finally { if (connection != null) { connection.close(); } } } } } public void testFailover() throws Exception { assumeTrue("at least one ldap server should be present for this test", ldapServers.length > 1); logger.debug("using [{}] ldap servers, urls {}", ldapServers.length, ldapUrls()); TestSessionFactory testSessionFactory = createSessionFactory(LdapLoadBalancing.FAILOVER); // first test that there is no round robin stuff going on final int firstPort = ldapServers[0].getListenPort(); for (int i = 0; i < numberOfLdapServers; i++) { LDAPConnection connection = null; try { connection = testSessionFactory.getServerSet().getConnection(); assertThat(connection.getConnectedPort(), is(firstPort)); } finally { if (connection != null) { connection.close(); } } } logger.debug("shutting down server index [0] listening on [{}]", ldapServers[0].getListenPort()); // always kill the first one ldapServers[0].shutDown(true); assertThat(ldapServers[0].getListenPort(), is(-1)); // now randomly shutdown some others if (ldapServers.length > 2) { // kill at least one other server, but we need at least one good one. Hence the upper bound is number - 2 since we need at least // one server to use! final int numberToKill = randomIntBetween(1, numberOfLdapServers - 2); InMemoryDirectoryServer[] allButFirstServer = Arrays.copyOfRange(ldapServers, 1, ldapServers.length); // get a subset to kil final List<InMemoryDirectoryServer> ldapServersToKill = randomSubsetOf(numberToKill, allButFirstServer); final List<InMemoryDirectoryServer> ldapServersList = Arrays.asList(ldapServers); for (InMemoryDirectoryServer ldapServerToKill : ldapServersToKill) { final int index = ldapServersList.indexOf(ldapServerToKill); assertThat(index, greaterThanOrEqualTo(1)); final Integer port = Integer.valueOf(ldapServers[index].getListenPort()); logger.debug("shutting down server index [{}] listening on [{}]", index, port); ldapServers[index].shutDown(true); assertThat(ldapServers[index].getListenPort(), is(-1)); } } int firstNonStoppedPort = -1; // now we find the first that isn't stopped for (int i = 0; i < numberOfLdapServers; i++) { if (ldapServers[i].getListenPort() != -1) { firstNonStoppedPort = ldapServers[i].getListenPort(); break; } } logger.debug("first non stopped port [{}]", firstNonStoppedPort); assertThat(firstNonStoppedPort, not(-1)); final int numberOfIterations = randomIntBetween(1, 5); for (int iteration = 0; iteration < numberOfIterations; iteration++) { LDAPConnection connection = null; try { logger.debug("attempting connection with expected port [{}] iteration [{}]", firstNonStoppedPort, iteration); connection = testSessionFactory.getServerSet().getConnection(); assertThat(connection.getConnectedPort(), is(firstNonStoppedPort)); } finally { if (connection != null) { connection.close(); } } } } private TestSessionFactory createSessionFactory(LdapLoadBalancing loadBalancing) throws Exception { String groupSearchBase = "cn=HMS Lydia,ou=crews,ou=groups,o=sevenSeas"; String userTemplate = "cn={0},ou=people,o=sevenSeas"; Settings settings = buildLdapSettings(ldapUrls(), new String[] { userTemplate }, groupSearchBase, LdapSearchScope.SUB_TREE, loadBalancing); RealmConfig config = new RealmConfig("test-session-factory", settings, Settings.builder().put("path.home", createTempDir()).build()); return new TestSessionFactory(config, null); } static class TestSessionFactory extends SessionFactory { protected TestSessionFactory(RealmConfig config, ClientSSLService sslService) { super(config, sslService); } @Override public LdapSession session(String user, SecuredString password) throws Exception { return null; } } }
package org.ovirt.engine.ui.uicommonweb.models.storage; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.ovirt.engine.core.common.action.ImportVmTemplateParameters; import org.ovirt.engine.core.common.action.VdcActionParametersBase; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.action.VmTemplateImportExportParameters; import org.ovirt.engine.core.common.businessentities.ArchitectureType; import org.ovirt.engine.core.common.businessentities.Entities; import org.ovirt.engine.core.common.businessentities.IVdcQueryable; import org.ovirt.engine.core.common.businessentities.StorageDomainSharedStatus; import org.ovirt.engine.core.common.businessentities.StorageDomainType; import org.ovirt.engine.core.common.businessentities.StoragePool; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.common.businessentities.profiles.CpuProfile; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.common.queries.GetAllFromExportDomainQueryParameters; import org.ovirt.engine.core.common.queries.VdcQueryReturnValue; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.StringHelper; import org.ovirt.engine.ui.frontend.AsyncQuery; import org.ovirt.engine.ui.frontend.Frontend; import org.ovirt.engine.ui.frontend.INewAsyncCallback; import org.ovirt.engine.ui.uicommonweb.Linq; import org.ovirt.engine.ui.uicommonweb.UICommand; import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider; import org.ovirt.engine.ui.uicommonweb.help.HelpTag; import org.ovirt.engine.ui.uicommonweb.models.ConfirmationModel; import org.ovirt.engine.ui.uicommonweb.models.EntityModel; import org.ovirt.engine.ui.uicommonweb.models.templates.ImportTemplateModel; import org.ovirt.engine.ui.uicommonweb.models.templates.TemplateImportDiskListModel; import org.ovirt.engine.ui.uicommonweb.models.vms.ImportTemplateData; import org.ovirt.engine.ui.uicommonweb.models.vms.UnitVmModel; import org.ovirt.engine.ui.uicommonweb.validation.I18NNameValidation; import org.ovirt.engine.ui.uicommonweb.validation.IValidation; import org.ovirt.engine.ui.uicommonweb.validation.LengthValidation; import org.ovirt.engine.ui.uicommonweb.validation.NotEmptyValidation; import org.ovirt.engine.ui.uicommonweb.validation.NotInCollectionValidation; import org.ovirt.engine.ui.uicommonweb.validation.ValidationResult; import org.ovirt.engine.ui.uicompat.ConstantsManager; import org.ovirt.engine.ui.uicompat.FrontendMultipleActionAsyncResult; import org.ovirt.engine.ui.uicompat.IFrontendMultipleActionAsyncCallback; import org.ovirt.engine.ui.uicompat.PropertyChangedEventArgs; import org.ovirt.engine.ui.uicompat.UIConstants; import org.ovirt.engine.ui.uicompat.UIMessages; import org.ovirt.engine.ui.uicompat.external.StringUtils; import com.google.inject.Inject; import com.google.inject.Provider; public class TemplateBackupModel extends ManageBackupModel<VmTemplate> { private ArrayList<Map.Entry<VmTemplate, List<DiskImage>>> extendedItems; private StoragePool pool; protected ImportTemplateModel importModel; protected Provider<? extends ImportTemplateModel> importModelProvider; /** used to save the names that were assigned for VMs which are going * to be created using import in case of choosing multiple VM imports */ protected Set<String> assignedVmNames = new HashSet<>(); protected Map<Guid, Object> cloneObjectMap; protected List<ImportTemplateData> objectsToClone; private static UIConstants constants = ConstantsManager.getInstance().getConstants(); private static UIMessages messages = ConstantsManager.getInstance().getMessages(); @Inject public TemplateBackupModel(Provider<ImportTemplateModel> importModelProvider) { this.importModelProvider = importModelProvider; setTitle(constants.templateImportTitle()); setHelpTag(HelpTag.template_import); setHashName("template_import"); //$NON-NLS-1$ } @Override protected void remove() { if (getWindow() != null) { return; } ConfirmationModel model = new ConfirmationModel(); setConfirmWindow(model); model.setTitle(constants.removeBackedUpTemplatesTitle()); model.setHelpTag(HelpTag.remove_backed_up_template); model.setHashName("remove_backed_up_template"); //$NON-NLS-1$ ArrayList<String> items = new ArrayList<>(); for (VmTemplate template : getSelectedItems()) { items.add(template.getName()); } model.setItems(items); model.setNote(constants.noteTheDeletedItemsMightStillAppearOntheSubTab()); model.getCommands().add(UICommand.createDefaultOkUiCommand("OnRemove", this)); //$NON-NLS-1$ model.getCommands().add(UICommand.createCancelUiCommand(CANCEL_COMMAND, this)); } private void onRemove() { AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { ArrayList<StoragePool> pools = (ArrayList<StoragePool>) returnValue; if (pools != null && !pools.isEmpty()) { pool = pools.get(0); checkVmsDependentOnTemplate(pool.getId(), getEntity().getId()); } } }), getEntity().getId()); } private void checkVmsDependentOnTemplate(Guid dataCenterId, Guid storageDomainId) { Frontend.getInstance().runQuery(VdcQueryType.GetVmsFromExportDomain, new GetAllFromExportDomainQueryParameters(dataCenterId, storageDomainId), new AsyncQuery(this, createGetVmsFromExportDomainCallback())); } private INewAsyncCallback createGetVmsFromExportDomainCallback() { return new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { VdcQueryReturnValue retVal = (VdcQueryReturnValue) returnValue; if (retVal == null || retVal.getReturnValue() == null || !retVal.getSucceeded()) { return; } List<VM> vmsInExportDomain = retVal.getReturnValue(); HashMap<String, List<String>> problematicVmNames = getDependentVMsForTemplates(vmsInExportDomain, getSelectedItems()); if (!problematicVmNames.isEmpty()) { showRemoveTemplateWithDependentVMConfirmationWindow(problematicVmNames); } else { removeTemplateBackup(); } } }; } private void showRemoveTemplateWithDependentVMConfirmationWindow(HashMap<String, List<String>> problematicVmNames) { ArrayList<String> missingTemplatesFromVms = new ArrayList<>(); for (Map.Entry<String, List<String>> templateName : problematicVmNames.entrySet()) { List<String> vms = problematicVmNames.get(templateName.getKey()); String vmsListString = StringUtils.join(vms, ", "); //$NON-NLS-1$ missingTemplatesFromVms.add(messages.templatesWithDependentVMs(templateName.getKey(), vmsListString)); } setConfirmWindow(null); ConfirmationModel confirmModel = new ConfirmationModel(); setConfirmWindow(confirmModel); confirmModel.setTitle(constants.removeBackedUpTemplatesWithDependentsVMTitle()); confirmModel.setHelpTag(HelpTag.remove_backed_up_template); confirmModel.setHashName("remove_backed_up_template"); //$NON-NLS-1$ confirmModel.setMessage(constants.theFollowingTemplatesHaveDependentVmsBackupOnExportDomainMsg()); confirmModel.setItems(missingTemplatesFromVms); confirmModel.getCommands().add(UICommand.createDefaultOkUiCommand("RemoveVmTemplates", this)); //$NON-NLS-1$ confirmModel.getCommands().add(UICommand.createCancelUiCommand(CANCEL_CONFIRMATION_COMMAND, this)); } private HashMap<String, List<String>> getDependentVMsForTemplates(List<VM> vmsInExportDomain, List<VmTemplate> templates) { // Build a map between the template ID and the template instance Map<Guid, VmTemplate> templateMap = Entities.businessEntitiesById(templates); // Build a map between the template ID and a list of dependent VMs names HashMap<String, List<String>> problematicVmNames = new HashMap<>(); for (VM vm : vmsInExportDomain) { VmTemplate template = templateMap.get(vm.getVmtGuid()); if (template != null) { List<String> vms = problematicVmNames.get(template.getName()); if (vms == null) { vms = new ArrayList<>(); problematicVmNames.put(template.getName(), vms); } vms.add(vm.getName()); } } return problematicVmNames; } private void removeTemplateBackup() { ArrayList<VdcActionParametersBase> prms = new ArrayList<>(); for (VmTemplate template : getSelectedItems()) { prms.add(new VmTemplateImportExportParameters(template.getId(), getEntity().getId(), pool.getId())); } Frontend.getInstance().runMultipleAction(VdcActionType.RemoveVmTemplateFromImportExport, prms); cancel(); } @Override protected ArchitectureType getArchitectureFromItem(VmTemplate template) { return template.getClusterArch(); } protected String getObjectName(ImportTemplateData templateData) { return templateData.getTemplate().getName(); } protected void setObjectName(ImportTemplateData templateData, String name) { templateData.getTemplate().setName(name); } protected boolean validateSuffix(String suffix, EntityModel entityModel) { for (Object object : objectsToClone) { VmTemplate template = ((ImportTemplateData) object).getTemplate(); if (!validateName(template.getName() + suffix, entityModel, getClonedAppendedNameValidators())) { return false; } } return true; } protected boolean validateName(String newVmName, EntityModel<String> entity, IValidation[] validators) { EntityModel<String> temp = new EntityModel<>(); temp.setIsValid(true); temp.setEntity(newVmName); temp.validateEntity(validators); if (!temp.getIsValid()) { entity.setInvalidityReasons(temp.getInvalidityReasons()); entity.setIsValid(false); } return temp.getIsValid(); } protected int getMaxClonedNameLength() { return UnitVmModel.VM_TEMPLATE_AND_INSTANCE_TYPE_NAME_MAX_LIMIT; } protected String getAlreadyAssignedClonedNameMessage() { return messages.alreadyAssignedClonedTemplateName(); } protected String getSuffixCauseToClonedNameCollisionMessage(String existingName) { return messages.suffixCauseToClonedTemplateNameCollision(existingName); } protected void executeImport() { ImportTemplateModel model = (ImportTemplateModel) getWindow(); if (model.getProgress() != null) { return; } if (!model.validate()) { return; } ArrayList<VdcActionParametersBase> prms = new ArrayList<>(); for (Object object : importModel.getItems()) { ImportTemplateData importData = (ImportTemplateData) object; VmTemplate template = importData.getTemplate(); ImportVmTemplateParameters importVmTemplateParameters = new ImportVmTemplateParameters(model.getStoragePool().getId(), getEntity().getId(), Guid.Empty, model.getCluster().getSelectedItem().getId(), template); if (importModel.getClusterQuota().getSelectedItem() != null && importModel.getClusterQuota().getIsAvailable()) { importVmTemplateParameters.setQuotaId(importModel.getClusterQuota().getSelectedItem().getId()); } CpuProfile cpuProfile = importModel.getCpuProfiles().getSelectedItem(); if (cpuProfile != null) { importVmTemplateParameters.setCpuProfileId(cpuProfile.getId()); } Map<Guid, Guid> map = new HashMap<>(); for (DiskImage disk : template.getDiskList()) { map.put(disk.getId(), importModel.getDiskImportData(disk.getId()).getSelectedStorageDomain().getId()); if (importModel.getDiskImportData(disk.getId()).getSelectedQuota() != null) { disk.setQuotaId(importModel.getDiskImportData(disk.getId()).getSelectedQuota().getId()); } } importVmTemplateParameters.setImageToDestinationDomainMap(map); if (importData.isExistsInSystem() || importData.getClone().getEntity()) { if (!cloneObjectMap.containsKey(template.getId())) { continue; } importVmTemplateParameters.setImportAsNewEntity(true); importVmTemplateParameters.getVmTemplate() .setName(((ImportTemplateData) cloneObjectMap.get(template.getId())).getTemplate().getName()); } prms.add(importVmTemplateParameters); } model.startProgress(); Frontend.getInstance().runMultipleAction(VdcActionType.ImportVmTemplate, prms, new IFrontendMultipleActionAsyncCallback() { @Override public void executed(FrontendMultipleActionAsyncResult result) { TemplateBackupModel templateBackupModel = (TemplateBackupModel) result.getState(); templateBackupModel.getWindow().stopProgress(); templateBackupModel.cancel(); ArrayList<VdcReturnValueBase> retVals = (ArrayList<VdcReturnValueBase>) result.getReturnValue(); if (retVals != null && templateBackupModel.getSelectedItems().size() == retVals.size()) { StringBuilder importedTemplates = new StringBuilder(); int counter = 0; boolean toShowConfirmWindow = false; for (VmTemplate template : templateBackupModel.getSelectedItems()) { if (retVals.get(counter) != null && retVals.get(counter).isValid()) { importedTemplates.append(template.getName()).append(", "); //$NON-NLS-1$ toShowConfirmWindow = true; } counter++; } if (toShowConfirmWindow) { ConfirmationModel confirmModel = new ConfirmationModel(); templateBackupModel.setConfirmWindow(confirmModel); confirmModel.setTitle(constants.importTemplatesTitle()); confirmModel.setHelpTag(HelpTag.import_template); confirmModel.setHashName("import_template"); //$NON-NLS-1$ confirmModel.setMessage(messages.importProcessHasBegunForTemplates(StringHelper.trimEnd(importedTemplates.toString().trim(), ','))); confirmModel.getCommands().add(new UICommand(CANCEL_CONFIRMATION_COMMAND, templateBackupModel) //$NON-NLS-1$ .setTitle(constants.close()) .setIsDefault(true) .setIsCancel(true) ); } } } }, this); } @Override protected void entityPropertyChanged(Object sender, PropertyChangedEventArgs e) { super.entityPropertyChanged(sender, e); if (e.propertyName.equals("storage_domain_shared_status")) { //$NON-NLS-1$ getSearchCommand().execute(); } } @Override protected void syncSearch() { if (getEntity() == null || getEntity().getStorageDomainType() != StorageDomainType.ImportExport || getEntity().getStorageDomainSharedStatus() != StorageDomainSharedStatus.Active) { setItems(Collections.<VmTemplate>emptyList()); } else { AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { TemplateBackupModel backupModel = (TemplateBackupModel) model; ArrayList<StoragePool> list = (ArrayList<StoragePool>) ReturnValue; if (list != null && list.size() > 0) { StoragePool dataCenter = list.get(0); AsyncQuery _asyncQuery1 = new AsyncQuery(); _asyncQuery1.setModel(backupModel); _asyncQuery1.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model1, Object ReturnValue1) { ArrayList<Map.Entry<VmTemplate, List<DiskImage>>> items = new ArrayList<>(); HashMap<VmTemplate, List<DiskImage>> dictionary = ((VdcQueryReturnValue) ReturnValue1).getReturnValue(); ArrayList<VmTemplate> list = new ArrayList<>(); for (Map.Entry<VmTemplate, List<DiskImage>> item : dictionary.entrySet()) { items.add(item); VmTemplate template = item.getKey(); template.setDiskList(new ArrayList<DiskImage>()); template.getDiskList().addAll(item.getValue()); list.add(template); } Collections.sort(list, new Linq.VmTemplateComparator()); setItems((ArrayList) list); TemplateBackupModel.this.extendedItems = items; } }; Frontend.getInstance().runQuery(VdcQueryType.GetTemplatesFromExportDomain, new GetAllFromExportDomainQueryParameters(dataCenter.getId(), backupModel.getEntity().getId()), _asyncQuery1); } } }; AsyncDataProvider.getInstance().getDataCentersByStorageDomain(_asyncQuery, getEntity().getId()); } } @Override protected void restore() { if (getWindow() != null) { return; } if (!validateSingleArchitecture()) { return; } ImportTemplateModel model = importModelProvider.get(); model.setEntity(getEntity().getId()); setWindow(model); model.startProgress(); model.getCommands().add(UICommand.createDefaultOkUiCommand("OnRestore", this)); //$NON-NLS-1$ model.getCommands().add(UICommand.createCancelUiCommand(CANCEL_COMMAND, this)); //$NON-NLS-1$); model.init(getSelectedItems(), getEntity().getId()); model.setTargetArchitecture(getArchitectureFromItem(getSelectedItems().get(0))); // Add 'Close' command model.setCloseCommand(new UICommand(CANCEL_COMMAND, this) //$NON-NLS-1$ .setTitle(ConstantsManager.getInstance().getConstants().close()) .setIsDefault(true) .setIsCancel(true) ); ((TemplateImportDiskListModel) ((ImportTemplateModel) getWindow()).getImportDiskListModel()).setExtendedItems(extendedItems); } @Override public void executeCommand(UICommand command) { switch (command.getName()) { case "OnRemove": //$NON-NLS-1$ onRemove(); break; case "OnRestore": //$NON-NLS-1$ onRestore(); break; case "RemoveVmTemplates": //$NON-NLS-1$ removeTemplateBackup(); break; case "onClone": //$NON-NLS-1$ onClone(); break; case "closeClone": //$NON-NLS-1$ closeClone(); break; case "multipleArchsOK": //$NON-NLS-1$ multipleArchsOK(); break; default: super.executeCommand(command); } } private void onClone() { ImportCloneModel cloneModel = (ImportCloneModel) getConfirmWindow(); if (cloneModel.getApplyToAll().getEntity()) { if (!cloneModel.getNoClone().getEntity()) { String suffix = cloneModel.getSuffix().getEntity(); if (!validateSuffix(suffix, cloneModel.getSuffix())) { return; } for (ImportTemplateData object : objectsToClone) { setObjectName(object, suffix, true); cloneObjectMap.put((Guid) ((IVdcQueryable) (object.getEntity())).getQueryableId(), object); } } objectsToClone.clear(); } else { ImportTemplateData object = (ImportTemplateData) cloneModel.getEntity(); if (!cloneModel.getNoClone().getEntity()) { String vmName = cloneModel.getName().getEntity(); if (!validateName(vmName, cloneModel.getName(), getClonedNameValidators())) { return; } setObjectName(object, vmName, false); cloneObjectMap.put((Guid) ((IVdcQueryable) object.getEntity()).getQueryableId(), object); } objectsToClone.remove(object); } setConfirmWindow(null); executeImportClone(); } protected IValidation[] getClonedNameValidators() { final int maxClonedNameLength = getMaxClonedNameLength(); return new IValidation[] { new NotEmptyValidation(), new LengthValidation(maxClonedNameLength), new I18NNameValidation() { @Override protected String composeMessage() { return ConstantsManager.getInstance() .getMessages() .nameMustConataionOnlyAlphanumericChars(maxClonedNameLength); } }, new UniqueClonedNameValidator(assignedVmNames) }; } private void setObjectName(ImportTemplateData templateData, String input, boolean isSuffix) { String nameForTheClonedVm = isSuffix ? getObjectName(templateData) + input : input; setObjectName(templateData, nameForTheClonedVm); assignedVmNames.add(nameForTheClonedVm); } private void closeClone() { setConfirmWindow(null); clearCachedAssignedVmNames(); } private void multipleArchsOK() { setConfirmWindow(null); } public void onRestore() { importModel = (ImportTemplateModel) getWindow(); if (importModel.getProgress() != null) { return; } if (!importModel.validate()) { return; } cloneObjectMap = new HashMap<>(); objectsToClone = new ArrayList<>(); for (Object object : importModel.getItems()) { ImportTemplateData item = (ImportTemplateData) object; if (item.getClone().getEntity()) { objectsToClone.add(item); } } executeImportClone(); } @Override protected String getListName() { return "TemplateBackupModel"; //$NON-NLS-1$ } protected String getImportConflictTitle() { return constants.importTemplateConflictTitle(); } private void executeImportClone() { // TODO: support running numbers (for suffix) if (objectsToClone.size() == 0) { clearCachedAssignedVmNames(); executeImport(); return; } ImportCloneModel entity = new ImportCloneModel(); Object object = objectsToClone.iterator().next(); entity.setEntity(object); entity.setTitle(getImportConflictTitle()); entity.setHelpTag(HelpTag.import_conflict); entity.setHashName("import_conflict"); //$NON-NLS-1$ entity.getCommands().add(UICommand.createDefaultOkUiCommand("onClone", this)); //$NON-NLS-1$ entity.getCommands().add(UICommand.createCancelUiCommand("closeClone", this)); //$NON-NLS-1$ setConfirmWindow(entity); } private void clearCachedAssignedVmNames() { assignedVmNames.clear(); } protected IValidation[] getClonedAppendedNameValidators() { final int maxClonedNameLength = getMaxClonedNameLength(); return new IValidation[] { new NotEmptyValidation(), new LengthValidation(maxClonedNameLength), new I18NNameValidation() { @Override protected String composeMessage() { return ConstantsManager.getInstance() .getMessages() .newNameWithSuffixCannotContainBlankOrSpecialChars(maxClonedNameLength); } }, new UniqueClonedAppendedNameValidator(assignedVmNames) }; } private class UniqueClonedAppendedNameValidator extends NotInCollectionValidation { public UniqueClonedAppendedNameValidator(Collection<?> collection) { super(collection); } @Override public ValidationResult validate(Object value) { ValidationResult result = super.validate(value); if (!result.getSuccess()) { result.getReasons().add(getSuffixCauseToClonedNameCollisionMessage((String) value)); } return result; } } private class UniqueClonedNameValidator extends NotInCollectionValidation { public UniqueClonedNameValidator(Collection<?> collection) { super(collection); } @Override public ValidationResult validate(Object value) { ValidationResult result = super.validate(value); if (!result.getSuccess()) { result.getReasons().add(getAlreadyAssignedClonedNameMessage()); } return result; } } }
package edu.kit.iti.formal.pse.worthwhile.interpreter; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Stack; import org.eclipse.emf.common.util.EList; import edu.kit.iti.formal.pse.worthwhile.model.ast.ASTNode; import edu.kit.iti.formal.pse.worthwhile.model.ast.Addition; import edu.kit.iti.formal.pse.worthwhile.model.ast.ArrayLength; import edu.kit.iti.formal.pse.worthwhile.model.ast.ArrayLiteral; import edu.kit.iti.formal.pse.worthwhile.model.ast.ArrayType; import edu.kit.iti.formal.pse.worthwhile.model.ast.Assertion; import edu.kit.iti.formal.pse.worthwhile.model.ast.Assignment; import edu.kit.iti.formal.pse.worthwhile.model.ast.Assumption; import edu.kit.iti.formal.pse.worthwhile.model.ast.Axiom; import edu.kit.iti.formal.pse.worthwhile.model.ast.Block; import edu.kit.iti.formal.pse.worthwhile.model.ast.BooleanLiteral; import edu.kit.iti.formal.pse.worthwhile.model.ast.BooleanType; import edu.kit.iti.formal.pse.worthwhile.model.ast.Conditional; import edu.kit.iti.formal.pse.worthwhile.model.ast.Conjunction; import edu.kit.iti.formal.pse.worthwhile.model.ast.Disjunction; import edu.kit.iti.formal.pse.worthwhile.model.ast.Division; import edu.kit.iti.formal.pse.worthwhile.model.ast.Equal; import edu.kit.iti.formal.pse.worthwhile.model.ast.Equivalence; import edu.kit.iti.formal.pse.worthwhile.model.ast.ExistsQuantifier; import edu.kit.iti.formal.pse.worthwhile.model.ast.Expression; import edu.kit.iti.formal.pse.worthwhile.model.ast.ForAllQuantifier; import edu.kit.iti.formal.pse.worthwhile.model.ast.FunctionCall; import edu.kit.iti.formal.pse.worthwhile.model.ast.FunctionDeclaration; import edu.kit.iti.formal.pse.worthwhile.model.ast.Greater; import edu.kit.iti.formal.pse.worthwhile.model.ast.GreaterOrEqual; import edu.kit.iti.formal.pse.worthwhile.model.ast.Implication; import edu.kit.iti.formal.pse.worthwhile.model.ast.IntegerLiteral; import edu.kit.iti.formal.pse.worthwhile.model.ast.IntegerType; import edu.kit.iti.formal.pse.worthwhile.model.ast.Invariant; import edu.kit.iti.formal.pse.worthwhile.model.ast.Less; import edu.kit.iti.formal.pse.worthwhile.model.ast.LessOrEqual; import edu.kit.iti.formal.pse.worthwhile.model.ast.Loop; import edu.kit.iti.formal.pse.worthwhile.model.ast.Minus; import edu.kit.iti.formal.pse.worthwhile.model.ast.Modulus; import edu.kit.iti.formal.pse.worthwhile.model.ast.Multiplication; import edu.kit.iti.formal.pse.worthwhile.model.ast.Negation; import edu.kit.iti.formal.pse.worthwhile.model.ast.Plus; import edu.kit.iti.formal.pse.worthwhile.model.ast.Postcondition; import edu.kit.iti.formal.pse.worthwhile.model.ast.Precondition; import edu.kit.iti.formal.pse.worthwhile.model.ast.Program; import edu.kit.iti.formal.pse.worthwhile.model.ast.ReturnStatement; import edu.kit.iti.formal.pse.worthwhile.model.ast.Statement; import edu.kit.iti.formal.pse.worthwhile.model.ast.Subtraction; import edu.kit.iti.formal.pse.worthwhile.model.ast.Unequal; import edu.kit.iti.formal.pse.worthwhile.model.ast.VariableDeclaration; import edu.kit.iti.formal.pse.worthwhile.model.ast.VariableReference; import edu.kit.iti.formal.pse.worthwhile.model.ast.visitor.HierarchialASTNodeVisitor; import edu.kit.iti.formal.pse.worthwhile.prover.SpecificationChecker; class InterpreterASTNodeVisitor extends HierarchialASTNodeVisitor { private Set<AbstractExecutionEventListener> executionEventHandlers; private SpecificationChecker prover; /** * @return the executionEventHandlers */ public Set<AbstractExecutionEventListener> getExecutionEventHandlers() { // begin-user-code return this.executionEventHandlers; // end-user-code } /** * @param executionEventHandlers * the executionEventHandlers to set */ public void setExecutionEventHandlers(Set<AbstractExecutionEventListener> executionEventHandlers) { // begin-user-code this.executionEventHandlers = executionEventHandlers; // end-user-code } private Stack<Value> resultStack = new Stack<Value>(); // private Map<String, Value> symbolMap; private Stack<Map<String, Value>> symbolStack = new Stack<Map<String, Value>>(); /** * @param key * @return */ protected Value getSymbol(String key) { Value temp = null; for (int i = this.symbolStack.size() - 1; i >= 0; i--) { // I won't take the 'nice' variant here because // I want to start at the top of the stack temp = symbolStack.get(i).get(key); if (temp.getClass().equals(Value.class)) { return temp; } } return null; } /** * @param key * @param value */ protected void setSymbol(String key, Value value) { this.symbolStack.peek().put(key, value); } /** * @return */ protected Map<String, Value> getAllSymbols() { return this.symbolStack.peek(); } protected InterpreterASTNodeVisitor() { prover = new SpecificationChecker(); } /** * * @param statement */ private void statementExecuted(Statement statement) { for (AbstractExecutionEventListener listener : this.executionEventHandlers) { listener.statementExecuted(statement); } } /** * * @param statement */ private void statementWillExecute(Statement statement) { for (AbstractExecutionEventListener listener : this.executionEventHandlers) { listener.statementWillExecute(statement); } } /** * * @param statement * @param error */ private void executionFailed(Statement statement, InterpreterError error) { for (AbstractExecutionEventListener listener : this.executionEventHandlers) { listener.executionFailed(statement, error); } } private void executionStarted() { for (AbstractExecutionEventListener listener : this.executionEventHandlers) { listener.executionStarted(); } } private void executionCompleted() { for (AbstractExecutionEventListener listener : this.executionEventHandlers) { listener.executionCompleted(); } } /** * * @param assertion */ private void assertionFailed(Assertion assertion) { for (AbstractExecutionEventListener listener : this.executionEventHandlers) { listener.assertionFailed(assertion); } } /** * * @param assertion */ private void assertionSucceeded(Assertion assertion) { for (AbstractExecutionEventListener listener : this.executionEventHandlers) { listener.assertionSucceeded(assertion); } } /** * * @param expression */ private void expressionEvaluated(Expression expression) { for (AbstractExecutionEventListener listener : this.executionEventHandlers) { listener.expressionEvaluated(expression); } } /** * Returns the value generated by the last return statement ran in this context * * @return the return value or null if none is available */ protected Value getReturnValue() { return this.resultStack.pop(); } /** * Adds a debug event handler to this context * * @param handler */ protected void addExecutionEventHandler(AbstractExecutionEventListener handler) { this.executionEventHandlers.add(handler); } /** * Removes a debug event handler from this context * * @param handler */ protected void removeExecutionEventHandler(AbstractExecutionEventListener handler) { this.executionEventHandlers.remove(handler); } /** * @return */ @Override protected InterpreterASTNodeVisitor clone() { // begin-user-code // TODO Auto-generated method stub return null; // end-user-code } public void visit(Addition addition) { addition.getLeft().accept(this); Value left = this.resultStack.pop(); addition.getRight().accept(this); Value right = this.resultStack.pop(); this.resultStack.push(new Value(left.getIntegerValue().add(right.getIntegerValue()))); this.expressionEvaluated(addition); } public void visit(ArrayLength arrayLength) { // TODO Auto-generated method stub this.expressionEvaluated(arrayLength); } public void visit(ArrayLiteral arrayLiteral) { // TODO Auto-generated method stub this.expressionEvaluated(arrayLiteral); } public void visit(ArrayType arrayType) { // TODO Auto-generated method stub } public void visit(Assertion assertion) { // TODO I have no clue what I am doing here prover.checkFormula(assertion.getExpression(), symbolStack.peek()); this.assertionSucceeded(assertion); } public void visit(Assignment assignment) { this.statementWillExecute(assignment); assignment.getValue().accept(this); symbolStack.peek().put(assignment.getVariable().getVariable().getName(), resultStack.pop()); this.statementExecuted(assignment); } public void visit(Assumption assumption) { // TODO Auto-generated method stub } public void visit(Axiom axiom) { // TODO Auto-generated method stub } public void visit(Block block) { Map<String, Value> symbolMap = new HashMap<String, Value>(); this.symbolStack.push(symbolMap); EList<Statement> statements = block.getStatements(); for (Statement statement : statements) { statement.accept(this); } this.symbolStack.pop(); } public void visit(BooleanLiteral booleanLiteral) { this.resultStack.push(new Value(booleanLiteral.getValue())); this.expressionEvaluated(booleanLiteral); } public void visit(BooleanType booleanType) { // TODO Auto-generated method stub } public void visit(Conditional conditional) { this.statementWillExecute(conditional); conditional.getCondition().accept(this); if (this.resultStack.pop().getBooleanValue()) { conditional.getTrueBlock().accept(this); } else { conditional.getFalseBlock().accept(this); } this.statementExecuted(conditional); } public void visit(Conjunction conjunction) { conjunction.getLeft().accept(this); Value left = this.resultStack.pop(); conjunction.getRight().accept(this); Value right = this.resultStack.pop(); this.resultStack.push(new Value(left.getBooleanValue() && right.getBooleanValue())); this.expressionEvaluated(conjunction); } public void visit(Disjunction disjunction) { disjunction.getLeft().accept(this); Value left = this.resultStack.pop(); disjunction.getRight().accept(this); Value right = this.resultStack.pop(); this.resultStack.push(new Value(left.getBooleanValue() || right.getBooleanValue())); this.expressionEvaluated(disjunction); } public void visit(Division division) { // TODO handle division by zero division.getLeft().accept(this); Value left = this.resultStack.pop(); division.getRight().accept(this); Value right = this.resultStack.pop(); this.resultStack.push(new Value(left.getIntegerValue().divide(right.getIntegerValue()))); this.expressionEvaluated(division); } public void visit(Equal equal) { equal.getLeft().accept(this); Value left = this.resultStack.pop(); equal.getRight().accept(this); Value right = this.resultStack.pop(); if (left.getValueType() == ValueType.BOOLEAN_TYPE) { this.resultStack.push(new Value(left.getBooleanValue() == (right.getBooleanValue()))); } else { this.resultStack.push(new Value(left.getIntegerValue().equals(right.getIntegerValue()))); } this.expressionEvaluated(equal); } public void visit(Equivalence equivalence) { equivalence.getLeft().accept(this); Value left = this.resultStack.pop(); equivalence.getRight().accept(this); Value right = this.resultStack.pop(); this.resultStack.push(new Value(left.getBooleanValue() == right.getBooleanValue())); this.expressionEvaluated(equivalence); } public void visit(ExistsQuantifier existsQuantifier) { // TODO Auto-generated method stub this.expressionEvaluated(existsQuantifier); } public void visit(ForAllQuantifier forAllQuantifier) { // TODO Auto-generated method stub this.expressionEvaluated(forAllQuantifier); } public void visit(FunctionCall functionCall) { InterpreterASTNodeVisitor functionVisitor = new InterpreterASTNodeVisitor(); functionVisitor.setExecutionEventHandlers(this.executionEventHandlers); FunctionDeclaration functionDeclaration = functionCall.getFunction(); EList<Expression> actuals = functionCall.getActuals(); for (int i = 0; i < actuals.size(); i++) { actuals.get(i).accept(this); functionVisitor.setSymbol(functionDeclaration.getParameters().get(i).getName(), this.resultStack.pop()); } functionDeclaration.getBody().accept(functionVisitor); this.resultStack.push(functionVisitor.getReturnValue()); this.expressionEvaluated(functionCall); } public void visit(FunctionDeclaration functionDeclaration) { // TODO Auto-generated method stub - does this even have to do anything? } public void visit(Greater greater) { greater.getLeft().accept(this); Value left = this.resultStack.pop(); greater.getRight().accept(this); Value right = this.resultStack.pop(); this.resultStack.push(new Value((left.getIntegerValue().compareTo(right.getIntegerValue()) == 1))); this.expressionEvaluated(greater); } public void visit(GreaterOrEqual greaterOrEqual) { greaterOrEqual.getLeft().accept(this); Value left = this.resultStack.pop(); greaterOrEqual.getRight().accept(this); Value right = this.resultStack.pop(); this.resultStack.push(new Value((left.getIntegerValue().compareTo(right.getIntegerValue()) != -1))); this.expressionEvaluated(greaterOrEqual); } public void visit(Implication implication) { implication.getLeft().accept(this); Value left = this.resultStack.pop(); implication.getRight().accept(this); Value right = this.resultStack.pop(); this.resultStack.push(new Value(!(left.getBooleanValue() && !right.getBooleanValue()))); this.expressionEvaluated(implication); } public void visit(IntegerLiteral integerLiteral) { this.resultStack.push(new Value(integerLiteral.getValue())); this.expressionEvaluated(integerLiteral); } public void visit(IntegerType integerType) { // TODO Auto-generated method stub } public void visit(Invariant invariant) { // TODO Auto-generated method stub } public void visit(Less less) { less.getLeft().accept(this); Value left = this.resultStack.pop(); less.getRight().accept(this); Value right = this.resultStack.pop(); this.resultStack.push(new Value((left.getIntegerValue().compareTo(right.getIntegerValue()) == -1))); this.expressionEvaluated(less); } public void visit(LessOrEqual lessOrEqual) { lessOrEqual.getLeft().accept(this); Value left = this.resultStack.pop(); lessOrEqual.getRight().accept(this); Value right = this.resultStack.pop(); this.resultStack.push(new Value((left.getIntegerValue().compareTo(right.getIntegerValue()) != 1))); this.expressionEvaluated(lessOrEqual); } public void visit(Loop loop) { // TODO incorporate invariant this.statementWillExecute(loop); loop.getCondition().accept(this); while (this.resultStack.pop().getBooleanValue()) { loop.getBody().accept(this); loop.getCondition().accept(this); } this.statementExecuted(loop); } public void visit(Minus minus) { this.resultStack.push(new Value(this.resultStack.pop().getIntegerValue().negate())); this.expressionEvaluated(minus); } public void visit(Modulus modulus) { // TODO handle modulo by zero modulus.getLeft().accept(this); Value left = this.resultStack.pop(); modulus.getRight().accept(this); Value right = this.resultStack.pop(); this.resultStack.push(new Value(left.getIntegerValue().mod(right.getIntegerValue()))); this.expressionEvaluated(modulus); } public void visit(Multiplication multiplication) { multiplication.getLeft().accept(this); Value left = this.resultStack.pop(); multiplication.getRight().accept(this); Value right = this.resultStack.pop(); this.resultStack.push(new Value(left.getIntegerValue().multiply(right.getIntegerValue()))); this.expressionEvaluated(multiplication); } public void visit(Negation negation) { negation.getOperand().accept(this); this.resultStack.push(new Value(!(this.resultStack.pop().getBooleanValue()))); this.expressionEvaluated(negation); } @Override public void visit(ASTNode node) { } public void visit(Plus plus) { plus.accept(this); this.expressionEvaluated(plus); } public void visit(Postcondition postcondition) { // TODO Auto-generated method stub } public void visit(Precondition precondition) { // TODO Auto-generated method stub } public void visit(Program program) { // TODO FIX THIS /* * EList<FunctionDeclaration> functionDeclarations = program.getFunctionDeclarations(); for * (FunctionDeclaration functionDeclaration : functionDeclarations) { functionDeclaration.accept(this); * } */ this.executionStarted(); program.getMainBlock().accept(this); this.executionCompleted(); } public void visit(ReturnStatement returnStatement) { // TODO Auto-generated method stub this.statementWillExecute(returnStatement); returnStatement.getReturnValue().accept(this); this.statementExecuted(returnStatement); } public void visit(Subtraction subtraction) { subtraction.getLeft().accept(this); Value left = this.resultStack.pop(); subtraction.getRight().accept(this); Value right = this.resultStack.pop(); this.resultStack.push(new Value(left.getIntegerValue().subtract(right.getIntegerValue()))); this.expressionEvaluated(subtraction); } public void visit(Unequal unequal) { unequal.getLeft().accept(this); Value left = this.resultStack.pop(); unequal.getRight().accept(this); Value right = this.resultStack.pop(); if (left.getValueType() == ValueType.BOOLEAN_TYPE) { this.resultStack.push(new Value(!(left.getBooleanValue() == (right.getBooleanValue())))); } else { this.resultStack.push(new Value(!(left.getIntegerValue().equals(right.getIntegerValue())))); } this.expressionEvaluated(unequal); } public void visit(VariableDeclaration variableDeclaration) { this.statementWillExecute(variableDeclaration); if (variableDeclaration.getInitialValue().getClass().equals(Expression.class)) { variableDeclaration.getInitialValue().accept(this); this.setSymbol(variableDeclaration.getName(), this.resultStack.pop()); } else { if (variableDeclaration.getType().getClass().equals(ArrayType.class)) { //if(variableDeclaration.getType().) //this.setSymbol(variableDeclaration.getName(), new Value(BigInteger.ZERO)); } else if (variableDeclaration.getType().getClass().equals(BooleanType.class)) { this.setSymbol(variableDeclaration.getName(), new Value(false)); } else if (variableDeclaration.getType().getClass().equals(IntegerType.class)) { this.setSymbol(variableDeclaration.getName(), new Value(BigInteger.ZERO)); } } this.statementExecuted(variableDeclaration); } public void visit(VariableReference variableReference) { this.resultStack.push(this.getSymbol(variableReference.getVariable().getName())); this.expressionEvaluated(variableReference); } }
package org.wso2.carbon.pc.core.assets.resources; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jaggeryjs.hostobjects.stream.StreamHostObject; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.wso2.carbon.pc.core.ProcessCenterConstants; import org.wso2.carbon.pc.core.ProcessCenterException; import org.wso2.carbon.pc.core.audit.util.RegPermissionUtil; import org.wso2.carbon.pc.core.internal.ProcessCenterServerHolder; import org.wso2.carbon.pc.core.util.Utils; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.session.UserRegistry; import org.xml.sax.InputSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.InputStream; import java.io.StringReader; /** * Class related to process document resources */ public class ProcessDocument { private static final Log log = LogFactory.getLog(ProcessDocument.class); /** * Check the documents availability for a given process * * @param resourcePath holds the process path * @return true if documents are available */ public boolean isDocumentAvailable(String resourcePath) { try { RegistryService registryService = ProcessCenterServerHolder.getInstance().getRegistryService(); if (registryService != null) { UserRegistry reg = registryService.getGovernanceSystemRegistry(); resourcePath = resourcePath.substring(ProcessCenterConstants.GREG_PATH.length()); Resource resourceAsset = reg.get(resourcePath); String resourceContent = new String((byte[]) resourceAsset.getContent()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(resourceContent))); NodeList documentElements = ((Element) document.getFirstChild()).getElementsByTagName("document"); if (documentElements.getLength() != 0) { return true; } } } catch (Exception e) { log.error("No documents available in the path: " + resourcePath, e); } return false; } /** * Upload a document * * @param processName process name * @param processVersion process version * @param docName document name * @param docSummary summary of the document * @param docUrl google document url * @param docObject document stream object * @param docExtension document extension * @return process id */ public String uploadDocument(String processName, String processVersion, String docName, String docSummary, String docUrl, Object docObject, String docExtension, String user) throws ProcessCenterException, JSONException { String processId = "FAILED TO UPLOAD DOCUMENT"; InputStream docStream = null; byte[] docContent = new byte[0]; //Getting associated document list of the process and creating json format of it String processDocList = this.getUploadedDocumentDetails( ProcessCenterConstants.GREG_PATH_PROCESS + processName + "/" + processVersion); JSONArray processDocs = new JSONArray(processDocList); //checking for a uploaded document with same name in the list, in positive case throws an error and exit for (int iteratorValue = 0; iteratorValue < processDocs.length(); iteratorValue++) { String path = ((JSONObject) processDocs.get(iteratorValue)).get("path").toString(); if ((getAssociatedDocFileName(path).equals(docName + "." + docExtension))) { throw new ProcessCenterException( "Associated document " + getAssociatedDocFileName(path) + " exits in " + processName + " version" + processVersion); } } try { if(docUrl.equals("NA")) { StreamHostObject s = (StreamHostObject) docObject; docStream = s.getStream(); docContent = IOUtils.toByteArray(docStream); } RegistryService registryService = ProcessCenterServerHolder.getInstance().getRegistryService(); if (registryService != null) { // UserRegistry reg = registryService.getGovernanceSystemRegistry(); UserRegistry reg = registryService.getGovernanceUserRegistry(user); RegPermissionUtil .setPutPermission(registryService, user, ProcessCenterConstants.AUDIT.PROCESS_DOC_PATH); // store doc content as a registry resource Resource docContentResource = reg.newResource(); String processAssetPath = ProcessCenterConstants.PROCESS_ASSET_ROOT + processName + "/" + processVersion; String docContentPath = null; if (docContent.length != 0) { docContentResource.setContent(docContent); if (docExtension.equalsIgnoreCase("pdf")) { docContentResource.setMediaType("application/pdf"); } else { docContentResource.setMediaType("application/msword"); } docContentPath = "doccontent/" + processName + "/" + processVersion + "/" + docName + "." + docExtension; reg.put(docContentPath, docContentResource); reg.addAssociation(docContentPath, processAssetPath, ProcessCenterConstants.ASSOCIATION_TYPE); } Resource resource = reg.get(processAssetPath); String processContent = new String((byte[]) resource.getContent()); Document doc = Utils.stringToXML(processContent); Element rootElement = doc.getDocumentElement(); Element docElement = Utils.append(doc, rootElement, "document", ProcessCenterConstants.MNS); Utils.appendText(doc, docElement, "name", ProcessCenterConstants.MNS, docName); Utils.appendText(doc, docElement, "summary", ProcessCenterConstants.MNS, docSummary); if ((docUrl != null) && (!docUrl.isEmpty())) { Utils.appendText(doc, docElement, "url", ProcessCenterConstants.MNS, docUrl); } else { Utils.appendText(doc, docElement, "url", ProcessCenterConstants.MNS, "NA"); } if (docContentPath != null) { Utils.appendText(doc, docElement, "path", ProcessCenterConstants.MNS, docContentPath); } else { Utils.appendText(doc, docElement, "path", ProcessCenterConstants.MNS, "NA"); } String newProcessContent = Utils.xmlToString(doc); resource.setContent(newProcessContent); reg.put(processAssetPath, resource); Resource storedProcessAsset = reg.get(processAssetPath); processId = storedProcessAsset.getUUID(); } } catch (Exception e) { String errMsg = docName + "." + docExtension + " document upload error for " + processName + ":" + processVersion; log.error(errMsg, e); throw new ProcessCenterException(errMsg, e); } return processId; } /** * Delete the resource collection (directory) created in the governance registry for the process to keep its * documents * * @param processName name of the process * @param processVersion version of the process * @throws ProcessCenterException */ public void deleteDocumentResourceCollection(String processName, String processVersion) throws ProcessCenterException, RegistryException { RegistryService registryService = ProcessCenterServerHolder.getInstance().getRegistryService(); String documentsResourceCollectionPath = ProcessCenterConstants.DOC_CONTENT_PATH + processName + "/" + processVersion; if (registryService != null) { UserRegistry reg = registryService.getGovernanceSystemRegistry(); reg.delete(documentsResourceCollectionPath); } } /** * Utility method for extracting file name from the registry path * * @param filepath * @return the name of the associated doc file */ private static String getAssociatedDocFileName(String filepath) { return filepath.substring(filepath.lastIndexOf("/") + 1); } /** * Get details of all the documents (including Google docs) added to a certain process * * @param resourcePath holds the process rxt path * @return document information */ public String getUploadedDocumentDetails(String resourcePath) throws ProcessCenterException { String documentString = "NA"; try { RegistryService registryService = ProcessCenterServerHolder.getInstance().getRegistryService(); if (registryService != null) { UserRegistry reg = registryService.getGovernanceSystemRegistry(); resourcePath = resourcePath.substring(ProcessCenterConstants.GREG_PATH.length()); Resource resourceAsset = reg.get(resourcePath); String resourceContent = new String((byte[]) resourceAsset.getContent()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse( new InputSource(new StringReader(resourceContent))); JSONArray documentArray = new JSONArray(); NodeList documentElements = ((Element) document.getFirstChild()).getElementsByTagName("document"); if (documentElements.getLength() != 0) { for (int i = 0; i < documentElements.getLength(); i++) { Element documentElement = (Element) documentElements.item(i); String docName = documentElement.getElementsByTagName("name").item(0).getTextContent(); String docSummary = documentElement.getElementsByTagName("summary").item(0).getTextContent(); String docUrl = documentElement.getElementsByTagName("url").item(0).getTextContent(); String docPath = documentElement.getElementsByTagName("path").item(0).getTextContent(); JSONObject processDoc = new JSONObject(); processDoc.put("name", docName); processDoc.put("summary", docSummary); processDoc.put("url", docUrl); processDoc.put("path", docPath); documentArray.put(processDoc); } } documentString = documentArray.toString(); } } catch (Exception e) { String errMsg = "Failed to fetch document: " + resourcePath; log.error(errMsg); throw new ProcessCenterException(errMsg, e); } return documentString; } /** * Download a document * * @param resourcePath holds the process path * @return document content as a String */ public String downloadDocument(String resourcePath) throws ProcessCenterException { String docString = "FAILED TO GET Document"; try { RegistryService registryService = ProcessCenterServerHolder.getInstance().getRegistryService(); if (registryService != null) { UserRegistry reg = registryService.getGovernanceSystemRegistry(); Resource docAsset = reg.get(resourcePath); byte[] docContent = (byte[]) docAsset.getContent(); docString = new sun.misc.BASE64Encoder().encode(docContent); if (log.isDebugEnabled()) { log.debug("Document Path:" + resourcePath); } } } catch (Exception e) { String errMsg = "Failed to download document: " + resourcePath; log.error(errMsg); throw new ProcessCenterException(errMsg, e); } return docString; } /** * delete a given document * * @param deleteDocument holds the information of the document that need to be deleted * @return true after successful deletion */ public boolean deleteDocument(String deleteDocument, String user) throws ProcessCenterException { try { RegistryService registryService = ProcessCenterServerHolder.getInstance().getRegistryService(); if (registryService != null) { UserRegistry reg = registryService.getGovernanceUserRegistry(user); JSONObject documentInfo = new JSONObject(deleteDocument); String processName = documentInfo.getString("processName"); String processVersion = documentInfo.getString("processVersion"); JSONObject removeDocument = documentInfo.getJSONObject("removeDocument"); String processAssetPath = ProcessCenterConstants.PROCESS_ASSET_ROOT + processName + "/" + processVersion; Resource resource = reg.get(processAssetPath); String processContent = new String((byte[]) resource.getContent()); Document doc = Utils.stringToXML(processContent); if (removeDocument != null) { NodeList documentElements = ((Element) doc.getFirstChild()).getElementsByTagName("document"); for (int i = 0; i < documentElements.getLength(); i++) { Element documentElement = (Element) documentElements.item(i); String documentName = documentElement.getElementsByTagName("name").item(0).getTextContent(); String documentSummary = documentElement.getElementsByTagName("summary").item(0) .getTextContent(); String documentUrl = documentElement.getElementsByTagName("url").item(0).getTextContent(); String documentPath = documentElement.getElementsByTagName("path").item(0).getTextContent(); if (documentName.equals(removeDocument.getString("name")) && documentSummary.equals(removeDocument.getString("summary")) && documentPath.equals(removeDocument.getString("path")) && documentUrl.equals(removeDocument.getString("url"))) { documentElement.getParentNode().removeChild(documentElement); break; } } String newProcessContent = Utils.xmlToString(doc); resource.setContent(newProcessContent); reg.put(processAssetPath, resource); String docContentResourcePath = removeDocument.getString("path"); if (!docContentResourcePath.equals("NA")) { if (reg.resourceExists(docContentResourcePath)) { reg.delete(docContentResourcePath); } } } } } catch (Exception e) { String errMsg = "Failed to delete a document: " + deleteDocument; log.error(errMsg, e); throw new ProcessCenterException(errMsg, e); } return true; } /** * Updates document details including name and summary * * @param documentDetails Details of the document to be updated * @param user current user name * @throws ProcessCenterException */ public String updateDocumentDetails(String documentDetails, String user) throws ProcessCenterException { String processId = "NA"; RegistryService registryService = ProcessCenterServerHolder.getInstance().getRegistryService(); try { if (registryService != null) { UserRegistry reg = registryService.getGovernanceUserRegistry(user); JSONObject processInfo = new JSONObject(documentDetails); String processName = processInfo.getString("processName"); String processVersion = processInfo.getString("processVersion"); String docSummary = processInfo.getString("summary"); String docIndex = processInfo.getString("name").replace("doc", ""); String processAssetPath = ProcessCenterConstants.PROCESS_ASSET_ROOT + processName + "/" + processVersion; Resource resource = reg.get(processAssetPath); String processContent = new String((byte[]) resource.getContent()); Document doc = Utils.stringToXML(processContent); NodeList documentElements = ((Element) doc.getFirstChild()).getElementsByTagName("document"); if (documentElements.getLength() != 0) { Element documentElement = (Element) documentElements.item(Integer.valueOf(docIndex)); documentElement.getElementsByTagName("summary").item(0).setTextContent(docSummary); } String newProcessContent = Utils.xmlToString(doc); resource.setContent(newProcessContent); reg.put(processAssetPath, resource); Resource storedProcess = reg.get(processAssetPath); processId = storedProcess.getUUID(); } } catch (Exception e) { String msg = "Failed to update document details of " + documentDetails; log.error(msg, e); throw new ProcessCenterException(msg, e); } return processId; } }
package mod._file.calc; import java.io.PrintWriter; import lib.Status; import lib.StatusException; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; import com.sun.star.beans.PropertyValue; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.uno.XInterface; /** * Here <code>com.sun.star.sdbc.Driver</code> service is tested.<p> * Test allows to run object tests in several threads concurently. * @see com.sun.star.sdbc.Driver * @see com.sun.star.sdbc.XDriver * @see com.sun.star.sdbcx.XCreateCatalog * @see com.sun.star.sdbcx.XDropCatalog * @see ifc.sdbc._XDriver * @see ifc.sdbcx._XCreateCatalog * @see ifc.sdbcx._XDropCatalog */ public class ODriver extends TestCase { /** * Creating a Testenvironment for the interfaces to be tested. * Creates an instance of the service * <code>com.sun.star.sdbc.Driver</code>. <p> * Object relations created : * <ul> * <li> <code>'XDriver.URL'</code> for {@link ifc.sdbc._XDriver}: * is the URL of the Spreadsheet document to which to connect. * The URL is obtained from the parameter <code>calc.url</code></li> * <li> <code>'XDriver.UNSUITABLE_URL'</code> for * {@link ifc.sdbc._XDriver}: * the wrong kind of URL to connect using given driver. * The URL is obtained from the parameter <code>jdbc.url</code></li> * <li> <code>'XDriver.INFO'</code> for {@link ifc.sdbc._XDriver}: * a list of arbitrary string tag/value pairs as connection arguments * </li> * </ul> */ public synchronized TestEnvironment createTestEnvironment( TestParameters Param, PrintWriter log ) throws StatusException { XInterface oObj = null; try { oObj = (XInterface)( (XMultiServiceFactory)Param.getMSF()).createInstance( "com.sun.star.comp.sdbc.calc.ODriver"); } catch (com.sun.star.uno.Exception e) { e.printStackTrace(log); throw new StatusException(Status.failed("Couldn't create object")); } log.println("creating a new environment for calc.ODriver object"); TestEnvironment tEnv = new TestEnvironment(oObj); //adding relation for sdbc.XDriver String calcURL = (String) Param.get("calc.url"); if (calcURL == null) { throw new StatusException(Status.failed( "Couldn't get 'calc.url' from ini-file")); } tEnv.addObjRelation("XDriver.URL", "sdbc:calc:" + calcURL); PropertyValue[] info = new PropertyValue[0]; tEnv.addObjRelation("XDriver.INFO", info); String jdbcUrl = (String) Param.get("jdbc.url"); if (jdbcUrl == null) { throw new StatusException(Status.failed( "Couldn't get 'jdbc.url' from ini-file")); } tEnv.addObjRelation("XDriver.UNSUITABLE_URL", "jdbc:" + jdbcUrl); tEnv.addObjRelation("NoBadURL", "TRUE"); return tEnv; } }
package uk.ac.ebi.pride.proteinidentificationindex.search.service.repository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.solr.core.query.result.FacetPage; import org.springframework.data.solr.core.query.result.HighlightPage; import org.springframework.data.solr.repository.Facet; import org.springframework.data.solr.repository.Highlight; import org.springframework.data.solr.repository.Query; import org.springframework.data.solr.repository.SolrCrudRepository; import uk.ac.ebi.pride.proteinidentificationindex.search.model.ProteinIdentification; import uk.ac.ebi.pride.proteinidentificationindex.search.model.ProteinIdentificationSummary; import java.util.Collection; import java.util.List; import static org.springframework.data.solr.core.query.Query.Operator.*; /** * @author Jose A. Dianes * @version $Id$ * * Note: using the Query annotation allows wildcards to go straight into the query */ public interface SolrProteinIdentificationRepository extends SolrCrudRepository<ProteinIdentification, String> { public static final String HIGHLIGHT_PRE_FRAGMENT = "<span class='search-hit'>"; public static final String HIGHLIGHT_POST_FRAGMENT = "</span>"; // Id query methods @Query("id:?0") List<ProteinIdentification> findById(String id); @Query("id:(?0)") List<ProteinIdentification> findByIdIn(Collection<String> id); // Accession query methods @Query("accession:?0") List<ProteinIdentification> findByAccession(String accession); @Query("accession:(?0)") List<ProteinIdentification> findByAccessionIn(Collection<String> accession); // Synonym query methods @Query("synonyms:?0 AND project_accession:?1") List<ProteinIdentification> findBySynonymAndProjectAccession(String synonym, String projectAccession); // Project accession query methods Long countByProjectAccession(String projectAccession); @Query("project_accession:?0") List<ProteinIdentification> findByProjectAccession(String projectAccession); @Query("project_accession:(?0)") List<ProteinIdentification> findByProjectAccessionIn(Collection<String> projectAccessions); @Query("project_accession:?0") Page<ProteinIdentification> findByProjectAccession(String projectAccession, Pageable pageable); @Query("project_accession:(?0)") Page<ProteinIdentification> findByProjectAccessionIn(Collection<String> projectAccessions, Pageable pageable); @Query(value = "project_accession:?0", filters = "mod_names:(?1)", defaultOperator = AND) Page<ProteinIdentification> findByProjectAccessionAndFilterModNames(String projectAccessions, List<String> modNameFilters, Pageable pageable); @Highlight(prefix = HIGHLIGHT_PRE_FRAGMENT, postfix = HIGHLIGHT_POST_FRAGMENT, fields = {"protein_sequence, submitted_accession, accession, ambiguity_group"}) @Query(value = "project_accession:?0 AND (protein_sequence:?1 OR submitted_accession:?1 OR accession:?1 OR ambiguity_group:?1)") HighlightPage<ProteinIdentification> findByProjectAccessionHighlights(String projectAccessions, String term, Pageable pageable); @Highlight(prefix = HIGHLIGHT_PRE_FRAGMENT, postfix = HIGHLIGHT_POST_FRAGMENT, fields = {"protein_sequence, submitted_accession, accession, ambiguity_group"}) @Query(value = "project_accession:?0 AND (protein_sequence:?1 OR submitted_accession:?1 OR accession:?1 OR ambiguity_group:?1)", filters = "mod_names:(?2)", defaultOperator = AND) HighlightPage<ProteinIdentification> findByProjectAccessionHighlightsAndFilterModNames(String projectAccessions, String term, List<String> modNameFilters, Pageable pageable); @Facet(fields = {"mod_names"}, limit = 100) @Query(value = "project_accession:?0 AND (protein_sequence:?1 OR submitted_accession:?1 OR accession:?1 OR ambiguity_group:?1)") FacetPage<ProteinIdentification> findByProjectAccessionFacet(String projectAccessions, String term, Pageable pageable); @Facet(fields = {"mod_names"}, limit = 100) @Query(value = "project_accession:?0", filters = "mod_names:(?1)", defaultOperator = AND) FacetPage<ProteinIdentification> findByProjectAccessionFacetAndFilterModNames(String projectAccessions, List<String> modNameFilters, Pageable pageable); @Facet(fields = {"mod_names"}, limit = 100) @Query(value = "project_accession:?0 AND (protein_sequence:?1 OR submitted_accession:?1 OR accession:?1 OR ambiguity_group:?1)", filters = "mod_names:(?2)", defaultOperator = AND) FacetPage<ProteinIdentification> findByProjectAccessionFacetAndFilterModNames(String projectAccessions, String term, List<String> modNameFilters, Pageable pageable); // Assay accession query methods Long countByAssayAccession(String assayAccession); @Query("assay_accession:?0") List<ProteinIdentification> findByAssayAccession(String assayAccession); @Query("assay_accession:(?0)") List<ProteinIdentification> findByAssayAccessionIn(Collection<String> assayAccessions); @Query("assay_accession:?0") Page<ProteinIdentification> findByAssayAccession(String assayAccession, Pageable pageable); @Query("assay_accession:(?0)") Page<ProteinIdentification> findByAssayAccessionIn(Collection<String> assayAccessions, Pageable pageable); @Query(value = "assay_accession:?0", filters = "mod_names:(?1)", defaultOperator = AND) Page<ProteinIdentification> findByAssayAccessionAndFilterModNames(String assayAccession, List<String> modNameFilters, Pageable pageable); @Highlight(prefix = HIGHLIGHT_PRE_FRAGMENT, postfix = HIGHLIGHT_POST_FRAGMENT, fields = {"protein_sequence, submitted_accession, accession, ambiguity_group"}) @Query(value = "assay_accession:?0 AND (protein_sequence:?1 OR submitted_accession:?1 OR accession:?1 OR ambiguity_group:?1)") HighlightPage<ProteinIdentification> findByAssayAccessionHighlights(String assayAccession, String term, Pageable pageable); @Highlight(prefix = HIGHLIGHT_PRE_FRAGMENT, postfix = HIGHLIGHT_POST_FRAGMENT, fields = {"protein_sequence, submitted_accession, accession, ambiguity_group"}) @Query(value = "assay_accession:?0 AND (protein_sequence:?1 OR submitted_accession:?1 OR accession:?1 OR ambiguity_group:?1)", filters = "mod_names:(?2)", defaultOperator = AND) HighlightPage<ProteinIdentification> findByAssayAccessionHighlightsAndFilterModNames(String assayAccession, String term, List<String> modNameFilters, Pageable pageable); @Facet(fields = {"mod_names"}, limit = 100) @Query(value = "assay_accession:?0 AND (protein_sequence:?1 OR submitted_accession:?1 OR accession:?1 OR ambiguity_group:?1)") FacetPage<ProteinIdentification> findByAssayAccessionFacet(String assayAccession, String term, Pageable pageable); @Facet(fields = {"mod_names"}, limit = 100) @Query(value = "assay_accession:?0", filters = "mod_names:(?1)", defaultOperator = AND) FacetPage<ProteinIdentification> findByAssayAccessionFacetAndFilterModNames(String assayAccession, List<String> modNameFilters, Pageable pageable); @Facet(fields = {"mod_names"}, limit = 100) @Query(value = "assay_accession:?0 AND (protein_sequence:?1 OR submitted_accession:?1 OR accession:?1 OR ambiguity_group:?1)", filters = "mod_names:(?2)", defaultOperator = AND) FacetPage<ProteinIdentification> findByAssayAccessionFacetAndFilterModNames(String assayAccession, String term, List<String> modNameFilters, Pageable pageable); // Submitted accession query methods @Query("submitted_accession:?0 AND assay_accession:?0") List<ProteinIdentification> findBySubmittedAccessionAndAssayAccession(String submitedAccession, String assayAccession); // Queries with Projections @Query(value = "project_accession:?0", fields = { "accession" }) List<ProteinIdentificationSummary> findSummaryByProjectAccession(String projectAccession); @Query(value = "assay_accession:?0", fields = { "accession" }) List<ProteinIdentificationSummary> findSummaryByAssayAccession(String assayAccession); }
package fr.inra.maiage.bibliome.alvisnlp.bibliomefactory.modules.tees; import java.io.File; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import fr.inra.maiage.bibliome.alvisnlp.bibliomefactory.modules.tees.CorpusTEES.Document.Sentence; import fr.inra.maiage.bibliome.alvisnlp.bibliomefactory.modules.tees.CorpusTEES.Document.Sentence.Entity; import fr.inra.maiage.bibliome.alvisnlp.bibliomefactory.modules.tees.CorpusTEES.Document.Sentence.Interaction; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.Annotation; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.Corpus; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.Document; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.DownCastElement; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.Element; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.Layer; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.Relation; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.Section; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.Tuple; import fr.inra.maiage.bibliome.alvisnlp.core.corpus.expressions.EvaluationContext; import fr.inra.maiage.bibliome.alvisnlp.core.module.ProcessingContext; import fr.inra.maiage.bibliome.alvisnlp.core.module.ProcessingException; import fr.inra.maiage.bibliome.alvisnlp.core.module.lib.ExternalHandler; import fr.inra.maiage.bibliome.alvisnlp.core.module.types.MultiMapping; import fr.inra.maiage.bibliome.util.Iterators; abstract class TEESMapperExternalHandler<T extends TEESMapper> extends ExternalHandler<Corpus,T> { private final Map<String,CorpusTEES> corpora = new LinkedHashMap<String,CorpusTEES>(); private final Map<String,Section> sentId2Sections = new LinkedHashMap<String,Section>(); private final Map<String,Element> entId2Elements = new LinkedHashMap<String,Element>(); private final Map<String,String> origId2teesId = new LinkedHashMap<String,String>(); protected TEESMapperExternalHandler(ProcessingContext<Corpus> processingContext, T module, Corpus annotable) { super(processingContext, module, annotable); } protected void createTheTeesCorpus() { Logger logger = getLogger(); EvaluationContext evalCtx = new EvaluationContext(logger); TEESMapper owner = getModule(); logger.info("Creating TEES input files"); for (Document documentAlvis : Iterators.loop(owner.documentIterator(evalCtx, getAnnotable()))) { String set = getSet(documentAlvis); CorpusTEES corpus = getCorpus(set); CorpusTEES.Document documentTees = new CorpusTEES.Document(); documentTees.setId("ALVIS.d" + corpus.getDocument().size()); Iterator<Section> alvisSectionsIterator = owner.sectionIterator(evalCtx, documentAlvis); createTheTeesSentences(documentTees.getSentence(), documentTees.getId(), alvisSectionsIterator); corpus.getDocument().add(documentTees); } } protected abstract String getSet(Document doc); protected CorpusTEES getCorpus(String set) { if (corpora.containsKey(set)) { return corpora.get(set); } CorpusTEES result = new CorpusTEES(); corpora.put(set, result); return result; } private List<CorpusTEES.Document.Sentence> createTheTeesSentences(List<CorpusTEES.Document.Sentence> sentences, String docId, Iterator<Section> alvisSectionsIterator) { int sentId = 0; TEESMapper owner = getModule(); for (Section sectionAlvis : Iterators.loop(alvisSectionsIterator)) { for (Layer sentLayer : sectionAlvis.getSentences(owner.getTokenLayerName(), owner.getSentenceLayerName())) { Annotation sentenceAlvis = sentLayer.getSentenceAnnotation(); if(sentenceAlvis == null) { continue; } // create a Tees sentence CorpusTEES.Document.Sentence sentenceTees = new CorpusTEES.Document.Sentence(); sentenceTees.setId(docId + ".s" + sentId++); sentenceTees.setText(sentenceAlvis.getForm()); sentenceTees.setCharOffset(sentenceAlvis.getStart() + "-" + sentenceAlvis.getEnd()); // add the TEES entities // logger.info("creating the TEES entities"); Layer alvisEntitiesLayer = sectionAlvis.ensureLayer(owner.getNamedEntityLayerName()); createTheTeesEntities(sentenceTees, sentenceTees.getId(), sentenceAlvis, alvisEntitiesLayer); // add the TEES interactions // logger.info("creating the TEES interactions "); createTheInteractions(sentenceTees, sentenceTees.getId(), sentenceAlvis); // add the set sentence sentences.add(sentenceTees); //sent2secId.put(sentenceTees.getId(), sectionAlvis.getStringId()); sentId2Sections.put(sentenceTees.getId(), sectionAlvis); // add the analyses TODO } } return sentences; } private void createTheTeesEntities(CorpusTEES.Document.Sentence sentenceTees, String sentId, Annotation sentenceAlvis, Layer alvisEntitiesLayer) { int entId = 0; TEESMapper owner = getModule(); // loop on entities for (Annotation entityAlvis : alvisEntitiesLayer) { if(!sentenceAlvis.includes(entityAlvis)) { continue; } // create a tees entity Entity entityTees = new CorpusTEES.Document.Sentence.Entity(); entityTees.setId(sentId + ".e" + entId++); entityTees.setOrigId(entityAlvis.getStringId()); entityTees.setCharOffset((entityAlvis.getStart()- sentenceAlvis.getStart()) + "-" + (entityAlvis.getEnd()-sentenceAlvis.getStart())); entityTees.setOrigOffset(entityAlvis.getStart() + "-" + entityAlvis.getEnd()); entityTees.setText(entityAlvis.getForm()); entityTees.setType(entityAlvis.getLastFeature(owner.getNamedEntityTypeFeature())); entityTees.setGiven(true); // add the entity sentenceTees.getEntity().add(entityTees); entId2Elements.put(entityTees.getId(), entityAlvis); origId2teesId.put(entityTees.getOrigId(), entityTees.getId()); } } private void createTheInteractions(CorpusTEES.Document.Sentence sentenceTees, String sentId, Annotation sentenceAlvis) { int intId = 0; Logger logger = getLogger(); Section sec = sentenceAlvis.getSection(); for (Map.Entry<String,String[]> e : getModule().getSchema().entrySet()) { String relName = e.getKey(); if (!sec.hasRelation(relName)) { continue; } Relation rel = sec.getRelation(relName); String[] roles = e.getValue(); for (Tuple t : rel.getTuples()) { if (!(t.hasArgument(roles[0]) && t.hasArgument(roles[1]))) { logger.warning("tuple " + t + " lacks argument"); continue; } Element arg1 = t.getArgument(roles[0]); Element arg2 = t.getArgument(roles[1]); Annotation ann1 = DownCastElement.toAnnotation(arg1); Annotation ann2 = DownCastElement.toAnnotation(arg2); // is the sentence contains the argument annotations if(!(sentenceAlvis.includes(ann1) && sentenceAlvis.includes(ann2))) { continue; } // creating interaction CorpusTEES.Document.Sentence.Interaction interaction = new CorpusTEES.Document.Sentence.Interaction(); interaction.setId(sentId + ".i" + intId++); interaction.setE1(origId2teesId.get(arg1.getStringId())); interaction.setE2(origId2teesId.get(arg2.getStringId())); interaction.setType(relName); interaction.setOrigId(t.getStringId()); interaction.setDirected(true); sentenceTees.getInteraction().add(interaction); } } } public void setRelations2CorpusAlvis(CorpusTEES corpusTEES) throws ProcessingException { for (CorpusTEES.Document docTEES : corpusTEES.getDocument()) { for (Sentence sentenceTEES : docTEES.getSentence()) { Section sectionAlvis = sentId2Sections.get(sentenceTEES.getId()); for (Entity entity : sentenceTEES.getEntity()) { String goldIds = entity.getGoldIds(); if (goldIds == null) { continue; } if (!entId2Elements.containsKey(goldIds)) { continue; } if (entId2Elements.containsKey(entity.id)) { continue; } Element elt = entId2Elements.get(goldIds); entId2Elements.put(entity.id, elt); } MultiMapping schema = getModule().getSchema(); for (Interaction interaction : sentenceTEES.getInteraction()) { String type = interaction.getType(); if (!schema.containsKey(type)) { throw new ProcessingException("TEES predicted something not in the schema: " + type); } String[] roles = schema.get(type); Relation rel = sectionAlvis.ensureRelation(getModule(), type); Tuple tuple = new Tuple(getModule(), rel); tuple.setArgument(roles[0], entId2Elements.get(interaction.getE1())); tuple.setArgument(roles[1], entId2Elements.get(interaction.getE2())); rel.addTuple(tuple); } } } } protected File getTEESPreprocessingScript() { return new File(getModule().getTeesHome(), "preprocess.py"); } }
package at.irian.ankorman.sample2.fxclient.task; import at.irian.ankor.action.Action; import at.irian.ankor.ref.Ref; import at.irian.ankor.ref.listener.RefChangeListener; import at.irian.ankor.ref.listener.RefListeners; import at.irian.ankorman.sample2.fxclient.BaseTabController; import at.irian.ankorman.sample2.viewmodel.task.Filter; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.layout.HBox; import javafx.util.Callback; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static at.irian.ankor.fx.binding.ValueBindingsBuilder.bindValue; import static at.irian.ankorman.sample2.fxclient.App.refFactory; public class TasksController extends BaseTabController { //private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(TasksController.class); @FXML public TextField newTodo; @FXML public HBox todoCount; @FXML public Label todoCountNum; @FXML public Button clearCompleted; @FXML public ListView tasksList; @FXML public Button filterAll; @FXML public Button filterActive; @FXML public Button filterCompleted; private List<Button> filterButtons = new ArrayList<Button>(); private Ref modelRef; public TasksController(String tabId) { super(tabId); } @Override public void initialize() { modelRef = getTabRef().append("model"); filterButtons.add(filterAll); filterButtons.add(filterActive); filterButtons.add(filterCompleted); String filterString = modelRef.append("filter").getValue(); Filter filterEnum = Filter.valueOf(filterString); setFilterButtonStyle(filterEnum); bindValue(modelRef.append("itemsLeft")) .toLabel(todoCountNum) .createWithin(bindingContext); bindValue(modelRef.append("tasks.rows")) .toList(tasksList) .createWithin(bindingContext); // XXX: Is there a better way to do this? Something like a "visibility variable" maybe? RefListeners.addPropChangeListener(modelRef.append("itemsLeft"), new RefChangeListener() { @Override public void processChange(Ref changedProperty) { String prop = changedProperty.getValue(); int itemsLeft = Integer.parseInt(prop); todoCount.setVisible(itemsLeft != 0); } }); RefListeners.addPropChangeListener(modelRef.append("filter"), new RefChangeListener() { @Override public void processChange(Ref changedProperty) { String prop = changedProperty.getValue(); Filter filterEnum = Filter.valueOf(prop); setFilterButtonStyle(filterEnum); } }); /* TaskComponent test = new TaskComponent(); test.setText("Dynamically created Task"); test.getCompleted().setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { System.out.println("The button was clicked! 2"); } }); tasks.getItems().add(test); tasks.getItems().add(new TaskComponent()); tasks.getItems().add(new TaskComponent()); getTabRef().append("model").append("itemsLeft").setValue(String.valueOf(tasks.getItems().size())); */ Platform.runLater(new Runnable() { @Override public void run() { newTodo.requestFocus(); } }); } private void setFilterButtonStyle(Filter filter) { for (Button b : filterButtons) { b.setStyle("-fx-font-weight: normal;"); } switch (filter) { case all: filterAll.setStyle("-fx-font-weight: bold;"); break; case active: filterActive.setStyle("-fx-font-weight: bold;"); break; case completed: filterCompleted.setStyle("-fx-font-weight: bold;"); break; } } @FXML public void newTodo(ActionEvent actionEvent) { if (!newTodo.getText().equals("")) { HashMap<String, Object> params = new HashMap<>(); params.put("title", newTodo.getText()); modelRef.fireAction(new Action("newTodo", params)); newTodo.clear(); String itemsLeftValue = modelRef.append("itemsLeft").getValue(); int itemsLeft = Integer.parseInt(itemsLeftValue); modelRef.append("itemsLeft").setValue(String.valueOf(itemsLeft + 1)); } } @FXML public void displayAll(ActionEvent actionEvent) { modelRef.append("filter").setValue(Filter.all.toString()); } @FXML public void displayActive(ActionEvent actionEvent) { modelRef.append("filter").setValue(Filter.active.toString()); } @FXML public void displayCompleted(ActionEvent actionEvent) { modelRef.append("filter").setValue(Filter.completed.toString()); } // XXX @Override public Ref getTabRef() { Ref rootRef = refFactory().rootRef(); return rootRef.append(String.format("tabsTask.%s", tabId)); } }
package org.vitrivr.cineast.standalone.importer.vbs2019.v3c1analysis; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.vitrivr.cineast.core.features.SegmentTags; import org.vitrivr.cineast.core.features.TagsFtSearch; import org.vitrivr.cineast.core.util.LogHelper; import org.vitrivr.cineast.standalone.importer.handlers.DataImportHandler; public class ClassificationsImportHandler extends DataImportHandler { private static final Logger LOGGER = LogManager.getLogger(); public ClassificationsImportHandler(int threads, int batchsize) { super(threads, batchsize); } @Override public void doImport(Path root) { try { LOGGER.info("Starting data import for classification files in: {} with {} threads and {} batchsize", root.toString(), this.numberOfThreads, this.batchsize); Path synset = root.resolve("synset.txt"); Files.walk(root.resolve("aggregate"), 2).filter(p -> p.toString().toLowerCase().endsWith(".json")).forEach(p -> { try { // TODO ? this.futures.add(this.service.submit(new DataImportRunner(new ClassificationsImporter(p, true), TagReader.TAG_ENTITY_NAME, "classification import synset tags"))); //this.futures.add(this.service.submit(new DataImportRunner(new ClassificationsImporter(p, synset, false, false), SegmentTags.SEGMENT_TAGS_TABLE_NAME, "classification import classifications"))); this.futures.add(this.service.submit(new DataImportRunner(new ClassificationsImporter(p, synset, false, true), TagsFtSearch.TAGS_FT_TABLE_NAME, "import classifications "+p.getFileName().toString()))); } catch (IOException e) { LOGGER.fatal("Failed to open path at {} ", p); throw new RuntimeException(e); } }); this.waitForCompletion(); LOGGER.info("Completed data import with classification Import files in: {}", root.toString()); } catch (IOException e) { LOGGER.error("Could not start data import process with path '{}' due to an IOException: {}. Aborting...", root.toString(), LogHelper.getStackTrace(e)); } } }
package io.quarkus.kubernetes.client.deployment; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.jandex.Type; import org.jboss.logging.Logger; import io.quarkus.arc.deployment.AdditionalBeanBuildItem; import io.quarkus.deployment.Capabilities; import io.quarkus.deployment.Capability; import io.quarkus.deployment.Feature; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.ApplicationIndexBuildItem; import io.quarkus.deployment.builditem.CombinedIndexBuildItem; import io.quarkus.deployment.builditem.ExtensionSslNativeSupportBuildItem; import io.quarkus.deployment.builditem.FeatureBuildItem; import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem; import io.quarkus.deployment.builditem.nativeimage.ReflectiveHierarchyBuildItem; import io.quarkus.deployment.util.JandexUtil; import io.quarkus.jackson.deployment.IgnoreJsonDeserializeClassBuildItem; import io.quarkus.kubernetes.client.runtime.KubernetesClientProducer; import io.quarkus.kubernetes.client.runtime.KubernetesConfigProducer; import io.quarkus.kubernetes.spi.KubernetesRoleBindingBuildItem; public class KubernetesClientProcessor { private static final DotName WATCHER = DotName.createSimple("io.fabric8.kubernetes.client.Watcher"); private static final DotName RESOURCE_EVENT_HANDLER = DotName .createSimple("io.fabric8.kubernetes.client.informers.ResourceEventHandler"); private static final DotName KUBERNETES_RESOURCE = DotName .createSimple("io.fabric8.kubernetes.api.model.KubernetesResource"); private static final Logger log = Logger.getLogger(KubernetesClientProcessor.class.getName()); private static final Predicate<DotName> IS_OKHTTP_CLASS = d -> d.toString().startsWith("okhttp3"); @BuildStep public void registerBeanProducers(BuildProducer<AdditionalBeanBuildItem> additionalBeanBuildItemBuildItem, Capabilities capabilities) { // wire up the Config bean support additionalBeanBuildItemBuildItem.produce(AdditionalBeanBuildItem.unremovableOf(KubernetesConfigProducer.class)); // do not register our client producer if the openshift client is present, because it provides it too if (capabilities.isMissing(Capability.OPENSHIFT_CLIENT)) { // wire up the KubernetesClient bean support additionalBeanBuildItemBuildItem.produce(AdditionalBeanBuildItem.unremovableOf(KubernetesClientProducer.class)); } } @BuildStep public void process(ApplicationIndexBuildItem applicationIndex, CombinedIndexBuildItem combinedIndexBuildItem, BuildProducer<ExtensionSslNativeSupportBuildItem> sslNativeSupport, BuildProducer<FeatureBuildItem> featureProducer, BuildProducer<ReflectiveClassBuildItem> reflectiveClasses, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchies, BuildProducer<IgnoreJsonDeserializeClassBuildItem> ignoredJsonDeserializationClasses, BuildProducer<KubernetesRoleBindingBuildItem> roleBindingProducer) { featureProducer.produce(new FeatureBuildItem(Feature.KUBERNETES_CLIENT)); roleBindingProducer.produce(new KubernetesRoleBindingBuildItem("view", true)); // make sure the watchers fully (and not weakly) register Kubernetes classes for reflection final Set<DotName> watchedClasses = new HashSet<>(); findWatchedClasses(WATCHER, applicationIndex, combinedIndexBuildItem, watchedClasses); findWatchedClasses(RESOURCE_EVENT_HANDLER, applicationIndex, combinedIndexBuildItem, watchedClasses); Predicate<DotName> reflectionIgnorePredicate = ReflectiveHierarchyBuildItem.DefaultIgnoreTypePredicate.INSTANCE .or(IS_OKHTTP_CLASS); for (DotName className : watchedClasses) { if (reflectionIgnorePredicate.test(className)) { continue; } final ClassInfo watchedClass = combinedIndexBuildItem.getIndex().getClassByName(className); if (watchedClass == null) { log.warnv("Unable to lookup class: {0}", className); } else { reflectiveHierarchies .produce(new ReflectiveHierarchyBuildItem.Builder() .type(Type.create(watchedClass.name(), Type.Kind.CLASS)) .ignoreTypePredicate(reflectionIgnorePredicate) .source(getClass().getSimpleName() + " > " + watchedClass.name()) .build()); } } final String[] modelClasses = combinedIndexBuildItem.getIndex() .getAllKnownImplementors(KUBERNETES_RESOURCE) .stream() .peek(c -> { // we need to make sure that the Jackson extension does not try to fully register the model classes // since we are going to register them weakly ignoredJsonDeserializationClasses.produce(new IgnoreJsonDeserializeClassBuildItem(c.name())); }) .map(ClassInfo::name) .filter(c -> !watchedClasses.contains(c)) .map(Object::toString) .toArray(String[]::new); reflectiveClasses.produce(ReflectiveClassBuildItem .builder(modelClasses).weak(true).methods(true).fields(false).build()); // we also ignore some classes that are annotated with @JsonDeserialize that would force the registration of the entire model ignoredJsonDeserializationClasses.produce( new IgnoreJsonDeserializeClassBuildItem(DotName.createSimple("io.fabric8.kubernetes.api.model.KubeSchema"))); ignoredJsonDeserializationClasses.produce( new IgnoreJsonDeserializeClassBuildItem( DotName.createSimple("io.fabric8.kubernetes.api.model.KubernetesResourceList"))); ignoredJsonDeserializationClasses.produce(new IgnoreJsonDeserializeClassBuildItem(KUBERNETES_RESOURCE)); final String[] deserializerClasses = combinedIndexBuildItem.getIndex() .getAllKnownSubclasses(DotName.createSimple("com.fasterxml.jackson.databind.JsonDeserializer")) .stream() .map(c -> c.name().toString()) .filter(s -> s.startsWith("io.fabric8.kubernetes")) .toArray(String[]::new); reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, deserializerClasses)); final String[] serializerClasses = combinedIndexBuildItem.getIndex() .getAllKnownSubclasses(DotName.createSimple("com.fasterxml.jackson.databind.JsonSerializer")) .stream() .map(c -> c.name().toString()) .filter(s -> s.startsWith("io.fabric8.kubernetes")) .toArray(String[]::new); reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, serializerClasses)); reflectiveClasses .produce(new ReflectiveClassBuildItem(true, false, "io.fabric8.kubernetes.api.model.IntOrString")); reflectiveClasses .produce(new ReflectiveClassBuildItem(true, false, "io.fabric8.kubernetes.internal.KubernetesDeserializer")); if (log.isDebugEnabled()) { final String watchedClassNames = watchedClasses .stream().map(Object::toString) .sorted() .collect(Collectors.joining("\n")); log.debugv("Watched Classes:\n{0}", watchedClassNames); Arrays.sort(modelClasses); log.debugv("Model Classes:\n{0}", String.join("\n", modelClasses)); } // Enable SSL support by default sslNativeSupport.produce(new ExtensionSslNativeSupportBuildItem(Feature.KUBERNETES_CLIENT)); } private void findWatchedClasses(final DotName implementor, final ApplicationIndexBuildItem applicationIndex, final CombinedIndexBuildItem combinedIndexBuildItem, final Set<DotName> watchedClasses) { applicationIndex.getIndex().getAllKnownImplementors(implementor) .forEach(c -> { try { final List<Type> watcherGenericTypes = JandexUtil.resolveTypeParameters(c.name(), implementor, combinedIndexBuildItem.getIndex()); if (watcherGenericTypes.size() == 1) { watchedClasses.add(watcherGenericTypes.get(0).name()); } } catch (IllegalArgumentException ignored) { // when the class has no subclasses and we were not able to determine the generic types, it's likely that // the watcher will fail due to not being able to deserialize the class if (applicationIndex.getIndex().getAllKnownSubclasses(c.name()).isEmpty()) { log.warnv("{0} '{1}' will most likely not work correctly in native mode. " + "Consider specifying the generic type of '{2}' that this class handles. " + "See https://quarkus.io/guides/kubernetes-client#note-on-implementing-the-watcher-interface for more details", implementor.local(), c.name(), implementor); } } }); } }
package org.ovirt.engine.ui.uicommonweb.builders.vm; import java.util.ArrayList; import java.util.List; import org.ovirt.engine.core.common.businessentities.VmBase; import org.ovirt.engine.core.common.businessentities.VmNumaNode; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.ui.uicommonweb.builders.BaseSyncBuilder; import org.ovirt.engine.ui.uicommonweb.models.vms.UnitVmModel; public class NumaUnitToVmBaseBuilder<T extends VmBase> extends BaseSyncBuilder<UnitVmModel, T> { @Override protected void build(UnitVmModel model, VmBase vm) { // Tune Mode: vm.setNumaTuneMode(model.getNumaTuneMode().getSelectedItem()); // Virtual nodes: Integer nodeCount = model.getNumaNodeCount().getEntity(); // clear NUMA nodes if (nodeCount == null || nodeCount == 0) { vm.setvNumaNodeList(null); } else { List<VmNumaNode> nodeList = null; if (model.getVmNumaNodes() != null && nodeCount == model.getVmNumaNodes().size()) { nodeList = model.getVmNumaNodes(); } else { nodeList = new ArrayList<VmNumaNode>(nodeCount); for (int i = 0; i < nodeCount; i++) { VmNumaNode newNode = new VmNumaNode(); newNode.setIndex(i); nodeList.add(newNode); } } Integer cpuCount = 0; for (int i = 0; i < nodeList.size(); i++) { VmNumaNode vmNumaNode = nodeList.get(i); updateMemory(vmNumaNode, model.getMemSize().getEntity() / nodeCount); cpuCount = updateCpus(vmNumaNode, Integer.parseInt(model.getTotalCPUCores().getEntity()) / nodeCount, cpuCount); updateNumaPinning(vmNumaNode, i); } vm.setvNumaNodeList(nodeList); } } private void updateMemory(VmNumaNode vmNumaNode, int memSize) { vmNumaNode.setMemTotal(memSize); } private Integer updateCpus(VmNumaNode vmNumaNode, int coresPerNode, Integer cpuCount) { List<Integer> coreList = new ArrayList<Integer>(); for (int j = 0; j < coresPerNode; j++, cpuCount++) { coreList.add(cpuCount); } vmNumaNode.setCpuIds(coreList); return cpuCount; } private void updateNumaPinning(VmNumaNode vmNumaNode, int index) { if (vmNumaNode.getVdsNumaNodeList() == null) { ArrayList<Pair<Guid, Pair<Boolean, Integer>>> list = new ArrayList<Pair<Guid, Pair<Boolean, Integer>>>(); Pair<Guid, Pair<Boolean, Integer>> pair = new Pair<Guid, Pair<Boolean, Integer>>(); pair.setSecond(new Pair<Boolean, Integer>(false, index)); list.add(pair); vmNumaNode.setVdsNumaNodeList(list); } } }
package org.ovirt.engine.ui.uicommonweb.models.networks; 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.Set; import org.ovirt.engine.core.common.action.AddNetworkStoragePoolParameters; import org.ovirt.engine.core.common.action.AttachNetworkToVdsGroupParameter; import org.ovirt.engine.core.common.action.VdcActionParametersBase; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.action.VnicProfileParameters; import org.ovirt.engine.core.common.businessentities.Provider; import org.ovirt.engine.core.common.businessentities.StoragePool; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.comparators.NameableComparator; import org.ovirt.engine.core.common.businessentities.network.Network; import org.ovirt.engine.core.common.businessentities.network.NetworkCluster; import org.ovirt.engine.core.common.businessentities.network.VnicProfile; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.StringHelper; import org.ovirt.engine.ui.frontend.AsyncQuery; import org.ovirt.engine.ui.frontend.Frontend; import org.ovirt.engine.ui.frontend.INewAsyncCallback; import org.ovirt.engine.ui.uicommonweb.Linq; import org.ovirt.engine.ui.uicommonweb.UICommand; import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider; import org.ovirt.engine.ui.uicommonweb.models.ListModel; import org.ovirt.engine.ui.uicommonweb.models.Model; import org.ovirt.engine.ui.uicommonweb.models.SearchableListModel; import org.ovirt.engine.ui.uicommonweb.models.providers.ExternalNetwork; import org.ovirt.engine.ui.uicompat.ConstantsManager; import org.ovirt.engine.ui.uicompat.Event; import org.ovirt.engine.ui.uicompat.EventArgs; import org.ovirt.engine.ui.uicompat.FrontendActionAsyncResult; import org.ovirt.engine.ui.uicompat.IEventListener; import org.ovirt.engine.ui.uicompat.IFrontendActionAsyncCallback; public class ImportNetworksModel extends Model { private static final String CMD_IMPORT = "OnImport"; //$NON-NLS-1$ private static final String CMD_CANCEL = "Cancel"; //$NON-NLS-1$ private final SearchableListModel sourceListModel; private final ListModel providers = new ListModel(); private final ListModel providerNetworks = new ListModel(); private final ListModel importedNetworks = new ListModel(); private UICommand addImportCommand = new UICommand(null, this); private UICommand cancelImportCommand = new UICommand(null, this); private Map<Guid, Collection<VDSGroup>> dcClusters; public ListModel getProviderNetworks() { return providerNetworks; } public ListModel getImportedNetworks() { return importedNetworks; } public ListModel getProviders() { return providers; } public UICommand getAddImportCommand() { return addImportCommand; } public UICommand getCancelImportCommand() { return cancelImportCommand; } public ImportNetworksModel(SearchableListModel sourceListModel) { this.sourceListModel = sourceListModel; setTitle(ConstantsManager.getInstance().getConstants().importNetworksTitle()); setHashName("import_networks"); //$NON-NLS-1$ UICommand importCommand = new UICommand(CMD_IMPORT, this); importCommand.setIsExecutionAllowed(false); importCommand.setTitle(ConstantsManager.getInstance().getConstants().importNetworksButton()); importCommand.setIsDefault(true); getCommands().add(importCommand); UICommand cancelCommand = new UICommand(CMD_CANCEL, this); cancelCommand.setTitle(ConstantsManager.getInstance().getConstants().cancel()); cancelCommand.setIsCancel(true); getCommands().add(cancelCommand); providers.getSelectedItemChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { onProviderChosen(); } }); initProviderList(); } protected void initProviderList() { startProgress(null); AsyncDataProvider.getAllNetworkProviders(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { stopProgress(); List<Provider> providers = (List<Provider>) returnValue; providers.add(0, null); getProviders().setItems(providers); } })); } private void onProviderChosen() { final Provider provider = (Provider) providers.getSelectedItem(); if (provider == null) { return; } final List<StoragePool> dataCenters = new LinkedList<StoragePool>(); final AsyncQuery networkQuery = new AsyncQuery(); networkQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { Map<Network, Set<Guid>> externalNetworkToDataCenters = (Map<Network, Set<Guid>>) returnValue; List<ExternalNetwork> items = new LinkedList<ExternalNetwork>(); for (Map.Entry<Network, Set<Guid>> entry : externalNetworkToDataCenters.entrySet()) { Network network = entry.getKey(); Set<Guid> attachedDataCenters = entry.getValue(); ExternalNetwork externalNetwork = new ExternalNetwork(); externalNetwork.setNetwork(network); externalNetwork.setDisplayName(network.getName()); externalNetwork.setPublicUse(true); List<StoragePool> availableDataCenters = new LinkedList<StoragePool>(); for (StoragePool dc : dataCenters) { if (!attachedDataCenters.contains(dc.getId())) { availableDataCenters.add(dc); } } externalNetwork.getDataCenters().setItems(availableDataCenters); externalNetwork.getDataCenters().setSelectedItem(Linq.firstOrDefault(availableDataCenters)); items.add(externalNetwork); } Collections.sort(items, new Linq.ExternalNetworkComparator()); providerNetworks.setItems(items); importedNetworks.setItems(new LinkedList<ExternalNetwork>()); stopProgress(); } }; final AsyncQuery dcQuery = new AsyncQuery(); dcQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { dataCenters.addAll((Collection<StoragePool>) returnValue); Collections.sort(dataCenters, new NameableComparator()); AsyncDataProvider.getExternalNetworkMap(networkQuery, provider.getId()); } }; startProgress(null); AsyncDataProvider.getDataCenterList(dcQuery); } public void cancel() { sourceListModel.setWindow(null); } public void onImport() { List<VdcActionParametersBase> multipleActionParameters = new LinkedList<VdcActionParametersBase>(); List<IFrontendActionAsyncCallback> callbacks = new LinkedList<IFrontendActionAsyncCallback>(); dcClusters = new HashMap<Guid, Collection<VDSGroup>>(); for (final ExternalNetwork externalNetwork : (Iterable<ExternalNetwork>) importedNetworks.getItems()) { final Network network = externalNetwork.getNetwork(); final Guid dcId = ((StoragePool) externalNetwork.getDataCenters().getSelectedItem()).getId(); network.setName(externalNetwork.getDisplayName()); network.setDataCenterId(dcId); AddNetworkStoragePoolParameters params = new AddNetworkStoragePoolParameters(dcId, network); params.setVnicProfileRequired(false); multipleActionParameters.add(params); callbacks.add(new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { VdcReturnValueBase returnValue = result.getReturnValue(); if (returnValue != null && returnValue.getSucceeded()) { network.setId((Guid) returnValue.getActionReturnValue()); // Perform sequentially: first fetch clusters, then attach network, then create VNIC profile fetchDcClusters(dcId, network, externalNetwork.isPublicUse()); } } }); } Frontend.RunMultipleActions(VdcActionType.AddNetwork, multipleActionParameters, callbacks); cancel(); } private void fetchDcClusters(final Guid dcId, final Network network, final boolean publicUse) { if (dcClusters.containsKey(dcId)) { attachNetworkToClusters(network, dcClusters.get(dcId), publicUse); } else { AsyncDataProvider.getClusterList(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { Collection<VDSGroup> clusters = (Collection<VDSGroup>) returnValue; dcClusters.put(dcId, clusters); attachNetworkToClusters(network, clusters, publicUse); } }), dcId); } } private void attachNetworkToClusters(final Network network, Collection<VDSGroup> clusters, final boolean publicUse) { NetworkCluster networkCluster = new NetworkCluster(); networkCluster.setRequired(false); network.setCluster(networkCluster); List<VdcActionParametersBase> parameters = new LinkedList<VdcActionParametersBase>(); for (VDSGroup cluster : clusters) { parameters.add(new AttachNetworkToVdsGroupParameter(cluster, network)); } Frontend.RunMultipleActions(VdcActionType.AttachNetworkToVdsGroup, parameters, new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { addVnicProfile(network, publicUse); } }); } private void addVnicProfile(Network network, boolean publicUse) { VnicProfile vnicProfile = new VnicProfile(); vnicProfile.setName(network.getName()); vnicProfile.setNetworkId(network.getId()); VnicProfileParameters parameters = new VnicProfileParameters(vnicProfile); parameters.setPublicUse(publicUse); Frontend.RunAction(VdcActionType.AddVnicProfile, parameters, new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { sourceListModel.getSearchCommand().execute(); } }); } private void addImport() { getDefaultCommand().setIsExecutionAllowed(true); } private void cancelImport() { List<ExternalNetwork> selectedNetworks = (List<ExternalNetwork>) getImportedNetworks().getSelectedItems(); Collection<ExternalNetwork> importedNetworks = (Collection<ExternalNetwork>) getImportedNetworks().getItems(); getDefaultCommand().setIsExecutionAllowed(selectedNetworks.size() < importedNetworks.size()); for (ExternalNetwork externalNetwork : selectedNetworks) { externalNetwork.setDisplayName(externalNetwork.getNetwork().getName()); } } @Override public void executeCommand(UICommand command) { super.executeCommand(command); if (StringHelper.stringsEqual(command.getName(), CMD_IMPORT)) { onImport(); } else if (StringHelper.stringsEqual(command.getName(), CMD_CANCEL)) { cancel(); } else if (getAddImportCommand().equals(command)) { addImport(); } else if (getCancelImportCommand().equals(command)) { cancelImport(); } } }
package no.uio.ifi.alboc.chargenerator; /* * module CharGenerator */ import java.io.*; import no.uio.ifi.alboc.alboc.AlboC; import no.uio.ifi.alboc.error.Error; import no.uio.ifi.alboc.log.Log; /* * Module for reading single characters. */ public class CharGenerator { public static char curC, nextC; private static LineNumberReader sourceFile = null; private static String sourceLine; private static int sourcePos; private static int sourceLength; public static void init() { try { sourceFile = new LineNumberReader(new FileReader(AlboC.sourceName)); } catch (FileNotFoundException e) { Error.error("Cannot read " + AlboC.sourceName + "!"); } sourceLine = ""; sourcePos = 0; curC = nextC = ' '; readNext(); readNext(); } public static void finish() { if (sourceFile != null) { try { sourceFile.close(); } catch (IOException e) { Error.error("Could not close source file!"); } } } public static boolean isMoreToRead() { return false; } public static int curLineNum() { return (sourceFile == null ? 0 : sourceFile.getLineNumber()); } public static void readNext() { curC = nextC; if (!isMoreToRead()) return; try { if (sourcePos == sourceLine.length()){ nextC = sourceLine.charAt(sourcePos); sourcePos++; sourceLine = sourceFile.readLine(); if(sourceLine.charAt(0) == ' sourceLine = sourceFile.readLine(); sourcePos = 0; } nextC = sourceLine.charAt(sourcePos); sourcePos++; } catch (Exception e) { e.printStackTrace(); } } }
package org.pocketcampus.plugin.freeroom.server.tests; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.HttpURLConnection; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Set; import junit.framework.Assert; import org.apache.commons.io.IOUtils; import org.apache.thrift.TException; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.pocketcampus.platform.sdk.server.database.ConnectionManager; import org.pocketcampus.platform.sdk.server.database.handlers.exceptions.ServerException; import org.pocketcampus.plugin.freeroom.android.utils.Converter; import org.pocketcampus.plugin.freeroom.server.FreeRoomServiceImpl; import org.pocketcampus.plugin.freeroom.shared.ActualOccupation; import org.pocketcampus.plugin.freeroom.shared.FRPeriod; import org.pocketcampus.plugin.freeroom.shared.FRRoom; import org.pocketcampus.plugin.freeroom.shared.FreeRoomReply; import org.pocketcampus.plugin.freeroom.shared.FreeRoomRequest; import org.pocketcampus.plugin.freeroom.shared.Occupancy; import org.pocketcampus.plugin.freeroom.shared.OccupancyReply; import org.pocketcampus.plugin.freeroom.shared.OccupancyRequest; import org.pocketcampus.plugin.freeroom.shared.OccupationType; /** * TESTS - Check Occupancy feature. * * @author FreeFroom Project Team - Julien WEBER <julien.weber@epfl.ch> and * Valentin MINDER <valentin.minder@epfl.ch> * */ public class TestFreeRoomSearchAndOccupancy { final static String DB_USERNAME = "root"; final static String DB_PASSWORD = "root"; final static String DBMS_URL = "jdbc:mysql://localhost/?allowMultiQueries=true"; final static String DB_URL = "jdbc:mysql://localhost/pocketcampustest?allowMultiQueries=true"; final static long ONE_HOUR_MS = 3600 * 1000; // we allow a margin for error final static long MARGIN_ERROR_MS = 60 * 1000; private Connection conn = null; public static void createDBTest() { Connection conn = null; PreparedStatement pstmt = null; try { conn = DriverManager.getConnection(DBMS_URL, DB_USERNAME, DB_PASSWORD); PreparedStatement stmt = conn .prepareStatement("CREATE DATABASE IF NOT EXISTS pocketcampustest"); stmt.execute(); conn.setCatalog("pocketcampustest"); File dbFile = new File( "src/org/pocketcampus/plugin/freeroom/server/tests/testdb-create.sql"); String query = IOUtils.toString(new FileReader(dbFile)); pstmt = conn.prepareStatement(query); pstmt.execute(); pstmt.close(); // TODO: check that the database and two tables are successfully // created ? } catch (SQLException e) { Assert.fail("There was an SQL Exception \n " + e); } catch (FileNotFoundException e) { Assert.fail("Thee test file for the database was not found \n " + e); } catch (IOException e) { Assert.fail("There was another IO Exception \n " + e); } } public static void removeDBTest() { Connection conn = null; try { conn = DriverManager.getConnection(DBMS_URL, DB_USERNAME, DB_PASSWORD); PreparedStatement stmt = conn .prepareStatement("DROP DATABASE pocketcampustest"); stmt.execute(); stmt.close(); // TODO : check that the database is successfully deleted ? } catch (SQLException e) { Assert.fail("There was an SQL Exception \n " + e); } } @BeforeClass public static void setUpBeforeClass() { createDBTest(); populate(); } @AfterClass public static void tearDownAfterClass() { // TODO: tests should remove their databases and tables, comment it if // you want to see them in SQL removeDBTest(); } @Before public void setUp() { try { conn = DriverManager.getConnection(DBMS_URL, DB_USERNAME, DB_PASSWORD); conn.setCatalog("pocketcampustest"); } catch (SQLException e) { Assert.fail("There was an SQL Exception \n " + e); } } @After public void tearDown() { try { conn.close(); } catch (SQLException e) { Assert.fail("There was an SQL Exception \n " + e); } } public static void populate() { Connection conn = null; try { conn = DriverManager .getConnection(DB_URL, DB_USERNAME, DB_PASSWORD); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); // return; } ArrayList<FRRoom> rooms = new ArrayList<FRRoom>(); rooms.add(new FRRoom("CO", "1")); rooms.add(new FRRoom("CO", "2")); rooms.add(new FRRoom("CO", "3")); rooms.add(new FRRoom("CM", "1")); rooms.add(new FRRoom("CM", "2")); rooms.add(new FRRoom("CM", "3")); ArrayList<ArrayList<FreeRoomRequest>> globalAL = new ArrayList<ArrayList<FreeRoomRequest>>(); ArrayList<FreeRoomRequest> requestco1 = new ArrayList<FreeRoomRequest>(); ArrayList<FreeRoomRequest> requestco2 = new ArrayList<FreeRoomRequest>(); ArrayList<FreeRoomRequest> requestco3 = new ArrayList<FreeRoomRequest>(); ArrayList<FreeRoomRequest> requestcm1 = new ArrayList<FreeRoomRequest>(); ArrayList<FreeRoomRequest> requestcm2 = new ArrayList<FreeRoomRequest>(); ArrayList<FreeRoomRequest> requestcm3 = new ArrayList<FreeRoomRequest>(); globalAL.add(requestco1); globalAL.add(requestco2); globalAL.add(requestco3); globalAL.add(requestcm1); globalAL.add(requestcm2); globalAL.add(requestcm3); // CO1 occupancies requestco1.add(Converter.convert(Calendar.MONDAY, 8, 9)); requestco1.add(Converter.convert(Calendar.THURSDAY, 12, 13)); // CO2 requestco2.add(Converter.convert(Calendar.MONDAY, 11, 12)); requestco2.add(Converter.convert(Calendar.WEDNESDAY, 8, 12)); // CO3 requestco3.add(Converter.convert(Calendar.MONDAY, 15, 16)); requestco3.add(Converter.convert(Calendar.TUESDAY, 15, 16)); requestco3.add(Converter.convert(Calendar.THURSDAY, 10, 11)); // CM1 requestcm1.add(Converter.convert(Calendar.MONDAY, 8, 9)); requestcm1.add(Converter.convert(Calendar.MONDAY, 10, 12)); requestcm1.add(Converter.convert(Calendar.WEDNESDAY, 8, 9)); // CM2 requestcm2.add(Converter.convert(Calendar.MONDAY, 15, 16)); requestcm2.add(Converter.convert(Calendar.TUESDAY, 12, 14)); // CM3 requestcm3.add(Converter.convert(Calendar.MONDAY, 15, 16)); requestcm3.add(Converter.convert(Calendar.WEDNESDAY, 10, 11)); // insert the rooms for (FRRoom r : rooms) { String req = "INSERT INTO roomslist(building, room_number, type, capacity) VALUES(?, ?, ?, ?)"; PreparedStatement query; try { query = conn.prepareStatement(req); // filling the query with values query.setString(1, r.getBuilding()); query.setInt(2, Integer.parseInt(r.getNumber())); query.setString(3, "AUDITORIUM"); query.setInt(4, 100); query.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } int i = 0; for (ArrayList<FreeRoomRequest> r : globalAL) { i++; for (FreeRoomRequest frreq : r) { String req = "INSERT INTO roomsoccupancy (rid, timestampStart, timestampEnd) VALUES(?, ?, ?)"; PreparedStatement query; try { query = conn.prepareStatement(req); // filling the query with values query.setInt(1, i); query.setLong(2, frreq.getPeriod().getTimeStampStart()); query.setLong(3, frreq.getPeriod().getTimeStampEnd()); query.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } @Test public void testOccupancyMonday8_12CO1() { try { FreeRoomServiceImpl server = new FreeRoomServiceImpl( new ConnectionManager(DB_URL, DB_USERNAME, DB_PASSWORD)); ArrayList<FRRoom> roomsList = new ArrayList<FRRoom>(); FRPeriod period = new FRPeriod(); OccupancyRequest request = null; OccupancyReply reply = null; // test1 roomsList.add(new FRRoom("CO", "1")); period = Converter.convert(Calendar.MONDAY, 8, 12).getPeriod(); request = new OccupancyRequest(roomsList, period); reply = server.checkTheOccupancy(request); assertTrue(reply.getOccupancyOfRoomsSize() == 1); Occupancy mOcc = reply.getOccupancyOfRooms().get(0); FRRoom room = mOcc.getRoom(); assertTrue(room.getBuilding() .equals(roomsList.get(0).getBuilding())); assertTrue(room.getNumber().equals(roomsList.get(0).getNumber())); List<ActualOccupation> mAccOcc = mOcc.getOccupancy(); assertTrue("size = " + mAccOcc.size(), mAccOcc.size() == 2); ActualOccupation firstOcc = mAccOcc.get(0); long durationFirstOcc = firstOcc.getPeriod().getTimeStampEnd() - firstOcc.getPeriod().getTimeStampStart(); assertTrue("First occupancy has wrong start, end, duration = " + durationFirstOcc, Math.abs(durationFirstOcc - ONE_HOUR_MS) < MARGIN_ERROR_MS); assertTrue("First occupancy is not free", firstOcc.getOccupationType() != OccupationType.FREE); ActualOccupation nextOcc = mAccOcc.get(1); long durationNextOcc = nextOcc.getPeriod().getTimeStampEnd() - nextOcc.getPeriod().getTimeStampStart(); assertTrue( "Next occupancy has wrong start, end, duration = " + durationNextOcc, Math.abs(durationNextOcc - ONE_HOUR_MS * 3) < MARGIN_ERROR_MS); assertTrue("First occupancy is free", nextOcc.getOccupationType() == OccupationType.FREE); } catch (ServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testOccupancyMonday8_19CM1() { try { FreeRoomServiceImpl server = new FreeRoomServiceImpl( new ConnectionManager(DB_URL, DB_USERNAME, DB_PASSWORD)); ArrayList<FRRoom> roomsList = new ArrayList<FRRoom>(); FRPeriod period = new FRPeriod(); OccupancyRequest request = null; OccupancyReply reply = null; // test1 roomsList.add(new FRRoom("CM", "1")); period = Converter.convert(Calendar.MONDAY, 8, 19).getPeriod(); request = new OccupancyRequest(roomsList, period); reply = server.checkTheOccupancy(request); assertTrue(reply.getOccupancyOfRoomsSize() == 1); Occupancy mOcc = reply.getOccupancyOfRooms().get(0); FRRoom room = mOcc.getRoom(); assertTrue(room.getBuilding() .equals(roomsList.get(0).getBuilding())); assertTrue(room.getNumber().equals(roomsList.get(0).getNumber())); List<ActualOccupation> mAccOcc = mOcc.getOccupancy(); assertTrue("size = " + mAccOcc.size(), mAccOcc.size() == 4); ActualOccupation firstOcc = mAccOcc.get(0); long durationFirstOcc = firstOcc.getPeriod().getTimeStampEnd() - firstOcc.getPeriod().getTimeStampStart(); assertTrue("First occupancy has wrong start, end, duration = " + durationFirstOcc, Math.abs(durationFirstOcc - ONE_HOUR_MS) < MARGIN_ERROR_MS); assertTrue("First occupancy is not free", firstOcc.getOccupationType() != OccupationType.FREE); ActualOccupation nextOcc = mAccOcc.get(1); long durationNextOcc = nextOcc.getPeriod().getTimeStampEnd() - nextOcc.getPeriod().getTimeStampStart(); assertTrue("Next occupancy has wrong start, end, duration = " + durationNextOcc, Math.abs(durationNextOcc - ONE_HOUR_MS) < MARGIN_ERROR_MS); assertTrue("First occupancy is free", nextOcc.getOccupationType() == OccupationType.FREE); nextOcc = mAccOcc.get(2); durationNextOcc = nextOcc.getPeriod().getTimeStampEnd() - nextOcc.getPeriod().getTimeStampStart(); assertTrue( "Next occupancy has wrong start, end, duration = " + durationNextOcc, Math.abs(durationNextOcc - ONE_HOUR_MS * 2) < MARGIN_ERROR_MS); assertTrue("First occupancy is free", nextOcc.getOccupationType() != OccupationType.FREE); nextOcc = mAccOcc.get(3); durationNextOcc = nextOcc.getPeriod().getTimeStampEnd() - nextOcc.getPeriod().getTimeStampStart(); assertTrue( "Next occupancy has wrong start, end, duration = " + durationNextOcc, Math.abs(durationNextOcc - ONE_HOUR_MS * 7) < MARGIN_ERROR_MS); assertTrue("First occupancy is free", nextOcc.getOccupationType() == OccupationType.FREE); } catch (ServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testOccupancyTuesday8_19CM2CO3CO1() { try { FreeRoomServiceImpl server = new FreeRoomServiceImpl( new ConnectionManager(DB_URL, DB_USERNAME, DB_PASSWORD)); ArrayList<FRRoom> roomsList = new ArrayList<FRRoom>(); FRPeriod period = new FRPeriod(); OccupancyRequest request = null; OccupancyReply reply = null; // test1 roomsList.add(new FRRoom("CM", "2")); roomsList.add(new FRRoom("CO", "3")); roomsList.add(new FRRoom("C0", "1")); period = Converter.convert(Calendar.TUESDAY, 8, 19).getPeriod(); request = new OccupancyRequest(roomsList, period); reply = server.checkTheOccupancy(request); assertTrue(reply.getOccupancyOfRoomsSize() == 3); // first room is CM2 Occupancy mOcc = reply.getOccupancyOfRooms().get(0); FRRoom room = mOcc.getRoom(); assertTrue(room.getBuilding() .equals(roomsList.get(0).getBuilding())); assertTrue(room.getNumber().equals(roomsList.get(0).getNumber())); List<ActualOccupation> mAccOcc = mOcc.getOccupancy(); assertTrue("size = " + mAccOcc.size(), mAccOcc.size() == 3); // second room is CO3 mOcc = reply.getOccupancyOfRooms().get(1); room = mOcc.getRoom(); assertTrue(room.getBuilding() .equals(roomsList.get(1).getBuilding())); assertTrue(room.getNumber().equals(roomsList.get(1).getNumber())); mAccOcc = mOcc.getOccupancy(); assertTrue("size = " + mAccOcc.size(), mAccOcc.size() == 3); // last room is CO1 mOcc = reply.getOccupancyOfRooms().get(2); room = mOcc.getRoom(); assertTrue(room.getBuilding() .equals(roomsList.get(2).getBuilding())); assertTrue(room.getNumber().equals(roomsList.get(2).getNumber())); mAccOcc = mOcc.getOccupancy(); assertTrue("size = " + mAccOcc.size(), mAccOcc.size() == 1); } catch (ServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testFreeRoomFriday8_19() { try { FreeRoomServiceImpl server = new FreeRoomServiceImpl( new ConnectionManager(DB_URL, DB_USERNAME, DB_PASSWORD)); FreeRoomRequest request = null; FreeRoomReply reply = null; request = Converter.convert(Calendar.FRIDAY, 8, 19); reply = server.getFreeRoomFromTime(request); assertTrue("Every rooms are availables, : " + reply.getRoomsSize(), reply.getRoomsSize() == 6); } catch (ServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testFreeRoomMonday9_10() { try { FreeRoomServiceImpl server = new FreeRoomServiceImpl( new ConnectionManager(DB_URL, DB_USERNAME, DB_PASSWORD)); FreeRoomRequest request = null; FreeRoomReply reply = null; request = Converter.convert(Calendar.MONDAY, 9, 10); reply = server.getFreeRoomFromTime(request); for (FRRoom r : reply.getRooms()) { System.out.println(r); } assertTrue("Every rooms are availables, : " + reply.getRoomsSize(), reply.getRoomsSize() == 6); } catch (ServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testFreeRoomMonday9_12() { try { FreeRoomServiceImpl server = new FreeRoomServiceImpl( new ConnectionManager(DB_URL, DB_USERNAME, DB_PASSWORD)); FreeRoomRequest request = null; FreeRoomReply reply = null; request = Converter.convert(Calendar.MONDAY, 9, 12); reply = server.getFreeRoomFromTime(request); assertTrue(reply.getRoomsSize() == 4); } catch (ServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testFreeRoomMonday9_11() { try { FreeRoomServiceImpl server = new FreeRoomServiceImpl( new ConnectionManager(DB_URL, DB_USERNAME, DB_PASSWORD)); FreeRoomRequest request = null; FreeRoomReply reply = null; request = Converter.convert(Calendar.MONDAY, 9, 11); reply = server.getFreeRoomFromTime(request); assertTrue(reply.getRoomsSize() == 5); Set<FRRoom> rooms = reply.getRooms(); assertTrue(rooms.contains(new FRRoom("CO", "1"))); assertTrue(rooms.contains(new FRRoom("CO", "2"))); assertTrue(rooms.contains(new FRRoom("CO", "3"))); assertTrue(rooms.contains(new FRRoom("CM", "2"))); assertTrue(rooms.contains(new FRRoom("CM", "3"))); } catch (ServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testFreeRoomTuesday13_16() { try { FreeRoomServiceImpl server = new FreeRoomServiceImpl( new ConnectionManager(DB_URL, DB_USERNAME, DB_PASSWORD)); FreeRoomRequest request = null; FreeRoomReply reply = null; request = Converter.convert(Calendar.TUESDAY, 13, 16); reply = server.getFreeRoomFromTime(request); assertTrue(reply.getRoomsSize() == 4); Set<FRRoom> rooms = reply.getRooms(); assertTrue(rooms.contains(new FRRoom("CO", "1"))); assertTrue(rooms.contains(new FRRoom("CO", "2"))); assertTrue(rooms.contains(new FRRoom("CM", "1"))); assertTrue(rooms.contains(new FRRoom("CM", "3"))); } catch (ServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testStartAfterEnd() { try { FreeRoomServiceImpl server = new FreeRoomServiceImpl( new ConnectionManager(DB_URL, DB_USERNAME, DB_PASSWORD)); FreeRoomRequest request = null; FreeRoomReply reply = null; request = Converter.convert(Calendar.TUESDAY, 13, 16); FreeRoomRequest request2 = Converter.convert(Calendar.TUESDAY, 12, 14); request.setPeriod(new FRPeriod(request.getPeriod() .getTimeStampStart(), request2.getPeriod() .getTimeStampStart(), false)); reply = server.getFreeRoomFromTime(request); assertTrue("Code is " + reply.getStatus(), reply.getStatus() == HttpURLConnection.HTTP_BAD_REQUEST); } catch (ServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testDayOutsideRange() { try { FreeRoomServiceImpl server = new FreeRoomServiceImpl( new ConnectionManager(DB_URL, DB_USERNAME, DB_PASSWORD)); FreeRoomRequest request = null; FreeRoomReply reply = null; request = Converter.convert(Calendar.SATURDAY, 13, 16); reply = server.getFreeRoomFromTime(request); assertTrue("Code is " + reply.getStatus(), reply.getStatus() == HttpURLConnection.HTTP_BAD_REQUEST); } catch (ServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testStartHourOutsideRange() { try { FreeRoomServiceImpl server = new FreeRoomServiceImpl( new ConnectionManager(DB_URL, DB_USERNAME, DB_PASSWORD)); FreeRoomRequest request = null; FreeRoomReply reply = null; request = Converter.convert(Calendar.MONDAY, 7, 16); reply = server.getFreeRoomFromTime(request); assertTrue("Code is " + reply.getStatus(), reply.getStatus() == HttpURLConnection.HTTP_BAD_REQUEST); } catch (ServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testEndHourOutsideRange() { try { FreeRoomServiceImpl server = new FreeRoomServiceImpl( new ConnectionManager(DB_URL, DB_USERNAME, DB_PASSWORD)); FreeRoomRequest request = null; FreeRoomReply reply = null; request = Converter.convert(Calendar.MONDAY, 9, 20); reply = server.getFreeRoomFromTime(request); assertTrue("Code is " + reply.getStatus(), reply.getStatus() == HttpURLConnection.HTTP_BAD_REQUEST); } catch (ServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.opengamma.financial.analytics.model.forex.forward; import java.util.Map; import java.util.Set; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.analytics.CurrencyLabelledMatrix1D; import com.opengamma.financial.analytics.model.CalculationPropertyNamesAndValues; import com.opengamma.financial.analytics.model.forex.ForexVisitors; import com.opengamma.financial.currency.CurrencyMatrixSpotSourcingFunction; import com.opengamma.financial.security.FinancialSecurity; import com.opengamma.financial.security.FinancialSecurityTypes; import com.opengamma.util.async.AsynchronousExecution; import com.opengamma.util.money.Currency; /** * Calculates Present Value on FX Forward instruments. */ public class FXForwardPresentValueFunction extends AbstractFunction.NonCompiledInvoker { @Override public ComputationTargetType getTargetType() { return FinancialSecurityTypes.FX_FORWARD_SECURITY.or(FinancialSecurityTypes.NON_DELIVERABLE_FX_FORWARD_SECURITY); } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) { return ImmutableSet.of(new ValueSpecification(ValueRequirementNames.PRESENT_VALUE, target.toSpecification(), ValueProperties.all())); } @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final ValueProperties constraints = desiredValue.getConstraints(); final Set<String> calculationMethod = constraints.getValues(ValuePropertyNames.CALCULATION_METHOD); if (calculationMethod != null && calculationMethod.size() == 1) { if (!CalculationPropertyNamesAndValues.DISCOUNTING.equals(Iterables.getOnlyElement(calculationMethod))) { return null; } } final ValueRequirement fxPvRequirement = new ValueRequirement(ValueRequirementNames.FX_PRESENT_VALUE, target.toSpecification(), constraints); final FinancialSecurity security = (FinancialSecurity) target.getSecurity(); final Currency payCurrency = getPayCurrency(security); final Currency receiveCurrency = getReceiveCurrency(security); final ValueRequirement spotRateRequirement = CurrencyMatrixSpotSourcingFunction.getConversionRequirement(payCurrency, receiveCurrency); return ImmutableSet.of(fxPvRequirement, spotRateRequirement); } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target, final Map<ValueSpecification, ValueRequirement> inputs) { ValueProperties properties = null; for (final Map.Entry<ValueSpecification, ValueRequirement> entry : inputs.entrySet()) { if (entry.getKey().getValueName().equals(ValueRequirementNames.FX_PRESENT_VALUE)) { properties = entry.getKey().getProperties(); break; } } if (properties == null) { return null; } final Currency currency = getPayCurrency((FinancialSecurity) target.getSecurity()); return ImmutableSet.of(new ValueSpecification(ValueRequirementNames.PRESENT_VALUE, target.toSpecification(), getResultProperties(currency, properties.copy()))); } @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) throws AsynchronousExecution { final FinancialSecurity security = (FinancialSecurity) target.getSecurity(); final Currency payCurrency = getPayCurrency(security); final Currency receiveCurrency = getReceiveCurrency(security); final ComputedValue input = inputs.getComputedValue(ValueRequirementNames.FX_PRESENT_VALUE); final ValueSpecification inputSpec = input.getSpecification(); final CurrencyLabelledMatrix1D fxPresentValue = (CurrencyLabelledMatrix1D) input.getValue(); if (fxPresentValue.size() != 2) { throw new OpenGammaRuntimeException("Expected " + ValueRequirementNames.FX_PRESENT_VALUE + " input to contain 2 currency values, but found " + fxPresentValue.size()); } int payIndex = -1; int receiveIndex = -1; for (int i = 0; i < 2; i++) { final Currency currency = fxPresentValue.getKeys()[i]; if (payCurrency.equals(currency)) { payIndex = i; } else if (receiveCurrency.equals(currency)) { receiveIndex = i; } else { throw new OpenGammaRuntimeException(ValueRequirementNames.FX_PRESENT_VALUE + " contains unexpected currency " + currency + ". Expected " + payCurrency + " or " + receiveCurrency + "."); } } final double payValue = fxPresentValue.getValues()[payIndex]; final double receiveValue = fxPresentValue.getValues()[receiveIndex]; final double spot = (Double) inputs.getValue(ValueRequirementNames.SPOT_RATE); final double pv = payValue + spot * receiveValue; return ImmutableSet.of(new ComputedValue(getResultSpec(target, inputSpec.getProperties().copy()), pv)); } protected ValueSpecification getResultSpec(final ComputationTarget target, final ValueProperties.Builder fxPresentValueProperties) { final Currency currency = getPayCurrency((FinancialSecurity) target.getSecurity()); return new ValueSpecification(ValueRequirementNames.PRESENT_VALUE, target.toSpecification(), getResultProperties(currency, fxPresentValueProperties)); } protected ValueProperties getResultProperties(final Currency currency, final ValueProperties.Builder fxPresentValueProperties) { return fxPresentValueProperties.withoutAny(ValuePropertyNames.FUNCTION) .with(ValuePropertyNames.FUNCTION, getUniqueId()) .with(ValuePropertyNames.CURRENCY, currency.getCode()) .get(); } protected Currency getPayCurrency(final FinancialSecurity security) { return security.accept(ForexVisitors.getPayCurrencyVisitor()); } protected Currency getReceiveCurrency(final FinancialSecurity security) { return security.accept(ForexVisitors.getReceiveCurrencyVisitor()); } }
package org.keycloak.testsuite.saml; import org.junit.Ignore; import org.junit.Test; import org.keycloak.saml.common.constants.JBossSAMLURIConstants; import org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude; import org.keycloak.testsuite.arquillian.annotation.SetDefaultProvider; import org.keycloak.testsuite.authentication.CustomTestingSamlArtifactResolver; import org.keycloak.testsuite.util.ContainerAssume; import org.keycloak.testsuite.util.SamlClient; import org.keycloak.testsuite.util.SamlClientBuilder; import java.io.ByteArrayInputStream; import java.util.Base64; import java.util.concurrent.atomic.AtomicReference; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.keycloak.testsuite.util.SamlClient.Binding.POST; import static org.junit.Assert.assertThat; @AuthServerContainerExclude({AuthServerContainerExclude.AuthServer.QUARKUS, AuthServerContainerExclude.AuthServer.REMOTE}) // Can't be done on quarkus or remote because currently quarkus or remote doesn't support the SetDefaultProvider annotation @SetDefaultProvider(spi = "saml-artifact-resolver", providerId = "0005") public class ArtifactBindingCustomResolverTest extends ArtifactBindingTest { @Test @Ignore @Override public void testArtifactBindingLogoutSingleClientCheckArtifact() {} @Test @Ignore @Override public void testArtifactBindingLoginCheckArtifactWithPost() {} @Test public void testCustomArtifact() { AtomicReference<String> artifactReference = new AtomicReference<>(); new SamlClientBuilder().authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, SAML_ASSERTION_CONSUMER_URL_SALES_POST, SamlClient.Binding.POST) .setProtocolBinding(JBossSAMLURIConstants.SAML_HTTP_ARTIFACT_BINDING.getUri()) .build() .login().user(bburkeUser).build() .handleArtifact(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST) .storeArtifact(artifactReference) .build() .execute(); String artifact = artifactReference.get(); byte[] byteArray = Base64.getDecoder().decode(artifact); ByteArrayInputStream bis = new ByteArrayInputStream(byteArray); bis.skip(2); int index = bis.read(); assertThat(byteArray[0], is((byte)0)); assertThat(byteArray[1], is((byte)5)); if (!suiteContext.getAuthServerInfo().isUndertow()) return; String storedResponse = CustomTestingSamlArtifactResolver.list.get(index); assertThat(storedResponse, notNullValue()); assertThat(storedResponse, containsString("samlp:Response")); } @Test public void testArtifactDoesntContainSignature() { ContainerAssume.assumeAuthServerUndertow(); AtomicReference<String> artifactReference = new AtomicReference<>(); new SamlClientBuilder().authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST_ASSERTION_AND_RESPONSE_SIG, SAML_ASSERTION_CONSUMER_URL_SALES_POST_ASSERTION_AND_RESPONSE_SIG, POST) .setProtocolBinding(JBossSAMLURIConstants.SAML_HTTP_ARTIFACT_BINDING.getUri()) .signWith(SAML_CLIENT_SALES_POST_SIG_PRIVATE_KEY, SAML_CLIENT_SALES_POST_SIG_PUBLIC_KEY) .build() .login().user(bburkeUser).build() .handleArtifact(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST_ASSERTION_AND_RESPONSE_SIG) .storeArtifact(artifactReference) .signWith(SAML_CLIENT_SALES_POST_SIG_PRIVATE_KEY, SAML_CLIENT_SALES_POST_SIG_PUBLIC_KEY) .build() .execute(); String artifact = artifactReference.get(); byte[] byteArray = Base64.getDecoder().decode(artifact); ByteArrayInputStream bis = new ByteArrayInputStream(byteArray); bis.skip(2); int index = bis.read(); assertThat(byteArray[0], is((byte)0)); assertThat(byteArray[1], is((byte)5)); String storedResponse = CustomTestingSamlArtifactResolver.list.get(index); assertThat(storedResponse, notNullValue()); assertThat(storedResponse, containsString("samlp:Response")); assertThat(storedResponse, not(containsString("Signature"))); } }
package org.jboss.as.test.integration.domain.mixed.eap700; import org.jboss.as.test.integration.domain.mixed.MixedDomainDeploymentTest; import org.jboss.as.test.integration.domain.mixed.Version; import org.jboss.as.test.integration.domain.mixed.Version.AsVersion; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.junit.Assume; import org.junit.BeforeClass; /** * * @author <a href="kabir.khan@jboss.com">Kabir Khan</a> */ @Version(AsVersion.EAP_7_0_0) public class MixedDomainDeployment700TestCase extends MixedDomainDeploymentTest { @BeforeClass public static void beforeClass() { // WFLY-12649 -- embedded broker doesn't start correctly on an EAP 7.0.0 server running on OpenJ9 Assume.assumeFalse(TestSuiteEnvironment.isJ9Jvm()); MixedDomain700TestSuite.initializeDomain(); } @Override protected boolean supportManagedExplodedDeployment() { return false; } }
package io.github.jklingsporn.vertx.jooq.shared.reactive; import io.github.jklingsporn.vertx.jooq.shared.internal.AbstractQueryExecutor; import io.reactiverse.pgclient.Tuple; import io.reactiverse.pgclient.impl.ArrayTuple; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import org.jooq.Configuration; import org.jooq.Param; import org.jooq.Query; import org.jooq.conf.ParamType; /** * @author jensklingsporn */ public abstract class AbstractReactiveQueryExecutor extends AbstractQueryExecutor { private static final Logger logger = LoggerFactory.getLogger(AbstractReactiveQueryExecutor.class); /** * Replace ':' but not '::' */ private static final String pattern = "(?<!:):(?!:)"; protected AbstractReactiveQueryExecutor(Configuration configuration) { super(configuration); } protected Tuple getBindValues(Query query) { ArrayTuple bindValues = new ArrayTuple(query.getParams().size()); for (Param<?> param : query.getParams().values()) { Object value = convertToDatabaseType(param); bindValues.add(value); } return bindValues; } protected <U> Object convertToDatabaseType(Param<U> param) { return Enum.class.isAssignableFrom(param.getBinding().converter().toType()) ? param.getValue().toString() : (param.getBinding().converter().to(param.getValue())); } protected void log(Query query){ if(logger.isDebugEnabled()){ logger.debug("Executing {}", query.getSQL(ParamType.INLINED)); } } protected String toPreparedQuery(Query query){ String namedQuery = query.getSQL(ParamType.NAMED); return namedQuery.replaceAll(pattern, "\\$"); } }
package org.eclipse.birt.report.item.crosstab.internal.ui.dnd; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.birt.report.designer.core.DesignerConstants; import org.eclipse.birt.report.designer.core.commands.CreateCommand; import org.eclipse.birt.report.designer.core.model.LibRootModel; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.core.util.mediator.request.ReportRequest; import org.eclipse.birt.report.designer.internal.ui.dnd.DNDLocation; import org.eclipse.birt.report.designer.internal.ui.dnd.DNDService; import org.eclipse.birt.report.designer.internal.ui.dnd.IDropAdapter; import org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.ui.ReportPlugin; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.designer.util.DNDUtil; import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants; import org.eclipse.birt.report.item.crosstab.core.de.CrosstabCellHandle; import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle; import org.eclipse.birt.report.item.crosstab.core.de.DimensionViewHandle; import org.eclipse.birt.report.item.crosstab.core.de.LevelViewHandle; import org.eclipse.birt.report.item.crosstab.core.util.CrosstabExtendedItemFactory; import org.eclipse.birt.report.item.crosstab.internal.ui.editors.model.CrosstabAdaptUtil; import org.eclipse.birt.report.model.api.CommandStack; import org.eclipse.birt.report.model.api.DataItemHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.ExtendedItemHandle; import org.eclipse.birt.report.model.api.LibraryHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.SlotHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.command.ContentException; import org.eclipse.birt.report.model.api.command.ExtendsException; import org.eclipse.birt.report.model.api.command.NameException; import org.eclipse.birt.report.model.api.extension.IReportItem; import org.eclipse.birt.report.model.api.olap.CubeHandle; import org.eclipse.birt.report.model.api.olap.DimensionHandle; import org.eclipse.birt.report.model.api.olap.LevelHandle; import org.eclipse.birt.report.model.api.olap.MeasureGroupHandle; import org.eclipse.birt.report.model.api.olap.MeasureHandle; import org.eclipse.birt.report.model.api.olap.TabularCubeHandle; import org.eclipse.birt.report.model.api.olap.TabularDimensionHandle; import org.eclipse.birt.report.model.elements.interfaces.IReportItemModel; import org.eclipse.gef.EditPart; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import sun.security.x509.EDIPartyName; public class CubeDropAdapter implements IDropAdapter { public int canDrop( Object transfer, Object target, int operation, DNDLocation location ) { if ( target != null && transfer instanceof TabularCubeHandle ) { SlotHandle targetSlot = getTargetSlotHandle( target, ICrosstabConstants.CROSSTAB_EXTENSION_NAME ); //$NON-NLS-1$ if ( targetSlot != null ) if ( DNDUtil.handleValidateTargetCanContainType( targetSlot, "Crosstab" ) && DNDUtil.handleValidateTargetCanContainMore( targetSlot, 0 ) ) return DNDService.LOGIC_TRUE; } return DNDService.LOGIC_UNKNOW; } private SlotHandle getTargetSlotHandle( Object target, String insertType ) { IStructuredSelection models = InsertInLayoutUtil.editPart2Model( new StructuredSelection( target ) ); if ( models.isEmpty( ) ) { return null; } // model = models.getFirstElement( ); Object model = DNDUtil.unwrapToModel( models.getFirstElement( ) ); if ( model instanceof LibRootModel ) { model = ( (LibRootModel) model ).getModel( ); } if ( model instanceof SlotHandle ) { return (SlotHandle) model; } else if ( model instanceof DesignElementHandle ) { DesignElementHandle handle = (DesignElementHandle) model; if ( handle.getDefn( ).isContainer( ) ) { int slotId = DEUtil.getDefaultSlotID( handle ); if ( handle.canContain( slotId, insertType ) ) { return handle.getSlot( slotId ); } } return handle.getContainerSlotHandle( ); } return null; } public boolean performDrop( Object transfer, Object target, int operation, DNDLocation location ) { CommandStack stack = SessionHandleAdapter.getInstance( ) .getCommandStack( ); stack.startTrans( "Create crosstab from Cube" ); //$NON-NLS-1$ TabularCubeHandle cube = (TabularCubeHandle) transfer; ModuleHandle moduleHandle = SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ); if ( cube.getModuleHandle( ) != moduleHandle && cube.getRoot( ) instanceof LibraryHandle ) { try { UIUtil.includeLibrary( moduleHandle, (LibraryHandle) cube.getRoot( ) ); cube = (TabularCubeHandle) moduleHandle.getElementFactory( ) .newElementFrom( cube, cube.getName( ) ); moduleHandle.addElement( cube, ReportDesignHandle.CUBE_SLOT ); } catch ( Exception e ) { stack.rollback( ); return false; } } ExtendedItemHandle handle = null; String name = ReportPlugin.getDefault( ) .getCustomName( ICrosstabConstants.CROSSTAB_EXTENSION_NAME ); try { handle = CrosstabExtendedItemFactory.createCrosstabReportItem( SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ), null, name ); } catch ( Exception e ) { stack.rollback( ); return false; } Map map = new HashMap( ); map.put( DesignerConstants.KEY_NEWOBJECT, handle ); CreateCommand command = new CreateCommand( map ); try { SlotHandle parentModel = getTargetSlotHandle( target, ICrosstabConstants.CROSSTAB_EXTENSION_NAME ); if ( parentModel != null ) { command.setParent( parentModel ); } else { command.setParent( SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) ); } command.execute( ); handle.setProperty( IReportItemModel.CUBE_PROP, cube ); List dimensions = cube.getContents( CubeHandle.DIMENSIONS_PROP ); for ( Iterator iterator = dimensions.iterator( ); iterator.hasNext( ); ) { TabularDimensionHandle dimension = (TabularDimensionHandle) iterator.next( ); if ( dimension.isTimeType( ) ) { createDimensionViewHandle( handle, dimension, ICrosstabConstants.COLUMN_AXIS_TYPE ); } else { createDimensionViewHandle( handle, dimension, ICrosstabConstants.ROW_AXIS_TYPE ); } } List measureGroups = cube.getContents( CubeHandle.MEASURE_GROUPS_PROP ); int index = 0; for ( Iterator iterator = measureGroups.iterator( ); iterator.hasNext( ); ) { MeasureGroupHandle measureGroup = (MeasureGroupHandle) iterator.next( ); List measures = measureGroup.getContents( MeasureGroupHandle.MEASURES_PROP ); for ( int j = 0; j < measures.size( ); j++ ) { Object temp = measures.get( j ); if ( temp instanceof MeasureHandle ) { addMeasureHandle( handle, (MeasureHandle) temp, index++ ); } } } stack.commit( ); if ( target instanceof EditPart ) { ( (EditPart) target ).getViewer( ).flush( ); } ReportRequest request = new ReportRequest( ); List selectionObjects = new ArrayList( ); selectionObjects.add( handle ); request.setSelectionObject( selectionObjects ); request.setType( ReportRequest.SELECTION ); SessionHandleAdapter.getInstance( ) .getMediator( ) .notifyRequest( request ); } catch ( Exception e ) { stack.rollback( ); return false; } return true; } private void addMeasureHandle( ExtendedItemHandle handle, MeasureHandle measureHandle, int index ) throws SemanticException { IReportItem reportItem = handle.getReportItem( ); CrosstabReportItemHandle xtabHandle = (CrosstabReportItemHandle) reportItem; CrosstabAdaptUtil.addMeasureHandle( xtabHandle, measureHandle, index ); } private void createDimensionViewHandle( ExtendedItemHandle handle, DimensionHandle dimensionHandle, int type ) throws SemanticException { if ( dimensionHandle.getDefaultHierarchy( ).getLevelCount( ) > 0 ) { IReportItem reportItem = handle.getReportItem( ); CrosstabReportItemHandle xtabHandle = (CrosstabReportItemHandle) reportItem; DimensionViewHandle viewHandle = xtabHandle.insertDimension( dimensionHandle, type, xtabHandle.getDimensionCount( type ) ); LevelHandle[] levels = getLevelHandles( dimensionHandle ); for ( int j = 0; j < levels.length; j++ ) { LevelHandle levelHandle = levels[j]; DataItemHandle dataHandle = CrosstabAdaptUtil.createColumnBindingAndDataItem( (ExtendedItemHandle) xtabHandle.getModelHandle( ), levelHandle ); LevelViewHandle levelViewHandle = viewHandle.insertLevel( levelHandle, j ); CrosstabCellHandle cellHandle = levelViewHandle.getCell( ); cellHandle.addContent( dataHandle ); } } } private LevelHandle[] getLevelHandles( DimensionHandle dimensionHandle ) { LevelHandle[] dimensionLevelHandles = new LevelHandle[dimensionHandle.getDefaultHierarchy( ) .getLevelCount( )]; for ( int i = 0; i < dimensionLevelHandles.length; i++ ) { dimensionLevelHandles[i] = dimensionHandle.getDefaultHierarchy( ) .getLevel( i ); } return dimensionLevelHandles; } }
package org.csstudio.utility.channelfinder; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** * The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "org.csstudio.utility.channelfinder"; // The shared instance private static Activator plugin; /** * The constructor */ public Activator() { } /* * (non-Javadoc) * * @see * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext * ) */ public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } /* * (non-Javadoc) * * @see * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext * ) */ public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } }
package de.ptb.epics.eve.editor.views.motoraxisview.filecomposite; import java.io.File; import org.apache.log4j.Logger; import org.eclipse.core.databinding.Binding; import org.eclipse.core.databinding.UpdateValueStrategy; import org.eclipse.core.databinding.beans.BeansObservables; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.jface.databinding.fieldassist.ControlDecorationSupport; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Button; import de.ptb.epics.eve.data.scandescription.Axis; import de.ptb.epics.eve.data.scandescription.axismode.FileMode; import de.ptb.epics.eve.editor.Activator; import de.ptb.epics.eve.editor.views.motoraxisview.MotorAxisViewComposite; /** * <code>MotorAxisFileComposite</code> is a composite to input a filename * with positions of the motor axis. * * @author Hartmut Scherr * @author Marcus Michalsky */ public class FileComposite extends MotorAxisViewComposite { private static Logger LOGGER = Logger.getLogger(FileComposite.class.getName()); private FileMode fileMode; private Label filenameLabel; private Text filenameText; private Binding filenameBinding; private IObservableValue fileNameModelObservable; private IObservableValue fileNameGUIObservable; private Button searchButton; private SearchButtonSelectionListener searchButtonSelectionListener; private TableViewer viewer; /** * Constructs a <code>MotorAxisFileComposite</code>. * * @param parent the parent composite * @param style the style * @param parentView the view the composite is contained in */ public FileComposite(Composite parent, int style) { super(parent, style); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 3; this.setLayout(gridLayout); // "Filename:" this.filenameLabel = new Label(this, SWT.NONE); this.filenameLabel.setText("Filename:"); // Filename Text field this.filenameText = new Text(this, SWT.BORDER); GridData gridData = new GridData(); gridData.grabExcessHorizontalSpace = true; gridData.horizontalAlignment = GridData.FILL; gridData.horizontalIndent = 7; this.filenameText.setLayoutData(gridData); this.filenameText.addFocusListener(new FileNameTextFocusListener()); // Search Button this.searchButton = new Button(this, SWT.NONE); this.searchButton.setText("Search..."); searchButtonSelectionListener = new SearchButtonSelectionListener(); this.searchButton.addSelectionListener(searchButtonSelectionListener); this.createViewer(this); this.createColumns(this); this.fileMode = null; } private void createViewer(final Composite parent) { this.viewer = new TableViewer(parent, SWT.BORDER); GridData gridData = new GridData(); gridData.grabExcessHorizontalSpace = true; gridData.horizontalAlignment = GridData.FILL; gridData.horizontalSpan = 3; this.viewer.getTable().setLayoutData(gridData); this.viewer.getTable().setHeaderVisible(true); } private void createColumns(final Composite parent) { TableViewerColumn countColumn = new TableViewerColumn(this.viewer, SWT.CENTER); countColumn.getColumn().setText("# points"); countColumn.getColumn().setWidth(80); TableViewerColumn minColumn = new TableViewerColumn(this.viewer, SWT.RIGHT); minColumn.getColumn().setText("Minimum"); minColumn.getColumn().setWidth(80); TableViewerColumn maxColumn = new TableViewerColumn(this.viewer, SWT.RIGHT); maxColumn.getColumn().setText("Maximum"); maxColumn.getColumn().setWidth(80); TableViewerColumn emptyColumn = new TableViewerColumn(this.viewer, SWT.NONE); emptyColumn.getColumn().setText(""); emptyColumn.getColumn().setWidth(10); } /** * calculate the height to see all entries of this composite * * @return the needed height of Composite to see all entries */ public int getTargetHeight() { return (filenameText.getBounds().y + filenameText.getBounds().height + 5); } /** * calculate the width to see all entries of this composite * * @return the needed width of Composite to see all entries */ public int getTargetWidth() { return (filenameText.getBounds().x + filenameText.getBounds().width + 5); } /** * {@inheritDoc} */ @Override public void setAxis(Axis axis) { this.reset(); if (axis == null) { return; } if (!(axis.getMode() instanceof FileMode)) { LOGGER.warn("invalid axis mode"); return; } this.fileMode = ((FileMode)axis.getMode()); this.createBinding(); } /** * {@inheritDoc} */ @Override protected void createBinding() { this.fileNameModelObservable = BeansObservables.observeValue( this.fileMode, FileMode.FILE_PROP); this.fileNameGUIObservable = SWTObservables.observeText( this.filenameText, SWT.Modify); UpdateValueStrategy targetToModel = new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE); targetToModel.setConverter(new FileNameTargetToModelConverter()); targetToModel.setAfterGetValidator(new FileNameValidator()); UpdateValueStrategy modelToTarget = new UpdateValueStrategy( UpdateValueStrategy.POLICY_UPDATE); modelToTarget.setConverter(new FileNameModelToTargetConverter()); filenameBinding = context.bindValue(fileNameGUIObservable, fileNameModelObservable, targetToModel, modelToTarget); ControlDecorationSupport.create(filenameBinding, SWT.LEFT); } /** * {@inheritDoc} */ protected void reset() { LOGGER.debug("reset"); if (this.fileMode != null) { this.context.removeBinding(this.filenameBinding); this.filenameBinding.dispose(); this.fileNameModelObservable.dispose(); this.fileNameGUIObservable.dispose(); } this.fileMode = null; } /** * {@link org.eclipse.swt.events.SelectionListener} of * <code>searchButton</code>. */ private class SearchButtonSelectionListener implements SelectionListener { /** * {@inheritDoc} */ @Override public void widgetDefaultSelected(final SelectionEvent e) { } /** * {@inheritDoc} */ @Override public void widgetSelected(final SelectionEvent e) { int lastSeperatorIndex; final String filePath; if (fileMode.getFile() == null || fileMode.getFile().getAbsolutePath().isEmpty()) { filePath = Activator.getDefault().getRootDirectory(); } else { // als filePath wird das vorhandene Verzeichnis gesetzt lastSeperatorIndex = fileMode.getFile().getAbsolutePath() .lastIndexOf(File.separatorChar); filePath = fileMode.getFile().getAbsolutePath() .substring(0, lastSeperatorIndex + 1); } FileDialog fileWindow = new FileDialog(getShell(), SWT.SAVE); fileWindow.setFilterPath(filePath); String name = fileWindow.open(); if (name == null) { // dialog was cancelled return; } filenameText.setText(name); fileMode.setFile(new File(name)); } } /** * * @author Marcus Michalsky * @since 1.7 */ private class FileNameTextFocusListener implements FocusListener { /** * {@inheritDoc} */ @Override public void focusGained(FocusEvent e) { } /** * {@inheritDoc} */ @Override public void focusLost(FocusEvent e) { if (filenameText.getText().isEmpty()) { filenameBinding.updateModelToTarget(); } } } }
package com.horcrux.svg; import android.graphics.PointF; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import java.util.ArrayList; import javax.annotation.Nonnull; import javax.annotation.Nullable; class GlyphContext { static final float DEFAULT_FONT_SIZE = 12f; private static final float DEFAULT_KERNING = 0f; private static final float DEFAULT_LETTER_SPACING = 0f; // Unique input attribute lists (only added if node sets a value) private final ArrayList<String[]> mXPositionsContext = new ArrayList<>(); private final ArrayList<String[]> mYPositionsContext = new ArrayList<>(); private final ArrayList<float[]> mRotationsContext = new ArrayList<>(); private final ArrayList<float[]> mDeltaXsContext = new ArrayList<>(); private final ArrayList<float[]> mDeltaYsContext = new ArrayList<>(); // Unique index into attribute list (one per unique list) private final ArrayList<Integer> mXPositionIndices = new ArrayList<>(); private final ArrayList<Integer> mYPositionIndices = new ArrayList<>(); private final ArrayList<Integer> mRotationIndices = new ArrayList<>(); private final ArrayList<Integer> mDeltaXIndices = new ArrayList<>(); private final ArrayList<Integer> mDeltaYIndices = new ArrayList<>(); // Index of unique context used (one per node push/pop) private final ArrayList<Integer> mXPositionsIndices = new ArrayList<>(); private final ArrayList<Integer> mYPositionsIndices = new ArrayList<>(); private final ArrayList<Integer> mRotationsIndices = new ArrayList<>(); private final ArrayList<Integer> mDeltaXsIndices = new ArrayList<>(); private final ArrayList<Integer> mDeltaYsIndices = new ArrayList<>(); // Current stack (one per node push/pop) private final ArrayList<ReadableMap> mFontContext = new ArrayList<>(); private final ArrayList<GroupShadowNode> mNodes = new ArrayList<>(); // Current accumulated values private @Nonnull final PointF mCurrentPosition = new PointF(); private @Nonnull final PointF mCurrentDelta = new PointF(); private double fontSize = DEFAULT_FONT_SIZE; // Current attribute list private float[] mRotations = new float[]{0}; private float[] mDeltaXs = new float[]{}; private float[] mDeltaYs = new float[]{}; private String[] mXs = new String[]{}; private String[] mYs = new String[]{}; // Current attribute list index private int mXPositionsIndex; private int mYPositionsIndex; private int mRotationsIndex; private int mDeltaXsIndex; private int mDeltaYsIndex; // Current value index in current attribute list private int mXPositionIndex = -1; private int mYPositionIndex = -1; private int mRotationIndex = -1; private int mDeltaXIndex = -1; private int mDeltaYIndex = -1; private int mContextLength; private int top = -1; // Constructor parameters private final float mScale; private final float mWidth; private final float mHeight; GlyphContext(float scale, float width, float height) { mScale = scale; mWidth = width; mHeight = height; mXPositionsContext.add(mXs); mYPositionsContext.add(mYs); mDeltaXsContext.add(mDeltaXs); mDeltaYsContext.add(mDeltaYs); mRotationsContext.add(mRotations); mXPositionIndices.add(mXPositionIndex); mYPositionIndices.add(mYPositionIndex); mRotationIndices.add(mRotationIndex); mDeltaXIndices.add(mDeltaXIndex); mDeltaYIndices.add(mDeltaYIndex); pushIndices(); } void pushContext(GroupShadowNode node, @Nullable ReadableMap font) { mFontContext.add(font); mNodes.add(node); mContextLength++; pushIndices(); top++; fontSize = getFontSize(); } void pushContext(TextShadowNode node, @Nullable ReadableMap font, @Nullable ReadableArray rotate, @Nullable ReadableArray deltaX, @Nullable ReadableArray deltaY, @Nullable String positionX, @Nullable String positionY, boolean resetPosition) { if (resetPosition) { reset(); } if (positionX != null) { mXPositionsIndex++; mXPositionIndex = -1; mXPositionIndices.add(mXPositionIndex); mXs = positionX.trim().split("\\s+"); mXPositionsContext.add(mXs); } if (positionY != null) { mYPositionsIndex++; mYPositionIndex = -1; mYPositionIndices.add(mYPositionIndex); mYs = positionY.trim().split("\\s+"); mYPositionsContext.add(mYs); } if (rotate != null && rotate.size() != 0) { mRotationsIndex++; mRotationIndex = -1; mRotationIndices.add(mRotationIndex); mRotations = getFloatArrayFromReadableArray(rotate); mRotationsContext.add(mRotations); } if (deltaX != null && deltaX.size() != 0) { mDeltaXsIndex++; mDeltaXIndex = -1; mDeltaXIndices.add(mDeltaXIndex); mDeltaXs = getFloatArrayFromReadableArray(deltaX); mDeltaXsContext.add(mDeltaXs); } if (deltaY != null && deltaY.size() != 0) { mDeltaYsIndex++; mDeltaYIndex = -1; mDeltaYIndices.add(mDeltaYIndex); mDeltaYs = getFloatArrayFromReadableArray(deltaY); mDeltaYsContext.add(mDeltaYs); } mFontContext.add(font); mNodes.add(node); mContextLength++; pushIndices(); top++; fontSize = getFontSize(); } private void pushIndices() { mXPositionsIndices.add(mXPositionsIndex); mYPositionsIndices.add(mYPositionsIndex); mRotationsIndices.add(mRotationsIndex); mDeltaXsIndices.add(mDeltaXsIndex); mDeltaYsIndices.add(mDeltaYsIndex); } private void reset() { mXPositionsIndex = mYPositionsIndex = mRotationsIndex = mDeltaXsIndex = mDeltaYsIndex = 0; mXPositionIndex = mYPositionIndex = mRotationIndex = mDeltaXIndex = mDeltaYIndex = -1; mCurrentPosition.x = mCurrentPosition.y = mCurrentDelta.x = mCurrentDelta.y = 0; } void popContext() { mContextLength top mFontContext.remove(mContextLength); mNodes.remove(mContextLength); mXPositionsIndices.remove(mContextLength); mYPositionsIndices.remove(mContextLength); mRotationsIndices.remove(mContextLength); mDeltaXsIndices.remove(mContextLength); mDeltaYsIndices.remove(mContextLength); int x = mXPositionsIndex; int y = mYPositionsIndex; int r = mRotationsIndex; int dx = mDeltaXsIndex; int dy = mDeltaYsIndex; mXPositionsIndex = mXPositionsIndices.get(mContextLength); mYPositionsIndex = mYPositionsIndices.get(mContextLength); mRotationsIndex = mRotationsIndices.get(mContextLength); mDeltaXsIndex = mDeltaXsIndices.get(mContextLength); mDeltaYsIndex = mDeltaYsIndices.get(mContextLength); if (x != mXPositionsIndex) { mXPositionsContext.remove(x); mXs = mXPositionsContext.get(mXPositionsIndex); mXPositionIndex = mXPositionIndices.get(mXPositionsIndex); } if (y != mYPositionsIndex) { mYPositionsContext.remove(y); mYs = mYPositionsContext.get(mYPositionsIndex); mYPositionIndex = mYPositionIndices.get(mYPositionsIndex); } if (r != mRotationsIndex) { mRotationsContext.remove(r); mRotations = mRotationsContext.get(mRotationsIndex); mRotationIndex = mRotationIndices.get(mRotationsIndex); } if (dx != mDeltaXsIndex) { mDeltaXsContext.remove(dx); mDeltaXs = mDeltaXsContext.get(mDeltaXsIndex); mDeltaXIndex = mDeltaXIndices.get(mDeltaXsIndex); } if (dy != mDeltaYsIndex) { mDeltaYsContext.remove(dy); mDeltaYs = mDeltaYsContext.get(mDeltaYsIndex); mDeltaYIndex = mDeltaYIndices.get(mDeltaYsIndex); } } PointF nextPoint(float glyphWidth) { nextPositionX(); nextPositionY(); mCurrentPosition.x += glyphWidth; return mCurrentPosition; } PointF nextDelta() { nextDeltaX(); nextDeltaY(); return mCurrentDelta; } float nextRotation() { for (int index = mRotationsIndex; index >= 0; index int rotationIndex = mRotationIndices.get(index); mRotationIndices.set(index, rotationIndex + 1); } mRotationIndex = Math.min(mRotationIndex + 1, mRotations.length - 1); return mRotations[mRotationIndex]; } private void nextDeltaX() { for (int index = mDeltaXsIndex; index >= 0; index int deltaIndex = mDeltaXIndices.get(index); mDeltaXIndices.set(index, deltaIndex + 1); } int nextIndex = mDeltaXIndex + 1; if (nextIndex < mDeltaXs.length) { mDeltaXIndex = nextIndex; float val = mDeltaXs[nextIndex]; mCurrentDelta.x += val * mScale; } } private void nextDeltaY() { for (int index = mDeltaYsIndex; index >= 0; index int deltaIndex = mDeltaYIndices.get(index); mDeltaYIndices.set(index, deltaIndex + 1); } int nextIndex = mDeltaYIndex + 1; if (nextIndex < mDeltaYs.length) { mDeltaYIndex = nextIndex; float val = mDeltaYs[nextIndex]; mCurrentDelta.y += val * mScale; } } private void nextPositionX() { for (int index = mXPositionsIndex; index >= 0; index int positionIndex = mXPositionIndices.get(index); mXPositionIndices.set(index, positionIndex + 1); } int nextIndex = mXPositionIndex + 1; if (nextIndex < mXs.length) { mCurrentDelta.x = 0; mXPositionIndex = nextIndex; String val = mXs[nextIndex]; mCurrentPosition.x = PropHelper.fromRelativeToFloat(val, mWidth, 0, mScale, fontSize); } } private void nextPositionY() { for (int index = mYPositionsIndex; index >= 0; index int positionIndex = mYPositionIndices.get(index); mYPositionIndices.set(index, positionIndex + 1); } int nextIndex = mYPositionIndex + 1; if (nextIndex < mYs.length) { mCurrentDelta.y = 0; mYPositionIndex = nextIndex; String val = mYs[nextIndex]; mCurrentPosition.y = PropHelper.fromRelativeToFloat(val, mHeight, 0, mScale, fontSize); } } float getWidth() { return mWidth; } float getHeight() { return mHeight; } double getFontSize() { for (int index = top; index >= 0; index ReadableMap font = mFontContext.get(index); if (mFontContext.get(index).hasKey("fontSize")) { return font.getDouble("fontSize"); } } if (top > -1) { return mNodes.get(0).getFontSizeFromParentContext(); } return DEFAULT_FONT_SIZE; } ReadableMap getFont() { WritableMap map = Arguments.createMap(); map.putDouble("letterSpacing", DEFAULT_LETTER_SPACING); map.putBoolean("isKerningValueSet", false); map.putDouble("kerning", DEFAULT_KERNING); map.putDouble("fontSize", fontSize); boolean letterSpacingSet = false; boolean fontFamilySet = false; boolean fontWeightSet = false; boolean fontStyleSet = false; boolean kerningSet = false; for (int index = top; index >= 0; index ReadableMap font = mFontContext.get(index); if (!fontFamilySet && font.hasKey("fontFamily")) { String fontFamily = font.getString("fontFamily"); map.putString("fontFamily", fontFamily); fontFamilySet = true; } if (!kerningSet && font.hasKey("kerning")) { float kerning = Float.valueOf(font.getString("kerning")); map.putBoolean("isKerningValueSet", true); map.putDouble("kerning", kerning); kerningSet = true; } if (!letterSpacingSet && font.hasKey("letterSpacing")) { float letterSpacing = Float.valueOf(font.getString("letterSpacing")); map.putDouble("letterSpacing", letterSpacing); letterSpacingSet = true; } if (!fontWeightSet && font.hasKey("fontWeight")) { String fontWeight = font.getString("fontWeight"); map.putString("fontWeight", fontWeight); fontWeightSet = true; } if (!fontStyleSet && font.hasKey("fontStyle")) { String fontStyle = font.getString("fontStyle"); map.putString("fontStyle", fontStyle); fontStyleSet = true; } if (fontFamilySet && kerningSet && letterSpacingSet && fontWeightSet && fontStyleSet) { break; } } return map; } private float[] getFloatArrayFromReadableArray(ReadableArray readableArray) { int size = readableArray.size(); float[] floats = new float[size]; for (int i = 0; i < size; i++) { switch (readableArray.getType(i)) { case String: String val = readableArray.getString(i); floats[i] = (float) (Float.valueOf(val.substring(0, val.length() - 2)) * fontSize); break; case Number: floats[i] = (float) readableArray.getDouble(i); break; } } return floats; } }
package org.csstudio.opibuilder.adl2boy.translator; import org.csstudio.opibuilder.model.AbstractContainerModel; import org.csstudio.opibuilder.model.AbstractWidgetModel; import org.csstudio.opibuilder.util.MacrosInput; import org.csstudio.opibuilder.widgetActions.ActionsInput; import org.csstudio.opibuilder.widgetActions.OpenDisplayAction; import org.csstudio.opibuilder.widgets.model.MenuButtonModel; import org.csstudio.utility.adlparser.fileParser.ADLWidget; import org.csstudio.utility.adlparser.fileParser.widgetParts.RelatedDisplayItem; import org.csstudio.utility.adlparser.fileParser.widgets.RelatedDisplay; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.swt.graphics.RGB; public class RelatedDisplay2Model extends AbstractADL2Model { MenuButtonModel menuModel = new MenuButtonModel(); public RelatedDisplay2Model(ADLWidget adlWidget, RGB[] colorMap, AbstractContainerModel parentModel) { super(adlWidget, colorMap, parentModel); parentModel.addChild(menuModel, true); RelatedDisplay rdWidget = new RelatedDisplay(adlWidget); if (rdWidget != null) { setADLObjectProps(rdWidget, menuModel); if ((rdWidget.getClr() != null) && !rdWidget.getClr().equals("")){ menuModel.setForegroundColor( colorMap[Integer.parseInt(rdWidget.getClr())] ); } if ((rdWidget.getBclr() != null) && !rdWidget.getClr().equals("")){ menuModel.setBackgroundColor( colorMap[Integer.parseInt(rdWidget.getBclr())] ); } RelatedDisplayItem[] rdDisplays = rdWidget.getRelatedDisplayItems(); if ( rdDisplays.length > 0){ ActionsInput ai = menuModel.getActionsInput(); for (int ii=0; ii< rdDisplays.length; ii++){ OpenDisplayAction odAction = new OpenDisplayAction(); //Try to add the filename to the PROP_PATH IPath fPath = new Path(rdDisplays[ii].getName().replaceAll("\"", "").replace(".adl", ".opi")); System.out.println("Related display file: " + rdDisplays[ii].getName().replace(".adl", ".opi")); System.out.println("Related display file from IPath: " + fPath.toString() + ", " + fPath.getFileExtension()); odAction.setPropertyValue(OpenDisplayAction.PROP_PATH, fPath); //Try to add macros System.out.println ("args " + rdDisplays[ii].getArgs()); if (rdDisplays[ii].getArgs() != null){ String argsIn = "true, " + rdDisplays[ii].getArgs().replaceAll("\"", ""); MacrosInput macIn; try { macIn = MacrosInput.recoverFromString( argsIn); odAction.setPropertyValue(OpenDisplayAction.PROP_MACROS, macIn ); } catch (Exception e) { e.printStackTrace(); } } if (rdDisplays[ii].getLabel() != null){ odAction.setPropertyValue(OpenDisplayAction.PROP_DESCRIPTION, rdDisplays[ii].getLabel().replaceAll("\"", "")); } ai.addAction(odAction); } } } menuModel.setPropertyValue(MenuButtonModel.PROP_LABEL, rdWidget.getLabel()); } @Override public AbstractWidgetModel getWidgetModel() { return menuModel; } }
package edu.umd.cs.findbugs.detect; import java.util.HashSet; import java.util.Set; import org.apache.bcel.Repository; import org.apache.bcel.classfile.JavaClass; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.ch.Subtypes; public class Analyze { static private JavaClass serializable; static private JavaClass collection; static private JavaClass map; static private ClassNotFoundException storedException; static { try { serializable = Repository.lookupClass("java.io.Serializable"); collection = Repository.lookupClass("java.util.Collection"); map = Repository.lookupClass("java.util.Map"); } catch (ClassNotFoundException e) { storedException = e; } } private static boolean containsConcreteClasses(Set<JavaClass> s) { for (JavaClass c : s) if (!c.isInterface() && !c.isAbstract()) return true; return false; } public static double isDeepSerializable(String refSig) throws ClassNotFoundException { if (storedException != null) throw storedException; String refName = getComponentClass(refSig); if (refName.equals("java.lang.Object")) return 0.99; JavaClass refJavaClass = Repository.lookupClass(refName); return isDeepSerializable(refJavaClass); } public static String getComponentClass(String refSig) { while (refSig.charAt(0) == '[') refSig = refSig.substring(1); assert refSig.charAt(0) == 'L'; //TODO: This method now returns primitive type signatures, is this ok? if (refSig.charAt(0) == 'L') return refSig.substring(1, refSig.length() - 1).replace('/', '.'); return refSig; } public static double isDeepSerializable(JavaClass x) throws ClassNotFoundException { if (storedException != null) throw storedException; double result = deepInstanceOf(x, serializable); if (result >= 0.9) return result; result = Math.max(result, deepInstanceOf(x, collection)); if (result >= 0.9) return result; result = Math.max(result, deepInstanceOf(x, map)); return result; } /** * Given two JavaClasses, try to estimate the probability that an reference * of type x is also an instance of type y. Will return 0 only if it is * impossiblem and 1 only if it is guaranteed. * * @param x * Known type of object * @param y * Type queried about * @return 0 - 1 value indicating probablility */ public static double deepInstanceOf(JavaClass x, JavaClass y) throws ClassNotFoundException { if (x.equals(y)) return 1.0; boolean xIsSubtypeOfY = Repository.instanceOf(x, y); if (xIsSubtypeOfY) return 1.0; boolean yIsSubtypeOfX = Repository.instanceOf(y, x); if (!yIsSubtypeOfX) { if (x.isFinal() || y.isFinal()) return 0.0; if (!x.isInterface() && !y.isInterface()) return 0.0; } Subtypes subtypes = AnalysisContext.currentAnalysisContext() .getSubtypes(); subtypes.addClass(x); subtypes.addClass(y); Set<JavaClass> xSubtypes = subtypes.getTransitiveSubtypes(x); Set<JavaClass> ySubtypes = subtypes.getTransitiveSubtypes(y); Set<JavaClass> both = new HashSet<JavaClass>(xSubtypes); both.retainAll(ySubtypes); Set<JavaClass> xButNotY = new HashSet<JavaClass>(xSubtypes); xButNotY.removeAll(ySubtypes); if (false && yIsSubtypeOfX && both.isEmpty()) { System.out.println("Strange: y is subtype of x, but no classes in both"); System.out.println("X : " + x.getClassName()); System.out.println("Immediate subtypes:"); for(JavaClass c : subtypes.getImmediateSubtypes(x)) System.out.println(" " + c.getClassName()); System.out.println("transitive subtypes:"); for(JavaClass c : xSubtypes) System.out.println(" " + c.getClassName()); System.out.println("Y : " + y.getClassName()); System.out.println("Immediate subtypes:"); for(JavaClass c : subtypes.getImmediateSubtypes(y)) System.out.println(" " + c.getClassName()); System.out.println("transitive subtypes:"); for(JavaClass c : ySubtypes) System.out.println(" " + c.getClassName()); } boolean concreteClassesInXButNotY = containsConcreteClasses(xButNotY); if (both.isEmpty()) { if (concreteClassesInXButNotY) { return 0.1; } return 0.3; } // exist classes that are both X and Y if (!concreteClassesInXButNotY) { // only abstract/interfaces that are X but not Y return 0.99; } // Concrete classes in X but not Y return 0.7; } }
package vgtest.testview.view; import rhcad.touchvg.IGraphView; import rhcad.touchvg.IViewHelper; import rhcad.touchvg.ViewFactory; import rhcad.touchvg.view.SFGraphView; import vgtest.testview.TestFlags; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.ViewGroup; import android.widget.Toast; import democmds.core.DemoCmdsGate; public class SFGraphView1 extends SFGraphView implements IGraphView.OnFirstRegenListener { protected static final String PATH = "mnt/sdcard/TouchVG/"; static { System.loadLibrary("democmds"); } public SFGraphView1(Context context) { this(context, null); } public SFGraphView1(Context context, Bundle savedInstanceState) { super(context, savedInstanceState); int flags = ((Activity) context).getIntent().getExtras().getInt("flags"); final IViewHelper helper = ViewFactory.createHelper(this); if (savedInstanceState == null && (flags & (TestFlags.RECORD | TestFlags.RAND_SHAPES)) != 0) { setOnFirstRegenListener(this); } flags = flags & TestFlags.CMD_MASK; if (flags == TestFlags.SELECT_CMD) { helper.setCommand("select"); } else if (flags == TestFlags.SPLINES_CMD) { helper.setCommand("splines"); } else if (flags == TestFlags.LINE_CMD) { helper.setCommand("line"); } else if (flags == TestFlags.LINES_CMD) { helper.setCommand("lines"); } else if (flags == TestFlags.HITTEST_CMD) { int n = DemoCmdsGate.registerCmds(helper.cmdViewHandle()); helper.setCommand("hittest"); Log.d("Test", "DemoCmdsGate.registerCmds = " + n + ", " + helper.getCommand()); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); int flags = ((Activity) getContext()).getIntent().getExtras().getInt("flags"); if ((flags & TestFlags.HAS_BACKDRAWABLE) != 0) { ViewGroup layout = (ViewGroup) getParent(); this.setBackgroundDrawable(layout.getBackground()); } } @Override public boolean onPreDoubleTap(MotionEvent e) { int flags = ((Activity) getContext()).getIntent().getExtras().getInt("flags"); final IViewHelper helper = ViewFactory.createHelper(this); if ((flags & TestFlags.SWITCH_CMD) != 0) { helper.switchCommand(); Toast.makeText(getContext(), helper.getCommand(), Toast.LENGTH_SHORT).show(); return true; } return false; } public void onFirstRegen(IGraphView view) { int flags = ((Activity) getContext()).getIntent().getExtras().getInt("flags"); final IViewHelper helper = ViewFactory.createHelper(view); if ((flags & TestFlags.RAND_SHAPES) != 0) { helper.addShapesForTest(); } if ((flags & TestFlags.RECORD) != 0) { helper.startRecord(PATH + "record"); } } }
package org.csstudio.opibuilder.adl2boy.translator; import org.csstudio.opibuilder.model.AbstractContainerModel; import org.csstudio.opibuilder.model.AbstractWidgetModel; import org.csstudio.opibuilder.util.MacrosInput; import org.csstudio.opibuilder.widgetActions.ActionsInput; import org.csstudio.opibuilder.widgetActions.OpenDisplayAction; import org.csstudio.opibuilder.widgets.model.MenuButtonModel; import org.csstudio.utility.adlparser.fileParser.ADLWidget; import org.csstudio.utility.adlparser.fileParser.widgetParts.RelatedDisplayItem; import org.csstudio.utility.adlparser.fileParser.widgets.RelatedDisplay; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.swt.graphics.RGB; public class RelatedDisplay2Model extends AbstractADL2Model { MenuButtonModel menuModel = new MenuButtonModel(); public RelatedDisplay2Model(ADLWidget adlWidget, RGB[] colorMap, AbstractContainerModel parentModel) { super(adlWidget, colorMap, parentModel); parentModel.addChild(menuModel, true); RelatedDisplay rdWidget = new RelatedDisplay(adlWidget); if (rdWidget != null) { setADLObjectProps(rdWidget, menuModel); setADLDynamicAttributeProps(rdWidget, menuModel); if (rdWidget.isForeColorDefined() ){ menuModel.setForegroundColor( colorMap[rdWidget.getForegroundColor()] ); } if (rdWidget.isBackColorDefined()){ menuModel.setBackgroundColor( colorMap[rdWidget.getBackgroundColor()] ); } RelatedDisplayItem[] rdDisplays = rdWidget.getRelatedDisplayItems(); if ( rdDisplays.length > 0){ ActionsInput ai = menuModel.getActionsInput(); for (int ii=0; ii< rdDisplays.length; ii++){ if (!(rdDisplays[ii].getName().replaceAll("\"", "").equals(""))){ OpenDisplayAction odAction = new OpenDisplayAction(); //Try to add the filename to the PROP_PATH IPath fPath = new Path(rdDisplays[ii].getName().replaceAll("\"", "").replace(".adl", ".opi")); System.out.println("Related display file: " + rdDisplays[ii].getName().replace(".adl", ".opi")); odAction.setPropertyValue(OpenDisplayAction.PROP_PATH, fPath); //Try to add macros System.out.println ("args " + rdDisplays[ii].getArgs()); if (rdDisplays[ii].getArgs() != null){ String argsIn = "true, " + rdDisplays[ii].getArgs().replaceAll("\"", ""); MacrosInput macIn; try { macIn = MacrosInput.recoverFromString( argsIn); odAction.setPropertyValue(OpenDisplayAction.PROP_MACROS, macIn ); } catch (Exception e) { e.printStackTrace(); } } if (rdDisplays[ii].getLabel() != null){ odAction.setPropertyValue(OpenDisplayAction.PROP_DESCRIPTION, rdDisplays[ii].getLabel().replaceAll("\"", "")); } if ((rdDisplays[ii].getPolicy() != null) ) { // policy is present if ( rdDisplays[ii].getPolicy().equals("replace display") ){ // replace the display odAction.setPropertyValue(OpenDisplayAction.PROP_REPLACE, true); } else { // don't replace the display odAction.setPropertyValue(OpenDisplayAction.PROP_REPLACE, false); } } else { // policy not present go to default odAction.setPropertyValue(OpenDisplayAction.PROP_REPLACE, false); //don't replace the display } ai.addAction(odAction); } } } } String label = rdWidget.getLabel(); if (label != null){ if (label.startsWith("-")){ // leading "-" was used to flag not using the icon. Just don't use the icon and throw this away label = label.substring(1); } } menuModel.setPropertyValue(MenuButtonModel.PROP_LABEL, label); } @Override public AbstractWidgetModel getWidgetModel() { return menuModel; } }
package gov.nih.nci.cabig.caaers.rules.business.service; import gov.nih.nci.cabig.caaers.AbstractTestCase; import gov.nih.nci.cabig.caaers.domain.*; import gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection; import gov.nih.nci.cabig.caaers.domain.report.Mandatory; import gov.nih.nci.cabig.caaers.domain.report.Report; import gov.nih.nci.cabig.caaers.domain.report.ReportMandatoryFieldDefinition; import java.util.ArrayList; import java.util.Collection; import java.util.List; import gov.nih.nci.cabig.caaers.domain.report.RequirednessIndicator; import gov.nih.nci.cabig.caaers.utils.DateUtils; import org.drools.spi.AgendaFilter; import org.easymock.classextension.EasyMock; import com.semanticbits.rules.api.BusinessRulesExecutionService; import com.semanticbits.rules.brxml.RuleSet; import com.semanticbits.rules.impl.RuleEvaluationResult; /** * * @author Biju Joseph * */ public class AdverseEventEvaluationServiceImplTest extends AbstractTestCase { Study study; BusinessRulesExecutionService businessRulesExecutionService; CaaersRulesEngineService caaersRulesEngineService; AdverseEventEvaluationServiceImpl impl; ExpeditedAdverseEventReport aeReport; List<Report> reports; List<AdverseEvent> aeList; final List<Object> evaluationResult = new ArrayList<Object>(); protected void setUp() throws Exception { super.setUp(); businessRulesExecutionService = new BusinessRulesExecutionService(){ public List<Object> fireRules(String arg0, List<Object> arg1) { return evaluationResult; } }; caaersRulesEngineService = registerMockFor(CaaersRulesEngineService.class); aeReport = registerMockFor(ExpeditedAdverseEventReport.class); study = registerMockFor(Study.class); EasyMock.expect(study.getId()).andReturn(1).anyTimes(); reports = new ArrayList<Report>(); Report r1 = Fixtures.createReport("r1"); Report r2 = Fixtures.createReport("r2"); Report r3 = Fixtures.createReport("r3"); reports.add(r1); reports.add(r2); reports.add(r3); aeList = new ArrayList<AdverseEvent>(); aeList.add(Fixtures.createAdverseEvent(1, Grade.SEVERE)); impl = new AdverseEventEvaluationServiceImpl(); impl.setBusinessRulesExecutionService(businessRulesExecutionService); impl.setCaaersRulesEngineService(caaersRulesEngineService); } /** * This method test {@link AdverseEventEvaluationServiceImpl#mandatorySections(gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport, gov.nih.nci.cabig.caaers.domain.report.ReportDefinition...)} */ public void testMandatorySections() throws Exception { if(DateUtils.compareDate(DateUtils.parseDate("05/28/2010"), DateUtils.today()) > 0){ assertTrue(true); return; } EasyMock.expect(aeReport.getTreatmentInformation()).andReturn(null).anyTimes(); EasyMock.expect(aeReport.getStudy()).andReturn(study).anyTimes(); EasyMock.expect(study.getStudyOrganizations()).andReturn(new ArrayList<StudyOrganization>()).anyTimes(); EasyMock.expect(aeReport.getAdverseEvents()).andReturn(aeList).anyTimes(); EasyMock.expect(study.getPrimaryFundingSponsorOrganization()).andReturn(Fixtures.createOrganization("test",1)).anyTimes(); EasyMock.expect(study.getShortTitle()).andReturn("test").anyTimes(); EasyMock.expect(caaersRulesEngineService.constructPackageName("SponsorDefinedStudy", "1", null, "1", "SAE Reporting Rules")).andReturn("abcd").anyTimes(); EasyMock.expect(caaersRulesEngineService.getRuleSetByPackageName("abcd")).andReturn(new RuleSet()).anyTimes(); //frame the evalutaion result RuleEvaluationResult result1 = new RuleEvaluationResult(); result1.setMessage("ADVERSE_EVENT_SECTION"); evaluationResult.add(result1); replayMocks(); Collection<ExpeditedReportSection> sections = impl.mandatorySections(aeReport, reports.get(0).getReportDefinition(), reports.get(1).getReportDefinition(), reports.get(2).getReportDefinition() ); assertEquals("ADVERSE_EVENT_SECTION", sections.iterator().next().name()); verifyMocks(); } /** * This method test {@link AdverseEventEvaluationServiceImpl#mandatorySections(gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport, gov.nih.nci.cabig.caaers.domain.report.ReportDefinition...)} */ public void testMandatorySections_AllReportsActive() throws Exception{ if(DateUtils.compareDate(DateUtils.parseDate("05/28/2010"), DateUtils.today()) > 0){ assertTrue(true); return; } EasyMock.expect(aeReport.getReports()).andReturn(reports); EasyMock.expect(aeReport.getTreatmentInformation()).andReturn(null).anyTimes(); EasyMock.expect(aeReport.getStudy()).andReturn(study).anyTimes(); EasyMock.expect(study.getStudyOrganizations()).andReturn(new ArrayList<StudyOrganization>()).anyTimes(); EasyMock.expect(aeReport.getAdverseEvents()).andReturn(aeList).anyTimes(); EasyMock.expect(study.getPrimaryFundingSponsorOrganization()).andReturn(Fixtures.createOrganization("test",1)).anyTimes(); EasyMock.expect(study.getShortTitle()).andReturn("test").anyTimes(); //frame the evalutaion result RuleEvaluationResult result1 = new RuleEvaluationResult(); result1.setMessage("ADVERSE_EVENT_SECTION"); evaluationResult.add(result1); replayMocks(); Collection<ExpeditedReportSection> sections = impl.mandatorySections(aeReport); assertEquals("ADVERSE_EVENT_SECTION", sections.iterator().next().name()); verifyMocks(); } /** * This method test {@link AdverseEventEvaluationServiceImpl#mandatorySections(gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport, gov.nih.nci.cabig.caaers.domain.report.ReportDefinition...)} */ public void testMandatorySections_AllReportsInActive() throws Exception{ EasyMock.expect(aeReport.getReports()).andReturn(reports); for(Report r: reports) r.setStatus(ReportStatus.REPLACED); EasyMock.expect(aeReport.getStudy()).andReturn(study).anyTimes(); EasyMock.expect(study.getStudyOrganizations()).andReturn(new ArrayList<StudyOrganization>()).anyTimes(); EasyMock.expect(aeReport.getAdverseEvents()).andReturn(aeList).anyTimes(); EasyMock.expect(study.getPrimaryFundingSponsorOrganization()).andReturn(Fixtures.createOrganization("test",1)).anyTimes(); EasyMock.expect(study.getShortTitle()).andReturn("test").anyTimes(); //frame the evalutaion result RuleEvaluationResult result1 = new RuleEvaluationResult(); result1.setMessage("ADVERSE_EVENT_SECTION"); evaluationResult.add(result1); replayMocks(); Collection<ExpeditedReportSection> sections = impl.mandatorySections(aeReport); assertTrue(sections.isEmpty()); verifyMocks(); } //optional when mandatory field has no rules information. public void testEvaluateFieldLevelRules(){ EasyMock.expect(aeReport.getTreatmentInformation()).andReturn(null).anyTimes(); replayMocks(); ReportMandatoryFieldDefinition def1 = Fixtures.createMandatoryField("a", RequirednessIndicator.OPTIONAL); assertEquals("OPTIONAL", impl.evaluateFieldLevelRules(aeReport, reports.get(0), def1)); verifyMocks(); } //checks that agenda filter is created and passed in the input public void testEvaluateFieldLevelRulesAgnedaFilterAvailable(){ impl.setBusinessRulesExecutionService(new BusinessRulesExecutionService(){ public List<Object> fireRules(String bindingURI, List<Object> objects) { boolean hasAgendaFilter = false; for(Object o : objects) hasAgendaFilter |= (o instanceof AgendaFilter); if(!hasAgendaFilter) throw new RuntimeException("Agenda filter not present in input"); return null; } }); EasyMock.expect(aeReport.getTreatmentInformation()).andReturn(null).anyTimes(); EasyMock.expect(aeReport.getStudy()).andReturn(study).anyTimes(); replayMocks(); ReportMandatoryFieldDefinition def1 = Fixtures.createMandatoryField("a", RequirednessIndicator.OPTIONAL); def1.setRuleBindURL("abc"); def1.setRuleName("a"); impl.evaluateFieldLevelRules(aeReport, reports.get(0), def1); verifyMocks(); } }
package com.goree.api.sample; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.goree.api.Application; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes={Application.class}) public class MyBatisTest { @Autowired private MybatisTestService service; @Test public void selectWithMybatis() { FooBar fooBar = service.selectFooBar(); Assert.assertNotNull(fooBar); } }
package de.itemis.xtext.utils.jface.viewers; import java.util.List; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.emf.ecore.EObject; import org.eclipse.jface.bindings.keys.KeyStroke; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.jface.text.source.AnnotationModel; import org.eclipse.jface.text.source.ICharacterPairMatcher; import org.eclipse.jface.text.source.ISharedTextColors; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.internal.editors.text.EditorsPlugin; import org.eclipse.ui.swt.IFocusService; import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor; import org.eclipse.ui.texteditor.AnnotationPreference; import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess; import org.eclipse.ui.texteditor.MarkerAnnotationPreferences; import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; import org.eclipse.xtext.nodemodel.ICompositeNode; import org.eclipse.xtext.nodemodel.ILeafNode; import org.eclipse.xtext.nodemodel.util.NodeModelUtils; import org.eclipse.xtext.parser.IParseResult; import org.eclipse.xtext.resource.XtextResource; import org.eclipse.xtext.ui.editor.XtextEditor; import org.eclipse.xtext.ui.editor.XtextSourceViewer; import org.eclipse.xtext.ui.editor.XtextSourceViewerConfiguration; import org.eclipse.xtext.ui.editor.bracketmatching.BracketMatchingPreferencesInitializer; import org.eclipse.xtext.ui.editor.model.XtextDocument; import org.eclipse.xtext.ui.editor.preferences.IPreferenceStoreAccess; import org.eclipse.xtext.ui.editor.quickfix.IssueResolutionProvider; import org.eclipse.xtext.ui.editor.validation.AnnotationIssueProcessor; import org.eclipse.xtext.ui.editor.validation.ValidationJob; import org.eclipse.xtext.util.concurrent.IUnitOfWork; import org.eclipse.xtext.validation.CheckMode; import org.eclipse.xtext.validation.IResourceValidator; import org.eclipse.xtext.validation.Issue; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import de.itemis.xtext.utils.jface.fieldassist.CompletionProposalAdapter; import de.itemis.xtext.utils.jface.viewers.context.IXtextFakeContextResourcesProvider; import de.itemis.xtext.utils.jface.viewers.context.XtextFakeResourceContext; /** * * @author andreas.muelder@itemis.de * @author alexander.nyssen@itemis.de * @author patrick.koenemann@itemis.de * */ @SuppressWarnings("restriction") public class StyledTextXtextAdapter { /** * The sourceViewer, that provides additional functions to the styled text * widget */ protected XtextSourceViewer sourceviewer; private ValidationJob validationJob; private IssueResolutionProvider resolutionProvider = new IssueResolutionProvider.NullImpl(); @Inject private IPreferenceStoreAccess preferenceStoreAccess; @Inject private ICharacterPairMatcher characterPairMatcher; @Inject private XtextSourceViewerConfiguration configuration; @Inject private XtextStyledTextHighlightingHelper xtextStyledTextHighlightingHelper; @Inject private IResourceValidator validator; @Inject private Provider<IDocumentPartitioner> documentPartitioner; @Inject private XtextDocument document; private XtextFakeResourceContext fakeResourceContext; private final IXtextFakeContextResourcesProvider contextFakeResourceProvider; private StyledText styledText; private ControlDecoration decoration; public StyledTextXtextAdapter(Injector injector, IXtextFakeContextResourcesProvider contextFakeResourceProvider) { this.contextFakeResourceProvider = contextFakeResourceProvider; injector.injectMembers(this); // create fake resource and containing resource set createFakeResourceContext(injector); } public StyledTextXtextAdapter(Injector injector) { this(injector, IXtextFakeContextResourcesProvider.NULL_CONTEXT_PROVIDER); } public void adapt(StyledText styledText) { this.styledText = styledText; // perform initialization of fake resource context updateFakeResourceContext(); // connect Xtext document to fake resource initXtextDocument(fakeResourceContext); // connect xtext document to xtext source viewer createXtextSourceViewer(); // install semantic highlighting support installHighlightingHelper(); validationJob = createValidationJob(); document.setValidationJob(validationJob); styledText.setData(StyledTextXtextAdapter.class.getCanonicalName(), this); final IContentAssistant contentAssistant = sourceviewer.getContentAssistant(); final CompletionProposalAdapter completionProposalAdapter = new CompletionProposalAdapter(styledText, contentAssistant, KeyStroke.getInstance(SWT.CTRL, SWT.SPACE), null); if ((styledText.getStyle() & SWT.SINGLE) != 0) { // The regular key down event is too late (after popup is closed). // when using the StyledText.VerifyKey event (3005), we get the // event early enough! styledText.addListener(3005, new Listener() { public void handleEvent(Event event) { if (event.character == SWT.CR && !completionProposalAdapter.isProposalPopupOpen()) { Event selectionEvent = new Event(); selectionEvent.type = SWT.DefaultSelection; selectionEvent.widget = event.widget; for (Listener l : event.widget.getListeners(SWT.DefaultSelection)) { l.handleEvent(selectionEvent); } } } }); } // Register focus tracker for evaluating the active focus control in // core expression IFocusService service = (IFocusService) PlatformUI.getWorkbench().getService(IFocusService.class); service.addFocusTracker(styledText, StyledText.class.getCanonicalName()); // add JDT Style code completion hint decoration createContentAssistDecoration(styledText); initSelectionProvider(); } protected void initSelectionProvider() { // Overrides the editors selection provider to provide the text // selection if opened within an editor context try { IWorkbenchPartSite site = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .getActiveEditor().getSite(); XtextStyledTextSelectionProvider xtextStyledTextSelectionProvider = new XtextStyledTextSelectionProvider(); ChangeSelectionProviderOnFocusGain listener = new ChangeSelectionProviderOnFocusGain(site, xtextStyledTextSelectionProvider); styledText.addFocusListener(listener); styledText.addDisposeListener(listener); } catch (NullPointerException ex) { //Do nothing, not opened within editor context } } private void createContentAssistDecoration(StyledText styledText) { decoration = new ControlDecoration(styledText, SWT.TOP | SWT.LEFT); decoration.setShowHover(true); decoration.setShowOnlyOnFocus(true); final Image image = ImageDescriptor.createFromFile(XtextStyledTextCellEditor.class, "images/content_assist_cue.gif").createImage(); decoration.setImage(image); decoration.setDescriptionText("Content Assist Available (CTRL + Space)"); decoration.setMarginWidth(2); styledText.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { if (decoration != null) { decoration.dispose(); } if (image != null) { image.dispose(); } } }); } protected ValidationJob createValidationJob() { return new ValidationJob(validator, document, new AnnotationIssueProcessor(document, sourceviewer.getAnnotationModel(), resolutionProvider), CheckMode.ALL); } protected void createFakeResourceContext(Injector injector) { this.fakeResourceContext = new XtextFakeResourceContext(injector); } protected void createXtextSourceViewer() { sourceviewer = new XtextSourceViewerEx(styledText, preferenceStoreAccess.getPreferenceStore()); sourceviewer.configure(configuration); sourceviewer.setDocument(document, new AnnotationModel()); SourceViewerDecorationSupport support = new SourceViewerDecorationSupport(sourceviewer, null, new DefaultMarkerAnnotationAccess(), getSharedColors()); configureSourceViewerDecorationSupport(support); } protected ISharedTextColors getSharedColors() { return EditorsPlugin.getDefault().getSharedTextColors(); } /** * Creates decoration support for the sourceViewer. code is entirely copied * from {@link XtextEditor} and its super class * {@link AbstractDecoratedTextEditor}. * */ protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) { MarkerAnnotationPreferences annotationPreferences = new MarkerAnnotationPreferences(); @SuppressWarnings("unchecked") List<AnnotationPreference> prefs = annotationPreferences.getAnnotationPreferences(); for (AnnotationPreference annotationPreference : prefs) { support.setAnnotationPreference(annotationPreference); } support.setCharacterPairMatcher(characterPairMatcher); support.setMatchingCharacterPainterPreferenceKeys(BracketMatchingPreferencesInitializer.IS_ACTIVE_KEY, BracketMatchingPreferencesInitializer.COLOR_KEY); support.install(preferenceStoreAccess.getPreferenceStore()); } protected void initXtextDocument(XtextFakeResourceContext context) { document.setInput(context.getFakeResource()); IDocumentPartitioner partitioner = documentPartitioner.get(); partitioner.connect(document); document.setDocumentPartitioner(partitioner); } public void setVisibleRegion(int start, int length) { sourceviewer.setVisibleRegion(start, length); } public void resetVisibleRegion() { sourceviewer.resetVisibleRegion(); } private void installHighlightingHelper() { if (xtextStyledTextHighlightingHelper != null) { xtextStyledTextHighlightingHelper.install(this, sourceviewer); } } private void uninstallHighlightingHelper() { if (xtextStyledTextHighlightingHelper != null) { xtextStyledTextHighlightingHelper.uninstall(); } } public void dispose() { uninstallHighlightingHelper(); document.disposeInput(); } protected XtextSourceViewerConfiguration getXtextSourceViewerConfiguration() { return configuration; } protected XtextDocument getXtextDocument() { return document; } protected XtextSourceViewer getXtextSourceviewer() { return sourceviewer; } public IParseResult getXtextParseResult() { return document.readOnly(new IUnitOfWork<IParseResult, XtextResource>() { public IParseResult exec(XtextResource state) throws Exception { return state.getParseResult(); } }); } public IContentAssistant getContentAssistant() { return getXtextSourceviewer().getContentAssistant(); } public List<Issue> getXtextValidationIssues() { return validationJob.createIssues(new NullProgressMonitor()); } public void updateFakeResourceContext() { fakeResourceContext.updateFakeResourceContext(contextFakeResourceProvider); } protected IXtextFakeContextResourcesProvider getFakeResourceContextProvider() { return contextFakeResourceProvider; } public XtextFakeResourceContext getFakeResourceContext() { return fakeResourceContext; } private class XtextStyledTextSelectionProvider implements ISelectionProvider { public void setSelection(ISelection selection) { } public void removeSelectionChangedListener(ISelectionChangedListener listener) { } public void addSelectionChangedListener(ISelectionChangedListener listener) { } public ISelection getSelection() { if (styledText.isDisposed()) return StructuredSelection.EMPTY; int offset = styledText.getCaretOffset() - 1; XtextResource fakeResource = StyledTextXtextAdapter.this.getFakeResourceContext().getFakeResource(); IParseResult parseResult = fakeResource.getParseResult(); if (parseResult == null) return StructuredSelection.EMPTY; ICompositeNode rootNode = parseResult.getRootNode(); ILeafNode selectedNode = NodeModelUtils.findLeafNodeAtOffset(rootNode, offset); final EObject selectedObject = NodeModelUtils.findActualSemanticObjectFor(selectedNode); if (selectedObject == null) { return StructuredSelection.EMPTY; } return new StructuredSelection(selectedObject); } } private class ChangeSelectionProviderOnFocusGain implements FocusListener, DisposeListener { private ISelectionProvider selectionProviderOnFocusGain; private ISelectionProvider selectionProviderOnFocusLost; private IWorkbenchPartSite site; public ChangeSelectionProviderOnFocusGain(IWorkbenchPartSite site, ISelectionProvider selectionProviderOnFocusGain) { this.selectionProviderOnFocusGain = selectionProviderOnFocusGain; this.site = site; } public void focusLost(FocusEvent e) { if (selectionProviderOnFocusLost != null) { site.setSelectionProvider(selectionProviderOnFocusLost); } } public void focusGained(FocusEvent e) { selectionProviderOnFocusLost = site.getSelectionProvider(); site.setSelectionProvider(selectionProviderOnFocusGain); } public void widgetDisposed(DisposeEvent e) { ((StyledText) e.getSource()).removeFocusListener(this); ((StyledText) e.getSource()).removeDisposeListener(this); } } }
package br.net.mirante.singular.exemplos.ggtox.primariasimplificada.common; import br.net.mirante.singular.exemplos.SelectBuilder; import br.net.mirante.singular.exemplos.SelectBuilder.CidadeDTO; import br.net.mirante.singular.exemplos.SelectBuilder.EstadoDTO; import br.net.mirante.singular.exemplos.ggtox.primariasimplificada.domain.SubgrupoEntity; import br.net.mirante.singular.exemplos.ggtox.primariasimplificada.form.SPackagePPSCommon; import br.net.mirante.singular.exemplos.ggtox.primariasimplificada.listeners.IngredienteAtivoUpdateListener; import br.net.mirante.singular.exemplos.ggtox.primariasimplificada.validators.ResiduoValidator; import br.net.mirante.singular.form.*; import br.net.mirante.singular.form.persistence.STypePersistentComposite; import br.net.mirante.singular.form.provider.SSimpleProvider; import br.net.mirante.singular.form.type.core.*; import br.net.mirante.singular.form.type.core.attachment.STypeAttachment; import br.net.mirante.singular.form.util.transformer.Value; import br.net.mirante.singular.form.view.SViewListByMasterDetail; import br.net.mirante.singular.form.view.SViewListByTable; import java.util.Optional; import static br.net.mirante.singular.exemplos.ggtox.primariasimplificada.form.SPackagePPSCommon.ppsService; import static br.net.mirante.singular.exemplos.ggtox.primariasimplificada.form.STypePeticaoPrimariaSimplificada.OBRIGATORIO; import static br.net.mirante.singular.exemplos.ggtox.primariasimplificada.form.STypePeticaoPrimariaSimplificada.QUANTIDADE_MINIMA; import static br.net.mirante.singular.form.util.SingularPredicates.*; @SInfoType(spackage = SPackagePPSCommon.class) public class STypeEstudosResiduos extends STypePersistentComposite { private EstudoResiduo estudoResiduo; @Override protected void onLoadType(TypeBuilder tb) { super.onLoadType(tb); this.asAtr() .label("Estudo de Resíduos"); estudoResiduo = new EstudoResiduo(this); estudoResiduo .ensaio .root .asAtr().dependsOn(estudoResiduo.origemEstudo) .exists(typeValueIsEqualsTo(estudoResiduo.origemEstudo, EstudoResiduo.ESTUDO_NOVO)); } public class EstudoResiduo { public static final String ESTUDO_PUBLICADO = "Publicado pela ANVISA"; public static final String ESTUDO_MATRIZ = "Conforme matriz"; public static final String ESTUDO_NOVO = "Novo"; public static final String NOME_OUTRA_CULTURA_FIELD_NAME = "nomeOutraCultura"; public static final String CULTURAS_PATH = "culturas"; public static final String ORIGEM_ESTUDO_PATH = "origemEstudo"; public static final String CULTURA = "cultura"; public static final String NOME_CULTURA = "nomeCultura"; public static final String OUTRA_CULTURA = "outraCultura"; private final STypeList<STypeComposite<SIComposite>, SIComposite> root; private final STypeComposite<SIComposite> rootType; final STypeString origemEstudo; public final Ensaio ensaio; public EstudoResiduo(STypeComposite<SIComposite> parentType) { root = parentType.addFieldListOfComposite(CULTURAS_PATH, CULTURA); rootType = root.getElementsType(); final STypeComposite<SIComposite> cultura = rootType.addFieldComposite(CULTURA); final STypeLong codCultura = cultura.addField("codCultura", STypeLong.class); final STypeLong codSubgrupo = cultura.addField("codSubgrupo", STypeLong.class); final STypeString nomeCultura = cultura.addField(NOME_CULTURA, STypeString.class); final STypeString nomeOutraCultura = rootType.addFieldString(NOME_OUTRA_CULTURA_FIELD_NAME); final STypeComposite<SIComposite> emprego = rootType.addFieldComposite("emprego"); final STypeLong codEmprego = emprego.addField("codEmprego", STypeLong.class); final STypeString nomeEmprego = emprego.addField("nomeEmprego", STypeString.class); final STypeBoolean outraCultura = rootType.addFieldBoolean(OUTRA_CULTURA); final STypeBoolean parteComestivel = rootType.addFieldBoolean("parteComestivel"); final STypeInteger intervaloPretendido = rootType.addFieldInteger("intervaloPretendido"); final STypeComposite<SIComposite> norma = rootType.addFieldComposite("norma"); final STypeInteger idNorma = norma.addFieldInteger("idNorma"); final STypeString descricaoNorma = norma.addFieldString("descricaoNorma"); final STypeString observacoes = rootType.addFieldString("observacoes"); origemEstudo = rootType.addFieldString(ORIGEM_ESTUDO_PATH); final STypeString estudoPublicado = rootType.addFieldString("estudoPublicado"); final STypeString numeroEstudo = rootType.addFieldString("numeroEstudo"); final STypeComposite<SIComposite> unidadeMediadaDosagem = rootType.addFieldComposite("unidadeMediadaDosagem"); final STypeInteger idDosagem = unidadeMediadaDosagem.addFieldInteger("idDosagem"); final STypeString siglaDosagem = unidadeMediadaDosagem.addFieldString("siglaDosagem"); final STypeBoolean adjuvante = rootType.addFieldBoolean("adjuvante"); ensaio = new Ensaio(rootType); // estudo = null; final STypeAttachment estudoResiduo = rootType.addFieldAttachment("estudoResiduo"); root .withView(new SViewListByMasterDetail() .col("Cultura", si -> { if (si instanceof SIComposite) { return Optional .ofNullable(((SIComposite) si).getField("cultura")) .map(sic -> ((SIComposite) sic).getField("nomeCultura")) .map(SInstance::getValue) .map(Object::toString) .orElse(Value.of(si, NOME_OUTRA_CULTURA_FIELD_NAME)); } else { return null; } }) .col(emprego) .col(origemEstudo) .largeSize() ); cultura .asAtrBootstrap() .colPreference(6) .asAtr() .label("Cultura") .required(OBRIGATORIO) .dependsOn(outraCultura, origemEstudo) .exists(allMatches(typeValueIsNotEqualsTo(outraCultura, Boolean.TRUE))); cultura .selection() .id(codCultura) .display(nomeCultura) .simpleProvider((SSimpleProvider) builder -> { ppsService(builder.getCurrentInstance()).buscarCulturas() .forEach(culturaEntity -> builder.add() .set(codCultura, culturaEntity.getCod()) .set(codSubgrupo, Optional.ofNullable(culturaEntity.getSubgrupo()).map(SubgrupoEntity::getCod).orElse(null)) .set(nomeCultura, culturaEntity.getNome())); }); nomeOutraCultura .asAtrBootstrap() .colPreference(6) .asAtr() .label("Nome da Cultura") .required(OBRIGATORIO) .dependsOn(outraCultura) .exists(typeValueIsTrue(outraCultura)); emprego .asAtrBootstrap() .colPreference(6) .asAtr() .required(OBRIGATORIO) .label("Emprego"); emprego .selection() .id(codEmprego) .display(nomeEmprego) .simpleProvider((SSimpleProvider) builder -> ppsService(builder.getCurrentInstance()) .buscarModalidadesDeEmprego() .forEach(empregoEntity -> { builder .add() .set(codEmprego, empregoEntity.getCod()) .set(nomeEmprego, empregoEntity.getNome()); })); outraCultura .asAtr() .label("Outra cultura") .asAtrBootstrap() .colPreference(6); parteComestivel .asAtr() .label("Parte Comestível?") .asAtrBootstrap() .colPreference(6); intervaloPretendido .asAtr() .required(OBRIGATORIO) .label("Intervalo de Segurança Pretendido (em dias)") .asAtrBootstrap() .colPreference(6); norma .asAtr() .required(OBRIGATORIO) .label("Norma") .asAtrBootstrap() .colPreference(4); norma .selection() .id(idNorma) .display(descricaoNorma) .simpleProvider(builder -> ppsService(builder.getCurrentInstance()) .buscarNormas() .forEach(normaEntity -> builder.add() .set(idNorma, normaEntity.getCod()) .set(descricaoNorma, normaEntity.getNome()))); observacoes .asAtr() .maxLength(1000) .label("Observações") .asAtrBootstrap() .colPreference(12); observacoes .withTextAreaView(); origemEstudo .withRadioView() .selectionOf(ESTUDO_MATRIZ, ESTUDO_PUBLICADO, ESTUDO_NOVO) .asAtr() .required(OBRIGATORIO) .label("Origem do Estudo") .asAtrBootstrap() .newRow(); estudoPublicado .asAtr() .required(OBRIGATORIO) .maxLength(20) .label("Código do Estudo Publicado pela ANVISA") .dependsOn(origemEstudo) .exists(typeValueIsEqualsTo(origemEstudo, ESTUDO_PUBLICADO)) .asAtrBootstrap().newRow(); numeroEstudo .asAtr() .label("Número do Estudo") .required(OBRIGATORIO) .dependsOn(origemEstudo) .exists(typeValueIsEqualsTo(origemEstudo, ESTUDO_NOVO)) .asAtrBootstrap() .colPreference(4); unidadeMediadaDosagem .asAtr() .required(OBRIGATORIO) .dependsOn(origemEstudo) .exists(typeValueIsEqualsTo(origemEstudo, ESTUDO_NOVO)) .label("Unidade de medida da dosagem") .asAtrBootstrap() .colPreference(4); unidadeMediadaDosagem .selection() .id(idDosagem) .display(siglaDosagem) .simpleProvider(builder -> { ppsService(builder.getCurrentInstance()).buscarTipoDeDose() .forEach(doseEntity -> builder.add() .set(idDosagem, doseEntity.getCod()) .set(siglaDosagem, doseEntity.getNome())); }); adjuvante .withSelectView() .selectionOf(Boolean.class) .selfId() .display(bool -> bool ? "Sim" : "Não") .simpleConverter(); adjuvante .asAtr() .required(OBRIGATORIO) .label("Adjuvante") .dependsOn(origemEstudo) .exists(typeValueIsEqualsTo(origemEstudo, ESTUDO_NOVO)) .asAtrBootstrap() .colPreference(4); estudoResiduo .asAtr() .required(OBRIGATORIO) .label("Estudo de Resíduo") .dependsOn(origemEstudo) .exists(typeValueIsEqualsTo(origemEstudo, ESTUDO_NOVO)); } } public class Ensaio { public final STypeList<STypeComposite<SIComposite>, SIComposite> root; public final STypeComposite<SIComposite> rootType; public STypeString codigoEnsaio; public STypeComposite<SIComposite> estado; public STypeString nomeEstado; public STypeString siglaEstado; public STypeComposite<SIComposite> cidade; public STypeInteger idCidade; public STypeString nomeCidade; public Amostra amostra; public Ensaio(STypeComposite<SIComposite> parent) { this.root = parent.addFieldListOfComposite("ensaios", "ensaio"); this.rootType = root.getElementsType(); create(); configure(); } private void create() { codigoEnsaio = rootType.addField("codigoEnsaio", STypeString.class); estado = rootType.addFieldComposite("estado"); nomeEstado = estado.addFieldString("nome"); siglaEstado = estado.addFieldString("sigla"); cidade = rootType.addFieldComposite("cidade"); idCidade = cidade.addFieldInteger("id"); nomeCidade = cidade.addFieldString("nome"); } private void configure() { codigoEnsaio .asAtr() .required(OBRIGATORIO) .label("ID do Ensaio") .asAtrBootstrap() .colPreference(3); estado .asAtr() .required(OBRIGATORIO) .label("Estado") .asAtrBootstrap() .colPreference(3); estado.selectionOf(EstadoDTO.class) .id(EstadoDTO::getSigla) .display("${nome} - ${sigla}") .autoConverterOf(EstadoDTO.class) .simpleProvider(ins -> SelectBuilder.buildEstados()); cidade .asAtr() .required(inst -> OBRIGATORIO) .label("Cidade") .enabled(inst -> Value.notNull(inst, siglaEstado)) .dependsOn(estado) .asAtrBootstrap() .colPreference(3); cidade.selectionOf(CidadeDTO.class) .id(CidadeDTO::getId) .display(CidadeDTO::getNome) .autoConverterOf(CidadeDTO.class) .simpleProvider(i -> SelectBuilder.buildMunicipiosFiltrado((String) Value.of(i, (STypeSimple) estado.getField(siglaEstado.getNameSimple())))); amostra = new Amostra(rootType); root .withView(new SViewListByMasterDetail() .col(codigoEnsaio, "ID") .col(estado, "Estado") .col(cidade, "Cidade") ) .asAtr().label("Ensaio"); } } public class Amostra { private final STypeList<STypeComposite<SIComposite>, SIComposite> root; private final STypeComposite<SIComposite> rootType; public final STypeAtivoAmostra ativoAmostra; public Amostra(STypeComposite<SIComposite> parentType) { root = parentType.addFieldListOfComposite("amostras", "amostra"); rootType = root.getElementsType(); final STypeString id = rootType.addFieldString("id"); final STypeDecimal dose = rootType.addFieldDecimal("dose"); final STypeInteger aplicacoes = rootType.addFieldInteger("aplicacoes"); final STypeInteger dat = rootType.addFieldInteger("dat"); final STypeDecimal loq = rootType.addFieldDecimal("loq"); final STypeDecimal residuo = rootType.addFieldDecimal("residuo"); ativoAmostra = rootType.addField("ativos", STypeAtivoAmostra.class); final STypeBoolean tempoMaior30Dias = rootType.addFieldBoolean("tempoMaior30Dias"); final STypeAttachment estudoEstabilidade = rootType.addFieldAttachment("estudoEstabilidade"); final STypeBoolean metabolito = rootType.addFieldBoolean("metabolito"); final STypeList<STypeComposite<SIComposite>, SIComposite> metabolitos = rootType.addFieldListOfComposite("metabolitos", "metabolito"); final STypeString descricaoMetabolito = metabolitos.getElementsType().addFieldString("descricao"); final STypeDecimal loqMetabolito = metabolitos.getElementsType().addFieldDecimal("loqMetabolito"); final STypeDecimal residuoMetabolito = metabolitos.getElementsType().addFieldDecimal("residuoMetabolito"); root .withView(new SViewListByMasterDetail() .col(id, "Id") .col(dose, "Dose") .col(aplicacoes, "Aplicações") .col(ativoAmostra.nomeComumPortugues, "Ingrediente Ativo") .col(residuo, "Residuo") .col(dat, "DAT") ) .asAtr().label("Amostras"); id .asAtr() .label("ID da Amostra") .required(OBRIGATORIO) .asAtrBootstrap() .colPreference(4); dose .asAtrBootstrap() .colPreference(4) .asAtr() .label("Dose") .required(OBRIGATORIO); aplicacoes .asAtrBootstrap() .colPreference(4) .asAtr() .label("Número de Aplicações") .required(OBRIGATORIO); dat .asAtr() .required(OBRIGATORIO) .label("DAT") .asAtrBootstrap() .colPreference(4); loq .asAtr() .required(OBRIGATORIO) .label("LoQ (mg/KG)") .fractionalMaxLength(4); residuo .addInstanceValidator(new ResiduoValidator(loq)) .asAtr() .required(OBRIGATORIO) .label("Resíduo (mg/KG)") .fractionalMaxLength(4); ativoAmostra .asAtr() .required(OBRIGATORIO) .label("Ingrediente Ativo da Amostra (informados na seção de ativos)") .asAtrBootstrap() .colPreference(6); ativoAmostra .asAtr() .dependsOn(rootType.getDictionary().getType(STypeIngredienteAtivoPeticaoPrimariaSimplificada.class).getField(STypeIngredienteAtivoPeticaoPrimariaSimplificada.FIELD_NAME_LIST_ATIVOS)); ativoAmostra .withUpdateListener(new IngredienteAtivoUpdateListener<>()); tempoMaior30Dias .asAtr() .label("Tempo Entre Análise e Colheita Maior que 30 Dias") .asAtrBootstrap().colPreference(6) .newRow(); estudoEstabilidade .asAtr() .required(OBRIGATORIO) .label("Estudo de Estabilidade") .dependsOn(tempoMaior30Dias) .exists(typeValueIsTrue(tempoMaior30Dias)); metabolito .withRadioView() .asAtr() .required(OBRIGATORIO) .label("Metabólito"); metabolitos .withMiniumSizeOf(QUANTIDADE_MINIMA) .withView(SViewListByTable::new) .asAtr() .label("Metabólitos") .dependsOn(metabolito) .exists(typeValueIsTrue(metabolito)); descricaoMetabolito .asAtr() .required(OBRIGATORIO) .label("Descrição"); loqMetabolito .asAtr() .required(OBRIGATORIO) .label("LoQ (mg/KG)") .fractionalMaxLength(4); residuoMetabolito .addInstanceValidator(new ResiduoValidator(loqMetabolito)) .asAtr() .required(OBRIGATORIO) .label("Resíduo (mg/KG)") .fractionalMaxLength(4); } } }
package uk.ac.ebi.spot.goci.curation.service.deposition; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import uk.ac.ebi.spot.goci.curation.service.AssociationOperationsService; import uk.ac.ebi.spot.goci.exception.EnsemblMappingException; import uk.ac.ebi.spot.goci.model.*; import uk.ac.ebi.spot.goci.model.deposition.DepositionAssociationDto; import uk.ac.ebi.spot.goci.repository.AssociationExtensionRepository; import uk.ac.ebi.spot.goci.service.LociAttributesService; import uk.ac.ebi.spot.goci.service.MapCatalogService; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.List; @Component public class DepositionAssociationService { @Autowired AssociationOperationsService associationOperationsService; @Autowired LociAttributesService lociService; @Autowired MapCatalogService mapCatalogService; @Autowired AssociationExtensionRepository extensionRepository; public DepositionAssociationService() {} public String saveAssociations(SecureUser currentUser, String studyTag, Study study, List<DepositionAssociationDto> associations) { //find associations in study StringBuffer studyNote = new StringBuffer(); Collection<Association> associationList = new ArrayList<>(); for (DepositionAssociationDto associationDto : associations) { if (associationDto.getStudyTag().equals(studyTag)) { Association association = new Association(); if (associationDto.getStandardError() != null) { association.setStandardError(associationDto.getStandardError().floatValue()); } String pValue = associationDto.getPValue(); if (pValue != null && pValue.toLowerCase().contains("e")) { String[] pValues = pValue.toLowerCase().split("e"); int exponent = Integer.valueOf(pValues[1]); int mantissa = Double.valueOf(pValues[0]).intValue(); association.setPvalueExponent(exponent); association.setPvalueMantissa(mantissa); } association.setPvalueDescription(associationDto.getPValueText()); String rsID = associationDto.getVariantID(); List<Locus> locusList = new ArrayList<>(); Locus locus = new Locus(); SingleNucleotidePolymorphism snp = lociService.createSnp(rsID); studyNote.append("added SNP " + rsID + "\n"); RiskAllele riskAllele = lociService.createRiskAllele(rsID + "-" + associationDto.getEffectAllele(), snp); List<RiskAllele> alleleList = new ArrayList<>(); alleleList.add(riskAllele); locus.setStrongestRiskAlleles(alleleList); locusList.add(locus); association.setLoci(locusList); associationOperationsService.saveAssociation(association, study, new ArrayList<>()); associationList.add(association); if(associationDto.getEffectAlleleFrequency() != null) { association.setRiskFrequency(associationDto.getEffectAlleleFrequency().toString()); } if(associationDto.getStandardError() != null) { association.setStandardError(associationDto.getStandardError().floatValue()); } if(associationDto.getOddsRatio() != null) { association.setOrPerCopyNum(associationDto.getOddsRatio().floatValue()); } if(associationDto.getBeta() != null) { association.setBetaNum(associationDto.getBeta().floatValue()); } if(associationDto.getBetaUnit() != null) { association.setBetaUnit(associationDto.getBetaUnit()); } if(associationDto.getCiLower() != null) { association.setRange("[" + associationDto.getCiLower() + "-" + associationDto.getCiUpper() + "]"); } association.setBetaDirection(associationDto.getBetaDirection()); AssociationExtension associationExtension = new AssociationExtension(); associationExtension.setAssociation(association); associationExtension.setEffectAllele(associationDto.getEffectAllele()); associationExtension.setOtherAllele(associationDto.getOtherAllele()); extensionRepository.save(associationExtension); association.setAssociationExtension(associationExtension); associationOperationsService.saveAssociation(association, study, new ArrayList<>()); } } try { mapCatalogService.mapCatalogContentsByAssociations(currentUser.getEmail(), associationList); studyNote.append("mapped associations" + "\n"); } catch (EnsemblMappingException e) { e.printStackTrace(); studyNote.append("error mapping associations" + "\n"); } return studyNote.toString(); } }
package uk.ac.ebi.spot.goci.curation.service; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import uk.ac.ebi.spot.goci.curation.builder.AssociationBuilder; import uk.ac.ebi.spot.goci.curation.builder.EfoTraitBuilder; import uk.ac.ebi.spot.goci.curation.builder.GeneBuilder; import uk.ac.ebi.spot.goci.curation.builder.LocationBuilder; import uk.ac.ebi.spot.goci.curation.builder.LocusBuilder; import uk.ac.ebi.spot.goci.curation.builder.RegionBuilder; import uk.ac.ebi.spot.goci.curation.builder.RiskAlleleBuilder; import uk.ac.ebi.spot.goci.curation.builder.SingleNucleotidePolymorphismBuilder; import uk.ac.ebi.spot.goci.curation.model.SnpAssociationStandardMultiForm; import uk.ac.ebi.spot.goci.curation.model.SnpFormRow; import uk.ac.ebi.spot.goci.model.Association; import uk.ac.ebi.spot.goci.model.EfoTrait; import uk.ac.ebi.spot.goci.model.Gene; import uk.ac.ebi.spot.goci.model.Location; import uk.ac.ebi.spot.goci.model.Locus; import uk.ac.ebi.spot.goci.model.Region; import uk.ac.ebi.spot.goci.model.RiskAllele; import uk.ac.ebi.spot.goci.model.SingleNucleotidePolymorphism; import uk.ac.ebi.spot.goci.repository.AssociationRepository; import uk.ac.ebi.spot.goci.repository.GenomicContextRepository; import uk.ac.ebi.spot.goci.repository.LocusRepository; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.tuple; import static org.junit.Assert.assertNull; @RunWith(MockitoJUnitRunner.class) public class SingleSnpMultiSnpAssociationServiceTest { @Mock private AssociationRepository associationRepository; @Mock private LocusRepository locusRepository; @Mock private GenomicContextRepository genomicContextRepository; @Mock private LociAttributesService lociAttributesService; private SnpAssociationFormService snpAssociationFormService; // Entity objects private static final EfoTrait EFO_01 = new EfoTraitBuilder() .setId(988L) .setTrait("atrophic rhinitis") .setUri("http: .build(); private static final EfoTrait EFO_02 = new EfoTraitBuilder() .setId(989L) .setTrait("HeLa") .setUri("http: .build(); private static final Gene GENE_01 = new GeneBuilder().setId(112L).setGeneName("NEGR1").build(); private static final Gene GENE_02 = new GeneBuilder().setId(113L).setGeneName("FRS2").build(); private static final Gene GENE_03 = new GeneBuilder().setId(113L).setGeneName("ELF1").build(); private static final Region REGION_01 = new RegionBuilder().setId(897L).setName("9q33.1").build(); private static final Location LOCATION_01 = new LocationBuilder().setId(654L).setChromosomeName("1").setChromosomePosition("159001296").build(); private static final SingleNucleotidePolymorphism PROXY_SNP_01 = new SingleNucleotidePolymorphismBuilder().setId(311L) .setLastUpdateDate(new Date()) .setRsId("rs6538678") .build(); private static final SingleNucleotidePolymorphism PROXY_SNP_02 = new SingleNucleotidePolymorphismBuilder().setId(311L) .setLastUpdateDate(new Date()) .setRsId("rs7329174") .build(); private static final SingleNucleotidePolymorphism PROXY_SNP_03 = new SingleNucleotidePolymorphismBuilder().setId(311L) .setLastUpdateDate(new Date()) .setRsId("rs1234567") .build(); private static final SingleNucleotidePolymorphism SNP_01 = new SingleNucleotidePolymorphismBuilder().setId(311L) .setLastUpdateDate(new Date()) .setRsId("rs579459") .build(); private static final SingleNucleotidePolymorphism SNP_02 = new SingleNucleotidePolymorphismBuilder().setId(311L) .setLastUpdateDate(new Date()) .setRsId("rs9533090") .build(); private static final SingleNucleotidePolymorphism SNP_03 = new SingleNucleotidePolymorphismBuilder().setId(311L) .setLastUpdateDate(new Date()) .setRsId("rs114205691") .build(); private static final RiskAllele RISK_ALLELE_01 = new RiskAlleleBuilder().setId(411L) .setRiskAlleleName("rs579459-?") .build(); private static final RiskAllele RISK_ALLELE_02 = new RiskAlleleBuilder().setId(412L) .setRiskAlleleName("rs9533090-?") .build(); private static final RiskAllele RISK_ALLELE_03 = new RiskAlleleBuilder().setId(413L) .setRiskAlleleName("rs114205691-?") .build(); private static final Locus LOCUS_01 = new LocusBuilder().setId(111L) .setDescription("Single variant") .build(); private static final Locus LOCUS_02 = new LocusBuilder().setId(111L) .setDescription("2-SNP haplotype") .setHaplotypeSnpCount(2) .build(); private static final Association BETA_SINGLE_ASSOCIATION = new AssociationBuilder().setId((long) 100) .setBetaDirection("decrease") .setBetaUnit("mm Hg") .setBetaNum((float) 1.06) .setSnpType("novel") .setMultiSnpHaplotype(false) .setSnpInteraction(false) .setSnpApproved(false) .setPvalueExponent(-8) .setPvalueMantissa(1) .setStandardError((float) 6.24) .setRange("[14.1-38.56]") .setPvalueDescription("(ferritin)") .setRiskFrequency(String.valueOf(0.93)) .setEfoTraits(Arrays.asList(EFO_01, EFO_02)) .setDescription("this is a test") .build(); private static final Association OR_MULTI_ASSOCIATION = new AssociationBuilder().setId((long) 101) .setSnpType("novel") .setMultiSnpHaplotype(true) .setSnpInteraction(false) .setSnpApproved(false) .setPvalueExponent(-8) .setPvalueMantissa(1) .setStandardError((float) 6.24) .setRange("[14.1-38.56]") .setOrPerCopyNum((float) 1.89) .setOrPerCopyRecip((float) 0.99) .setOrPerCopyRecipRange("[1.0-8.0]") .setPvalueDescription("(ferritin)") .setRiskFrequency(String.valueOf(0.12)) .setEfoTraits(Arrays.asList(EFO_01, EFO_02)) .setDescription("this is a test") .build(); @BeforeClass public static void setUpModelObjects() throws Exception { // Create the links between all our objects REGION_01.setLocations(Collections.singletonList(LOCATION_01)); LOCATION_01.setRegion(REGION_01); // For testing all SNPs can have the same locations SNP_01.setLocations(Collections.singletonList(LOCATION_01)); SNP_02.setLocations(Collections.singletonList(LOCATION_01)); SNP_03.setLocations(Collections.singletonList(LOCATION_01)); // Set snp risk alleles SNP_01.setRiskAlleles(Collections.singletonList(RISK_ALLELE_01)); SNP_02.setRiskAlleles(Collections.singletonList(RISK_ALLELE_02)); SNP_03.setRiskAlleles(Collections.singletonList(RISK_ALLELE_03)); // Set risk allele snp RISK_ALLELE_01.setSnp(SNP_01); RISK_ALLELE_02.setSnp(SNP_02); RISK_ALLELE_03.setSnp(SNP_03); // Set risk allele proxy snp RISK_ALLELE_01.setProxySnps(Collections.singletonList(PROXY_SNP_01)); RISK_ALLELE_02.setProxySnps(Collections.singletonList(PROXY_SNP_02)); RISK_ALLELE_03.setProxySnps(Collections.singletonList(PROXY_SNP_03)); // Set locus risk allele LOCUS_01.setStrongestRiskAlleles(Collections.singletonList(RISK_ALLELE_01)); LOCUS_02.setStrongestRiskAlleles(Arrays.asList(RISK_ALLELE_02, RISK_ALLELE_03)); // Set Locus genes LOCUS_01.setAuthorReportedGenes(Arrays.asList(GENE_01, GENE_02)); LOCUS_02.setAuthorReportedGenes(Collections.singletonList(GENE_03)); // Build association links BETA_SINGLE_ASSOCIATION.setLoci(Collections.singletonList(LOCUS_01)); OR_MULTI_ASSOCIATION.setLoci(Collections.singletonList(LOCUS_02)); } @Before public void setUp() throws Exception { snpAssociationFormService = new SingleSnpMultiSnpAssociationService(associationRepository, locusRepository, genomicContextRepository, lociAttributesService); } @Test public void testCreateSingleForm() throws Exception { assertThat(snpAssociationFormService.createForm(BETA_SINGLE_ASSOCIATION)).isInstanceOf( SnpAssociationStandardMultiForm.class); SnpAssociationStandardMultiForm form = (SnpAssociationStandardMultiForm) snpAssociationFormService.createForm(BETA_SINGLE_ASSOCIATION); // Check values we would expect in form assertThat(form.getAssociationId()).as("Check form ID").isEqualTo(BETA_SINGLE_ASSOCIATION.getId()); assertThat(form.getBetaDirection()).as("Check form BETA DIRECTION") .isEqualTo(BETA_SINGLE_ASSOCIATION.getBetaDirection()); assertThat(form.getBetaUnit()).as("Check form BETA UNIT").isEqualTo(BETA_SINGLE_ASSOCIATION.getBetaUnit()); assertThat(form.getBetaNum()).as("Check form BETA NUM").isEqualTo(BETA_SINGLE_ASSOCIATION.getBetaNum()); assertThat(form.getSnpType()).as("Check form SNP TYPE").isEqualTo(BETA_SINGLE_ASSOCIATION.getSnpType()); assertThat(form.getMultiSnpHaplotype()).as("Check form MULTI SNP HAPLOTYPE") .isEqualTo(BETA_SINGLE_ASSOCIATION.getMultiSnpHaplotype()); assertThat(form.getSnpApproved()).as("Check form SNP APPROVED") .isEqualTo(BETA_SINGLE_ASSOCIATION.getSnpApproved()); assertThat(form.getPvalueExponent()).as("Check form PVALUE EXPONENT") .isEqualTo(BETA_SINGLE_ASSOCIATION.getPvalueExponent()); assertThat(form.getPvalueMantissa()).as("Check form PVALUE MANTISSA") .isEqualTo(BETA_SINGLE_ASSOCIATION.getPvalueMantissa()); assertThat(form.getStandardError()).as("Check form STANDARD ERROR") .isEqualTo(BETA_SINGLE_ASSOCIATION.getStandardError()); assertThat(form.getRange()).as("Check form RANGE").isEqualTo(BETA_SINGLE_ASSOCIATION.getRange()); assertThat(form.getPvalueDescription()).as("Check form PVALUE DESCRIPTION") .isEqualTo(BETA_SINGLE_ASSOCIATION.getPvalueDescription()); assertThat(form.getRiskFrequency()).as("Check form RISK FREQUENCY") .isEqualTo(BETA_SINGLE_ASSOCIATION.getRiskFrequency()); assertThat(form.getDescription()).as("Check form DESCRIPTION") .isEqualTo(BETA_SINGLE_ASSOCIATION.getDescription()); // Check EFO traits assertThat(form.getEfoTraits()).extracting("id", "trait", "uri") .contains(tuple(988L, "atrophic rhinitis", "http: tuple(989L, "HeLa", "http: // Check null values assertNull(form.getOrPerCopyNum()); assertNull(form.getOrPerCopyRecip()); assertNull(form.getOrPerCopyRecipRange()); assertNull(form.getMultiSnpHaplotypeNum()); // Test locus attributes assertThat(form.getMultiSnpHaplotypeDescr()).as("Check form MULTI HAPLOTYPE DESCRIPTION") .isEqualTo("Single variant"); assertThat(form.getAuthorReportedGenes()).isInstanceOf(Collection.class); assertThat(form.getAuthorReportedGenes()).contains("NEGR1", "FRS2"); // Test the row values Collection<SnpFormRow> rows = form.getSnpFormRows(); assertThat(rows).hasSize(1); assertThat(rows).extracting("snp", "strongestRiskAllele") .containsExactly(tuple("rs579459", "rs579459-?")); assertThat(rows).extracting("proxySnps").isNotEmpty(); List<String> proxyNames = new ArrayList<String>(); for (SnpFormRow row : rows) { proxyNames.addAll(row.getProxySnps()); } assertThat(proxyNames).containsOnlyOnce("rs6538678"); } @Test public void testCreateMultiForm() throws Exception { assertThat(snpAssociationFormService.createForm(OR_MULTI_ASSOCIATION)).isInstanceOf( SnpAssociationStandardMultiForm.class); SnpAssociationStandardMultiForm form = (SnpAssociationStandardMultiForm) snpAssociationFormService.createForm(OR_MULTI_ASSOCIATION); // Check values we would expect in form assertThat(form.getAssociationId()).as("Check form ID").isEqualTo(OR_MULTI_ASSOCIATION.getId()); assertThat(form.getSnpType()).as("Check form SNP TYPE").isEqualTo(OR_MULTI_ASSOCIATION.getSnpType()); assertThat(form.getMultiSnpHaplotype()).as("Check form MULTI SNP HAPLOTYPE") .isEqualTo(OR_MULTI_ASSOCIATION.getMultiSnpHaplotype()); assertThat(form.getSnpApproved()).as("Check form SNP APPROVED") .isEqualTo(OR_MULTI_ASSOCIATION.getSnpApproved()); assertThat(form.getPvalueExponent()).as("Check form PVALUE EXPONENT") .isEqualTo(OR_MULTI_ASSOCIATION.getPvalueExponent()); assertThat(form.getPvalueMantissa()).as("Check form PVALUE MANTISSA") .isEqualTo(OR_MULTI_ASSOCIATION.getPvalueMantissa()); assertThat(form.getStandardError()).as("Check form STANDARD ERROR") .isEqualTo(OR_MULTI_ASSOCIATION.getStandardError()); assertThat(form.getRange()).as("Check form RANGE").isEqualTo(OR_MULTI_ASSOCIATION.getRange()); assertThat(form.getPvalueDescription()).as("Check form PVALUE DESCRIPTION") .isEqualTo(OR_MULTI_ASSOCIATION.getPvalueDescription()); assertThat(form.getRiskFrequency()).as("Check form RISK FREQUENCY") .isEqualTo(OR_MULTI_ASSOCIATION.getRiskFrequency()); assertThat(form.getDescription()).as("Check form DESCRIPTION") .isEqualTo(OR_MULTI_ASSOCIATION.getDescription()); // Check EFO traits assertThat(form.getEfoTraits()).extracting("id", "trait", "uri") .contains(tuple(988L, "atrophic rhinitis", "http: tuple(989L, "HeLa", "http: // Check null values assertNull(form.getBetaDirection()); assertNull(form.getBetaNum()); assertNull(form.getBetaUnit()); // Test locus attributes assertThat(form.getMultiSnpHaplotypeDescr()).as("Check form MULTI HAPLOTYPE DESCRIPTION") .isEqualTo("2-SNP haplotype"); assertThat(form.getMultiSnpHaplotypeNum()).as("Check form MULTI HAPLOTYPE NUMBER") .isEqualTo(2); assertThat(form.getAuthorReportedGenes()).isInstanceOf(Collection.class); assertThat(form.getAuthorReportedGenes()).containsOnly("ELF1"); // Test the row values Collection<SnpFormRow> rows = form.getSnpFormRows(); assertThat(rows).hasSize(2); assertThat(rows).extracting("proxySnps").isNotEmpty(); assertThat(rows).extracting("snp").isNotEmpty(); assertThat(rows).extracting("strongestRiskAllele").isNotEmpty(); assertThat(rows).extracting("snp").containsExactly("rs9533090", "rs114205691"); assertThat(rows).extracting("strongestRiskAllele").containsExactly("rs9533090-?", "rs114205691-?"); List<String> proxyNames = new ArrayList<String>(); for (SnpFormRow row : rows) { proxyNames.addAll(row.getProxySnps()); } assertThat(proxyNames).containsExactly("rs7329174", "rs1234567"); } }
package io.quarkus.it.kubernetes; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.nio.file.Path; import java.util.Collections; import java.util.List; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.rbac.PolicyRule; import io.fabric8.kubernetes.api.model.rbac.Role; import io.fabric8.kubernetes.api.model.rbac.RoleBinding; import io.quarkus.bootstrap.model.AppArtifact; import io.quarkus.builder.Version; import io.quarkus.test.ProdBuildResults; import io.quarkus.test.ProdModeTestResults; import io.quarkus.test.QuarkusProdModeTest; public class KubernetesConfigWithSecretsTest { @RegisterExtension static final QuarkusProdModeTest config = new QuarkusProdModeTest() .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class).addClasses(GreetingResource.class)) .setApplicationName("kubernetes-config-with-secrets") .setApplicationVersion("0.1-SNAPSHOT") .withConfigurationResource("kubernetes-config-with-secrets.properties") .setForcedDependencies(Collections.singletonList( new AppArtifact("io.quarkus", "quarkus-kubernetes-config", Version.getVersion()))); @ProdBuildResults private ProdModeTestResults prodModeTestResults; @Test public void assertGeneratedResources() throws IOException { Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes"); assertThat(kubernetesDir) .isDirectoryContaining(p -> p.getFileName().endsWith("kubernetes.json")) .isDirectoryContaining(p -> p.getFileName().endsWith("kubernetes.yml")); List<HasMetadata> kubernetesList = DeserializationUtil.deserializeAsList(kubernetesDir.resolve("kubernetes.yml")); assertThat(kubernetesList).filteredOn(h -> "Role".equals(h.getKind())).hasSize(1); assertThat(kubernetesList).anySatisfy(res -> { assertThat(res).isInstanceOfSatisfying(Role.class, role -> { assertThat(role.getMetadata()).satisfies(m -> { assertThat(m.getName()).isEqualTo("view-secrets"); }); assertThat(role.getRules()).singleElement().satisfies(r -> { assertThat(r).isInstanceOfSatisfying(PolicyRule.class, rule -> { assertThat(rule.getApiGroups()).containsExactly(""); assertThat(rule.getResources()).containsExactly("secrets"); assertThat(rule.getVerbs()).containsExactly("get"); }); }); }); }); assertThat(kubernetesList).filteredOn(h -> "RoleBinding".equals(h.getKind())).hasSize(2) .anySatisfy(res -> { assertThat(res).isInstanceOfSatisfying(RoleBinding.class, roleBinding -> { assertThat(roleBinding.getMetadata()).satisfies(m -> { assertThat(m.getName()).isEqualTo("kubernetes-config-with-secrets-view-secrets"); }); assertThat(roleBinding.getRoleRef().getKind()).isEqualTo("Role"); assertThat(roleBinding.getRoleRef().getName()).isEqualTo("view-secrets"); assertThat(roleBinding.getSubjects()).singleElement().satisfies(subject -> { assertThat(subject.getKind()).isEqualTo("ServiceAccount"); assertThat(subject.getName()).isEqualTo("kubernetes-config-with-secrets"); }); }); }) .anySatisfy(res -> { assertThat(res).isInstanceOfSatisfying(RoleBinding.class, roleBinding -> { assertThat(roleBinding.getMetadata()).satisfies(m -> { assertThat(m.getName()).isEqualTo("kubernetes-config-with-secrets-view"); }); assertThat(roleBinding.getRoleRef().getKind()).isEqualTo("ClusterRole"); assertThat(roleBinding.getRoleRef().getName()).isEqualTo("view"); assertThat(roleBinding.getSubjects()).singleElement().satisfies(subject -> { assertThat(subject.getKind()).isEqualTo("ServiceAccount"); assertThat(subject.getName()).isEqualTo("kubernetes-config-with-secrets"); }); }); }); } }
package com.googlecode.jmxtrans.model.output.support; import com.googlecode.jmxtrans.test.IntegrationTest; import com.googlecode.jmxtrans.test.RequiresIO; import com.googlecode.jmxtrans.test.UdpLoggingServer; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.concurrent.Callable; import static com.google.common.base.Charsets.UTF_8; import static com.googlecode.jmxtrans.model.QueryFixtures.dummyQuery; import static com.googlecode.jmxtrans.model.ResultFixtures.dummyResults; import static com.googlecode.jmxtrans.model.ServerFixtures.dummyServer; import static com.jayway.awaitility.Awaitility.await; import static java.util.concurrent.TimeUnit.MILLISECONDS; @Category({IntegrationTest.class, RequiresIO.class}) public class UdpOutputWriterBuilderIT { @Rule public UdpLoggingServer udpLoggingServer = new UdpLoggingServer(UTF_8); @Test public void messageIsSent() throws Exception { WriterPoolOutputWriter<DummyWriterBasedOutputWriter> outputWriter = UdpOutputWriterBuilder.builder( udpLoggingServer.getLocalSocketAddress(), new DummyWriterBasedOutputWriter("message")) .build(); outputWriter.doWrite(dummyServer(), dummyQuery(), dummyResults()); outputWriter.close(); await().atMost(500, MILLISECONDS).until(messageReceived("message")); } private Callable<Boolean> messageReceived(final String message) { return new Callable<Boolean>() { @Override public Boolean call() throws Exception { return udpLoggingServer.messageReceived(message); } }; } }
package util; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.ClassFile; import javassist.bytecode.annotation.Annotation; import javassist.bytecode.annotation.AnnotationMemberValue; import javassist.bytecode.annotation.ArrayMemberValue; import javassist.bytecode.annotation.BooleanMemberValue; import javassist.bytecode.annotation.MemberValue; import javassist.bytecode.annotation.StringMemberValue; import models.User; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FileUtils; public class ModuleChecker { public static List<Diagnostic> collectModulesAndDiagnostics( List<File> uploadedFiles, List<Module> modules, File uploadsDir, User user) { List<Diagnostic> diagnostics = new ArrayList<Diagnostic>(); Map<String, File> fileByPath = new HashMap<String, File>(); for(File f : uploadedFiles){ String name = f.getName(); String path = getPathRelativeTo(uploadsDir, f); fileByPath.put(path, f); if(name.endsWith(".car")){ int sep = name.indexOf('-'); if(sep == -1){ if(name.equals("default.car")) diagnostics.add(new Diagnostic("error", "Default module not allowed.")); else diagnostics.add(new Diagnostic("error", "Module car has no version: "+name)); continue; } int dot = name.lastIndexOf('.'); String module = name.substring(0, sep); if(module.isEmpty()){ diagnostics.add(new Diagnostic("error", "Empty module name not allowed: "+name)); continue; } if(module.equals("default")){ diagnostics.add(new Diagnostic("error", "Default module not allowed: "+name)); continue; } String version = name.substring(sep+1, dot); if(version.isEmpty()){ diagnostics.add(new Diagnostic("error", "Empty version number not allowed: "+name)); continue; } modules.add(new Module(module, version, path.substring(0, path.length()-name.length()), f)); } } for(Module m : modules){ checkModule(uploadsDir, fileByPath, m, user, modules); } if(modules.isEmpty()) diagnostics.add(new Diagnostic("error", "No module defined")); if(!fileByPath.isEmpty()){ for(String key : fileByPath.keySet()) diagnostics.add(new Diagnostic("error", "Unknown file: "+key, key.substring(1))); } return diagnostics; } public static void checkModule(File uploadsDir, Map<String, File> fileByPath, Module m, User user, List<Module> modules) { // check the path first (we always start and end with a separator) String expectedPath = File.separatorChar + m.name.replace('.', File.separatorChar) + File.separatorChar + m.version + File.separatorChar; if(!expectedPath.equals(m.path)){ m.diagnostics.add(new Diagnostic("error", "Module is not in the right path: "+m.path+" (expecting "+expectedPath+")")); } models.Project project = models.Project.findOwner(m.name); if(project == null){ // nobody owns it, but perhaps we already have a claim for it project = models.Project.findForOwner(m.name, user); m.diagnostics.add(new Diagnostic("error", "You do not own this module", project)); }else{ // do we own it? if(project.owner == user) m.diagnostics.add(new Diagnostic("success", "You own this module")); else{ // we don't own it but we may be admin models.Module publishedModule = models.Module.findByName(m.name); if(publishedModule == null || !publishedModule.canEdit(user)){ // we're not the owner, and not admin, but perhaps we already have a claim for it project = models.Project.findForOwner(m.name, user); m.diagnostics.add(new Diagnostic("error", "You do not own this module", project)); }else m.diagnostics.add(new Diagnostic("success", "You are admin on this module")); } } models.ModuleVersion publishedModule = models.ModuleVersion.findByVersion(m.name, m.version); if(publishedModule != null) m.diagnostics.add(new Diagnostic("error", "Module already published")); String carName = m.name + "-" + m.version + ".car"; fileByPath.remove(m.path + carName); // car m.diagnostics.add(new Diagnostic("success", "Has car: "+carName)); String checksumPath = m.path + carName + ".sha1"; m.hasChecksum = fileByPath.containsKey(checksumPath); if(m.hasChecksum){ fileByPath.remove(checksumPath); // car checksum m.checksumValid = checkChecksum(uploadsDir, checksumPath, m.file); if(m.checksumValid) m.diagnostics.add(new Diagnostic("success", "Checksum valid")); else m.diagnostics.add(new Diagnostic("error", "Invalid checksum")); }else m.diagnostics.add(new Diagnostic("error", "Missing checksum")); loadModuleInfo(uploadsDir, m.path+carName, m, modules); String srcName = m.name + "-" + m.version + ".src"; File srcFile = new File(uploadsDir, m.path + srcName); if(srcFile.exists()){ m.hasSource = true; m.diagnostics.add(new Diagnostic("success", "Has source")); fileByPath.remove(m.path + srcName); // source archive String srcChecksumPath = m.path + srcName + ".sha1"; m.hasSourceChecksum = fileByPath.containsKey(srcChecksumPath); if(m.hasSourceChecksum){ fileByPath.remove(srcChecksumPath); // car checksum m.sourceChecksumValid = checkChecksum(uploadsDir, srcChecksumPath, srcFile); if(m.sourceChecksumValid) m.diagnostics.add(new Diagnostic("success", "Source checksum valid")); else m.diagnostics.add(new Diagnostic("error", "Invalid source checksum")); }else m.diagnostics.add(new Diagnostic("error", "Missing source checksum")); }else m.diagnostics.add(new Diagnostic("warning", "Missing source archive")); String docName = m.path + "module-doc" + File.separator + "index.html"; File docFile = new File(uploadsDir, docName); if(docFile.exists()){ m.hasDocs = true; m.diagnostics .add(new Diagnostic("success", "Has docs")); String prefix = m.path + "module-doc" + File.separator; Iterator<String> iterator = fileByPath.keySet().iterator(); while(iterator.hasNext()){ String key = iterator.next(); // count all the doc files if(key.startsWith(prefix)) iterator.remove(); } }else m.diagnostics.add(new Diagnostic("warning", "Missing docs")); } private static void loadModuleInfo(File uploadsDir, String carName, Module m, List<Module> modules) { try { ZipFile car = new ZipFile(new File(uploadsDir, carName)); try{ ZipEntry moduleEntry = car.getEntry(m.name.replace('.', '/') + "/module.class"); if(moduleEntry == null){ m.diagnostics.add(new Diagnostic("error", ".car file does not contain module information")); return; } m.diagnostics.add(new Diagnostic("success", ".car file contains module descriptor")); DataInputStream inputStream = new DataInputStream(car.getInputStream(moduleEntry)); ClassFile classFile = new ClassFile(inputStream); inputStream.close(); AnnotationsAttribute visible = (AnnotationsAttribute) classFile.getAttribute(AnnotationsAttribute.visibleTag); Annotation moduleAnnotation = visible.getAnnotation("com.redhat.ceylon.compiler.java.metadata.Module"); if(moduleAnnotation == null){ m.diagnostics.add(new Diagnostic("error", ".car does not contain @Module annotation on module.class")); return; } m.diagnostics.add(new Diagnostic("success", ".car file module descriptor has @Module annotation")); String name = getString(moduleAnnotation, "name", m); String version = getString(moduleAnnotation, "version", m); if(name == null || version == null) return; if(!name.equals(m.name)){ m.diagnostics.add(new Diagnostic("error", ".car file contains unexpected module: "+name)); return; } if(!version.equals(m.version)){ m.diagnostics.add(new Diagnostic("error", ".car file contains unexpected module version: "+version)); return; } m.diagnostics.add(new Diagnostic("success", ".car file module descriptor has valid name/version")); MemberValue dependencies = moduleAnnotation.getMemberValue("dependencies"); if(dependencies == null){ m.diagnostics.add(new Diagnostic("success", "Module has no dependencies")); return; // we're good } if(!(dependencies instanceof ArrayMemberValue)){ m.diagnostics.add(new Diagnostic("error", "Invalid 'dependencies' annotation value (expecting array)")); return; } MemberValue[] dependencyValues = ((ArrayMemberValue)dependencies).getValue(); if(dependencyValues.length == 0){ m.diagnostics.add(new Diagnostic("success", "Module has no dependencies")); return; // we're good } for(MemberValue dependencyValue : dependencyValues){ checkDependency(dependencyValue, m, modules); } }finally{ car.close(); } } catch (IOException e) { e.printStackTrace(); m.diagnostics.add(new Diagnostic("error", "Invalid car file: "+e.getMessage())); } } private static void checkDependency(MemberValue dependencyValue, Module m, List<Module> modules) { if(!(dependencyValue instanceof AnnotationMemberValue)){ m.diagnostics.add(new Diagnostic("error", "Invalid dependency value (expecting annotation)")); return; } Annotation dependency = ((AnnotationMemberValue)dependencyValue).getValue(); if(!dependency.getTypeName().equals("com.redhat.ceylon.compiler.java.metadata.Import")){ m.diagnostics.add(new Diagnostic("error", "Invalid 'dependency' value (expecting @Import)")); return; } String name = getString(dependency, "name", m); String version = getString(dependency, "version", m); if(name == null || version == null) return; if(name.isEmpty()){ m.diagnostics.add(new Diagnostic("error", "Invalid empty dependency name")); return; } if(version.isEmpty()){ m.diagnostics.add(new Diagnostic("error", "Invalid empty dependency version")); return; } MemberValue optionalValue = dependency.getMemberValue("optional"); if(optionalValue == null){ m.diagnostics.add(new Diagnostic("error", "Invalid @Import annotation: missing 'optional' value")); return; } if(!(optionalValue instanceof BooleanMemberValue)){ m.diagnostics.add(new Diagnostic("error", "Invalid @Import 'optional' value (expecting boolean)")); return; } boolean optional = ((BooleanMemberValue)optionalValue).getValue(); if(optional){ m.diagnostics.add(new Diagnostic("success", "Dependency "+name+"/"+version+" is optional")); return; } // must make sure it exists checkDependencyExists(name, version, m, modules); } private static void checkDependencyExists(String name, String version, Module m, List<Module> modules) { // try to find it in the list of uploaded modules for(Module module : modules){ if(module.name.equals(name) && module.version.equals(version)){ m.diagnostics.add(new Diagnostic("success", "Dependency "+name+"/"+version+" is to be uploaded")); return; } } // try to find it in the repo models.ModuleVersion dep = models.ModuleVersion.find("name = ? AND version = ?", name, version).first(); if(dep == null){ m.diagnostics.add(new Diagnostic("error", "Dependency "+name+"/"+version+" cannot be found in upload or repo")); }else{ m.diagnostics.add(new Diagnostic("success", "Dependency "+name+"/"+version+" present in repo")); } } private static String getString(Annotation annotation, String field, Module m) { MemberValue value = annotation.getMemberValue(field); if(value == null){ m.diagnostics.add(new Diagnostic("error", "Missing '"+field+"' annotation value")); return null; } if(!(value instanceof StringMemberValue)){ m.diagnostics.add(new Diagnostic("error", "Invalid '"+field+"' annotation value (expecting String)")); return null; } return ((StringMemberValue)value).getValue(); } private static boolean checkChecksum(File uploadsDir, String checksumPath, File checkedFile) { File checksumFile = new File(uploadsDir, checksumPath); try{ String checksum = FileUtils.readFileToString(checksumFile); String realChecksum = sha1(checkedFile); return realChecksum.equals(checksum); }catch(Exception x){ return false; } } public static String sha1(File file) throws IOException{ InputStream is = new FileInputStream(file); try{ String realChecksum = DigestUtils.shaHex(is); return realChecksum; }finally{ is.close(); } } private static String getPathRelativeTo(File uploadsDir, File f) { try{ String prefix = uploadsDir.getCanonicalPath(); String path = f.getCanonicalPath(); if(path.startsWith(prefix)) return path.substring(prefix.length()); }catch(IOException x){ throw new RuntimeException(x); } throw new RuntimeException("Invalid path: "+f.getPath()); } public static class Diagnostic { public String type; public String message; public String unknownPath; public models.Project project; public boolean projectClaim; Diagnostic(String type, String message){ this.type = type; this.message = message; } public Diagnostic(String type, String message, String unknownPath) { this(type, message); this.unknownPath = unknownPath; } public Diagnostic(String type, String message, models.Project project) { this(type, message); this.project = project; this.projectClaim = true; } } public static class Module { public List<Diagnostic> diagnostics = new ArrayList<Diagnostic>(); public String name; public String version; public String path; public File file; public boolean hasChecksum; public boolean checksumValid; public boolean hasSource; public boolean hasSourceChecksum; public boolean sourceChecksumValid; public boolean hasDocs; Module(String name, String version, String path, File file){ this.name = name; this.version = version; this.path = path; this.file = file; } public String getType(){ String worse = "success"; for(Diagnostic d : diagnostics){ if(d.type.equals("error")) return d.type; if(d.type.equals("warning")) worse = d.type; } return worse; } public String getDocPath(){ return path.substring(1) + "module-doc" + "/" + "index.html"; } } public static class UploadInfo { public List<Diagnostic> diagnostics; public List<Module> modules; public models.Upload upload; public String status; public UploadInfo(models.Upload upload, List<Module> modules, List<Diagnostic> diagnostics) { this.upload = upload; this.modules = modules; this.diagnostics = diagnostics; setStatus(); } private void setStatus(){ status = "success"; for(Diagnostic d : diagnostics){ if(d.type.equals("error")){ status = d.type; return; } if(d.type.equals("warning")) status = d.type; } for(Module m : modules){ String type = m.getType(); if(type.equals("error")){ status = type; return; } if(type.equals("warning")) status = type; } } public boolean isPublishable(){ return status.equals("success") || status.equals("warning"); } } }
package utils; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.services.sqs.AmazonSQSClient; import com.amazonaws.services.sqs.model.*; import com.beust.jcommander.internal.Lists; import com.beust.jcommander.internal.Maps; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaModule; import play.Logger; import play.Play; import play.libs.Akka; import scala.concurrent.duration.FiniteDuration; import java.io.IOException; import java.util.List; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; /** Generic queuing support to enable us to throw stuff into SQS */ public class QueueManager { /** maintain a singleton manager */ private static QueueManager manager; /** The prefix to use for these queues */ private final String prefix; /** The SQS client */ private final AmazonSQSClient sqs; private static final ObjectMapper objectMapper = new ObjectMapper(); private boolean polling; static { objectMapper.registerModule(new JodaModule()); } /** URL of queue that brings single point results back from the cluster */ private final String outputQueue; private final ConcurrentMap<String, Consumer<ResultEnvelope>> callbacks = new ConcurrentHashMap<>(); /** Create a queue manager with credentials and prefixes taken from the environment */ public QueueManager () { prefix = Play.application().configuration().getString("cluster.queue-prefix"); // create the SQS client String credentialsFilename = Play.application().configuration().getString("cluster.aws-credentials"); if (credentialsFilename != null) { AWSCredentials creds = new ProfileCredentialsProvider(credentialsFilename, "default").getCredentials(); sqs = new AmazonSQSClient(creds); } else { // default credentials providers, e.g. IAM role sqs = new AmazonSQSClient(); } // create the output queue String outQueueName = prefix + "_output_" + UUID.randomUUID().toString(); outputQueue = createQueue(outQueueName); Logger.info("Receiving single point results from queue " + outQueueName); // listen to the output queue Akka.system().scheduler().scheduleOnce(new FiniteDuration(1, TimeUnit.SECONDS), new QueueListener(), Akka.system().dispatcher()); } /** Enqueue a single point request */ public boolean enqueue (AnalystClusterRequest req) { return enqueue(req, null); } public boolean enqueue (AnalystClusterRequest req, Consumer<ResultEnvelope> callback) { String queueUrl = getOrCreateSinglePointQueue(req.graphId); // state tracking req.jobId = null; req.id = "single-" + UUID.randomUUID().toString(); req.disposition = AnalystClusterRequest.RequestDisposition.ENQUEUE; req.outputLocation = outputQueue; // store the callback callbacks.put(req.id, callback); // enqueue it try { String json = objectMapper.writeValueAsString(req); sqs.sendMessage(queueUrl, json); } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** Get the URL for a single-point queue, creating the queue if necessary */ private String getOrCreateSinglePointQueue(String graphId) { String queueName = prefix + "_" + graphId + "_single"; return getOrCreateQueue(queueName); } /** Get the URL for the named queue, creating it if necessary */ private String getOrCreateQueue(String queueName) { try { GetQueueUrlResult res = sqs.getQueueUrl(queueName); return res.getQueueUrl(); } catch (QueueDoesNotExistException e) { return createQueue(queueName); } } /** Create the queue with the given name */ private String createQueue(String queueName) { // TODO: visibility timeout defaults to 30s, which is probably about right as we shouldn't be // waiting for a graph build. IAM policy should perhaps be set here? CreateQueueRequest cqr = new CreateQueueRequest(queueName); CreateQueueResult res = sqs.createQueue(cqr); return res.getQueueUrl(); } /** maintain a single instance of QueueManager */ public static QueueManager getManager () { if (manager == null) { synchronized(QueueManager.class) { manager = new QueueManager(); } } return manager; } /** Listen to the queue and call callbacks as needed */ public class QueueListener implements Runnable { @Override public void run() { while (true) { // don't poll unless we're expecting jobs back if (callbacks.isEmpty()) { try { // only sleep for 1s so we don't miss new jobs being enqueued Thread.sleep(1000l); } catch (InterruptedException e) { break; } continue; } ReceiveMessageRequest rmr = new ReceiveMessageRequest(); // long poll so we have fewer requests and are sure to get responses // TODO does this mean we wait 20 seconds to get any response even if messages are // available before that? if so this is a non-starter. rmr.setWaitTimeSeconds(20); rmr.setMaxNumberOfMessages(10); rmr.setQueueUrl(outputQueue); ReceiveMessageResult res = sqs.receiveMessage(rmr); List<String> messagesToDelete = Lists.newArrayList(); for (Message message : res.getMessages()) { String json = message.getBody(); // deserialize to result envelope ResultEnvelope env; try { env = objectMapper.readValue(json, ResultEnvelope.class); } catch (IOException e) { Logger.error("Unable to parse JSON from message {}", message.getMessageId()); e.printStackTrace(); // it's not likely that this message will be received correctly the next time messagesToDelete.add(message.getReceiptHandle()); continue; } Consumer<ResultEnvelope> callback = callbacks.get(env.id); if (callback != null) { // callback could be null if the frontend was restarted callback.accept(env); callbacks.remove(env.id); } messagesToDelete.add(message.getReceiptHandle()); } } } } }
package org.javacint.gps; import java.util.Hashtable; import org.javacint.logging.Logger; import org.javacint.settings.Settings; import org.javacint.settings.SettingsProvider; /** * High level GPS chip management. This is mostly useful for GPS chip * auto-detection. */ public class GpsManager implements Runnable, SettingsProvider { // CONSTANTS private final int PORT_SPEEDS[] = {4800, 9600, 19200, 38400, 115200}; private final String SETTING_GPS_ENABLED = "gps.enabled"; private final String SETTING_GPS_PORT_NB = "gps.portnb"; private final String SETTING_GPS_PORT_SPEED = "gps.portspeed"; // MEMBERS private final GpsPositionListener listener; private GpsNmeaParser parser; private boolean keepWorking = true; private boolean enabled; private Thread thread; // STATIC private static final Object serialPortsDetectionLock_ = new Object(); private GpsStatesHandler statesHandler; /** * GPS Manager constructor * * @param atc ATCommand */ public GpsManager(GpsPositionListener listener) { this.listener = listener; if (Logger.BUILD_DEBUG) { Logger.log("GpsManager.init()"); } Settings.addProvider(this); } public void setGpsStatesHandler(GpsStatesHandler h) { statesHandler = h; } private void loadSettings() { parseSetting(SETTING_GPS_ENABLED); } private void openGps(int portId, int portSpeed) { if (Logger.BUILD_NOTICE) { Logger.log(this + ".openGps( " + portId + ", " + portSpeed + " );", true); } Logger.setStdoutLogging(false); parser = new GpsNmeaParser(listener, portId, portSpeed); parser.start(); if (statesHandler != null) { statesHandler.prepareGpsStart(); } } private void closeGps() { if (Logger.BUILD_NOTICE) { Logger.log(this + ".closeGps();"); } if (parser != null) { parser.stop(); parser = null; } Logger.setStdoutLogging(true); if (statesHandler != null) { statesHandler.prepareGpsStop(); } } /** * The thread method * * This method loads the the GPS NMEA parser and if the parser doesn't parse * anything it launches the autodetection. */ public void run() { if (Logger.BUILD_DEBUG) { Logger.log(this + ".run();"); } try { if (!Settings.getBool(SETTING_GPS_ENABLED)) { return; } if (parser != null) { closeGps(); } int portId = 0; int portSpeed = 0; try { portId = Settings.getInt(SETTING_GPS_PORT_NB); portSpeed = Settings.getInt(SETTING_GPS_PORT_SPEED); } catch (Exception ex) { if (Logger.BUILD_DEBUG) { Logger.log(this + ".run:114", ex, true); } } synchronized (serialPortsDetectionLock_) { if (portSpeed != 0) { // We start the GPS on this port openGps(portId, portSpeed); sleep(5000); if (parser.getNbSentences() > 0) { if (Logger.BUILD_NOTICE) { Logger.log("GPS chip is working fine !", true); } // Thread ends now return; } else { if (Logger.BUILD_NOTICE) { Logger.log("No data was received from the GPS chip...", true); } closeGps(); } } // We could reduce the detection time by detecting the two ports at the same time. // and maybe also by reducing the time to wait before checking for sentences for (int j = 1; j >= 0; --j) { // Port: ASC0, ASC1 for (int i = 0; i < PORT_SPEEDS.length && keepWorking; ++i) { // Speed: 2400, 4800, 9600, 19200, 38400, 57600, 115200 portId = j; portSpeed = PORT_SPEEDS[i]; openGps(portId, portSpeed); sleep(5000); if (parser.getNbSentences() > 0) { if (Logger.BUILD_NOTICE) { Logger.log("GPS chip was found on ASC" + portId + ":" + portSpeed, true); } Settings.set(SETTING_GPS_PORT_NB, portId + ""); Settings.set(SETTING_GPS_PORT_SPEED, portSpeed + ""); // This is rare enough that we can afford to save the file Settings.save(); return; } else { closeGps(); } } // for j } // for i } // synchronized ( Global.portDetectionLock ) } catch (Throwable ex) { if (Logger.BUILD_CRITICAL) { Logger.log(this + ".run", ex, true); } } finally { thread = null; } } /** * Sleeping * * @param time Sleeping */ private void sleep(long time) { try { synchronized (this) { this.wait(time); } } catch (Exception ex) { if (Logger.BUILD_CRITICAL) { Logger.log(this + ".sleep", ex, true); } } } /** * Start the GPSManager */ private void startThread() { try { if (Logger.BUILD_DEBUG) { Logger.log(this + ".start();"); } keepWorking = true; synchronized (this) { if (thread != null) { if (Logger.BUILD_WARNING) { Logger.log("GPS Thread is already started!"); } return; } thread = new Thread(this, "gpm"); thread.start(); } } catch (Exception ex) { if (Logger.BUILD_CRITICAL) { Logger.log("gps.start", ex, true); } } } /** * Stop the GPSManager */ public void stop() { if (Logger.BUILD_DEBUG) { Logger.log("gps.stop();"); } keepWorking = false; closeGps(); // To interrupt the sleep synchronized (this) { this.notifyAll(); } } public void getDefaultSettings(Hashtable settings) { if (Logger.BUILD_DEBUG) { Logger.log("GpsManager.getDefaultSettings();"); } settings.put(SETTING_GPS_ENABLED, "1"); settings.put(SETTING_GPS_PORT_NB, "0"); settings.put(SETTING_GPS_PORT_SPEED, "4800"); } public void settingsChanged(String[] settings) { for (int i = 0; i < settings.length; ++i) { parseSetting(settings[i]); } } private boolean parseSetting(String name) { if (name.compareTo(SETTING_GPS_ENABLED) == 0) { setEnabled(Settings.getBool(SETTING_GPS_ENABLED)); } else { return false; } return true; } private void setEnabled(boolean enabled) { if (Logger.BUILD_DEBUG) { Logger.log(this + ".setEnabled( " + enabled + " );"); } if (this.enabled != enabled) { this.enabled = enabled; if (Logger.BUILD_DEBUG) { Logger.log(this + ".setEnabled( " + enabled + " ): confirmed!"); } if (this.enabled) { startThread(); } else { stop(); } } } public void start() { loadSettings(); } public String toString() { return "GPSManager"; } }
package org.jetel.graph; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.TreeMap; import java.util.concurrent.CyclicBarrier; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.MDC; import org.jetel.data.DataRecord; import org.jetel.enums.EnabledEnum; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationProblem; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.ConfigurationStatus.Priority; import org.jetel.exception.ConfigurationStatus.Severity; import org.jetel.exception.JetelRuntimeException; import org.jetel.graph.distribution.EngineComponentAllocation; import org.jetel.graph.runtime.CloverPost; import org.jetel.graph.runtime.CloverWorkerListener; import org.jetel.graph.runtime.ErrorMsgBody; import org.jetel.graph.runtime.Message; import org.jetel.graph.runtime.tracker.ComplexComponentTokenTracker; import org.jetel.graph.runtime.tracker.ComponentTokenTracker; import org.jetel.graph.runtime.tracker.PrimitiveComponentTokenTracker; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.ClusterUtils; import org.jetel.util.bytes.CloverBuffer; import org.jetel.util.string.StringUtils; import org.w3c.dom.Element; /** * A class that represents atomic transformation task. It is a base class for * all kinds of transformation components. * *@author D.Pavlis *@created January 31, 2003 *@since April 2, 2002 *@see org.jetel.component */ public abstract class Node extends GraphElement implements Runnable, CloverWorkerListener { private static final Log logger = LogFactory.getLog(Node.class); protected Thread nodeThread; /** * List of all threads under this component. * For instance parallel reader uses threads for parallel reading. * It is component's responsibility to register all inner threads via addChildThread() method. */ protected List<Thread> childThreads; protected EnabledEnum enabled; protected int passThroughInputPort; protected int passThroughOutputPort; protected TreeMap<Integer, OutputPort> outPorts; protected TreeMap<Integer, InputPort> inPorts; protected volatile boolean runIt = true; private volatile Result runResult; protected Throwable resultException; protected String resultMessage; protected Phase phase; /** * Distribution of this node processing at cluster environment. */ protected EngineComponentAllocation allocation; // buffered values protected OutputPort[] outPortsArray; protected int outPortsSize; //synchronization barrier for all components in a phase //all components have to finish pre-execution before execution method private CyclicBarrier executeBarrier; //synchronization barrier for all components in a phase //watchdog needs to have all components with thread assignment before can continue to watch the phase private CyclicBarrier preExecuteBarrier; /** * Component token tracker encapsulates graph's token tracker. * All jobflow logging for this component should be provided through this tracker. * Tracker cannot be null, at least {@link PrimitiveComponentTokenTracker} is used. */ protected ComponentTokenTracker tokenTracker; /** * Various PORT kinds identifiers * *@since August 13, 2002 */ public final static char OUTPUT_PORT = 'O'; /** Description of the Field */ public final static char INPUT_PORT = 'I'; /** * XML attributes of every cloverETL component */ public final static String XML_NAME_ATTRIBUTE = "guiName"; public final static String XML_TYPE_ATTRIBUTE="type"; public final static String XML_ENABLED_ATTRIBUTE="enabled"; public final static String XML_ALLOCATION_ATTRIBUTE = "allocation"; /** * Standard constructor. * *@param id Unique ID of the Node *@since April 4, 2002 */ public Node(String id){ this(id,null); } /** * Standard constructor. * *@param id Unique ID of the Node *@since April 4, 2002 */ public Node(String id, TransformationGraph graph) { super(id,graph); outPorts = new TreeMap<Integer, OutputPort>(); inPorts = new TreeMap<Integer, InputPort>(); phase = null; runResult=Result.N_A; // result is not known yet childThreads = new ArrayList<Thread>(); allocation = EngineComponentAllocation.createBasedOnNeighbours(); } /** * Sets the EOF for particular output port. EOF indicates that no more data * will be sent throught the output port. * *@param portNum The new EOF value * @throws IOException * @throws IOException *@since April 18, 2002 */ public void setEOF(int portNum) throws InterruptedException, IOException { try { ((OutputPort) outPorts.get(Integer.valueOf(portNum))).eof(); } catch (IndexOutOfBoundsException ex) { ex.printStackTrace(); } } /** * Returns the type of this Node (subclasses/Components should override * this method to return appropriate type). * *@return The Type value *@since April 4, 2002 */ public abstract String getType(); /** * Returns True if this Node is Leaf Node - i.e. only consumes data (has only * input ports connected to it) * *@return True if Node is a Leaf *@since April 4, 2002 */ public boolean isLeaf() { //this implementation is necessary for remote edges //even component with a connected edge can be leaf if the edge is the remote one for (OutputPort outputPort : getOutPorts()) { if (outputPort.getReader() != null) { return false; } } return true; } /** * Returns True if this node is Root Node - i.e. it produces data (has only output ports * connected to id). * *@return True if Node is a Root *@since April 4, 2002 */ public boolean isRoot() { //this implementation is necessary for remote edges //even component with a connected edge can be root if the edge is the remote one for (InputPort inputPort : getInPorts()) { if (inputPort.getWriter() != null) { return false; } } return true; } /** * Sets the processing phase of the Node object.<br> * Default is 0 (ZERO). * *@param phase The new phase number */ public void setPhase(Phase phase) { this.phase = phase; } /** * Gets the processing phase of the Node object * *@return The phase value */ public Phase getPhase() { return phase; } /** * @return phase number */ public int getPhaseNum(){ return phase.getPhaseNum(); } /** * Gets the OutPorts attribute of the Node object * *@return Collection of OutPorts *@since April 18, 2002 */ public Collection<OutputPort> getOutPorts() { return outPorts.values(); } /** * @return map with all output ports (key is index of output port) */ public Map<Integer, OutputPort> getOutputPorts() { return outPorts; } /** * Gets the InPorts attribute of the Node object * *@return Collection of InPorts *@since April 18, 2002 */ public Collection<InputPort> getInPorts() { return inPorts.values(); } /** * @return map with all input ports (key is index of input port) */ public Map<Integer, InputPort> getInputPorts() { return inPorts; } /** * Gets the metadata on output ports of the Node object * *@return Collection of output ports metadata */ public List<DataRecordMetadata> getOutMetadata() { List<DataRecordMetadata> ret = new ArrayList<DataRecordMetadata>(outPorts.size()); for(Iterator<OutputPort> it = getOutPorts().iterator(); it.hasNext();) { ret.add(it.next().getMetadata()); } return ret; } /** * Gets the metadata on output ports of the Node object * * @return array of output ports metadata */ public DataRecordMetadata[] getOutMetadataArray() { return getOutMetadata().toArray(new DataRecordMetadata[0]); } /** * Gets the metadata on input ports of the Node object * *@return Collection of input ports metadata */ public List<DataRecordMetadata> getInMetadata() { List<DataRecordMetadata> ret = new ArrayList<DataRecordMetadata>(inPorts.size()); for(Iterator<InputPort> it = getInPorts().iterator(); it.hasNext();) { ret.add(it.next().getMetadata()); } return ret; } /** * Gets the metadata on input ports of the Node object * * @return array of input ports metadata */ public DataRecordMetadata[] getInMetadataArray() { return getInMetadata().toArray(new DataRecordMetadata[0]); } /** * Gets the number of records passed through specified port type and number * *@param portType Port type (IN, OUT, LOG) *@param portNum port number (0...) *@return The RecordCount value *@since May 17, 2002 *@deprecated */ @Deprecated public long getRecordCount(char portType, int portNum) { long count; // Integer used as key to TreeMap containing ports Integer port = Integer.valueOf(portNum); try { switch (portType) { case OUTPUT_PORT: count = ((OutputPort) outPorts.get(port)).getOutputRecordCounter(); break; case INPUT_PORT: count = ((InputPort) inPorts.get(port)).getInputRecordCounter(); break; default: count = -1; } } catch (Exception ex) { count = -1; } return count; } /** * Gets the result code of finished Node.<br> * *@return The Result value *@since July 29, 2002 *@see org.jetel.graph.Node.Result */ public synchronized Result getResultCode() { return runResult; } /** * Sets the result code of component. * @param result */ public synchronized void setResultCode(Result result) { this.runResult = result; } /** * Sets the component result to new value if and only if the current result equals to the given expectation. * This is atomic operation for 'if' and 'set'. * @param newResult new component result * @param expectedOldResult expected value of current result */ public synchronized void setResultCode(Result newResult, Result expectedOldResult) { if (runResult == expectedOldResult) { runResult = newResult; } } /** * Gets the ResultMsg of finished Node.<br> * This message briefly describes what caused and error (if there was any). * *@return The ResultMsg value *@since July 29, 2002 */ public synchronized String getResultMsg() { return runResult!=null ? runResult.message() : null; } /** * Gets exception which caused Node to fail execution - if * there was such failure. * * @return * @since 13.12.2006 */ public Throwable getResultException(){ return resultException; } // Operations /* (non-Javadoc) * @see org.jetel.graph.GraphElement#init() */ @Override public void init() throws ComponentNotReadyException { super.init(); runResult = Result.READY; refreshBufferedValues(); //initialise component token tracker if necessary if (getGraph() != null && getGraph().getJobType() == JobType.JOBFLOW && getGraph().getRuntimeContext().isTokenTracking()) { tokenTracker = createComponentTokenTracker(); } else { tokenTracker = new PrimitiveComponentTokenTracker(this); } } /* (non-Javadoc) * @see org.jetel.graph.GraphElement#preExecute() */ @Override public void preExecute() throws ComponentNotReadyException { super.preExecute(); //cluster related settings can be used only in cluster environment if (!getGraph().getAuthorityProxy().isClusterEnabled()) { //cluster components cannot be used in non-cluster environment if (ClusterUtils.isClusterComponent(getType())) { throw new JetelRuntimeException("Cluster component cannot be used in non-cluster environment."); } //non empty allocation is not allowed in non-cluster environment EngineComponentAllocation allocation = getAllocation(); if (allocation != null && !allocation.isInferedFromNeighbours()) { throw new JetelRuntimeException("Component allocation cannot be specified in non-cluster environment."); } } runResult = Result.RUNNING; } /** * main execution method of Node (calls in turn execute()) * *@since April 2, 2002 */ @Override public void run() { runResult = Result.RUNNING; // set running result, so we know run() method was started ContextProvider.registerNode(this); try { //store the current thread like a node executor setNodeThread(Thread.currentThread()); //we need a synchronization point for all components in a phase //watchdog starts all components in phase and wait on this barrier for real startup preExecuteBarrier.await(); //preExecute() invocation try { preExecute(); } catch (Throwable e) { throw new ComponentNotReadyException(this, "Component pre-execute initialization failed.", e); } //waiting for other nodes in the current phase - first all pre-execution has to be done at all nodes executeBarrier.await(); //execute() invocation if((runResult = execute()) == Result.ERROR) { Message<ErrorMsgBody> msg = Message.createErrorMessage(this, new ErrorMsgBody(runResult.code(), resultMessage != null ? resultMessage : runResult.message(), null)); sendMessage(msg); } if (runResult == Result.FINISHED_OK) { if (runIt == false) { //component returns ok tag, but the component was actually aborted runResult = Result.ABORTED; } else if (checkEofOnInputPorts()) { // true by default //check whether all input ports are already closed for (InputPort inputPort : getInPorts()) { if (!inputPort.isEOF()) { runResult = Result.ERROR; Message<ErrorMsgBody> msg = Message.createErrorMessage(this, new ErrorMsgBody(runResult.code(), "Component has finished and input port " + inputPort.getInputPortNumber() + " still contains some unread records.", null)); sendMessage(msg); return; } } } //broadcast all output ports with EOF information broadcastEOF(); } } catch (InterruptedException ex) { runResult=Result.ABORTED; } catch (Exception ex) { runResult=Result.ERROR; resultException = createNodeException(ex); Message<ErrorMsgBody> msg = Message.createErrorMessage(this, new ErrorMsgBody(runResult.code(), runResult.message(), resultException)); sendMessage(msg); } catch (Throwable ex) { logger.fatal(ex); runResult=Result.ERROR; resultException = createNodeException(ex); Message<ErrorMsgBody> msg = Message.createErrorMessage(this, new ErrorMsgBody(runResult.code(), runResult.message(), resultException)); sendMessage(msg); } finally { sendFinishMessage(); setNodeThread(null); ContextProvider.unregister(); } } protected abstract Result execute() throws Exception; private Exception createNodeException(Throwable cause) { return new JetelRuntimeException("Component " + this + " finished with status ERROR.", cause); } /** * This method should be called every time when node finishes its work. */ private void sendFinishMessage() { //sends notification - node has finished sendMessage(Message.createNodeFinishedMessage(this)); } /** * Abort execution of Node - only inform node, that should finish processing. * *@since April 4, 2002 */ public void abort() { abort(null); } public synchronized void abort(Throwable cause) { int attempts = 30; runIt = false; while (!runResult.isStop() && attempts if (logger.isTraceEnabled()) logger.trace("try to interrupt thread "+getNodeThread()); getNodeThread().interrupt(); try { Thread.sleep(10); } catch (InterruptedException e) { } } if (cause != null) { runResult=Result.ERROR; resultException = createNodeException(cause); Message<ErrorMsgBody> msg = Message.createErrorMessage(this, new ErrorMsgBody(runResult.code(), runResult.message(), resultException)); sendMessage(msg); sendFinishMessage(); } else if (!runResult.isStop()) { logger.debug("Node '" + getId() + "' was not interrupted in legal way."); runResult = Result.ABORTED; sendFinishMessage(); } } /** * @return thread of running node; <b>null</b> if node does not running */ public synchronized Thread getNodeThread() { return nodeThread; } /** * Sets actual thread in which this node current running. * @param nodeThread */ private synchronized void setNodeThread(Thread nodeThread) { if(nodeThread != null) { this.nodeThread = nodeThread; //thread context classloader is preset to a reasonable classloader //this is just for sure, threads are recycled and no body can guarantee which context classloader remains preset nodeThread.setContextClassLoader(this.getClass().getClassLoader()); String oldName = nodeThread.getName(); long runId = getGraph().getRuntimeContext().getRunId(); nodeThread.setName(getId()+"_"+runId); MDC.put("runId", getGraph().getRuntimeContext().getRunId()); if (logger.isTraceEnabled()) { logger.trace("set thread name; old:"+oldName+" new:"+ nodeThread.getName()); logger.trace("set thread runId; runId:"+runId+" thread name:"+Thread.currentThread().getName()); } } else { MDC.remove("runId"); long runId = getGraph().getRuntimeContext().getRunId(); if (logger.isTraceEnabled()) logger.trace("reset thread runId; runId:"+runId+" thread name:"+Thread.currentThread().getName()); this.nodeThread.setName("<unnamed>"); this.nodeThread = null; } } /** * End execution of Node - let Node finish gracefully * *@since April 4, 2002 */ public void end() { runIt = false; } public void sendMessage(Message<?> msg) { CloverPost post = getGraph().getPost(); if (post != null) { post.sendMessage(msg); } else { getLog().info("Component reports a message, but its graph is already released. Message: " + msg.toString()); } } /** * An operation that adds port to list of all InputPorts * *@param port Port (Input connection) to be added *@since April 2, 2002 *@deprecated Use the other method which takes 2 arguments (portNum, port) */ @Deprecated public void addInputPort(InputPort port) { Integer portNum; int keyVal; try { portNum = (Integer) inPorts.lastKey(); keyVal = portNum.intValue() + 1; } catch (NoSuchElementException ex) { keyVal = 0; } inPorts.put(Integer.valueOf(keyVal), port); port.connectReader(this, keyVal); } /** * An operation that adds port to list of all InputPorts * *@param portNum Number to be associated with this port *@param port Port (Input connection) to be added *@since April 2, 2002 */ public void addInputPort(int portNum, InputPort port) { inPorts.put(Integer.valueOf(portNum), port); port.connectReader(this, portNum); } /** * An operation that adds port to list of all OutputPorts * *@param port Port (Output connection) to be added *@since April 4, 2002 *@deprecated Use the other method which takes 2 arguments (portNum, port) */ @Deprecated public void addOutputPort(OutputPort port) { Integer portNum; int keyVal; try { portNum = (Integer) inPorts.lastKey(); keyVal = portNum.intValue() + 1; } catch (NoSuchElementException ex) { keyVal = 0; } outPorts.put(Integer.valueOf(keyVal), port); port.connectWriter(this, keyVal); resetBufferedValues(); } /** * An operation that adds port to list of all OutputPorts * *@param portNum Number to be associated with this port *@param port The feature to be added to the OutputPort attribute *@since April 4, 2002 */ public void addOutputPort(int portNum, OutputPort port) { outPorts.put(Integer.valueOf(portNum), port); port.connectWriter(this, portNum); resetBufferedValues(); } /** * Gets the port which has associated the num specified * *@param portNum number associated with the port *@return The outputPort */ public OutputPort getOutputPort(int portNum) { Object outPort=outPorts.get(Integer.valueOf(portNum)); if (outPort instanceof OutputPort) { return (OutputPort)outPort ; }else if (outPort==null) { return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement OutputPort interface "+outPort.getClass().getName()); } /** * Gets the port which has associated the num specified * *@param portNum number associated with the port *@return The outputPort */ public OutputPortDirect getOutputPortDirect(int portNum) { Object outPort=outPorts.get(Integer.valueOf(portNum)); if (outPort instanceof OutputPortDirect) { return (OutputPortDirect)outPort ; }else if (outPort==null) { return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement OutputPortDirect interface"); } /** * Gets the port which has associated the num specified * *@param portNum portNum number associated with the port *@return The inputPort */ public InputPort getInputPort(int portNum) { Object inPort=inPorts.get(Integer.valueOf(portNum)); if (inPort instanceof InputPort) { return (InputPort)inPort ; }else if (inPort==null){ return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement InputPort interface"); } /** * Gets the port which has associated the num specified * *@param portNum portNum number associated with the port *@return The inputPort */ public InputPortDirect getInputPortDirect(int portNum) { Object inPort=inPorts.get(Integer.valueOf(portNum)); if (inPort instanceof InputPortDirect) { return (InputPortDirect)inPort ; }else if (inPort==null){ return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement InputPortDirect interface"); } /** * Removes input port. * @param inputPort */ public void removeInputPort(InputPort inputPort) { inPorts.remove(Integer.valueOf(inputPort.getInputPortNumber())); } /** * Removes output port. * @param outputPort */ public void removeOutputPort(OutputPort outputPort) { outPorts.remove(Integer.valueOf(outputPort.getOutputPortNumber())); resetBufferedValues(); } /** * An operation that does removes/unregisteres por<br> * Not yet implemented. * *@param _portNum Description of Parameter *@param _portType Description of Parameter *@since April 2, 2002 */ public void deletePort(int _portNum, char _portType) { throw new UnsupportedOperationException("Deleting port is not supported !"); } /** * An operation that writes one record through specified output port.<br> * As this operation gets the Port object from TreeMap, don't use it in loops * or when time is critical. Instead obtain the Port object directly and * use it's writeRecord() method. * *@param _portNum Description of Parameter *@param _record Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public void writeRecord(int _portNum, DataRecord _record) throws IOException, InterruptedException { ((OutputPort) outPorts.get(Integer.valueOf(_portNum))).writeRecord(_record); } /** * An operation that reads one record through specified input port.<br> * As this operation gets the Port object from TreeMap, don't use it in loops * or when time is critical. Instead obtain the Port object directly and * use it's readRecord() method. * *@param _portNum Description of Parameter *@param record Description of Parameter *@return Description of the Returned Value *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public DataRecord readRecord(int _portNum, DataRecord record) throws IOException, InterruptedException { return ((InputPort) inPorts.get(Integer.valueOf(_portNum))).readRecord(record); } /** * An operation that does ... * *@param record Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public void writeRecordBroadcast(DataRecord record) throws IOException, InterruptedException { for(int i=0;i<outPortsSize;i++){ outPortsArray[i].writeRecord(record); } } /** * Description of the Method * *@param recordBuffer Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since August 13, 2002 */ public void writeRecordBroadcastDirect(CloverBuffer recordBuffer) throws IOException, InterruptedException { for(int i=0;i<outPortsSize;i++){ ((OutputPortDirect) outPortsArray[i]).writeRecordDirect(recordBuffer); recordBuffer.rewind(); } } /** * @deprecated use {@link #writeRecordBroadcastDirect(CloverBuffer)} instead */ @Deprecated public void writeRecordBroadcastDirect(ByteBuffer recordBuffer) throws IOException, InterruptedException { for(int i = 0; i < outPortsSize; i++) { ((OutputPortDirect) outPortsArray[i]).writeRecordDirect(recordBuffer); recordBuffer.rewind(); } } /** * Closes all output ports - sends EOF signal to them. * @throws IOException * *@since April 11, 2002 */ public void closeAllOutputPorts() throws InterruptedException, IOException { for (OutputPort outputPort : getOutPorts()) { outputPort.eof(); } } /** * Send EOF (no more data) to all connected output ports * @throws IOException * *@since April 18, 2002 */ public void broadcastEOF() throws InterruptedException, IOException{ closeAllOutputPorts(); } /** * Closes specified output port - sends EOF signal. * *@param portNum Which port to close * @throws IOException *@since April 11, 2002 */ public void closeOutputPort(int portNum) throws InterruptedException, IOException { OutputPort port = (OutputPort) outPorts.get(Integer.valueOf(portNum)); if (port == null) { throw new RuntimeException(this.getId()+" - can't close output port \"" + portNum + "\" - does not exists!"); } port.eof(); } /** * Compares this Node to specified Object * * @param obj * Node to compare with * @return True if obj represents node with the same ID * @since April 18, 2002 */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Node)) { return false; } final Node other = (Node) obj; return getId().equals(other.getId()); } @Override public int hashCode(){ return getId().hashCode(); } /** * @return Object.hashCode(), which is based on identity */ public int hashCodeIdentity() { return super.hashCode(); } /** * Description of the Method * *@return Description of the Returned Value *@since May 21, 2002 *@deprecated implementation of this method is for now useless and is not required */ public void toXML(Element xmlElement) { //DO NOT IMPLEMENT THIS METHOD } /** * Description of the Method * *@param nodeXML Description of Parameter *@return Description of the Returned Value *@since May 21, 2002 */ public static Node fromXML(TransformationGraph graph, Element xmlElement) throws Exception { throw new UnsupportedOperationException("not implemented in org.jetel.graph.Node"); } /** * @return <b>true</b> if node is enabled; <b>false</b> else */ public EnabledEnum getEnabled() { return enabled; } /** * @param enabled whether node is enabled */ public void setEnabled(String enabledStr) { enabled = EnabledEnum.fromString(enabledStr, EnabledEnum.ENABLED); } /** * @param enabled whether node is enabled */ public void setEnabled(EnabledEnum enabled) { this.enabled = (enabled != null ? enabled : EnabledEnum.ENABLED); } /** * @return index of "pass through" input port */ public int getPassThroughInputPort() { return passThroughInputPort; } /** * Sets "pass through" input port. * @param passThroughInputPort */ public void setPassThroughInputPort(int passThroughInputPort) { this.passThroughInputPort = passThroughInputPort; } /** * @return index of "pass through" output port */ public int getPassThroughOutputPort() { return passThroughOutputPort; } /** * Sets "pass through" output port * @param passThroughOutputPort */ public void setPassThroughOutputPort(int passThroughOutputPort) { this.passThroughOutputPort = passThroughOutputPort; } /** * @return node allocation in parallel processing (cluster environment) */ public EngineComponentAllocation getAllocation() { return allocation; } /** * @param required node allocation in parallel processing (cluster environment) */ public void setAllocation(EngineComponentAllocation alloc) { this.allocation = alloc; } protected void resetBufferedValues(){ outPortsArray=null; outPortsSize=0; } protected void refreshBufferedValues(){ Collection<OutputPort> op = getOutPorts(); outPortsArray = (OutputPort[]) op.toArray(new OutputPort[op.size()]); outPortsSize = outPortsArray.length; } /** * Checks number of input ports, whether is in the given interval. * @param status * @param min * @param max * @param checkNonAssignedPorts should be checked non-assigned ports (for example first port without edge and second port with edge) * @return true if the number of input ports is in the given interval; else false */ protected boolean checkInputPorts(ConfigurationStatus status, int min, int max, boolean checkNonAssignedPorts) { boolean retValue = true; Collection<InputPort> inPorts = getInPorts(); if(inPorts.size() < min) { status.add(new ConfigurationProblem("At least " + min + " input port must be defined!", Severity.ERROR, this, Priority.NORMAL)); retValue = false; } if(inPorts.size() > max) { status.add(new ConfigurationProblem("At most " + max + " input ports can be defined!", Severity.ERROR, this, Priority.NORMAL)); retValue = false; } int index = 0; for (InputPort inputPort : inPorts) { if (inputPort.getMetadata() == null){ //TODO interface for matadata status.add(new ConfigurationProblem("Metadata on input port " + inputPort.getInputPortNumber() + " are not defined!", Severity.WARNING, this, Priority.NORMAL)); retValue = false; } if (checkNonAssignedPorts && inputPort.getInputPortNumber() != index){ status.add(new ConfigurationProblem("Input port " + index + " is not defined!", Severity.ERROR, this, Priority.NORMAL)); retValue = false; } index++; } return retValue; } protected boolean checkInputPorts(ConfigurationStatus status, int min, int max) { return checkInputPorts(status, min, max, true); } /** * Checks number of output ports, whether is in the given interval. * @param status * @param min * @param max * @param checkNonAssignedPorts should be checked non-assigned ports (for example first port without edge and second port with edge) * @return true if the number of output ports is in the given interval; else false */ protected boolean checkOutputPorts(ConfigurationStatus status, int min, int max, boolean checkNonAssignedPorts) { Collection<OutputPort> outPorts = getOutPorts(); if(outPorts.size() < min) { status.add(new ConfigurationProblem("At least " + min + " output port must be defined!", Severity.ERROR, this, Priority.NORMAL)); return false; } if(outPorts.size() > max) { status.add(new ConfigurationProblem("At most " + max + " output ports can be defined!", Severity.ERROR, this, Priority.NORMAL)); return false; } int index = 0; for (OutputPort outputPort : outPorts) { if (outputPort.getMetadata() == null){ status.add(new ConfigurationProblem("Metadata on output port " + outputPort.getOutputPortNumber() + " are not defined!", Severity.WARNING, this, Priority.NORMAL)); return false; } if (checkNonAssignedPorts && outputPort.getOutputPortNumber() != index){ status.add(new ConfigurationProblem("Output port " + index + " is not defined!", Severity.ERROR, this, Priority.NORMAL)); return false; } index++; } return true; } protected boolean checkOutputPorts(ConfigurationStatus status, int min, int max) { return checkOutputPorts(status, min, max, true); } /** * Checks if metadatas in given list are all equal * * @param status * @param metadata list of metadata to check * @return */ protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> metadata){ return checkMetadata(status, metadata, (Collection<DataRecordMetadata>)null); } /** * Checks if all metadata (in inMetadata list as well as in outMetadata list) are equal * * @param status * @param inMetadata * @param outMetadata * @return */ protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> inMetadata, Collection<DataRecordMetadata> outMetadata){ return checkMetadata(status, inMetadata, outMetadata, true); } /** * Checks if all metadata (in inMetadata list as well as in outMetadata list) are equal * If checkFixDelType is true then checks fixed/delimited state. * * @param status * @param inMetadata * @param outMetadata * @param checkFixDelType * @return */ protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> inMetadata, Collection<DataRecordMetadata> outMetadata, boolean checkFixDelType){ Iterator<DataRecordMetadata> iterator = inMetadata.iterator(); DataRecordMetadata metadata = null, nextMetadata; if (iterator.hasNext()) { metadata = iterator.next(); } //check input metadata while (iterator.hasNext()) { nextMetadata = iterator.next(); if (metadata == null || !metadata.equals(nextMetadata)) { status.add(new ConfigurationProblem("Metadata " + StringUtils.quote(metadata == null ? "null" : metadata.getName()) + " does not equal to metadata " + StringUtils.quote(nextMetadata == null ? "null" : nextMetadata.getName()), metadata == null || nextMetadata == null ? Severity.WARNING : Severity.ERROR, this, Priority.NORMAL)); } metadata = nextMetadata; } if (outMetadata == null) { return status; } //check if input metadata equals output metadata iterator = outMetadata.iterator(); if (iterator.hasNext()) { nextMetadata = iterator.next(); if (metadata == null || !metadata.equals(nextMetadata, checkFixDelType)) { status.add(new ConfigurationProblem("Metadata " + StringUtils.quote(metadata == null ? "null" : metadata.getName()) + " does not equal to metadata " + StringUtils.quote(nextMetadata == null ? "null" : nextMetadata.getName()), metadata == null || nextMetadata == null ? Severity.WARNING : Severity.ERROR, this, Priority.NORMAL)); } metadata = nextMetadata; } //check output metadata while (iterator.hasNext()) { nextMetadata = iterator.next(); if (metadata == null || !metadata.equals(nextMetadata)) { status.add(new ConfigurationProblem("Metadata " + StringUtils.quote(metadata == null ? "null" : metadata.getName()) + " does not equal to metadata " + StringUtils.quote(nextMetadata == null ? "null" : nextMetadata.getName()), metadata == null || nextMetadata == null ? Severity.WARNING : Severity.ERROR, this, Priority.NORMAL)); } metadata = nextMetadata; } return status; } protected ConfigurationStatus checkMetadata(ConfigurationStatus status, DataRecordMetadata inMetadata, Collection<DataRecordMetadata> outMetadata){ Collection<DataRecordMetadata> inputMetadata = new ArrayList<DataRecordMetadata>(1); inputMetadata.add(inMetadata); return checkMetadata(status, inputMetadata, outMetadata); } protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> inMetadata, DataRecordMetadata outMetadata){ Collection<DataRecordMetadata> outputMetadata = new ArrayList<DataRecordMetadata>(1); outputMetadata.add(outMetadata); return checkMetadata(status, inMetadata, outputMetadata); } protected ConfigurationStatus checkMetadata(ConfigurationStatus status, DataRecordMetadata inMetadata, DataRecordMetadata outMetadata) { Collection<DataRecordMetadata> inputMetadata = new ArrayList<DataRecordMetadata>(1); inputMetadata.add(inMetadata); Collection<DataRecordMetadata> outputMetadata = new ArrayList<DataRecordMetadata>(1); outputMetadata.add(outMetadata); return checkMetadata(status, inputMetadata, outputMetadata); } /** * The given thread is registered as a child thread of this component. * The child threads are exploited for gathering of tracking information - CPU usage of this component * is sum of all threads. * @param childThread */ public void registerChildThread(Thread childThread) { childThreads.add(childThread); } /** * The given threads are registered as child threads of this component. * The child threads are exploited for gathering of tracking information - for instance * CPU usage of this component is sum of all threads. * @param childThreads */ protected void registerChildThreads(List<Thread> childThreads) { this.childThreads.addAll(childThreads); } /** * @return list of all child threads - threads running under this component */ public List<Thread> getChildThreads() { return childThreads; } /* (non-Javadoc) * @see org.jetel.graph.GraphElement#reset() * @deprecated see {@link org.jetel.graph.IGraphElement#preExecute()} and {@link org.jetel.graph.IGraphElement#postExecute()} methods */ @Override @Deprecated synchronized public void reset() throws ComponentNotReadyException { super.reset(); runIt = true; runResult=Result.READY; resultMessage = null; resultException = null; childThreads.clear(); } @Override public synchronized void free() { super.free(); childThreads.clear(); } /** * This method is intended to be overridden. * @return URLs which this component is using */ public String[] getUsedUrls() { return new String[0]; } public void setPreExecuteBarrier(CyclicBarrier preExecuteBarrier) { this.preExecuteBarrier = preExecuteBarrier; } public void setExecuteBarrier(CyclicBarrier executeBarrier) { this.executeBarrier = executeBarrier; } /** * That is not nice solution to make public this variable. Unfortunately this is necessary * for new ComponentAlgorithm interface. Whenever this class will be removed also this * getter can be removed. * @return current status of runIt variable */ public boolean runIt() { return runIt; } @Override public void workerFinished(Event e) { // ignore by default } @Override public void workerCrashed(Event e) { //e.getException().printStackTrace(); resultException = e.getException(); abort(e.getException()); } /** * @return token tracker for this component or null cannot be returned, * at least {@link PrimitiveComponentTokenTracker} is returned. */ public ComponentTokenTracker getTokenTracker() { return tokenTracker; } /** * Creates suitable token tracker for this component. {@link ComplexComponentTokenTracker} is used by default. * This method is intended to be overridden if custom type of token tracking is necessary. */ protected ComponentTokenTracker createComponentTokenTracker() { return new ComplexComponentTokenTracker(this); } /** * Can be overridden by components to avoid default checking of input ports - * all input ports are checked whether EOF flag was reached * after the component finish processing. * * @see com.cloveretl.server.graph.RemoteEdgeDataTransmitter * @return */ protected boolean checkEofOnInputPorts() { return true; } }
package org.jetel.graph; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Properties; import java.util.TreeMap; import java.util.concurrent.CyclicBarrier; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.MDC; import org.jetel.component.ComponentDescription; import org.jetel.component.ComponentDescriptionImpl; import org.jetel.data.DataRecord; import org.jetel.enums.EnabledEnum; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationProblem; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.ConfigurationStatus.Priority; import org.jetel.exception.ConfigurationStatus.Severity; import org.jetel.exception.JetelRuntimeException; import org.jetel.graph.ContextProvider.Context; import org.jetel.graph.distribution.EngineComponentAllocation; import org.jetel.graph.runtime.CloverPost; import org.jetel.graph.runtime.CloverWorkerListener; import org.jetel.graph.runtime.ErrorMsgBody; import org.jetel.graph.runtime.ExecutionType; import org.jetel.graph.runtime.Message; import org.jetel.graph.runtime.tracker.ComplexComponentTokenTracker; import org.jetel.graph.runtime.tracker.ComponentTokenTracker; import org.jetel.graph.runtime.tracker.PrimitiveComponentTokenTracker; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.ClusterUtils; import org.jetel.util.MiscUtils; import org.jetel.util.bytes.CloverBuffer; import org.jetel.util.string.StringUtils; import org.w3c.dom.Element; /** * A class that represents atomic transformation task. It is a base class for * all kinds of transformation components. * *@author D.Pavlis *@created January 31, 2003 *@since April 2, 2002 *@see org.jetel.component */ public abstract class Node extends GraphElement implements Runnable, CloverWorkerListener { private static final Log logger = LogFactory.getLog(Node.class); private Thread nodeThread; // is guarde by nodeThreadMonitor private final Object nodeThreadMonitor = new Object(); // nodeThread variable and childThreads variable are guarded by this monitor private String formerThreadName; /** * List of all threads under this component. * For instance parallel reader uses threads for parallel reading. * It is component's responsibility to register all inner threads via addChildThread() method. */ protected List<Thread> childThreads; // is guarded by nodeThreadMonitor protected EnabledEnum enabled; protected int passThroughInputPort; protected int passThroughOutputPort; protected TreeMap<Integer, OutputPort> outPorts; protected TreeMap<Integer, InputPort> inPorts; protected volatile boolean runIt = true; private Result runResult; private final Object runResultMonitor = new Object(); // runResult variable is guarded by this monitor protected Throwable resultException; protected String resultMessage; protected Phase phase; /** * Distribution of this node processing at cluster environment. */ protected EngineComponentAllocation allocation; // buffered values protected OutputPort[] outPortsArray; protected int outPortsSize; //synchronization barrier for all components in a phase //all components have to finish pre-execution before execution method private CyclicBarrier executeBarrier; //synchronization barrier for all components in a phase //watchdog needs to have all components with thread assignment before can continue to watch the phase private CyclicBarrier preExecuteBarrier; /** * Component token tracker encapsulates graph's token tracker. * All jobflow logging for this component should be provided through this tracker. * Tracker cannot be null, at least {@link PrimitiveComponentTokenTracker} is used. */ protected ComponentTokenTracker tokenTracker; private Properties attributes; /** Subgraph only. Is this component part of debug input phase of the subgraph. */ private boolean partOfDebugInput = false; /** Subgraph only. Is this component part of debug output phase of the subgraph. */ private boolean partOfDebugOutput = false; /** * Various PORT kinds identifiers * *@since August 13, 2002 */ public final static char OUTPUT_PORT = 'O'; /** Description of the Field */ public final static char INPUT_PORT = 'I'; /** * XML attributes of every cloverETL component */ public final static String XML_NAME_ATTRIBUTE = "guiName"; public final static String XML_TYPE_ATTRIBUTE="type"; public final static String XML_ENABLED_ATTRIBUTE="enabled"; public final static String XML_ALLOCATION_ATTRIBUTE = "allocation"; public final static String XML_PART_OF_DEBUG_INPUT_ATTRIBUTE = "debugInput"; public final static String XML_PART_OF_DEBUG_OUTPUT_ATTRIBUTE = "debugOutput"; /** * Standard constructor. * *@param id Unique ID of the Node *@since April 4, 2002 */ public Node(String id){ this(id,null); } /** * Standard constructor. * *@param id Unique ID of the Node *@since April 4, 2002 */ public Node(String id, TransformationGraph graph) { super(id,graph); outPorts = new TreeMap<Integer, OutputPort>(); inPorts = new TreeMap<Integer, InputPort>(); phase = null; setResultCode(Result.N_A); // result is not known yet childThreads = new ArrayList<Thread>(); allocation = EngineComponentAllocation.createNeighboursAllocation(); } /** * Sets the EOF for particular output port. EOF indicates that no more data * will be sent throught the output port. * *@param portNum The new EOF value * @throws IOException * @throws IOException *@since April 18, 2002 */ public void setEOF(int portNum) throws InterruptedException, IOException { try { ((OutputPort) outPorts.get(Integer.valueOf(portNum))).eof(); } catch (IndexOutOfBoundsException ex) { ex.printStackTrace(); } } /** * Returns the type of this Node (subclasses/Components should override * this method to return appropriate type). * *@return The Type value *@since April 4, 2002 */ public String getType() { return getDescriptor().getType(); } /** * Returns True if this Node is Leaf Node - i.e. only consumes data (has only * input ports connected to it) * *@return True if Node is a Leaf *@since April 4, 2002 */ public boolean isLeaf() { //this implementation is necessary for remote edges //even component with a connected edge can be leaf if the edge is the remote one for (OutputPort outputPort : getOutPorts()) { if (outputPort.getReader() != null) { return false; } } return true; } /** * Returns True if this node is Root Node - i.e. it produces data (has only output ports * connected to id). * *@return True if Node is a Root *@since April 4, 2002 */ public boolean isRoot() { //this implementation is necessary for remote edges //even component with a connected edge can be root if the edge is the remote one for (InputPort inputPort : getInPorts()) { if (inputPort.getWriter() != null) { return false; } } return true; } /** * Sets the processing phase of the Node object.<br> * Default is 0 (ZERO). * *@param phase The new phase number */ public void setPhase(Phase phase) { this.phase = phase; } /** * Gets the processing phase of the Node object * *@return The phase value */ public Phase getPhase() { return phase; } /** * @return phase number */ public int getPhaseNum(){ return phase.getPhaseNum(); } /** * Gets the OutPorts attribute of the Node object * *@return Collection of OutPorts *@since April 18, 2002 */ public Collection<OutputPort> getOutPorts() { return outPorts.values(); } /** * @return map with all output ports (key is index of output port) */ public Map<Integer, OutputPort> getOutputPorts() { return outPorts; } /** * Gets the InPorts attribute of the Node object * *@return Collection of InPorts *@since April 18, 2002 */ public Collection<InputPort> getInPorts() { return inPorts.values(); } /** * @return map with all input ports (key is index of input port) */ public Map<Integer, InputPort> getInputPorts() { return inPorts; } /** * Gets the metadata on output ports of the Node object * *@return Collection of output ports metadata */ public List<DataRecordMetadata> getOutMetadata() { List<DataRecordMetadata> ret = new ArrayList<DataRecordMetadata>(outPorts.size()); for(Iterator<OutputPort> it = getOutPorts().iterator(); it.hasNext();) { ret.add(it.next().getMetadata()); } return ret; } /** * Gets the metadata on output ports of the Node object * * @return array of output ports metadata */ public DataRecordMetadata[] getOutMetadataArray() { return getOutMetadata().toArray(new DataRecordMetadata[0]); } /** * Gets the metadata on input ports of the Node object * *@return Collection of input ports metadata */ public List<DataRecordMetadata> getInMetadata() { List<DataRecordMetadata> ret = new ArrayList<DataRecordMetadata>(inPorts.size()); for(Iterator<InputPort> it = getInPorts().iterator(); it.hasNext();) { ret.add(it.next().getMetadata()); } return ret; } /** * Gets the metadata on input ports of the Node object * * @return array of input ports metadata */ public DataRecordMetadata[] getInMetadataArray() { return getInMetadata().toArray(new DataRecordMetadata[0]); } /** * Gets the number of records passed through specified port type and number * *@param portType Port type (IN, OUT, LOG) *@param portNum port number (0...) *@return The RecordCount value *@since May 17, 2002 *@deprecated */ @Deprecated public long getRecordCount(char portType, int portNum) { long count; // Integer used as key to TreeMap containing ports Integer port = Integer.valueOf(portNum); try { switch (portType) { case OUTPUT_PORT: count = ((OutputPort) outPorts.get(port)).getOutputRecordCounter(); break; case INPUT_PORT: count = ((InputPort) inPorts.get(port)).getInputRecordCounter(); break; default: count = -1; } } catch (Exception ex) { count = -1; } return count; } /** * Gets the result code of finished Node.<br> * *@return The Result value *@since July 29, 2002 *@see org.jetel.graph.Node.Result */ public Result getResultCode() { synchronized (runResultMonitor) { return runResult; } } /** * Sets the result code of component. * @param result */ public void setResultCode(Result result) { synchronized (runResultMonitor) { this.runResult = result; } } /** * Sets the component result to new value if and only if the current result equals to the given expectation. * This is atomic operation for 'if' and 'set'. * @param newResult new component result * @param expectedOldResult expected value of current result */ public void setResultCode(Result newResult, Result expectedOldResult) { synchronized (runResultMonitor) { if (runResult == expectedOldResult) { runResult = newResult; } } } /** * Gets the ResultMsg of finished Node.<br> * This message briefly describes what caused and error (if there was any). * *@return The ResultMsg value *@since July 29, 2002 */ public String getResultMsg() { Result result = getResultCode(); return result != null ? result.message() : null; } /** * Gets exception which caused Node to fail execution - if * there was such failure. * * @return * @since 13.12.2006 */ public Throwable getResultException(){ return resultException; } // Operations /* (non-Javadoc) * @see org.jetel.graph.GraphElement#init() */ @Override public void init() throws ComponentNotReadyException { super.init(); setResultCode(Result.READY); refreshBufferedValues(); //initialise component token tracker if necessary if (getGraph() != null && getGraph().getRuntimeJobType().isJobflow() && getGraph().getRuntimeContext().isTokenTracking()) { tokenTracker = createComponentTokenTracker(); } else { tokenTracker = new PrimitiveComponentTokenTracker(this); } } /* (non-Javadoc) * @see org.jetel.graph.GraphElement#preExecute() */ @Override public void preExecute() throws ComponentNotReadyException { super.preExecute(); //cluster related settings can be used only in cluster environment if (!getGraph().getAuthorityProxy().isClusterEnabled()) { //cluster components cannot be used in non-cluster environment if (ClusterUtils.isClusterComponent(getType())) { throw new JetelRuntimeException("Cluster component cannot be used in non-cluster environment."); } //non empty allocation is not allowed in non-cluster environment EngineComponentAllocation allocation = getAllocation(); if (allocation != null && !allocation.isNeighboursAllocation()) { throw new JetelRuntimeException("Component allocation cannot be specified in non-cluster environment."); } } setResultCode(Result.RUNNING); } /** * main execution method of Node (calls in turn execute()) * *@since April 2, 2002 */ @Override public void run() { setResultCode(Result.RUNNING); // set running result, so we know run() method was started Context c = ContextProvider.registerNode(this); try { //store the current thread like a node executor setNodeThread(Thread.currentThread()); //Node.preExecute() is not performed for single thread execution //SingleThreadWatchDog executes preExecution itself if (getGraph().getRuntimeContext().getExecutionType() != ExecutionType.SINGLE_THREAD_EXECUTION) { //we need a synchronization point for all components in a phase //watchdog starts all components in phase and wait on this barrier for real startup preExecuteBarrier.await(); //preExecute() invocation try { preExecute(); } catch (Throwable e) { throw new ComponentNotReadyException(this, "Component pre-execute initialization failed.", e); } finally { //waiting for other nodes in the current phase - first all pre-execution has to be done at all nodes executeBarrier.await(); } } //execute() invocation Result result = execute(); //broadcast all output ports with EOF information if (result == Result.FINISHED_OK) { broadcastEOF(); } //set the result of execution to the component (broadcastEOF needs to be done before this set, see CLO-1364) setResultCode(result); if (result == Result.ERROR) { Message<ErrorMsgBody> msg = Message.createErrorMessage(this, new ErrorMsgBody(Result.ERROR.code(), resultMessage != null ? resultMessage : Result.ERROR.message(), null)); sendMessage(msg); } if (result == Result.FINISHED_OK) { if (runIt == false) { //component returns ok tag, but the component was actually aborted setResultCode(Result.ABORTED); } else if (checkEofOnInputPorts()) { // true by default //check whether all input ports are already closed for (InputPort inputPort : getInPorts()) { //if the edge base of the input port is not shared due this component and some data records are still in input port, report an error if (!inputPort.getEdge().isSharedEdgeBaseFromReader() && !inputPort.isEOF()) { setResultCode(Result.ERROR); Message<ErrorMsgBody> msg = Message.createErrorMessage(this, new ErrorMsgBody(Result.ERROR.code(), Result.ERROR.message(), createNodeException(new JetelRuntimeException("Component has finished and input port " + inputPort.getInputPortNumber() + " still contains some unread records.")))); sendMessage(msg); return; } } } } } catch (InterruptedException ex) { setResultCode(Result.ABORTED); } catch (Exception ex) { setResultCode(Result.ERROR); resultException = createNodeException(ex); Message<ErrorMsgBody> msg = Message.createErrorMessage(this, new ErrorMsgBody(Result.ERROR.code(), Result.ERROR.message(), resultException)); sendMessage(msg); } catch (Throwable ex) { logger.fatal(ex); setResultCode(Result.ERROR); resultException = createNodeException(ex); Message<ErrorMsgBody> msg = Message.createErrorMessage(this, new ErrorMsgBody(Result.ERROR.code(), Result.ERROR.message(), resultException)); sendMessage(msg); } finally { ContextProvider.unregister(c); setNodeThread(null); sendFinishMessage(); } } protected abstract Result execute() throws Exception; private Exception createNodeException(Throwable cause) { //compose error message, for example //"Component [Reformat:REFORMAT] finished with status ERROR. (In0: 11 recs, Out0: 10 recs, Out1: 0 recs)" String recordsMessage = MiscUtils.getInOutRecordsMessage(this); return new JetelRuntimeException("Component " + this + " finished with status ERROR." + (recordsMessage.length() > 0 ? " (" + recordsMessage + ")" : ""), cause); } /** * This method should be called every time when node finishes its work. */ private void sendFinishMessage() { //sends notification - node has finished sendMessage(Message.createNodeFinishedMessage(this)); } /** * Abort execution of Node - only inform node, that should finish processing. * *@since April 4, 2002 */ public void abort() { abort(null); } public void abort(Throwable cause) { int attempts = 30; runIt = false; synchronized (nodeThreadMonitor) { Thread nodeThread = getNodeThread(); if (nodeThread != null) { //rename node thread String newThreadName = "exNode_" + getGraph().getRuntimeContext().getRunId() + "_" + getGraph().getId() + "_" + getId(); if (logger.isTraceEnabled()) logger.trace("rename thread " + nodeThread.getName() + " to " + newThreadName); nodeThread.setName(newThreadName); //interrupt node threads while (!getResultCode().isStop() && attempts if (logger.isDebugEnabled()) { logger.debug("trying to interrupt thread " + nodeThread); } //interrupt main node thread nodeThread.interrupt(); //interrupt all child threads if any abortChildThreads(); //wait some time for graph result try { Thread.sleep(10); } catch (InterruptedException e) { } } } } if (cause != null) { setResultCode(Result.ERROR); resultException = createNodeException(cause); Message<ErrorMsgBody> msg = Message.createErrorMessage(this, new ErrorMsgBody(Result.ERROR.code(), Result.ERROR.message(), resultException)); sendMessage(msg); sendFinishMessage(); } else if (!getResultCode().isStop()) { logger.debug("Node '" + getId() + "' was not interrupted in legal way."); setResultCode(Result.ABORTED); sendFinishMessage(); } } private void abortChildThreads() { synchronized(nodeThreadMonitor) { for (Thread childThread : childThreads) { if (logger.isDebugEnabled()) { logger.debug("trying to interrupt child thread " + childThread); } childThread.interrupt(); } } } /** * @return thread of running node; <b>null</b> if node does not running */ public Thread getNodeThread() { synchronized (nodeThreadMonitor) { return nodeThread; } } /** * Sets actual thread in which this node current running. * @param nodeThread */ public void setNodeThread(Thread nodeThread) { synchronized (nodeThreadMonitor) { if(nodeThread != null) { if (this.nodeThread != nodeThread) { this.nodeThread = nodeThread; //thread context classloader is preset to a reasonable classloader //this is just for sure, threads are recycled and no body can guarantee which context classloader remains preset nodeThread.setContextClassLoader(this.getClass().getClassLoader()); formerThreadName = nodeThread.getName(); long runId = getGraph().getRuntimeContext().getRunId(); nodeThread.setName(getId()+"_"+runId); MDC.put("runId", getGraph().getRuntimeContext().getRunId()); if (logger.isTraceEnabled()) { logger.trace("set thread name; old:"+formerThreadName+" new:"+ nodeThread.getName()); logger.trace("set thread runId; runId:"+runId+" thread name:"+Thread.currentThread().getName()); } } } else { MDC.remove("runId"); long runId = getGraph().getRuntimeContext().getRunId(); if (logger.isTraceEnabled()) logger.trace("reset thread runId; runId:"+runId+" thread name:"+Thread.currentThread().getName()); if (!StringUtils.isEmpty(formerThreadName)) { this.nodeThread.setName(formerThreadName); //use former thread name if any } else { this.nodeThread.setName("<unnamed>"); } this.nodeThread = null; } } } /** * End execution of Node - let Node finish gracefully * *@since April 4, 2002 */ public void end() { runIt = false; } public void sendMessage(Message<?> msg) { CloverPost post = getGraph().getPost(); if (post != null) { post.sendMessage(msg); } else { getLog().info("Component reports a message, but its graph is already released. Message: " + msg.toString()); } } /** * An operation that adds port to list of all InputPorts * *@param port Port (Input connection) to be added *@since April 2, 2002 *@deprecated Use the other method which takes 2 arguments (portNum, port) */ @Deprecated public void addInputPort(InputPort port) { Integer portNum; int keyVal; try { portNum = (Integer) inPorts.lastKey(); keyVal = portNum.intValue() + 1; } catch (NoSuchElementException ex) { keyVal = 0; } inPorts.put(Integer.valueOf(keyVal), port); port.connectReader(this, keyVal); } /** * An operation that adds port to list of all InputPorts * *@param portNum Number to be associated with this port *@param port Port (Input connection) to be added *@since April 2, 2002 */ public void addInputPort(int portNum, InputPort port) { inPorts.put(Integer.valueOf(portNum), port); port.connectReader(this, portNum); } /** * An operation that adds port to list of all OutputPorts * *@param port Port (Output connection) to be added *@since April 4, 2002 *@deprecated Use the other method which takes 2 arguments (portNum, port) */ @Deprecated public void addOutputPort(OutputPort port) { Integer portNum; int keyVal; try { portNum = (Integer) inPorts.lastKey(); keyVal = portNum.intValue() + 1; } catch (NoSuchElementException ex) { keyVal = 0; } outPorts.put(Integer.valueOf(keyVal), port); port.connectWriter(this, keyVal); resetBufferedValues(); } /** * An operation that adds port to list of all OutputPorts * *@param portNum Number to be associated with this port *@param port The feature to be added to the OutputPort attribute *@since April 4, 2002 */ public void addOutputPort(int portNum, OutputPort port) { outPorts.put(Integer.valueOf(portNum), port); port.connectWriter(this, portNum); resetBufferedValues(); } /** * Gets the port which has associated the num specified * *@param portNum number associated with the port *@return The outputPort */ public OutputPort getOutputPort(int portNum) { Object outPort=outPorts.get(Integer.valueOf(portNum)); if (outPort instanceof OutputPort) { return (OutputPort)outPort ; }else if (outPort==null) { return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement OutputPort interface "+outPort.getClass().getName()); } /** * Gets the port which has associated the num specified * *@param portNum number associated with the port *@return The outputPort */ public OutputPortDirect getOutputPortDirect(int portNum) { Object outPort=outPorts.get(Integer.valueOf(portNum)); if (outPort instanceof OutputPortDirect) { return (OutputPortDirect)outPort ; }else if (outPort==null) { return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement OutputPortDirect interface"); } /** * Gets the port which has associated the num specified * *@param portNum portNum number associated with the port *@return The inputPort */ public InputPort getInputPort(int portNum) { Object inPort=inPorts.get(Integer.valueOf(portNum)); if (inPort instanceof InputPort) { return (InputPort)inPort ; }else if (inPort==null){ return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement InputPort interface"); } /** * Gets the port which has associated the num specified * *@param portNum portNum number associated with the port *@return The inputPort */ public InputPortDirect getInputPortDirect(int portNum) { Object inPort=inPorts.get(Integer.valueOf(portNum)); if (inPort instanceof InputPortDirect) { return (InputPortDirect)inPort ; }else if (inPort==null){ return null; } throw new RuntimeException("Port number \""+portNum+"\" does not implement InputPortDirect interface"); } /** * Removes input port. * @param inputPort */ public void removeInputPort(InputPort inputPort) { inPorts.remove(Integer.valueOf(inputPort.getInputPortNumber())); } /** * Removes output port. * @param outputPort */ public void removeOutputPort(OutputPort outputPort) { outPorts.remove(Integer.valueOf(outputPort.getOutputPortNumber())); resetBufferedValues(); } /** * An operation that does removes/unregisteres por<br> * Not yet implemented. * *@param _portNum Description of Parameter *@param _portType Description of Parameter *@since April 2, 2002 */ public void deletePort(int _portNum, char _portType) { throw new UnsupportedOperationException("Deleting port is not supported !"); } /** * An operation that writes one record through specified output port.<br> * As this operation gets the Port object from TreeMap, don't use it in loops * or when time is critical. Instead obtain the Port object directly and * use it's writeRecord() method. * *@param _portNum Description of Parameter *@param _record Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public void writeRecord(int _portNum, DataRecord _record) throws IOException, InterruptedException { ((OutputPort) outPorts.get(Integer.valueOf(_portNum))).writeRecord(_record); } /** * An operation that reads one record through specified input port.<br> * As this operation gets the Port object from TreeMap, don't use it in loops * or when time is critical. Instead obtain the Port object directly and * use it's readRecord() method. * *@param _portNum Description of Parameter *@param record Description of Parameter *@return Description of the Returned Value *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public DataRecord readRecord(int _portNum, DataRecord record) throws IOException, InterruptedException { return ((InputPort) inPorts.get(Integer.valueOf(_portNum))).readRecord(record); } /** * An operation that does ... * *@param record Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since April 2, 2002 */ public void writeRecordBroadcast(DataRecord record) throws IOException, InterruptedException { for(int i=0;i<outPortsSize;i++){ outPortsArray[i].writeRecord(record); } } /** * Description of the Method * *@param recordBuffer Description of Parameter *@exception IOException Description of Exception *@exception InterruptedException Description of Exception *@since August 13, 2002 */ public void writeRecordBroadcastDirect(CloverBuffer recordBuffer) throws IOException, InterruptedException { for(int i=0;i<outPortsSize;i++){ ((OutputPortDirect) outPortsArray[i]).writeRecordDirect(recordBuffer); recordBuffer.rewind(); } } /** * @deprecated use {@link #writeRecordBroadcastDirect(CloverBuffer)} instead */ @Deprecated public void writeRecordBroadcastDirect(ByteBuffer recordBuffer) throws IOException, InterruptedException { for(int i = 0; i < outPortsSize; i++) { ((OutputPortDirect) outPortsArray[i]).writeRecordDirect(recordBuffer); recordBuffer.rewind(); } } /** * Closes all output ports - sends EOF signal to them. * @throws IOException * *@since April 11, 2002 */ public void closeAllOutputPorts() throws InterruptedException, IOException { for (OutputPort outputPort : getOutPorts()) { outputPort.eof(); } } /** * Send EOF (no more data) to all connected output ports * @throws IOException * *@since April 18, 2002 */ public void broadcastEOF() throws InterruptedException, IOException{ closeAllOutputPorts(); } /** * Closes specified output port - sends EOF signal. * *@param portNum Which port to close * @throws IOException *@since April 11, 2002 */ public void closeOutputPort(int portNum) throws InterruptedException, IOException { OutputPort port = (OutputPort) outPorts.get(Integer.valueOf(portNum)); if (port == null) { throw new RuntimeException(this.getId()+" - can't close output port \"" + portNum + "\" - does not exists!"); } port.eof(); } /** * Compares this Node to specified Object * * @param obj * Node to compare with * @return True if obj represents node with the same ID * @since April 18, 2002 */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Node)) { return false; } final Node other = (Node) obj; return getId().equals(other.getId()); } @Override public int hashCode(){ return getId().hashCode(); } /** * @return Object.hashCode(), which is based on identity */ public int hashCodeIdentity() { return super.hashCode(); } /** * Description of the Method * *@return Description of the Returned Value *@since May 21, 2002 *@deprecated implementation of this method is for now useless and is not required */ public void toXML(Element xmlElement) { //DO NOT IMPLEMENT THIS METHOD } /** * Description of the Method * *@param nodeXML Description of Parameter *@return Description of the Returned Value *@since May 21, 2002 */ public static Node fromXML(TransformationGraph graph, Element xmlElement) throws Exception { throw new UnsupportedOperationException("not implemented in org.jetel.graph.Node"); } /** * @return <b>true</b> if node is enabled; <b>false</b> else */ public EnabledEnum getEnabled() { return enabled; } /** * @param enabled whether node is enabled */ public void setEnabled(String enabledStr) { enabled = EnabledEnum.fromString(enabledStr, EnabledEnum.ENABLED); } /** * @param enabled whether node is enabled */ public void setEnabled(EnabledEnum enabled) { this.enabled = (enabled != null ? enabled : EnabledEnum.ENABLED); } /** * @return index of "pass through" input port */ public int getPassThroughInputPort() { return passThroughInputPort; } /** * Sets "pass through" input port. * @param passThroughInputPort */ public void setPassThroughInputPort(int passThroughInputPort) { this.passThroughInputPort = passThroughInputPort; } /** * @return index of "pass through" output port */ public int getPassThroughOutputPort() { return passThroughOutputPort; } /** * Sets "pass through" output port * @param passThroughOutputPort */ public void setPassThroughOutputPort(int passThroughOutputPort) { this.passThroughOutputPort = passThroughOutputPort; } /** * @return node allocation in parallel processing (cluster environment) */ public EngineComponentAllocation getAllocation() { return allocation; } /** * @param required node allocation in parallel processing (cluster environment) */ public void setAllocation(EngineComponentAllocation alloc) { this.allocation = alloc; } protected void resetBufferedValues(){ outPortsArray=null; outPortsSize=0; } protected void refreshBufferedValues(){ Collection<OutputPort> op = getOutPorts(); outPortsArray = (OutputPort[]) op.toArray(new OutputPort[op.size()]); outPortsSize = outPortsArray.length; } @Override public ConfigurationStatus checkConfig(ConfigurationStatus status) { status = super.checkConfig(status); //component allocation is limited for jobflows if (!getGraph().getRuntimeJobType().isGraph()) { if (!getAllocation().isNeighboursAllocation()) { status.add("Invalid component allocation. Only regular ETL graphs can be distributed.", Severity.ERROR, this, Priority.NORMAL); } } return status; } /** * Checks number of input ports, whether is in the given interval. * @param status * @param min * @param max * @param checkNonAssignedPorts should be checked non-assigned ports (for example first port without edge and second port with edge) * @return true if the number of input ports is in the given interval; else false */ protected boolean checkInputPorts(ConfigurationStatus status, int min, int max, boolean checkNonAssignedPorts) { boolean retValue = true; Collection<InputPort> inPorts = getInPorts(); if(inPorts.size() < min) { status.add(new ConfigurationProblem("At least " + min + " input port must be defined!", Severity.ERROR, this, Priority.NORMAL)); retValue = false; } if(inPorts.size() > max) { status.add(new ConfigurationProblem("At most " + max + " input ports can be defined!", Severity.ERROR, this, Priority.NORMAL)); retValue = false; } int index = 0; for (InputPort inputPort : inPorts) { if (inputPort.getMetadata() == null){ //TODO interface for matadata status.add(new ConfigurationProblem("Metadata on input port " + inputPort.getInputPortNumber() + " are not defined!", Severity.WARNING, this, Priority.NORMAL)); retValue = false; } if (checkNonAssignedPorts && inputPort.getInputPortNumber() != index){ status.add(new ConfigurationProblem("Input port " + index + " is not defined!", Severity.ERROR, this, Priority.NORMAL)); retValue = false; } index++; } return retValue; } protected boolean checkInputPorts(ConfigurationStatus status, int min, int max) { return checkInputPorts(status, min, max, true); } /** * Checks number of output ports, whether is in the given interval. * @param status * @param min * @param max * @param checkNonAssignedPorts should be checked non-assigned ports (for example first port without edge and second port with edge) * @return true if the number of output ports is in the given interval; else false */ protected boolean checkOutputPorts(ConfigurationStatus status, int min, int max, boolean checkNonAssignedPorts) { Collection<OutputPort> outPorts = getOutPorts(); if(outPorts.size() < min) { status.add(new ConfigurationProblem("At least " + min + " output port must be defined!", Severity.ERROR, this, Priority.NORMAL)); return false; } if(outPorts.size() > max) { status.add(new ConfigurationProblem("At most " + max + " output ports can be defined!", Severity.ERROR, this, Priority.NORMAL)); return false; } int index = 0; for (OutputPort outputPort : outPorts) { if (outputPort.getMetadata() == null){ status.add(new ConfigurationProblem("Metadata on output port " + outputPort.getOutputPortNumber() + " are not defined!", Severity.WARNING, this, Priority.NORMAL)); return false; } if (checkNonAssignedPorts && outputPort.getOutputPortNumber() != index){ status.add(new ConfigurationProblem("Output port " + index + " is not defined!", Severity.ERROR, this, Priority.NORMAL)); return false; } index++; } return true; } protected boolean checkOutputPorts(ConfigurationStatus status, int min, int max) { return checkOutputPorts(status, min, max, true); } /** * Checks if metadatas in given list are all equal * * @param status * @param metadata list of metadata to check * @return */ protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> metadata){ return checkMetadata(status, metadata, (Collection<DataRecordMetadata>)null); } /** * Checks if all metadata (in inMetadata list as well as in outMetadata list) are equal * * @param status * @param inMetadata * @param outMetadata * @return */ protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> inMetadata, Collection<DataRecordMetadata> outMetadata){ return checkMetadata(status, inMetadata, outMetadata, true); } /** * Checks if all metadata (in inMetadata list as well as in outMetadata list) are equal * If checkFixDelType is true then checks fixed/delimited state. * * @param status * @param inMetadata * @param outMetadata * @param checkFixDelType * @return */ protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> inMetadata, Collection<DataRecordMetadata> outMetadata, boolean checkFixDelType){ Iterator<DataRecordMetadata> iterator = inMetadata.iterator(); DataRecordMetadata metadata = null, nextMetadata; if (iterator.hasNext()) { metadata = iterator.next(); } //check input metadata while (iterator.hasNext()) { nextMetadata = iterator.next(); if (metadata == null || !metadata.equals(nextMetadata)) { status.add(new ConfigurationProblem("Metadata " + StringUtils.quote(metadata == null ? "null" : metadata.getName()) + " does not equal to metadata " + StringUtils.quote(nextMetadata == null ? "null" : nextMetadata.getName()), metadata == null || nextMetadata == null ? Severity.WARNING : Severity.ERROR, this, Priority.NORMAL)); } metadata = nextMetadata; } if (outMetadata == null) { return status; } //check if input metadata equals output metadata iterator = outMetadata.iterator(); if (iterator.hasNext()) { nextMetadata = iterator.next(); if (metadata == null || !metadata.equals(nextMetadata, checkFixDelType)) { status.add(new ConfigurationProblem("Metadata " + StringUtils.quote(metadata == null ? "null" : metadata.getName()) + " does not equal to metadata " + StringUtils.quote(nextMetadata == null ? "null" : nextMetadata.getName()), metadata == null || nextMetadata == null ? Severity.WARNING : Severity.ERROR, this, Priority.NORMAL)); } metadata = nextMetadata; } //check output metadata while (iterator.hasNext()) { nextMetadata = iterator.next(); if (metadata == null || !metadata.equals(nextMetadata)) { status.add(new ConfigurationProblem("Metadata " + StringUtils.quote(metadata == null ? "null" : metadata.getName()) + " does not equal to metadata " + StringUtils.quote(nextMetadata == null ? "null" : nextMetadata.getName()), metadata == null || nextMetadata == null ? Severity.WARNING : Severity.ERROR, this, Priority.NORMAL)); } metadata = nextMetadata; } return status; } protected ConfigurationStatus checkMetadata(ConfigurationStatus status, DataRecordMetadata inMetadata, Collection<DataRecordMetadata> outMetadata){ Collection<DataRecordMetadata> inputMetadata = new ArrayList<DataRecordMetadata>(1); inputMetadata.add(inMetadata); return checkMetadata(status, inputMetadata, outMetadata); } protected ConfigurationStatus checkMetadata(ConfigurationStatus status, Collection<DataRecordMetadata> inMetadata, DataRecordMetadata outMetadata){ Collection<DataRecordMetadata> outputMetadata = new ArrayList<DataRecordMetadata>(1); outputMetadata.add(outMetadata); return checkMetadata(status, inMetadata, outputMetadata); } protected ConfigurationStatus checkMetadata(ConfigurationStatus status, DataRecordMetadata inMetadata, DataRecordMetadata outMetadata) { Collection<DataRecordMetadata> inputMetadata = new ArrayList<DataRecordMetadata>(1); inputMetadata.add(inMetadata); Collection<DataRecordMetadata> outputMetadata = new ArrayList<DataRecordMetadata>(1); outputMetadata.add(outMetadata); return checkMetadata(status, inputMetadata, outputMetadata); } /** * The given thread is registered as a child thread of this component. * The child threads are exploited for gathering of tracking information - CPU usage of this component * is sum of all threads. * @param childThread */ public void registerChildThread(Thread childThread) { synchronized(nodeThreadMonitor) { if (runIt) { //new child thread can be registered only for running components childThreads.add(childThread); } else { throw new JetelRuntimeException("New component's child thread cannot be registered. Component has been already finished."); } } } /** * The given thread is unregistered from this node. Should be invoked by the child thread * right before the thread finish. * @param childThread */ public void unregisterChildThread(Thread childThread) { synchronized(nodeThreadMonitor) { childThreads.remove(childThread); } } /** * The given threads are registered as child threads of this component. * The child threads are exploited for gathering of tracking information - for instance * CPU usage of this component is sum of all threads. * @param childThreads */ protected void registerChildThreads(List<Thread> childThreads) { synchronized(nodeThreadMonitor) { if (runIt) { //new child thread can be registered only for running components this.childThreads.addAll(childThreads); } else { throw new JetelRuntimeException("New component's child threads cannot be registered. Component has been already finished."); } } } /** * @return list of all child threads - threads running under this component */ public List<Thread> getChildThreads() { synchronized(nodeThreadMonitor) { return new ArrayList<Thread>(childThreads); //duplicate is returned to ensure thread safety } } /* (non-Javadoc) * @see org.jetel.graph.GraphElement#reset() * @deprecated see {@link org.jetel.graph.IGraphElement#preExecute()} and {@link org.jetel.graph.IGraphElement#postExecute()} methods */ @Override @Deprecated synchronized public void reset() throws ComponentNotReadyException { super.reset(); runIt = true; setResultCode(Result.READY); resultMessage = null; resultException = null; //should be uncommented after CLO-2574 is fixed // synchronized(nodeThreadMonitor) { // childThreads.clear(); } @Override public synchronized void free() { super.free(); //should be uncommented after CLO-2574 is fixed // synchronized(nodeThreadMonitor) { // childThreads.clear(); } /** * This method is intended to be overridden. * @return URLs which this component is using */ public String[] getUsedUrls() { return new String[0]; } public void setPreExecuteBarrier(CyclicBarrier preExecuteBarrier) { this.preExecuteBarrier = preExecuteBarrier; } public void setExecuteBarrier(CyclicBarrier executeBarrier) { this.executeBarrier = executeBarrier; } /** * That is not nice solution to make public this variable. Unfortunately this is necessary * for new ComponentAlgorithm interface. Whenever this class will be removed also this * getter can be removed. * @return current status of runIt variable */ public boolean runIt() { return runIt; } @Override public void workerFinished(Event e) { // ignore by default } @Override public void workerCrashed(Event e) { //e.getException().printStackTrace(); resultException = e.getException(); abort(e.getException()); } /** * @return token tracker for this component or null cannot be returned, * at least {@link PrimitiveComponentTokenTracker} is returned. */ public ComponentTokenTracker getTokenTracker() { return tokenTracker; } /** * Creates suitable token tracker for this component. {@link ComplexComponentTokenTracker} is used by default. * This method is intended to be overridden if custom type of token tracking is necessary. */ protected ComponentTokenTracker createComponentTokenTracker() { return new ComplexComponentTokenTracker(this); } /** * Can be overridden by components to avoid default checking of input ports - * all input ports are checked whether EOF flag was reached * after the component finish processing. * * @see com.cloveretl.server.graph.RemoteEdgeDataTransmitter * @return */ protected boolean checkEofOnInputPorts() { return true; } @Override public ComponentDescription getDescriptor() { ComponentDescription componentDescription = (ComponentDescription) super.getDescriptor(); if (componentDescription == null) { componentDescription = new ComponentDescriptionImpl.MissingComponentDescription(); setDescriptor(componentDescription); } return componentDescription; } public Properties getAttributes() { return attributes; } public void setAttributes(Properties attributes) { this.attributes = attributes; } /** * This method blocks current thread until all input and output edges are * complete - last record is read, EOF indicator is reached. */ protected void waitForEdgesEOF() throws InterruptedException { for (InputPort inputPort : getInPorts()) { inputPort.getEdge().waitForEOF(); } for (OutputPort outputPort : getOutPorts()) { outputPort.getEdge().waitForEOF(); } } public void setPartOfDebugInput(boolean partOfDebugInput) { this.partOfDebugInput = partOfDebugInput; } /** * Subgraph only feature. * @return true if this component is part of debug input phase of this subgraph */ public boolean isPartOfDebugInput() { return partOfDebugInput; } public void setPartOfDebugOutput(boolean partOfDebugOutput) { this.partOfDebugOutput = partOfDebugOutput; } /** * Subgraph only feature. * @return true if this component is part of debug output phase of this subgraph */ public boolean isPartOfDebugOutput() { return partOfDebugOutput; } }
package com.Ryan.Calculator; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import java.math.BigInteger; public class MainActivity extends Activity { public Complex currentValue=Complex.ZERO; /** Called when the activity is first created. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) { getActionBar().hide(); if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.ICE_CREAM_SANDWICH) findViewById(R.id.mainLayout).setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); } setZero(); } public Complex parseComplex(String num) { if (num==null || num.indexOf("Error", 0)==0 || num.indexOf("ERROR", 0)==0) return Complex.ZERO; if ("Not prime".equals(num) || "Not prime or composite".equals(num)) return Complex.ZERO; if ("Prime".equals(num)) return Complex.ONE; if (num.charAt(num.length()-1)=='\u03C0') { if (num.length()==1) return Complex.PI; else if (num.length()==2 && num.charAt(0)=='-') // If the string is two long and the first character is a negation return Complex.negate(Complex.PI); // Return negative pi return Complex.multiply(parseComplex(num.substring(0, num.length()-1)), Complex.PI); } if (num.charAt(num.length()-1)=='e') { if (num.length()==1) return Complex.E; else if (num.length()==2 && num.charAt(0)=='-') // If the string is two long and the first character is a negation return Complex.negate(Complex.E); // Return negative e return Complex.multiply(parseComplex(num.substring(0, num.length()-1)), Complex.E); } try { return Complex.parseNaiveString(num); } catch (NumberFormatException ex) { try { return Complex.parseString(num); } catch (NumberFormatException e) { setText("ERROR: Invalid number"); View v=findViewById(R.id.mainCalculateButton); v.setOnClickListener(null); // Cancel existing computation v.setVisibility(View.GONE); // Remove the button return Complex.ZERO; } } } public String inIntTermsOfPi(double num) { if (num==0) return "0"; double tmp=num/Math.PI; int n=(int)tmp; if (n==tmp) { if (n==-1) // If it is a negative, but otherwise 1 return "-\u03C0"; // Return negative pi return (n==1 ? "" : Integer.toString(n))+"\u03C0"; } else return Double.toString(num); } public String inIntTermsOfPi(Complex num) { if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i" return "0"; if (num.isReal()) return inIntTermsOfPi(num.real); if (num.isImaginary()) return inIntTermsOfPi(num.imaginary)+'i'; String out=inIntTermsOfPi(num.real); if (num.imaginary>0) out+="+"; out+=inIntTermsOfPi(num.imaginary)+'i'; return out; } public String inIntTermsOfE(double num) { if (num==0) return "0"; double tmp=num/Math.E; int n=(int)tmp; if (n==tmp) { if (n==-1) // If it is a negative, but otherwise 1 return "-e"; // Return negative e return (n==1 ? "" : Integer.toString((int)tmp))+"e"; } else return Double.toString(num); } public String inIntTermsOfE(Complex num) { if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i" return "0"; if (num.isReal()) return inIntTermsOfE(num.real); if (num.isImaginary()) return inIntTermsOfE(num.imaginary)+'i'; String out=inIntTermsOfE(num.real); if (num.imaginary>0) out+="+"; out+=inIntTermsOfE(num.imaginary)+'i'; return out; } public String inIntTermsOfAny(double num) { if (Double.isNaN(num)) // "Last-resort" check return "ERROR: Nonreal or non-numeric result."; // Trap NaN and return a generic error for it. // Because of that check, we can guarantee that NaN's will not be floating around for more than one expression. String out=inIntTermsOfPi(num); if (!out.equals(Double.toString(num))) return out; else return inIntTermsOfE(num); } public String inIntTermsOfAny(Complex num) { if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i" return "0"; if (num.isReal()) return inIntTermsOfAny(num.real); if (num.isImaginary()) return inIntTermsOfAny(num.imaginary)+'i'; String out=inIntTermsOfAny(num.real); if (num.imaginary>0) out+="+"; out+=inIntTermsOfAny(num.imaginary)+'i'; return out; } public void zero(View v) { setZero(); } public void setZero(EditText ev) { setText("0", ev); } public void setZero() { setZero((EditText) findViewById(R.id.mainTextField)); } public void setText(String n, EditText ev) { ev.setText(n); ev.setSelection(0, n.length()); // Ensure the cursor is at the end } public void setText(String n) { setText(n, (EditText) findViewById(R.id.mainTextField)); } public void terms(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(parseComplex(ev.getText().toString())), ev); } public void decimal(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(Complex.toString(parseComplex(ev.getText().toString())), ev); } public Complex getValue(final EditText ev) // Parses the content of ev into a double. { return parseComplex(ev.getText().toString().trim()); } public void doCalculate(final EditText ev, OnClickListener ocl) // Common code for buttons that use the mainCalculateButton. { doCalculate(ev, ocl, Complex.ZERO); } public void doCalculate(final EditText ev, OnClickListener ocl, Complex n) // Common code for buttons that use the mainCalculateButton, setting the default value to n rather than zero. { setText(inIntTermsOfAny(n), ev); final Button b=(Button)findViewById(R.id.mainCalculateButton); b.setVisibility(View.VISIBLE); b.setOnClickListener(ocl); } public void add(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num = ev.getText().toString().trim(); if ("".equals(num)) return; setText(inIntTermsOfAny(currentValue.addTo(parseComplex(num))), ev); v.setVisibility(View.GONE); } }); } public void subtract(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; setText(inIntTermsOfAny(currentValue.subtractTo(parseComplex(num))), ev); v.setVisibility(View.GONE); } }); } public void subtract2(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; setText(inIntTermsOfAny(parseComplex(num).subtractTo(currentValue)), ev); v.setVisibility(View.GONE); } }); } public void multiply(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; setText(inIntTermsOfAny(currentValue.multiplyTo(parseComplex(num))), ev); v.setVisibility(View.GONE); } }); } public void divide(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; Complex n=parseComplex(num); if (n.equals(Complex.ZERO)) setText("Error: Divide by zero."); else setText(inIntTermsOfAny(currentValue.divideTo(n)), ev); v.setVisibility(View.GONE); } }, Complex.ONE); } public void divide2(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; Complex n=parseComplex(num); if (n.equals(Complex.ZERO)) setText("Error: Divide by zero."); else setText(inIntTermsOfAny(n.divideTo(currentValue)), ev); v.setVisibility(View.GONE); } }, Complex.ONE); } public void remainder(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); if (!Complex.round(currentValue).equals(currentValue)) { setText("Error: Parameter is not an integer: "+ev.getText(), ev); return; } doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; v.setVisibility(View.GONE); Complex tmp=parseComplex(num); if (!Complex.round(tmp).equals(tmp)) setText("Error: Parameter is not an integer: "+num, ev); else if (Complex.round(tmp).equals(Complex.ZERO)) setText("Error: Divide by zero."); else setText(inIntTermsOfAny(Complex.round(currentValue).modulo(Complex.round(tmp))), ev); } }, Complex.ONE); } public void remainder2(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); if (!Complex.round(currentValue).equals(currentValue)) { setText("Error: Parameter is not an integer: "+ev.getText(), ev); return; } doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; v.setVisibility(View.GONE); Complex tmp=parseComplex(num); if (!Complex.round(tmp).equals(tmp)) setText("Error: Parameter is not an integer: "+num, ev); else if (Complex.round(currentValue).equals(Complex.ZERO)) setText("Error: Divide by zero."); else setText(inIntTermsOfAny(Complex.round(tmp).modulo(Complex.round(currentValue))), ev); } }, Complex.ONE); } public void e(View v) { setText("e"); } public void pi(View v) { setText("\u03C0"); } public void i(View v) { setText("i"); } public void negate(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.negate(Complex.ONE).multiplyTo(parseComplex(ev.getText().toString()))), ev); } public void sin(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.sin(parseComplex(ev.getText().toString()))), ev); } public void cos(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.cos(parseComplex(ev.getText().toString()))), ev); } public void tan(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.tan(parseComplex(ev.getText().toString()))), ev); } public void arcsin(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.asin(parseComplex(ev.getText().toString()))), ev); } public void arccos(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.acos(parseComplex(ev.getText().toString()))), ev); } public void arctan(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.atan(parseComplex(ev.getText().toString()))), ev); } public void exp(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfE(Complex.exp(parseComplex(ev.getText().toString()))), ev); } public void degrees(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText((Complex.toDegrees(parseComplex(ev.getText().toString()))).toString(), ev); } public void radians(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.toRadians(parseComplex(ev.getText().toString()))), ev); } public void radians2(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); Complex tmp=parseComplex(ev.getText().toString()); tmp=Complex.divide(tmp, new Complex(180)); setText(Complex.toString(tmp)+'\u03C0', ev); } public void ln(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfE(Complex.ln(parseComplex(ev.getText().toString()))), ev); } public void log(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.log10(parseComplex(ev.getText().toString()))), ev); } public void logb(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=parseComplex(ev.getText().toString()); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num = ev.getText().toString(); if ("".equals(num)) return; setText(inIntTermsOfAny(Complex.log(currentValue, parseComplex(num))), ev); v.setVisibility(View.GONE); } }, new Complex(10)); } public void logb2(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=parseComplex(ev.getText().toString()); doCalculate(ev,new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString(); if ("".equals(num)) return; setText(inIntTermsOfAny(Complex.log(parseComplex(num), currentValue)), ev); v.setVisibility(View.GONE); } }, new Complex(10)); } public void round(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(Complex.toString(Complex.round(parseComplex(ev.getText().toString())))); } public void sqrt(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); Complex n=parseComplex(ev.getText().toString()); setText(inIntTermsOfAny(Complex.sqrt(n)), ev); } public void cbrt(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.cbrt(parseComplex(ev.getText().toString()))), ev); } public void ceil(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(Complex.toString(Complex.ceil(parseComplex(ev.getText().toString()))), ev); } public void floor(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(Complex.toString(Complex.floor(parseComplex(ev.getText().toString()))), ev); } public void pow(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=parseComplex(ev.getText().toString()); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num = ev.getText().toString(); if (!"".equals(num)) setText(inIntTermsOfAny(Complex.pow(currentValue, parseComplex(num))), ev); v.setVisibility(View.GONE); } }, currentValue); } public void pow2(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=parseComplex(ev.getText().toString()); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString(); if (!"".equals(num)) setText(inIntTermsOfAny(Complex.pow(parseComplex(num), currentValue)), ev); v.setVisibility(View.GONE); } }, currentValue); } public void abs (View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.abs(parseComplex(ev.getText().toString()))), ev); } public void sinh(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.sinh(parseComplex(ev.getText().toString()))), ev); } public void expm(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Math.expm1(parseDouble(ev.getText().toString()))), ev); } public void cosh(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Math.cosh(parseDouble(ev.getText().toString()))), ev); } public void tanh(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Math.tanh(parseDouble(ev.getText().toString()))), ev); } public void lnp(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Math.log1p(parseDouble(ev.getText().toString()))), ev); } public void square(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); double num=parseDouble(ev.getText().toString()); setText(inIntTermsOfAny(num*num), ev); } public void cube(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); double num=parseDouble(ev.getText().toString()); setText(inIntTermsOfAny(num*num*num), ev); } public void isPrime(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); double num=parseDouble(ev.getText().toString()); int n=(int)Math.floor(num); if (n!=num || n<1 || isDivisible(n,2)) { setText("Not prime"); return; } if (n==1) { setText("Not prime or composite"); return; } for (int i=3; i<=Math.sqrt(n); i+=2) { if (isDivisible(n, i)) { setText("Not prime"); return; } } setText("Prime"); } public boolean isDivisible(int num, int den) { return num%den==0; } public double fastPow(double val, int power) { if (val==2) return fastPow(power).doubleValue(); switch (power) { case 0: return 1; case 1: return val; case 2: return val*val; default: if (power<0) return 1/fastPow(val, -1*power); if (power%2==0) return fastPow(fastPow(val, 2), power>>1); return val*fastPow(val, power-1); } } public BigInteger fastPow(int pow) // 2 as base { return BigInteger.ZERO.flipBit(pow); } public void raise2(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); double num=parseDouble(ev.getText().toString()); if (Math.round(num)==num) // Integer power. Use the fastpow() and a BigInteger. setText(fastPow((int)Math.round(num)).toString(), ev); else setText(Double.toString(Math.pow(2, num)), ev); } }
package com.nordicsemi.nrfUARTv2; import android.util.Log; public class Braille { private final int ASCII_0 = 48; private final int ASCII_9 = 57; private final int ASCII_A = 65; private final int ASCII_Z = 90; private final int ASCII_a = 97; private final int ASCII_z = 122; private final int ASCII_space = 32; private final int ASCII_exclamation = 33; private final int ASCII_doublequote = 34; private final int ASCII_apostrophe = 39; private final int ASCII_openparenthesis = 40; private final int ASCII_closeparenthesis = 41; private final int ASCII_comma = 44; private final int ASCII_hyphen = 45; private final int ASCII_period = 46; private final int ASCII_colon = 58; private final int ASCII_semicolon = 59; private final int ASCII_question = 63; // - 1 , 0 private final static String[] BrailleData_alphabet = { "100000", "101000", "110000", "110100", "100100", "111000", "111100", "101100", "011000", "011100", "100010", "101010", "110010", "110110", "100110", "111010", "111110", "101110", "011010", "011110", "100011", "101011", "011101", "110011", "110111", "100111" }; private final static String BrailleData_capital = "000001"; private final static String[] BrailleData_number = { "011100", "100000", "101000", "110000", "110100", "100100", "111000", "111100", "101100", "011000" }; private final static String BrailleData_numbersign = "010111"; // sign private final static String BrailleData_space = "000000"; private final static String BrailleData_exclamation = "001110"; private final static String BrailleData_opendoublequote = "001011"; private final static String BrailleData_closedoublequote = "000111"; private final static String BrailleData_apostrophe = "000010"; private final static String BrailleData_parenthesis = "001111"; private final static String BrailleData_comma = "001000"; private final static String BrailleData_hyphen = "000011"; private final static String BrailleData_period = "001101"; private final static String BrailleData_colon = "001100"; private final static String BrailleData_semicolon = "001010"; private final static String BrailleData_question = "001011"; String data; Braille(){ data = ""; } Braille(String s) { // constructor makeBraille(s); } String toBraille(String s) { makeBraille(s); return data; } private void makeBraille (String s) { data=""; // initialize int length = s.length(); boolean number_reading = false; boolean doublequote_using = false; boolean singlequote_using = false; for (int i=0; i<length; i++) { int ascii = (int)(s.charAt(i)); Log.d("Braille",Integer.toString(ascii)); if (ascii >= ASCII_A && ascii <= ASCII_Z) { if (number_reading == true) data = data.concat(BrailleData_space); int index = ascii - ASCII_A; Log.d("Braille","index: "+Integer.toString(index)); data = data.concat(BrailleData_capital); data = data.concat(BrailleData_alphabet[index]); number_reading = false; } else if (ascii >= ASCII_a && ascii <= ASCII_z) { if (number_reading == true) data = data.concat(BrailleData_space); int index = ascii - ASCII_a; Log.d("Braille","index: "+Integer.toString(index)); data = data.concat(BrailleData_alphabet[index]); number_reading = false; } else if (ascii >= ASCII_0 && ascii <= ASCII_9) { if (number_reading == false) { number_reading = true; data = data.concat(BrailleData_numbersign); } int index = ascii - ASCII_0; data = data.concat(BrailleData_number[index]); number_reading = true; } else if (ascii==ASCII_space) { data = data.concat(BrailleData_space); number_reading = false; } else if (ascii==ASCII_exclamation) { data = data.concat(BrailleData_exclamation); number_reading = false; } else if (ascii==ASCII_doublequote) { if (doublequote_using) data = data.concat(BrailleData_closedoublequote); else data = data.concat(BrailleData_opendoublequote); doublequote_using = !doublequote_using; number_reading = false; } else if (ascii == ASCII_apostrophe) { data = data.concat(BrailleData_apostrophe); number_reading = false; } else if (ascii == ASCII_openparenthesis || ascii == ASCII_closeparenthesis) { data = data.concat(BrailleData_parenthesis); number_reading = false; } else if (ascii == ASCII_comma) { data = data.concat(BrailleData_comma); number_reading = false; } else if (ascii == ASCII_hyphen) { data = data.concat(BrailleData_hyphen); number_reading = false; } else if (ascii == ASCII_period) { data = data.concat(BrailleData_period); number_reading = false; } else if (ascii == ASCII_colon) { data = data.concat(BrailleData_colon); number_reading = false; } else if (ascii == ASCII_semicolon) { data = data.concat(BrailleData_semicolon); number_reading = false; } else if (ascii == ASCII_question) { data = data.concat(BrailleData_question); number_reading = false; } else { // -> space data = data.concat(BrailleData_space); number_reading = false; } } } public String getString() { // binary string return data; } }
package com.platypii.basemap; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import android.os.AsyncTask; import android.util.Log; import java.util.ArrayList; import java.util.Iterator; import java.util.List; class ASRDatabase { private static ASRDatabaseHelper helper; private static SQLiteDatabase database; private static boolean started = false; private static boolean loading = false; public static synchronized void start(Context appContext) { // Start database if (!started) { helper = new ASRDatabaseHelper(appContext); database = helper.getReadableDatabase(); Log.w("ASRDatabase", "Database started"); started = true; } else { Log.e("ASRDatabase", "Already started"); if (database == null) { database = helper.getReadableDatabase(); } } } /** Return true iff there is data ready to query */ public static boolean isReady() { if(!started) { Log.i("ASRDatabase", "Not ready: database is not started"); return false; } else if(loading) { Log.i("ASRDatabase", "Not ready: database is loading"); return false; } else { // Return true iff there is data ready to query final int rows = getRows(); Log.w("ASRDatabase", "Database ready with " + rows + " rows"); return rows > 0; } } private static int getRows() { // Assumes started and not loading final Cursor cursor = database.rawQuery("SELECT COUNT(id) FROM asr", null); cursor.moveToFirst(); final int rows = cursor.getInt(0); cursor.close(); return rows; } public static void loadDataAsync(final Iterator<ASRRecord> asrIterator) { if (started && !loading) { loading = true; new LoadDataTask(asrIterator).execute(); } else { Log.e("ASRDatabase", "Unexpected load data callback"); } } private static class LoadDataTask extends AsyncTask<Void, Integer, Void> { private final Iterator<ASRRecord> asrIterator; private int totalSize = -1; LoadDataTask(Iterator<ASRRecord> asrIterator) { this.asrIterator = asrIterator; } @Override protected void onPreExecute() { MapsActivity.startProgress("Loading data..."); } @Override protected Void doInBackground(Void... params) { Log.w("ASRDatabase", "Loading database"); // Get row count totalSize = ASRFile.rowCount(); Log.w("ASRDatabase", "Rows: " + totalSize); int count = 0; publishProgress(0); // Write to database database.close(); database = null; final SQLiteDatabase writableDatabase = helper.getWritableDatabase(); writableDatabase.beginTransaction(); writableDatabase.execSQL("DELETE FROM asr"); // Prepared statement final SQLiteStatement insertStatement = writableDatabase.compileStatement("INSERT OR IGNORE INTO asr VALUES (?,?,?,?)"); while (asrIterator.hasNext()) { final ASRRecord record = asrIterator.next(); if (record != null) { // Add to database insertStatement.bindLong(1, record.id); insertStatement.bindDouble(2, record.latitude); insertStatement.bindDouble(3, record.longitude); insertStatement.bindDouble(4, record.height); insertStatement.executeInsert(); // Update progress dialog if (count % 100 == 0) { if (count % 1000 == 0) { Log.i("ASRDatabase", "Populating database row " + count); } publishProgress(count); } count++; } } writableDatabase.setTransactionSuccessful(); writableDatabase.endTransaction(); writableDatabase.close(); database = helper.getReadableDatabase(); loading = false; Log.w("ASRDatabase", "Database loaded from file"); return null; } @Override protected void onProgressUpdate(Integer... progress) { super.onProgressUpdate(progress); MapsActivity.updateProgress("Loading data...", progress[0], totalSize); } @Override protected void onPostExecute(Void result) { MapsActivity.dismissProgress(); ASR.ready(); } } /** * Search for the N tallest towers in view */ public static List<ASRRecord> query(double minLatitude, double maxLatitude, double minLongitude, double maxLongitude, int limit) { if(started && !loading) { final String params[] = {"" + minLatitude, "" + maxLatitude, "" + minLongitude, "" + maxLongitude, "" + limit}; final String longitudeQuery = (minLongitude <= maxLongitude) ? " AND ? < longitude AND longitude < ?" : " AND ? < longitude OR longitude < ?"; final Cursor cursor = database.rawQuery( "SELECT * FROM asr" + " WHERE ? < latitude AND latitude < ?" + longitudeQuery + " ORDER BY height DESC LIMIT ?", params); final ArrayList<ASRRecord> records = new ArrayList<>(); while (cursor.moveToNext()) { final long id = cursor.getLong(0); final double latitude = cursor.getDouble(1); final double longitude = cursor.getDouble(2); final double height = cursor.getDouble(3); final ASRRecord record = new ASRRecord(id, latitude, longitude, height); records.add(record); } cursor.close(); return records; } else if(loading) { Log.w("ASRDatabase", "Query attempted while still loading"); return null; } else { Log.e("ASRDatabase", "Query attempted on uninitialized database"); return null; } } }
package com.samourai.wallet.util; import android.content.Context; import android.util.Log; //import android.util.Log; import com.samourai.wallet.R; import org.apache.commons.io.IOUtils; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import ch.boye.httpclientandroidlib.HttpResponse; import ch.boye.httpclientandroidlib.NameValuePair; import ch.boye.httpclientandroidlib.client.entity.UrlEncodedFormEntity; import ch.boye.httpclientandroidlib.client.methods.HttpGet; import ch.boye.httpclientandroidlib.client.methods.HttpPost; import ch.boye.httpclientandroidlib.message.BasicNameValuePair; import info.guardianproject.netcipher.client.StrongHttpsClient; public class WebUtil { public static final String BLOCKCHAIN_DOMAIN = "https://blockchain.info/"; public static final String BLOCKCHAIN_DOMAIN_TOR = "https://blockchainbdgpzk.onion/"; public static final String SAMOURAI_API = "https://api.samouraiwallet.com/"; public static final String SAMOURAI_API_CHECK = "https://api.samourai.io/v1/status"; public static final String SAMOURAI_API2 = "https://api.samouraiwallet.com/v2/"; public static final String LBC_EXCHANGE_URL = "https://localbitcoins.com/bitcoinaverage/ticker-all-currencies/"; public static final String BTCe_EXCHANGE_URL = "https://btc-e.com/api/3/ticker/"; public static final String BFX_EXCHANGE_URL = "https://api.bitfinex.com/v1/pubticker/btcusd"; public static final String VALIDATE_SSL_URL = SAMOURAI_API; public static final String DYNAMIC_FEE_URL = "https://bitcoinfees.21.co/api/v1/fees/recommended"; public static final String BTCX_FEE_URL = "http://bitcoinexchangerate.org/fees"; public static final String CHAINSO_TX_PREV_OUT_URL = "https://chain.so/api/v2/tx/BTC/"; public static final String CHAINSO_PUSHTX_URL = "https://chain.so/api/v2/send_tx/BTC/"; public static final String CHAINSO_GET_RECEIVE_TX_URL = "https://chain.so/api/v2/get_tx_received/BTC/"; public static final String RECOMMENDED_BIP47_URL = "http://samouraiwallet.com/api/v1/get-pcodes"; public static final String PAYMENTCODE_IO_SEARCH = "https://paymentcode.io/api/v1/search/"; private static final int DefaultRequestRetry = 2; private static final int DefaultRequestTimeout = 60000; private static final String strProxyType = StrongHttpsClient.TYPE_SOCKS; private static final String strProxyIP = "127.0.0.1"; private static final int proxyPort = 9050; /* HTTP Proxy: private static final String strProxyType = StrongHttpsClient.TYPE_HTTP; private static final String strProxyIP = "127.0.0.1"; private static final int strProxyPort = 8118; */ private static WebUtil instance = null; private static Context context = null; private WebUtil() { ; } public static WebUtil getInstance(Context ctx) { context = ctx; if(instance == null) { instance = new WebUtil(); } return instance; } public String postURL(String request, String urlParameters) throws Exception { if(context == null) { return postURL(null, request, urlParameters); } else { Log.i("WebUtil", "Tor enabled status:" + TorUtil.getInstance(context).statusFromBroadcast()); if(TorUtil.getInstance(context).statusFromBroadcast()) { if(urlParameters.startsWith("tx=")) { HashMap<String,String> args = new HashMap<String,String>(); args.put("tx", urlParameters.substring(3)); return tor_postURL(request, args); } else { return tor_postURL(request + urlParameters, null); } } else { return postURL(null, request, urlParameters); } } } public String postURL(String contentType, String request, String urlParameters) throws Exception { String error = null; for (int ii = 0; ii < DefaultRequestRetry; ++ii) { URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try { connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", contentType == null ? "application/x-www-form-urlencoded" : contentType); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"); connection.setUseCaches (false); connection.setConnectTimeout(DefaultRequestTimeout); connection.setReadTimeout(DefaultRequestTimeout); connection.connect(); DataOutputStream wr = new DataOutputStream(connection.getOutputStream ()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); connection.setInstanceFollowRedirects(false); if (connection.getResponseCode() == 200) { // System.out.println("postURL:return code 200"); return IOUtils.toString(connection.getInputStream(), "UTF-8"); } else { error = IOUtils.toString(connection.getErrorStream(), "UTF-8"); // System.out.println("postURL:return code " + error); } Thread.sleep(5000); } finally { connection.disconnect(); } } throw new Exception("Invalid Response " + error); } public String getURL(String URL) throws Exception { if(context == null) { return _getURL(URL); } else { //if(TorUtil.getInstance(context).orbotIsRunning()) { Log.i("WebUtil", "Tor enabled status:" + TorUtil.getInstance(context).statusFromBroadcast()); if(TorUtil.getInstance(context).statusFromBroadcast()) { return tor_getURL(URL); } else { return _getURL(URL); } } } private String _getURL(String URL) throws Exception { URL url = new URL(URL); String error = null; for (int ii = 0; ii < DefaultRequestRetry; ++ii) { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try { connection.setRequestMethod("GET"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"); connection.setConnectTimeout(DefaultRequestTimeout); connection.setReadTimeout(DefaultRequestTimeout); connection.setInstanceFollowRedirects(false); connection.connect(); if (connection.getResponseCode() == 200) return IOUtils.toString(connection.getInputStream(), "UTF-8"); else error = IOUtils.toString(connection.getErrorStream(), "UTF-8"); Thread.sleep(5000); } finally { connection.disconnect(); } } return error; } private String tor_getURL(String URL) throws Exception { if(URL.startsWith(WebUtil.BLOCKCHAIN_DOMAIN)) { URL = WebUtil.BLOCKCHAIN_DOMAIN_TOR + URL.substring(WebUtil.BLOCKCHAIN_DOMAIN.length()); } StrongHttpsClient httpclient = new StrongHttpsClient(context, R.raw.debiancacerts); httpclient.useProxy(true, strProxyType, strProxyIP, proxyPort); HttpGet httpget = new HttpGet(URL); HttpResponse response = httpclient.execute(httpget); StringBuffer sb = new StringBuffer(); sb.append(response.getStatusLine()).append("\n\n"); InputStream is = response.getEntity().getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } httpclient.close(); String result = sb.toString(); // Log.d("WebUtil", "GET result via Tor:" + result); int idx = result.indexOf("{"); if(idx != -1) { return result.substring(idx); } else { return result; } } private String tor_postURL(String URL, HashMap<String,String> args) throws Exception { Log.d("WebUtil", URL); if(URL.startsWith(WebUtil.BLOCKCHAIN_DOMAIN)) { URL = WebUtil.BLOCKCHAIN_DOMAIN_TOR + URL.substring(WebUtil.BLOCKCHAIN_DOMAIN.length()); } StrongHttpsClient httpclient = new StrongHttpsClient(context, R.raw.debiancacerts); httpclient.useProxy(true, strProxyType, strProxyIP, proxyPort); HttpPost httppost = new HttpPost(new URI(URL)); httppost.setHeader("Content-Type", "application/x-www-form-urlencoded"); httppost.setHeader("charset", "utf-8"); httppost.setHeader("Accept", "application/json"); // httppost.setHeader("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); httppost.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"); if(args != null) { List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); for(String key : args.keySet()) { urlParameters.add(new BasicNameValuePair(key, args.get(key))); } httppost.setEntity(new UrlEncodedFormEntity(urlParameters)); } HttpResponse response = httpclient.execute(httppost); StringBuffer sb = new StringBuffer(); sb.append(response.getStatusLine()).append("\n\n"); InputStream is = response.getEntity().getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } httpclient.close(); String result = sb.toString(); // Log.d("WebUtil", "POST result via Tor:" + result); int idx = result.indexOf("{"); if(idx != -1) { return result.substring(idx); } else { return result; } } }
package deadline.statebutton; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.StateListDrawable; import android.support.annotation.ColorInt; import android.support.annotation.FloatRange; import android.support.annotation.IntRange; import android.support.v7.widget.AppCompatButton; import android.util.AttributeSet; /** * @author deadline * @time 2016-11-07 */ public class StateButton extends AppCompatButton{ //text color private int mNormalTextColor = 0; private int mPressedTextColor = 0; private int mUnableTextColor = 0; ColorStateList mTextColorStateList; //animation duration private int mDuration = 0; //radius private float mRadius = 0; private boolean mRound; //stroke private float mStrokeDashWidth = 0; private float mStrokeDashGap = 0; private int mNormalStrokeWidth = 0; private int mPressedStrokeWidth = 0; private int mUnableStrokeWidth = 0; private int mNormalStrokeColor = 0; private int mPressedStrokeColor = 0; private int mUnableStrokeColor = 0; //background color private int mNormalBackgroundColor = 0; private int mPressedBackgroundColor = 0; private int mUnableBackgroundColor = 0; private GradientDrawable mNormalBackground; private GradientDrawable mPressedBackground; private GradientDrawable mUnableBackground; private int[][] states; StateListDrawable mStateBackground; public StateButton(Context context) { this(context, null); } public StateButton(Context context, AttributeSet attrs) { this(context, attrs, android.support.v7.appcompat.R.attr.buttonStyle); } public StateButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setup(attrs); } private void setup(AttributeSet attrs) { states = new int[4][]; Drawable drawable = getBackground(); if(drawable != null && drawable instanceof StateListDrawable){ mStateBackground = (StateListDrawable) drawable; }else{ mStateBackground = new StateListDrawable(); } mNormalBackground = new GradientDrawable(); mPressedBackground = new GradientDrawable(); mUnableBackground = new GradientDrawable(); //pressed, focused, normal, unable states[0] = new int[] { android.R.attr.state_enabled, android.R.attr.state_pressed }; states[1] = new int[] { android.R.attr.state_enabled, android.R.attr.state_focused }; states[3] = new int[] { -android.R.attr.state_enabled}; states[2] = new int[] { android.R.attr.state_enabled }; TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.StateButton); //get original text color as default //set text color mTextColorStateList = getTextColors(); int mDefaultNormalTextColor = mTextColorStateList.getColorForState(states[2], getCurrentTextColor()); int mDefaultPressedTextColor = mTextColorStateList.getColorForState(states[0], getCurrentTextColor()); int mDefaultUnableTextColor = mTextColorStateList.getColorForState(states[3], getCurrentTextColor()); mNormalTextColor = a.getColor(R.styleable.StateButton_normalTextColor, mDefaultNormalTextColor); mPressedTextColor = a.getColor(R.styleable.StateButton_pressedTextColor, mDefaultPressedTextColor); mUnableTextColor = a.getColor(R.styleable.StateButton_unableTextColor, mDefaultUnableTextColor); setTextColor(); //set animation duration mDuration = a.getInteger(R.styleable.StateButton_animationDuration, mDuration); mStateBackground.setEnterFadeDuration(mDuration); mStateBackground.setExitFadeDuration(mDuration); //set background color mNormalBackgroundColor = a.getColor(R.styleable.StateButton_normalBackgroundColor, 0); mPressedBackgroundColor = a.getColor(R.styleable.StateButton_pressedBackgroundColor, 0); mUnableBackgroundColor = a.getColor(R.styleable.StateButton_unableBackgroundColor, 0); mNormalBackground.setColor(mNormalBackgroundColor); mPressedBackground.setColor(mPressedBackgroundColor); mUnableBackground.setColor(mUnableBackgroundColor); //set radius mRadius = a.getDimensionPixelSize(R.styleable.StateButton_radius, 0); mRound = a.getBoolean(R.styleable.StateButton_round, false); mNormalBackground.setCornerRadius(mRadius); mPressedBackground.setCornerRadius(mRadius); mUnableBackground.setCornerRadius(mRadius); //set stroke mStrokeDashWidth = a.getDimensionPixelSize(R.styleable.StateButton_strokeDashWidth, 0); mStrokeDashGap = a.getDimensionPixelSize(R.styleable.StateButton_strokeDashWidth, 0); mNormalStrokeWidth = a.getDimensionPixelSize(R.styleable.StateButton_normalStrokeWidth, 0); mPressedStrokeWidth = a.getDimensionPixelSize(R.styleable.StateButton_pressedStrokeWidth, 0); mUnableStrokeWidth = a.getDimensionPixelSize(R.styleable.StateButton_unableStrokeWidth, 0); mNormalStrokeColor = a.getColor(R.styleable.StateButton_normalStrokeColor, 0); mPressedStrokeColor = a.getColor(R.styleable.StateButton_pressedStrokeColor, 0); mUnableStrokeColor = a.getColor(R.styleable.StateButton_unableStrokeColor, 0); setStroke(); //set background mStateBackground.addState(states[0], mPressedBackground); mStateBackground.addState(states[1], mPressedBackground); mStateBackground.addState(states[3], mUnableBackground); mStateBackground.addState(states[2], mNormalBackground); setBackgroundDrawable(mStateBackground); a.recycle(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { setStateListAnimator(null); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setRound(mRound); } public void setNormalStrokeColor(@ColorInt int normalStrokeColor) { this.mNormalStrokeColor = normalStrokeColor; setStroke(mNormalBackground, mNormalStrokeColor, mNormalStrokeWidth); } public void setPressedStrokeColor(@ColorInt int pressedStrokeColor) { this.mPressedStrokeColor = pressedStrokeColor; setStroke(mPressedBackground, mPressedStrokeColor, mPressedStrokeWidth); } public void setUnableStrokeColor(@ColorInt int unableStrokeColor) { this.mUnableStrokeColor = unableStrokeColor; setStroke(mUnableBackground, mUnableStrokeColor, mUnableStrokeWidth); } public void setStateStrokeColor(@ColorInt int normal, @ColorInt int pressed, @ColorInt int unable){ mNormalStrokeColor = normal; mPressedStrokeColor = pressed; mUnableStrokeColor = unable; setStroke(); } public void setNormalStrokeWidth(int normalStrokeWidth) { this.mNormalStrokeWidth = normalStrokeWidth; setStroke(mNormalBackground, mNormalStrokeColor, mNormalStrokeWidth); } public void setPressedStrokeWidth(int pressedStrokeWidth) { this.mPressedStrokeWidth = pressedStrokeWidth; setStroke(mPressedBackground, mPressedStrokeColor, mPressedStrokeWidth); } public void setUnableStrokeWidth(int unableStrokeWidth) { this.mUnableStrokeWidth = unableStrokeWidth; setStroke(mUnableBackground, mUnableStrokeColor, mUnableStrokeWidth); } public void setStateStrokeWidth(int normal, int pressed, int unable){ mNormalStrokeWidth = normal; mPressedStrokeWidth = pressed; mUnableStrokeWidth= unable; setStroke(); } public void setStrokeDash(float strokeDashWidth, float strokeDashGap) { this.mStrokeDashWidth = strokeDashWidth; this.mStrokeDashGap = strokeDashWidth; setStroke(); } private void setStroke(){ setStroke(mNormalBackground, mNormalStrokeColor, mNormalStrokeWidth); setStroke(mPressedBackground, mPressedStrokeColor, mPressedStrokeWidth); setStroke(mUnableBackground, mUnableStrokeColor, mUnableStrokeWidth); } private void setStroke(GradientDrawable mBackground, int mStrokeColor, int mStrokeWidth) { mBackground.setStroke(mStrokeWidth, mStrokeColor, mStrokeDashWidth, mStrokeDashGap); } public void setRadius(@FloatRange(from = 0) float radius) { this.mRadius = radius; mNormalBackground.setCornerRadius(mRadius); mPressedBackground.setCornerRadius(mRadius); mUnableBackground.setCornerRadius(mRadius); } public void setRound(boolean round){ this.mRound = round; int height = getMeasuredHeight(); if(mRound){ setRadius(height / 2f); } } public void setRadius(float[] radii){ mNormalBackground.setCornerRadii(radii); mPressedBackground.setCornerRadii(radii); mUnableBackground.setCornerRadii(radii); } public void setStateBackgroundColor(@ColorInt int normal, @ColorInt int pressed, @ColorInt int unable){ mNormalBackgroundColor = normal; mPressedBackgroundColor = pressed; mUnableBackgroundColor = unable; mNormalBackground.setColor(mNormalBackgroundColor); mPressedBackground.setColor(mPressedBackgroundColor); mUnableBackground.setColor(mUnableBackgroundColor); } public void setNormalBackgroundColor(@ColorInt int normalBackgroundColor) { this.mNormalBackgroundColor = normalBackgroundColor; mNormalBackground.setColor(mNormalBackgroundColor); } public void setPressedBackgroundColor(@ColorInt int pressedBackgroundColor) { this.mPressedBackgroundColor = pressedBackgroundColor; mPressedBackground.setColor(mPressedBackgroundColor); } public void setUnableBackgroundColor(@ColorInt int unableBackgroundColor) { this.mUnableBackgroundColor = unableBackgroundColor; mUnableBackground.setColor(mUnableBackgroundColor); } public void setAnimationDuration(@IntRange(from = 0)int duration){ this.mDuration = duration; mStateBackground.setEnterFadeDuration(mDuration); } private void setTextColor() { int[] colors = new int[] {mPressedTextColor, mPressedTextColor, mNormalTextColor, mUnableTextColor}; mTextColorStateList = new ColorStateList(states, colors); setTextColor(mTextColorStateList); } public void setStateTextColor(@ColorInt int normal, @ColorInt int pressed, @ColorInt int unable){ this.mNormalTextColor = normal; this.mPressedTextColor = pressed; this.mUnableTextColor = unable; setTextColor(); } public void setNormalTextColor(@ColorInt int normalTextColor) { this.mNormalTextColor = normalTextColor; setTextColor(); } public void setPressedTextColor(@ColorInt int pressedTextColor) { this.mPressedTextColor = pressedTextColor; setTextColor(); } public void setUnableTextColor(@ColorInt int unableTextColor) { this.mUnableTextColor = unableTextColor; setTextColor(); } }
package edu.deanza.calendar.models; import org.joda.time.LocalTime; public class Event { protected String name, description, location; protected LocalTime startTime, endTime; // TODO: add `categories` field Event(String name, String description, String location, String startTime, String endTime) { this.name = name; this.description = description; this.location = location; this.startTime = LocalTime.parse(startTime); this.endTime = LocalTime.parse(endTime); } }
package org.stepic.droid.util; import android.os.Build; import android.support.annotation.ColorInt; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.stepic.droid.configuration.Config; import org.stepic.droid.notifications.model.Notification; import java.util.ArrayList; import java.util.List; import java.util.Locale; import kotlin.collections.CollectionsKt; import timber.log.Timber; public class HtmlHelper { /** * Trims trailing whitespace. Removes any of these characters: * 0009, HORIZONTAL TABULATION * 000A, LINE FEED * 000B, VERTICAL TABULATION * 000C, FORM FEED * 000D, CARRIAGE RETURN * 001C, FILE SEPARATOR * 001D, GROUP SEPARATOR * 001E, RECORD SEPARATOR * 001F, UNIT SEPARATOR * * @return "" if source is null, otherwise string with all trailing whitespace removed */ public static CharSequence trimTrailingWhitespace(CharSequence source) { if (source == null) return ""; int i = source.length(); // loop back to the first non-whitespace character while (--i >= 0 && Character.isWhitespace(source.charAt(i))) { } return source.subSequence(0, i + 1); } public static boolean isForWebView(@NotNull String text) { //FIXME REMOVE <img>??? and make ImageGetter with simple textview //TODO: REGEXP IS SLOWER return text.contains("$") || text.contains("wysiwyg-") || text.contains("<h") || text.contains("\\[") || text.contains("<pre><code") || text.contains("kotlin-runnable") || text.contains("<img") || text.contains("<iframe") || text.contains("<audio"); } public static boolean hasLaTeX(String textString) { return textString.contains("$") || textString.contains("\\["); } private static boolean hasKotlinRunnableSample(String text) { return text.contains("kotlin-runnable"); } /** * get meta value * * @param htmlText with meta tags * @param metaKey meta key of 'name' attribute in meta tag * @return value of 'content' attribute in tag meta with 'name' == metaKey */ @Nullable public static String getValueOfMetaOrNull(String htmlText, String metaKey) { Document document = Jsoup.parse(htmlText); Elements elements = document.select("meta"); try { return elements.attr("name", metaKey).last().attr("content"); //WTF? first is csrf param, but jsoup can't handle } catch (Exception ex) { return ""; } } @Nullable public static Long parseCourseIdFromNotification(@NotNull Notification notification) { String htmlRaw = notification.getHtmlText(); if (htmlRaw == null) return null; return parseCourseIdFromNotification(htmlRaw); } @Nullable public static Long parseIdFromSlug(String slug) { Long id = null; try { id = Long.parseLong(slug); } catch (NumberFormatException ignored) { //often it is not number then it is "Some-Name-idNum" or just "-idNum" } if (id != null) { //if, for example, -432 -> 432 return Math.abs(id); } int indexOfLastDash = slug.lastIndexOf("-"); if (indexOfLastDash < 0) return null; try { String number = slug.substring(indexOfLastDash + 1, slug.length()); id = Long.parseLong(number); } catch (NumberFormatException | IndexOutOfBoundsException ignored) { } return id; } private final static String syllabusModulePrefix = "syllabus?module="; public static Integer parseModulePositionFromNotification(String htmlRaw) { int indexOfStart = htmlRaw.indexOf(syllabusModulePrefix); if (indexOfStart < 0) return null; String begin = htmlRaw.substring(indexOfStart + syllabusModulePrefix.length()); int end = begin.indexOf("\""); String substring = begin.substring(0, end); try { return Integer.parseInt(substring); } catch (Exception exception) { return null; } } private static Long parseCourseIdFromNotification(String htmlRaw) { int start = htmlRaw.indexOf('<'); int end = htmlRaw.indexOf('>'); if (start == -1 || end == -1) return null; String substring = htmlRaw.substring(start, end); String[] resultOfSplit = substring.split("-"); if (resultOfSplit.length > 0) { String numb = resultOfSplit[resultOfSplit.length - 1]; StringBuilder n = new StringBuilder(); for (int i = 0; i < numb.length(); i++) { if (Character.isDigit(numb.charAt(i))) { n.append(numb.charAt(i)); } } if (n.length() > 0) return Long.parseLong(n.toString()); return null; } return null; } private static String getStyle(@Nullable String fontPath, @ColorInt int textColorHighlight) { final String fontStyle; if (fontPath == null) { fontStyle = DefaultFontStyle; } else { fontStyle = String.format(Locale.getDefault(), CustomFontStyle, fontPath); } final String selectionColorStyle = String.format(Locale.getDefault(), SelectionColorStyle, 0xFFFFFF & textColorHighlight); return fontStyle + selectionColorStyle; } private static String buildPage(CharSequence body, List<String> additionalScripts, String fontPath, @ColorInt int textColorHighlight, int widthPx, String baseUrl) { if (hasKotlinRunnableSample(body.toString())) { additionalScripts.add(KotlinRunnableSamplesScript); } String scripts = CollectionsKt.joinToString(additionalScripts, "", "", "", -1, "", null); String preBody = String.format(Locale.getDefault(), PRE_BODY, scripts, getStyle(fontPath, textColorHighlight), widthPx, baseUrl); return preBody + body + POST_BODY; } public static String buildMathPage(CharSequence body, @ColorInt int textColorHighlight, int widthPx, String baseUrl) { return buildPage(body, CollectionsKt.arrayListOf(MathJaxScript), null, textColorHighlight, widthPx, baseUrl); } public static String buildPageWithAdjustingTextAndImage(CharSequence body, @ColorInt int textColorHighlight, int widthPx, String baseUrl) { return buildPage(body, new ArrayList<String>(), null, textColorHighlight, widthPx, baseUrl); } public static String buildPageWithCustomFont(CharSequence body, String fontPath, @ColorInt int textColorHighlight, int widthPx, String baseUrl) { return buildPage(body, new ArrayList<String>(), fontPath, textColorHighlight, widthPx, baseUrl); } public static final String HORIZONTAL_SCROLL_LISTENER = "scrollListener"; private static final String HORIZONTAL_SCROLL_STYLE; // this block is needed to force render of WebView private static final String MIN_RENDERED_BLOCK = "<div style=\"height: 1px; overflow: hidden; width: 1px; background-color: rgba(0,0,0,0.001); pointer-events: none; user-select: none; -webkit-user-select: none;\"></div>"; static { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { HORIZONTAL_SCROLL_STYLE = "<style>\n" + "body > * {\n" + " max-width: 100%%;\n" + " overflow-x: scroll;\n" + " vertical-align: middle;\n" + "}\n" + "</style>\n"; } else { HORIZONTAL_SCROLL_STYLE = ""; } if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { POST_BODY = MIN_RENDERED_BLOCK + "</body>\n" + "</html>"; } else { POST_BODY = "</body>\n" + "</html>"; } } private static final String KotlinRunnableSamplesScript = "<script src=\"https://unpkg.com/kotlin-playground@1\" data-selector=\"kotlin-runnable\"></script>"; private static final String KOTLIN_PLAYGROUND_SCROLL_RULE = "elem.className !== 'CodeMirror-scroll' && elem.className !== 'code-output'"; private static final String DEFAULT_SCROLL_RULE = "elem.parentElement.tagName !== 'BODY' && elem.parentElement.tagName !== 'HTML'"; private static final String HORIZONTAL_SCROLL_SCRIPT = "<script type=\"text/javascript\">\n" + "function measureScroll(x, y) {" + "var elem = document.elementFromPoint(x, y);" + "while(" + DEFAULT_SCROLL_RULE + " && " + KOTLIN_PLAYGROUND_SCROLL_RULE + ") {" + "elem = elem.parentElement;" + "}" + HORIZONTAL_SCROLL_LISTENER + ".onScroll(elem.offsetWidth, elem.scrollWidth, elem.scrollLeft);" + "}" + "</script>\n"; //string with 2 format args private static final String PRE_BODY = "<html>\n" + "<head>\n" + "<title>Step</title>\n" + "%s" + "%s" + "<meta name=\"viewport\" content=\"width=" + "%d" + ", user-scalable=no" + ", target-densitydpi=medium-dpi" + "\" />" + "<link rel=\"stylesheet\" type=\"text/css\" href=\"wysiwyg.css\"/>" + HORIZONTAL_SCROLL_SCRIPT + HORIZONTAL_SCROLL_STYLE + "<base href=\"%s\">" + "</head>\n" + "<body style='margin:0;padding:0;'>"; private static final String SelectionColorStyle = "<style>\n" + "::selection { background: #%06X; }\n" + "</style>"; private static final String DefaultFontStyle = "<style>\n" + "\nhtml{-webkit-text-size-adjust: 100%%;}" + "\nbody{font-size: 12pt; font-family:Arial, Helvetica, sans-serif; line-height:1.6em;}" + "\nh1{font-size: 20pt; font-family:Arial, Helvetica, sans-serif; line-height:1.6em;text-align: center;}" + "\nh2{font-size: 17pt; font-family:Arial, Helvetica, sans-serif; line-height:1.6em;text-align: center;}" + "\nh3{font-size: 14pt; font-family:Arial, Helvetica, sans-serif; line-height:1.6em;text-align: center;}" + "\nimg { max-width: 100%%; }" + "</style>\n"; private static final String CustomFontStyle = "<style>\n" + "@font-face {" + " font-family: 'Roboto';\n" + " src: url(\"%s\")\n" + "}" + "\nhtml{-webkit-text-size-adjust: 100%%;}" + "\nbody{font-size: 14px; font-family:'Roboto', Helvetica, sans-serif; line-height:1.6em;}" + "\nh1{font-size: 22px; font-family:'Roboto', Helvetica, sans-serif; line-height:1.6em;text-align: center;}" + "\nh2{font-size: 19px; font-family:'Roboto', Helvetica, sans-serif; line-height:1.6em;text-align: center;}" + "\nh3{font-size: 16px; font-family:'Roboto', Helvetica, sans-serif; line-height:1.6em;text-align: center;}" + "\nimg { max-width: 100%%; }" + "</style>\n"; private static final String POST_BODY; private static final String MathJaxScript = "<script type=\"text/x-mathjax-config\">\n" + " MathJax.Hub.Config({" + "showMathMenu: false, " + "messageStyle: \"none\", " + "TeX: {extensions: [ \"color.js\"]}, " + "tex2jax: {preview: \"none\", inlineMath: [['$','$'], ['\\\\(','\\\\)']]}});\n" + "displayMath: [ ['$$','$$'], ['\\[','\\]'] ]" + "</script>\n" + "<script type=\"text/javascript\"\n" + " src=\"file:///android_asset/MathJax/MathJax.js?config=TeX-AMS_HTML\">\n" + "</script>\n"; public static String getUserPath(Config config, int userId) { return new StringBuilder() .append(config.getBaseUrl()) .append(AppConstants.WEB_URI_SEPARATOR) .append("users") .append(AppConstants.WEB_URI_SEPARATOR) .append(userId) .append("/?from_mobile_app=true") .toString(); } @Nullable public static String parseNLinkInText(@NotNull String htmlText, String baseUrl, int position) { try { Document document = Jsoup.parse(htmlText); document.setBaseUri(baseUrl); Elements elements = document.getElementsByTag("a"); Element our = elements.get(position); String absolute = our.absUrl("href"); Timber.d(absolute); return absolute; } catch (Exception exception) { return null; } } }
package org.stepic.droid.util; import android.text.Html; import android.text.Spanned; import net.htmlparser.jericho.Element; import net.htmlparser.jericho.Source; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.stepic.droid.notifications.model.Notification; import java.util.List; public class HtmlHelper { @NotNull public static Spanned fromHtml(@Nullable String content) { if (content == null) return Html.fromHtml(""); return Html.fromHtml(content); } /** * get meta value * * @param htmlText with meta tags * @param metaKey meta key of 'name' attribute in meta tag * @return value of 'content' attribute in tag meta with 'name' == metaKey */ @Nullable public static String getValueOfMetaOrNull(String htmlText, String metaKey) { Source source = new Source(htmlText); String strData = ""; List<Element> elements = source.getAllElements("meta"); for (Element element : elements) { final String id = element.getAttributeValue("name"); // Get Attribute 'id' if (id != null && id.equals(metaKey)) { strData = element.getAttributeValue("content"); } } return strData; } @Nullable public static Long parseCourseIdFromNotification(@NotNull Notification notification) { String htmlRaw = notification.getHtmlText(); if (htmlRaw == null) return null; return parseCourseIdFromNotification(htmlRaw); } private static Long parseCourseIdFromNotification(String htmlRaw) { int start = htmlRaw.indexOf('<'); int end = htmlRaw.indexOf('>'); if (start == -1 || end == -1) return null; String substring = htmlRaw.substring(start, end); String[] resultOfSplit = substring.split("-"); if (resultOfSplit.length > 0) { String numb = resultOfSplit[resultOfSplit.length - 1]; StringBuilder n = new StringBuilder(); for (int i = 0; i < numb.length(); i++) { if (Character.isDigit(numb.charAt(i))) { n.append(numb.charAt(i)); } } if (n.length() > 0) return Long.parseLong(n.toString()); return null; } return null; } public static String buildMathPage(CharSequence body, int widthPx) { String preBody = String.format(PRE_BODY, MathJaxScript, widthPx); String result = preBody + body + POST_BODY; return result; } public static String buildPageWithAdjustingTextAndImage(CharSequence body, int widthPx) { String preBody = String.format(PRE_BODY, " ", widthPx); String result = preBody + body + POST_BODY; return result; } //string with 2 format args public static final String PRE_BODY = "<html>\n" + "<head>\n" + "<title>Step</title>\n" + "%s" + "<style>\n" + "\nhtml{-webkit-text-size-adjust: 100%%;}" + "\nbody{font-size: 12pt; font-family:Arial, Helvetica, sans-serif; line-height:1.6em;}" + "\nh1{font-size: 20pt; font-family:Arial, Helvetica, sans-serif; line-height:1.6em;}" + "\nh2{font-size: 17pt; font-family:Arial, Helvetica, sans-serif; line-height:1.6em;}" + "\nh3{font-size: 14pt; font-family:Arial, Helvetica, sans-serif; line-height:1.6em;}" + "\nimg { max-width: 100%%; }" + "<meta name=\"viewport\" content=\"width=" + "%d" + ", user-scalable=no\" />" + "</style>\n" + "</head>\n" + "<body>"; public static final String POST_BODY = "</body>\n" + "</html>"; public static final String MathJaxScript = "<script type=\"text/x-mathjax-config\">\n" + " MathJax.Hub.Config({" + "messageStyle: \"none\", " + "tex2jax: {preview: \"none\", inlineMath: [['$','$'], ['\\\\(','\\\\)']]}});\n" + "</script>\n" + "<script type=\"text/javascript\"\n" + " src=\"file:///android_asset/MathJax/MathJax.js?config=TeX-AMS-MML_HTMLorMML-full\">\n" + "</script>\n"; }
package org.safehaus.kiskis.mgmt.server.ui.modules.oozie.management; import org.safehaus.kiskis.mgmt.api.taskrunner.Task; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.data.util.IndexedContainer; import com.vaadin.ui.Button; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Table; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.ServiceReference; import org.safehaus.kiskis.mgmt.shared.protocol.*; import org.safehaus.kiskis.mgmt.api.agentmanager.AgentManager; import org.safehaus.kiskis.mgmt.server.ui.modules.oozie.OozieConfig; import org.safehaus.kiskis.mgmt.server.ui.modules.oozie.wizard.exec.ServiceManager; public class NodesWindow extends Window { private final Table table; private IndexedContainer container; ServiceManager serviceManager; OozieConfig config; OozieCommandEnum cce; Item selectedItem; public NodesWindow(OozieConfig config, ServiceManager manager) { this.config = config; this.serviceManager = manager; setCaption("Cluster: " + config.getUuid()); setSizeUndefined(); setWidth("800px"); setHeight("500px"); setModal(true); center(); VerticalLayout verticalLayout = new VerticalLayout(); HorizontalLayout buttons = new HorizontalLayout(); table = new Table("", getCassandraContainer()); table.setSizeFull(); table.setPageLength(6); table.setImmediate(true); verticalLayout.addComponent(buttons); verticalLayout.addComponent(table); addComponent(verticalLayout); } @Override public void addListener(CloseListener listener) { getWindow().getParent().removeWindow(this); } private IndexedContainer getCassandraContainer() { container = new IndexedContainer(); container.addContainerProperty("Hostname", String.class, ""); container.addContainerProperty("Type", String.class, ""); container.addContainerProperty("Start", Button.class, ""); container.addContainerProperty("Stop", Button.class, ""); container.addContainerProperty("Status", Button.class, ""); // container.addContainerProperty("Destroy", Button.class, ""); addOrderToContainer(container, config.getServer(), "Server"); for (Agent agent : config.getClients()) { addOrderToContainer(container, agent, "Client"); } return container; } private void addOrderToContainer(Container container, final Agent agent, String type) { Object itemId = container.addItem(); final Item item = container.getItem(itemId); item.getItemProperty("Hostname").setValue(agent.getHostname()); item.getItemProperty("Type").setValue(type); if (type.equals("Server")) { Button startButton = new Button("Start"); startButton.addListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { getWindow().showNotification("Starting instance: " + agent.getHostname()); cce = OozieCommandEnum.START_SERVER; selectedItem = item; // table.setEnabled(false); serviceManager.runCommand(agent, cce); } }); Button stopButton = new Button("Stop"); stopButton.addListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { getWindow().showNotification("Stopping instance: " + agent.getHostname()); cce = OozieCommandEnum.STOP_SERVER; selectedItem = item; // table.setEnabled(false); serviceManager.runCommand(agent, cce); } }); Button statusButton = new Button("Status"); statusButton.addListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { getWindow().showNotification("Checking the status: " + agent.getHostname()); cce = OozieCommandEnum.STATUS; selectedItem = item; // table.setEnabled(false); serviceManager.runCommand(agent, cce); } }); item.getItemProperty("Start").setValue(startButton); item.getItemProperty("Stop").setValue(stopButton); item.getItemProperty("Status").setValue(statusButton); } // item.getItemProperty("Destroy").setValue(destroyButton); } public static AgentManager getAgentManager() { // get bundle instance via the OSGi Framework Util class BundleContext ctx = FrameworkUtil.getBundle(NodesWindow.class).getBundleContext(); if (ctx != null) { ServiceReference serviceReference = ctx.getServiceReference(AgentManager.class.getName()); if (serviceReference != null) { return AgentManager.class.cast(ctx.getService(serviceReference)); } } return null; } public void updateUI(Task task, String stdOut, String stdErr) { if (cce != null) { switch (cce) { case START_SERVER: { // Emin needs to fix agent EXECUTE_RESPONSE_DONE error of locked thread switchState(false); getWindow().showNotification("Start success."); // switch (task.getTaskStatus()) { // case SUCCESS: { // switchState(false); // getWindow().showNotification("Start success."); // break; // case FAIL: { // getWindow().showNotification("Start failed."); // break; break; } case STOP_SERVER: { switchState(true); getWindow().showNotification("Stop success."); // switch (task.getTaskStatus()) { // case SUCCESS: { // switchState(true); // getWindow().showNotification("Stop success."); // break; // case FAIL: { // getWindow().showNotification("Stop failed."); // break; break; } case STATUS: { if (stdOut.contains("Oozie Server is running")) { getWindow().showNotification("Oozie Server is running"); switchState(false); } /* else { getWindow().showNotification(" Oozie Server is not running"); switchState(true); } */ // switch (task.getTaskStatus()) { // case SUCCESS: { // if (stdOut.contains("Oozie Server is running")) { // getWindow().showNotification("Oozie Server is running"); // switchState(false); // break; // case FAIL: { // getWindow().showNotification(" Oozie Server is not running"); // switchState(true); // break; break; } } } // table.setEnabled(true); } private void switchState(Boolean state) { Button start = (Button) selectedItem.getItemProperty("Start").getValue(); start.setEnabled(state); Button stop = (Button) selectedItem.getItemProperty("Stop").getValue(); stop.setEnabled(!state); } }
package org.opendaylight.controller.sal.rest.doc.impl; import static org.opendaylight.controller.sal.rest.doc.util.RestDocgenUtil.resolvePathArgumentsName; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule; import com.google.common.base.Preconditions; import java.io.IOException; import java.net.URI; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.ws.rs.core.UriInfo; import org.json.JSONException; import org.json.JSONObject; import org.opendaylight.controller.sal.rest.doc.model.builder.OperationBuilder; import org.opendaylight.controller.sal.rest.doc.swagger.Api; import org.opendaylight.controller.sal.rest.doc.swagger.ApiDeclaration; import org.opendaylight.controller.sal.rest.doc.swagger.Operation; import org.opendaylight.controller.sal.rest.doc.swagger.Parameter; import org.opendaylight.controller.sal.rest.doc.swagger.Resource; import org.opendaylight.controller.sal.rest.doc.swagger.ResourceList; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; import org.opendaylight.yangtools.yang.model.api.Module; import org.opendaylight.yangtools.yang.model.api.RpcDefinition; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BaseYangSwaggerGenerator { private static Logger _logger = LoggerFactory.getLogger(BaseYangSwaggerGenerator.class); protected static final String API_VERSION = "1.0.0"; protected static final String SWAGGER_VERSION = "1.2"; protected static final String RESTCONF_CONTEXT_ROOT = "restconf"; static final String MODULE_NAME_SUFFIX = "_module"; protected final DateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); private final ModelGenerator jsonConverter = new ModelGenerator(); // private Map<String, ApiDeclaration> MODULE_DOC_CACHE = new HashMap<>() private final ObjectMapper mapper = new ObjectMapper(); protected BaseYangSwaggerGenerator() { mapper.registerModule(new JsonOrgModule()); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); } /** * * @param uriInfo * @param operType * @return list of modules converted to swagger compliant resource list. */ public ResourceList getResourceListing(UriInfo uriInfo, SchemaContext schemaContext, String context) { ResourceList resourceList = createResourceList(); Set<Module> modules = getSortedModules(schemaContext); List<Resource> resources = new ArrayList<>(modules.size()); _logger.info("Modules found [{}]", modules.size()); for (Module module : modules) { String revisionString = SIMPLE_DATE_FORMAT.format(module.getRevision()); Resource resource = new Resource(); _logger.debug("Working on [{},{}]...", module.getName(), revisionString); ApiDeclaration doc = getApiDeclaration(module.getName(), revisionString, uriInfo, schemaContext, context); if (doc != null) { resource.setPath(generatePath(uriInfo, module.getName(), revisionString)); resources.add(resource); } else { _logger.debug("Could not generate doc for {},{}", module.getName(), revisionString); } } resourceList.setApis(resources); return resourceList; } protected ResourceList createResourceList() { ResourceList resourceList = new ResourceList(); resourceList.setApiVersion(API_VERSION); resourceList.setSwaggerVersion(SWAGGER_VERSION); return resourceList; } protected String generatePath(UriInfo uriInfo, String name, String revision) { URI uri = uriInfo.getRequestUriBuilder().path(generateCacheKey(name, revision)).build(); return uri.toASCIIString(); } public ApiDeclaration getApiDeclaration(String module, String revision, UriInfo uriInfo, SchemaContext schemaContext, String context) { Date rev = null; try { rev = SIMPLE_DATE_FORMAT.parse(revision); } catch (ParseException e) { throw new IllegalArgumentException(e); } Module m = schemaContext.findModuleByName(module, rev); Preconditions.checkArgument(m != null, "Could not find module by name,revision: " + module + "," + revision); return getApiDeclaration(m, rev, uriInfo, context, schemaContext); } public ApiDeclaration getApiDeclaration(Module module, Date revision, UriInfo uriInfo, String context, SchemaContext schemaContext) { String basePath = createBasePathFromUriInfo(uriInfo); ApiDeclaration doc = getSwaggerDocSpec(module, basePath, context, schemaContext); if (doc != null) { return doc; } return null; } protected String createBasePathFromUriInfo(UriInfo uriInfo) { String portPart = ""; int port = uriInfo.getBaseUri().getPort(); if (port != -1) { portPart = ":" + port; } String basePath = new StringBuilder(uriInfo.getBaseUri().getScheme()).append(": .append(uriInfo.getBaseUri().getHost()).append(portPart).append("/").append(RESTCONF_CONTEXT_ROOT) .toString(); return basePath; } public ApiDeclaration getSwaggerDocSpec(Module m, String basePath, String context, SchemaContext schemaContext) { ApiDeclaration doc = createApiDeclaration(basePath); List<Api> apis = new ArrayList<Api>(); Collection<DataSchemaNode> dataSchemaNodes = m.getChildNodes(); _logger.debug("child nodes size [{}]", dataSchemaNodes.size()); for (DataSchemaNode node : dataSchemaNodes) { if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) { _logger.debug("Is Configuration node [{}] [{}]", node.isConfiguration(), node.getQName().getLocalName()); List<Parameter> pathParams = new ArrayList<Parameter>(); String resourcePath = getDataStorePath("/config/", context); addRootPostLink(m, (DataNodeContainer) node, pathParams, resourcePath, apis); addApis(node, apis, resourcePath, pathParams, schemaContext, true); pathParams = new ArrayList<Parameter>(); resourcePath = getDataStorePath("/operational/", context); addApis(node, apis, resourcePath, pathParams, schemaContext, false); } } Set<RpcDefinition> rpcs = m.getRpcs(); for (RpcDefinition rpcDefinition : rpcs) { String resourcePath = getDataStorePath("/operations/", context); addRpcs(rpcDefinition, apis, resourcePath, schemaContext); } _logger.debug("Number of APIs found [{}]", apis.size()); if (!apis.isEmpty()) { doc.setApis(apis); JSONObject models = null; try { models = jsonConverter.convertToJsonSchema(m, schemaContext); doc.setModels(models); if (_logger.isDebugEnabled()) { _logger.debug(mapper.writeValueAsString(doc)); } } catch (IOException | JSONException e) { e.printStackTrace(); } return doc; } return null; } private void addRootPostLink(final Module m, final DataNodeContainer node, final List<Parameter> pathParams, final String resourcePath, final List<Api> apis) { if (containsListOrContainer(m.getChildNodes())) { final Api apiForRootPostUri = new Api(); apiForRootPostUri.setPath(resourcePath); apiForRootPostUri.setOperations(operationPost(m.getName()+MODULE_NAME_SUFFIX, m.getDescription(), m, pathParams, true)); apis.add(apiForRootPostUri); } } protected ApiDeclaration createApiDeclaration(String basePath) { ApiDeclaration doc = new ApiDeclaration(); doc.setApiVersion(API_VERSION); doc.setSwaggerVersion(SWAGGER_VERSION); doc.setBasePath(basePath); doc.setProduces(Arrays.asList("application/json", "application/xml")); return doc; } protected String getDataStorePath(String dataStore, String context) { return dataStore + context; } private String generateCacheKey(Module m) { return generateCacheKey(m.getName(), SIMPLE_DATE_FORMAT.format(m.getRevision())); } private String generateCacheKey(String module, String revision) { return module + "(" + revision + ")"; } private void addApis(DataSchemaNode node, List<Api> apis, String parentPath, List<Parameter> parentPathParams, SchemaContext schemaContext, boolean addConfigApi) { Api api = new Api(); List<Parameter> pathParams = new ArrayList<Parameter>(parentPathParams); String resourcePath = parentPath + createPath(node, pathParams, schemaContext) + "/"; _logger.debug("Adding path: [{}]", resourcePath); api.setPath(resourcePath); Iterable<DataSchemaNode> childSchemaNodes = Collections.<DataSchemaNode> emptySet(); if ((node instanceof ListSchemaNode) || (node instanceof ContainerSchemaNode)) { DataNodeContainer dataNodeContainer = (DataNodeContainer) node; childSchemaNodes = dataNodeContainer.getChildNodes(); } api.setOperations(operation(node, pathParams, addConfigApi, childSchemaNodes)); apis.add(api); for (DataSchemaNode childNode : childSchemaNodes) { if (childNode instanceof ListSchemaNode || childNode instanceof ContainerSchemaNode) { // keep config and operation attributes separate. if (childNode.isConfiguration() == addConfigApi) { addApis(childNode, apis, resourcePath, pathParams, schemaContext, addConfigApi); } } } } private boolean containsListOrContainer(final Iterable<DataSchemaNode> nodes) { for (DataSchemaNode child : nodes) { if (child instanceof ListSchemaNode || child instanceof ContainerSchemaNode) { return true; } } return false; } /** * @param node * @param pathParams * @return */ private List<Operation> operation(DataSchemaNode node, List<Parameter> pathParams, boolean isConfig, Iterable<DataSchemaNode> childSchemaNodes) { List<Operation> operations = new ArrayList<>(); OperationBuilder.Get getBuilder = new OperationBuilder.Get(node, isConfig); operations.add(getBuilder.pathParams(pathParams).build()); if (isConfig) { OperationBuilder.Put putBuilder = new OperationBuilder.Put(node.getQName().getLocalName(), node.getDescription()); operations.add(putBuilder.pathParams(pathParams).build()); OperationBuilder.Delete deleteBuilder = new OperationBuilder.Delete(node); operations.add(deleteBuilder.pathParams(pathParams).build()); if (containsListOrContainer(childSchemaNodes)) { operations.addAll(operationPost(node.getQName().getLocalName(), node.getDescription(), (DataNodeContainer) node, pathParams, isConfig)); } } return operations; } /** * @param node * @param pathParams * @return */ private List<Operation> operationPost(final String name, final String description, final DataNodeContainer dataNodeContainer, List<Parameter> pathParams, boolean isConfig) { List<Operation> operations = new ArrayList<>(); if (isConfig) { OperationBuilder.Post postBuilder = new OperationBuilder.Post(name, description, dataNodeContainer); operations.add(postBuilder.pathParams(pathParams).build()); } return operations; } private String createPath(final DataSchemaNode schemaNode, List<Parameter> pathParams, SchemaContext schemaContext) { ArrayList<LeafSchemaNode> pathListParams = new ArrayList<LeafSchemaNode>(); StringBuilder path = new StringBuilder(); String localName = resolvePathArgumentsName(schemaNode, schemaContext); path.append(localName); if ((schemaNode instanceof ListSchemaNode)) { final List<QName> listKeys = ((ListSchemaNode) schemaNode).getKeyDefinition(); for (final QName listKey : listKeys) { DataSchemaNode _dataChildByName = ((DataNodeContainer) schemaNode).getDataChildByName(listKey); pathListParams.add(((LeafSchemaNode) _dataChildByName)); String pathParamIdentifier = new StringBuilder("/{").append(listKey.getLocalName()).append("}") .toString(); path.append(pathParamIdentifier); Parameter pathParam = new Parameter(); pathParam.setName(listKey.getLocalName()); pathParam.setDescription(_dataChildByName.getDescription()); pathParam.setType("string"); pathParam.setParamType("path"); pathParams.add(pathParam); } } return path.toString(); } protected void addRpcs(RpcDefinition rpcDefn, List<Api> apis, String parentPath, SchemaContext schemaContext) { Api rpc = new Api(); String resourcePath = parentPath + resolvePathArgumentsName(rpcDefn, schemaContext); rpc.setPath(resourcePath); Operation operationSpec = new Operation(); operationSpec.setMethod("POST"); operationSpec.setNotes(rpcDefn.getDescription()); operationSpec.setNickname(rpcDefn.getQName().getLocalName()); if (rpcDefn.getOutput() != null) { operationSpec.setType("(" + rpcDefn.getQName().getLocalName() + ")output"); } if (rpcDefn.getInput() != null) { Parameter payload = new Parameter(); payload.setParamType("body"); payload.setType("(" + rpcDefn.getQName().getLocalName() + ")input"); operationSpec.setParameters(Collections.singletonList(payload)); } rpc.setOperations(Arrays.asList(operationSpec)); apis.add(rpc); } protected SortedSet<Module> getSortedModules(SchemaContext schemaContext) { if (schemaContext == null) { return new TreeSet<>(); } Set<Module> modules = schemaContext.getModules(); SortedSet<Module> sortedModules = new TreeSet<>(new Comparator<Module>() { @Override public int compare(Module o1, Module o2) { int result = o1.getName().compareTo(o2.getName()); if (result == 0) { result = o1.getRevision().compareTo(o2.getRevision()); } if (result == 0) { result = o1.getNamespace().compareTo(o2.getNamespace()); } return result; } }); for (Module m : modules) { if (m != null) { sortedModules.add(m); } } return sortedModules; } }
package org.carewebframework.ui.zk; import org.apache.commons.lang.StringUtils; import org.carewebframework.common.StrUtil; import org.zkoss.zk.ui.Component; import org.zkoss.zul.Cell; import org.zkoss.zul.Column; import org.zkoss.zul.Columns; import org.zkoss.zul.Detail; import org.zkoss.zul.Grid; import org.zkoss.zul.Group; import org.zkoss.zul.Row; import org.zkoss.zul.RowRenderer; import org.zkoss.zul.Rows; /** * Base row renderer. * * @param <T> Data type of row-associated object. * @param <G> Data type of group-associated object. */ public abstract class AbstractRowRenderer<T, G> extends AbstractRenderer implements RowRenderer<T> { private static final String ATTR_DETAIL = AbstractRowRenderer.class.getName() + ".detail"; private static final String ATTR_DETAIL_EXPAND = ATTR_DETAIL + ".expand"; private static final String ATTR_GROUP_EXPAND = AbstractRowRenderer.class.getName() + ".group.expand"; /** * Associates the detail view with the specified row. This allows better performance when * changing the expand detail state by avoiding iterating over the component tree to find the * detail component. * * @param row Row with which to associate the detail. * @param detail The detail. */ private static void associateDetail(Row row, Detail detail) { row.setAttribute(ATTR_DETAIL, detail); } /** * Returns the detail associated with the row. * * @param row The row whose associated detail is sought. * @return The associated detail, or null if none. */ private static Detail getDetail(Row row) { return row.hasAttribute(ATTR_DETAIL) ? (Detail) row.getAttribute(ATTR_DETAIL) : row.getDetailChild(); } /** * Updates the detail open state for all detail views in the grid. * * @param grid The grid. * @param detailOpen The open state for detail views. If null, the open state for detail views * is unaffected. * @param groupOpen The open state for groups. If null, the open state for groups is unaffected. */ public static void expandAll(Grid grid, Boolean detailOpen, Boolean groupOpen) { Rows rows = grid.getRows(); if (rows != null) { for (Row row : rows.<Row> getChildren()) { if (groupOpen != null && row instanceof Group) { ((Group) row).setOpen(groupOpen); } if (detailOpen != null) { Detail detail = getDetail(row); if (detail != null) { detail.setOpen(detailOpen); } } } } } /** * Returns the default detail expansion state for the grid. * * @param grid The grid. * @return The default detail expansion state. */ public static boolean getExpandDetail(Grid grid) { Boolean expandDetail = (Boolean) grid.getAttribute(ATTR_DETAIL_EXPAND); return expandDetail != null && expandDetail; } /** * Sets the default detail expansion state for the grid and for any existing detail views within * the grid. * * @param grid The grid. * @param value The default detail expansion state. */ public static void setExpandDetail(Grid grid, boolean value) { boolean oldValue = getExpandDetail(grid); if (oldValue != value) { grid.setAttribute(ATTR_DETAIL_EXPAND, value); expandAll(grid, value, null); } } /** * Returns the default group expansion state for the grid. * * @param grid The grid. * @return The default group expansion state. */ public static boolean getExpandGroup(Grid grid) { Boolean expandGroup = (Boolean) grid.getAttribute(ATTR_GROUP_EXPAND); return expandGroup == null || expandGroup; } /** * Sets the default group expansion state for all groups within the grid. * * @param grid The grid. * @param value The default group expansion state. */ public static void setExpandGroup(Grid grid, boolean value) { boolean oldValue = getExpandGroup(grid); if (oldValue != value) { grid.setAttribute(ATTR_GROUP_EXPAND, value); expandAll(grid, null, value); } } /** * No args Constructor */ public AbstractRowRenderer() { super(); } /** * @param rowStyle Style to be applied to each rendered row. * @param cellStyle Style to be applied to each cell. */ public AbstractRowRenderer(String rowStyle, String cellStyle) { super(rowStyle, cellStyle); } /** * Row rendering logic. * * @param row Row being rendered. * @param object The data object associated with the row. * @return Parent component for detail. If null, no detail will be created. */ protected abstract Component renderRow(Row row, T object); /** * Groups rendering logic. * * @param group Group being rendered. * @param object The data object associated with the group. */ protected void renderGroup(Group group, G object) { group.setLabel(object.toString()); } /** * Detail rendering logic. * * @param detail The detail being rendered. * @param object The data object associated with the row. */ protected void renderDetail(Detail detail, T object) { } /** * @see org.zkoss.zul.RowRenderer#render(org.zkoss.zul.Row, java.lang.Object, int) */ @SuppressWarnings("unchecked") @Override public final void render(Row row, Object object, int index) throws Exception { row.setValue(object); if (row instanceof Group) { Group group = (Group) row; group.setOpen(getExpandGroup(row.getGrid())); renderGroup(group, (G) object); return; } row.setStyle(compStyle); row.setValign("middle"); Component detailParent = renderRow(row, (T) object); if (detailParent != null) { Detail detail = createDetail(row, detailParent); renderDetail(detail, (T) object); if (detail.getFirstChild() == null) { detail.setVisible(false); } } else { associateDetail(row, null); } } /** * Creates a cell containing a label with the specified parameters. * * @param parent Component that will be the parent of the cell. * @param value Value to be used as label text. * @return The newly created cell. */ public Cell createCell(Component parent, Object value) { return createCell(parent, value, null); } /** * Creates a cell containing a label with the specified parameters. * * @param parent Component that will be the parent of the cell. * @param value Value to be used as label text. * @param prefix Value to be used as a prefix for the label text. * @return The newly created cell. */ public Cell createCell(Component parent, Object value, String prefix) { return createCell(parent, value, prefix, null); } /** * Creates a cell containing a label with the specified parameters. * * @param parent Component that will be the parent of the cell. * @param value Value to be used as label text. * @param prefix Value to be used as a prefix for the label text. * @param style Style to be applied to the label. * @return The newly created cell. */ public Cell createCell(Component parent, Object value, String prefix, String style) { return createCell(parent, value, prefix, style, null); } /** * Creates a cell containing a label with the specified parameters. * * @param parent Component that will be the parent of the cell. * @param value Value to be used as label text. * @param prefix Value to be used as a prefix for the label text. * @param style Style to be applied to the label. * @param width Width of the cell. * @return The newly created cell. */ public Cell createCell(Component parent, Object value, String prefix, String style, String width) { return createCell(parent, value, prefix, style, width, Cell.class); } /** * If a value to be added is empty or null, rather than creating a new cell with no content, * will increase the span count of the preceding cell by one. * * @param parent Parent for a newly created cell. * @param cell The preceding cell, or null to force new cell creation. * @param value The content for the new cell. * @return If the previous cell was re-used, this is returned. Otherwise, returns a new cell. */ public Cell createOrMergeCell(Component parent, Cell cell, Object value) { return createOrMergeCell(parent, cell, value, null); } /** * If a value to be added is empty or null, rather than creating a new cell with no content, * will increase the span count of the preceding cell by one. * * @param parent Parent for a newly created cell. * @param cell The preceding cell, or null to force new cell creation. * @param value The content for the new cell. * @param prefix Text prefix for content. * @return If the previous cell was re-used, this is returned. Otherwise, returns a new cell. */ public Cell createOrMergeCell(Component parent, Cell cell, Object value, String prefix) { return createOrMergeCell(parent, cell, value, prefix, null); } /** * If a value to be added is empty or null, rather than creating a new cell with no content, * will increase the span count of the preceding cell by one. * * @param parent Parent for a newly created cell. * @param cell The preceding cell, or null to force new cell creation. * @param value The content for the new cell. * @param prefix Text prefix for content. * @param style Optional style for label. * @return If the previous cell was re-used, this is returned. Otherwise, returns a new cell. */ public Cell createOrMergeCell(Component parent, Cell cell, Object value, String prefix, String style) { value = value instanceof String ? StringUtils.trimToNull(createLabelText(value, prefix)) : value; if (cell == null || value != null) { cell = createCell(parent, value, null, style, "100%"); cell.setColspan(1); } else { cell.setColspan(cell.getColspan() + 1); } return cell; } /** * Creates a grid for detail view. * * @param parent The detail parent. * @param colWidths Array of column widths. * @return The detail grid. */ public Grid createDetailGrid(Component parent, String[] colWidths) { return createDetailGrid(parent, colWidths, null); } /** * Creates a grid for detail view. * * @param parent The detail parent. * @param colWidths Array of column widths. * @param colLabels Array of column labels (may be null). * @return The detail grid. */ public Grid createDetailGrid(Component parent, String[] colWidths, String[] colLabels) { Grid detailGrid = new Grid(); detailGrid.setOddRowSclass("none"); detailGrid.setWidth("100%"); detailGrid.setParent(parent); Columns detailColumns = new Columns(); detailColumns.setSizable(true); detailColumns.setParent(detailGrid); int cols = Math.max(colWidths == null ? 0 : colWidths.length, colLabels == null ? 0 : colLabels.length); for (int i = 0; i < cols; i++) { String colLabel = colLabels == null || i >= colLabels.length ? " " : StrUtil.formatMessage(colLabels[i]); Column col = new Column(colLabel); String colWidth = colWidths == null || i >= colWidths.length ? null : colWidths[i]; col.setWidth(colWidth); col.setParent(detailColumns); } detailGrid.appendChild(new Rows()); return detailGrid; } private Detail createDetail(Row row, Component parent) { Detail detail = new Detail(); detail.setParent(parent); associateDetail(row, detail); detail.setOpen(getExpandDetail(row.getGrid())); return detail; } }
package org.opendaylight.bgpcep.pcep.tunnel.provider; import static java.util.Objects.requireNonNull; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.FluentFuture; import java.util.Dictionary; import java.util.Hashtable; import java.util.concurrent.TimeUnit; import javax.annotation.Nonnull; import javax.annotation.concurrent.GuardedBy; import org.opendaylight.bgpcep.programming.spi.InstructionScheduler; import org.opendaylight.bgpcep.topology.DefaultTopologyReference; import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; import org.opendaylight.mdsal.common.api.CommitInfo; import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService; import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration; import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.network.topology.rev140113.NetworkTopologyContext; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.tunnel.pcep.programming.rev131030.TopologyTunnelPcepProgrammingService; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceRegistration; import org.osgi.util.tracker.ServiceTracker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class PCEPTunnelClusterSingletonService implements ClusterSingletonService, AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(PCEPTunnelClusterSingletonService.class); private final PCEPTunnelTopologyProvider ttp; private final TunnelProgramming tp; private final ServiceGroupIdentifier sgi; private final TopologyId tunnelTopologyId; private final TunnelProviderDependencies dependencies; @GuardedBy("this") private ServiceRegistration<?> serviceRegistration; @GuardedBy("this") private ClusterSingletonServiceRegistration pcepTunnelCssReg; @GuardedBy("this") private BindingAwareBroker.RoutedRpcRegistration<TopologyTunnelPcepProgrammingService> reg; public PCEPTunnelClusterSingletonService( final TunnelProviderDependencies dependencies, final InstanceIdentifier<Topology> pcepTopology, final TopologyId tunnelTopologyId ) { this.dependencies = requireNonNull(dependencies); this.tunnelTopologyId = requireNonNull(tunnelTopologyId); final TopologyId pcepTopologyId = pcepTopology.firstKeyOf(Topology.class).getTopologyId(); final InstructionScheduler scheduler; ServiceTracker<InstructionScheduler, ?> tracker = null; try { tracker = new ServiceTracker<>(dependencies.getBundleContext(), dependencies.getBundleContext().createFilter(String.format("(&(%s=%s)%s)", Constants.OBJECTCLASS, InstructionScheduler.class.getName(), "(" + InstructionScheduler.class.getName() + "=" + pcepTopologyId.getValue() + ")")), null); tracker.open(); scheduler = (InstructionScheduler) tracker.waitForService( TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES)); Preconditions.checkState(scheduler != null, "InstructionScheduler service not found"); } catch (InvalidSyntaxException | InterruptedException e) { throw new IllegalStateException("Error retrieving InstructionScheduler service", e); } finally { if (tracker != null) { tracker.close(); } } final InstanceIdentifier<Topology> tunnelTopology = InstanceIdentifier.builder(NetworkTopology.class) .child(Topology.class, new TopologyKey(tunnelTopologyId)).build(); this.ttp = new PCEPTunnelTopologyProvider(dependencies.getDataBroker(), pcepTopology, pcepTopologyId, tunnelTopology, tunnelTopologyId); this.sgi = scheduler.getIdentifier(); this.tp = new TunnelProgramming(scheduler, dependencies); final Dictionary<String, String> properties = new Hashtable<>(); properties.put(PCEPTunnelTopologyProvider.class.getName(), tunnelTopologyId.getValue()); this.serviceRegistration = dependencies.getBundleContext() .registerService(DefaultTopologyReference.class.getName(), this.ttp, properties); LOG.info("PCEP Tunnel Cluster Singleton service {} registered", getIdentifier().getValue()); this.pcepTunnelCssReg = dependencies.getCssp().registerClusterSingletonService(this); } @Override public synchronized void instantiateServiceInstance() { LOG.info("Instantiate PCEP Tunnel Topology Provider Singleton Service {}", getIdentifier().getValue()); this.reg = this.dependencies.getRpcProviderRegistry() .addRoutedRpcImplementation(TopologyTunnelPcepProgrammingService.class, this.tp); final InstanceIdentifier<Topology> topology = InstanceIdentifier .builder(NetworkTopology.class).child(Topology.class, new TopologyKey(this.tunnelTopologyId)).build(); this.reg.registerPath(NetworkTopologyContext.class, topology); this.ttp.init(); } @Override public synchronized FluentFuture<? extends CommitInfo> closeServiceInstance() { LOG.info("Close Service Instance PCEP Tunnel Topology Provider Singleton Service {}", getIdentifier().getValue()); this.reg.close(); this.tp.close(); this.ttp.close(); return CommitInfo.emptyFluentFuture(); } @Nonnull @Override public ServiceGroupIdentifier getIdentifier() { return this.sgi; } @Override @SuppressWarnings("checkstyle:IllegalCatch") public synchronized void close() { LOG.info("Close PCEP Tunnel Topology Provider Singleton Service {}", getIdentifier().getValue()); if (this.pcepTunnelCssReg != null) { try { this.pcepTunnelCssReg.close(); } catch (final Exception e) { LOG.debug("Failed to close PCEP Tunnel Topology service {}", this.sgi.getValue(), e); } this.pcepTunnelCssReg = null; } if (this.serviceRegistration != null) { this.serviceRegistration.unregister(); this.serviceRegistration = null; } } }
package com.github.rnowling.bps.datagenerator.generators.store; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; import org.junit.Test; import com.github.rnowling.bps.datagenerator.datamodels.Pair; import com.github.rnowling.bps.datagenerator.datamodels.inputs.ZipcodeRecord; import com.github.rnowling.bps.datagenerator.datamodels.outputs.Store; import com.github.rnowling.bps.datagenerator.framework.SeedFactory; import com.github.rnowling.bps.datagenerator.framework.samplers.Sampler; public class TestStoreSamplerBuilder { @Test public void testBuild() throws Exception { List<ZipcodeRecord> zipcodes = Arrays.asList(new ZipcodeRecord[] { new ZipcodeRecord("11111", Pair.create(1.0, 1.0), 30000.0, 100), new ZipcodeRecord("22222", Pair.create(2.0, 2.0), 45000.0, 200), new ZipcodeRecord("33333", Pair.create(3.0, 3.0), 60000.0, 300) }); assertTrue(zipcodes.size() > 0); SeedFactory factory = new SeedFactory(1234); StoreSamplerBuilder builder = new StoreSamplerBuilder(zipcodes, factory); Sampler<Store> sampler = builder.build(); Store store = sampler.sample(); assertNotNull(store); assertTrue(store.getId() >= 0); assertNotNull(store.getName()); assertNotNull(store.getLocation()); } }
package org.cyclops.commoncapabilities.modcompat.vanilla.capability.recipehandler; import com.google.common.base.Function; import com.google.common.base.Predicates; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import net.minecraft.init.Items; import net.minecraft.init.PotionTypes; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import net.minecraft.potion.PotionHelper; import net.minecraft.potion.PotionType; import net.minecraft.potion.PotionUtils; import net.minecraft.tileentity.TileEntityBrewingStand; import net.minecraft.util.EnumFacing; import net.minecraft.util.NonNullList; import net.minecraftforge.common.brewing.BrewingRecipeRegistry; import net.minecraftforge.common.brewing.IBrewingRecipe; import net.minecraftforge.common.brewing.VanillaBrewingRecipe; import net.minecraftforge.fml.relauncher.ReflectionHelper; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import org.cyclops.commoncapabilities.api.capability.recipehandler.*; import org.cyclops.commoncapabilities.core.CompositeList; import javax.annotation.Nullable; import java.util.Collections; import java.util.List; import java.util.Set; /** * Recipe handler capability for the vanilla brewing stand. * @author rubensworks */ public class VanillaBrewingStandRecipeHandler implements IRecipeHandler { private static final Set<RecipeComponent<?, ?>> COMPONENTS_INPUT = Sets.newHashSet(RecipeComponent.ITEMSTACK); private static final Set<RecipeComponent<?, ?>> COMPONENTS_OUTPUT = Sets.newHashSet(RecipeComponent.ITEMSTACK); private static final int[] OUTPUT_SLOTS = new int[] {1, 2, 3}; private static final IRecipeIngredient<ItemStack, ItemHandlerRecipeTarget> EMPTY = new IRecipeIngredient<ItemStack, ItemHandlerRecipeTarget>() { @Override public RecipeComponent<ItemStack, ItemHandlerRecipeTarget> getComponent() { return RecipeComponent.ITEMSTACK; } @Override public List<ItemStack> getMatchingInstances() { return Collections.emptyList(); } @Override public boolean test(ItemStack itemStack) { return false; } }; private static final IRecipeIngredient<ItemStack, ItemHandlerRecipeTarget> ANY = new IRecipeIngredient<ItemStack, ItemHandlerRecipeTarget>() { @Override public RecipeComponent<ItemStack, ItemHandlerRecipeTarget> getComponent() { return RecipeComponent.ITEMSTACK; } @Override public List<ItemStack> getMatchingInstances() { return Collections.emptyList(); } @Override public boolean test(ItemStack itemStack) { return true; } }; private static List<RecipeDefinition> VANILLA_RECIPES = null; private final TileEntityBrewingStand tile; public VanillaBrewingStandRecipeHandler(TileEntityBrewingStand tile) { this.tile = tile; } @Override public Set<RecipeComponent<?, ?>> getRecipeInputComponents() { return COMPONENTS_INPUT; } @Override public Set<RecipeComponent<?, ?>> getRecipeOutputComponents() { return COMPONENTS_OUTPUT; } @Override public boolean isValidSizeInput(RecipeComponent component, int size) { return component == RecipeComponent.ITEMSTACK && (size >= 2 || size <= 4); } @Override public List<RecipeDefinition> getRecipes() { return new CompositeList<>(Lists.newArrayList(generateVanillaRecipes(), Lists.newArrayList(Iterables.filter(Lists.transform(BrewingRecipeRegistry.getRecipes(), new Function<IBrewingRecipe, RecipeDefinition>() { @Nullable @Override public RecipeDefinition apply(@Nullable IBrewingRecipe recipe) { BrewingIngredientInput input; BrewingIngredientIngredient ingredient; IRecipeIngredient<ItemStack, ItemHandlerRecipeTarget> output; if (recipe instanceof VanillaBrewingRecipe) { return null; } else { input = new BrewingIngredientInput(recipe); ingredient = new BrewingIngredientIngredient(recipe); output = ANY; } return new RecipeDefinition(new RecipeIngredients(ingredient, input, input, input), new RecipeIngredients(EMPTY, output, output, output)); } }), Predicates.notNull())))); } protected List<RecipeDefinition> generateVanillaRecipes() { if (VANILLA_RECIPES == null) { VANILLA_RECIPES = Lists.newArrayList(); List<ItemStack> inputItems = Lists.newArrayList( PotionUtils.addPotionToItemStack(new ItemStack(Items.POTIONITEM), PotionTypes.WATER), new ItemStack(Items.POTIONITEM), new ItemStack(Items.SPLASH_POTION), new ItemStack(Items.LINGERING_POTION) ); for (ItemStack inputItem : inputItems) { IRecipeIngredient<ItemStack, ItemHandlerRecipeTarget> item = new RecipeIngredientItemStack(inputItem); for (PotionHelper.MixPredicate<Item> mixPredicate : getPotionItems()) { IRecipeIngredient<ItemStack, ItemHandlerRecipeTarget> ingredient = new RecipeIngredientItemStack(getMixReagent(mixPredicate)); IRecipeIngredient<ItemStack, ItemHandlerRecipeTarget> output = new RecipeIngredientItemStack(PotionHelper.doReaction( Iterables.getFirst(ingredient.getMatchingInstances(), ItemStack.EMPTY).copy(), inputItem.copy())); VANILLA_RECIPES.add(new RecipeDefinition( new RecipeIngredients(ingredient, item, item, item), new RecipeIngredients(EMPTY, output, output, output)) ); } for (PotionHelper.MixPredicate<PotionType> mixPredicate : getPotionTypes()) { IRecipeIngredient<ItemStack, ItemHandlerRecipeTarget> ingredient = new RecipeIngredientItemStack(getMixReagent(mixPredicate)); IRecipeIngredient<ItemStack, ItemHandlerRecipeTarget> output = new RecipeIngredientItemStack(PotionHelper.doReaction( Iterables.getFirst(ingredient.getMatchingInstances(), ItemStack.EMPTY).copy(), inputItem.copy())); VANILLA_RECIPES.add(new RecipeDefinition( new RecipeIngredients(ingredient, item, item, item), new RecipeIngredients(EMPTY, output, output, output)) ); } } } return VANILLA_RECIPES; } @Nullable @Override public RecipeIngredients simulate(RecipeIngredients input) { List<IRecipeIngredient<ItemStack, ItemHandlerRecipeTarget>> recipeIngredients = input.getIngredients(RecipeComponent.ITEMSTACK); if (input.getComponents().size() != 1 || !isValidSizeInput(RecipeComponent.ITEMSTACK, recipeIngredients.size())) { return null; } NonNullList<ItemStack> brewingItemStacks = NonNullList.withSize(4, ItemStack.EMPTY); for (int i = 0; i < recipeIngredients.size(); i++) { brewingItemStacks.set(i, Iterables.getFirst(recipeIngredients.get(i).getMatchingInstances(), ItemStack.EMPTY).copy()); } BrewingRecipeRegistry.brewPotions(brewingItemStacks, brewingItemStacks.get(0), OUTPUT_SLOTS); brewingItemStacks.set(0, ItemStack.EMPTY); return new RecipeIngredients(Lists.transform(brewingItemStacks, new Function<ItemStack, RecipeIngredientItemStack>() { @Nullable @Override public RecipeIngredientItemStack apply(@Nullable ItemStack input) { return new RecipeIngredientItemStack(input); } })); } @Nullable @Override public <R> R[] getInputComponentTargets(RecipeComponent<?, R> component) { if (component == RecipeComponent.ITEMSTACK) { IItemHandler itemHandler = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.NORTH); return (R[]) new ItemHandlerRecipeTarget[]{ new ItemHandlerRecipeTarget(itemHandler, 3), new ItemHandlerRecipeTarget(itemHandler, 0), new ItemHandlerRecipeTarget(itemHandler, 1), new ItemHandlerRecipeTarget(itemHandler, 2) }; } return null; } @Nullable @Override public <R> R[] getOutputComponentTargets(RecipeComponent<?, R> component) { if (component == RecipeComponent.ITEMSTACK) { IItemHandler itemHandler = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.DOWN); return (R[]) new ItemHandlerRecipeTarget[]{ new ItemHandlerRecipeTarget(itemHandler, 3), new ItemHandlerRecipeTarget(itemHandler, 0), new ItemHandlerRecipeTarget(itemHandler, 1), new ItemHandlerRecipeTarget(itemHandler, 2) }; } return null; } private static List<PotionHelper.MixPredicate<PotionType>> getPotionTypes() { return ReflectionHelper.getPrivateValue(PotionHelper.class, null, "field_185213_a", "POTION_TYPE_CONVERSIONS"); } private static List<PotionHelper.MixPredicate<Item>> getPotionItems() { return ReflectionHelper.getPrivateValue(PotionHelper.class, null, "field_185214_b", "POTION_ITEM_CONVERSIONS"); } private static Ingredient getMixReagent(PotionHelper.MixPredicate<?> mixPredicate) { return ReflectionHelper.getPrivateValue(PotionHelper.MixPredicate.class, mixPredicate, "field_185199_b", "reagent"); } public static class BrewingIngredientInput implements IRecipeIngredient<ItemStack, ItemHandlerRecipeTarget> { protected final IBrewingRecipe brewingRecipe; public BrewingIngredientInput(IBrewingRecipe brewingRecipe) { this.brewingRecipe = brewingRecipe; } @Override public RecipeComponent<ItemStack, ItemHandlerRecipeTarget> getComponent() { return RecipeComponent.ITEMSTACK; } @Override public List<ItemStack> getMatchingInstances() { return Collections.emptyList(); } @Override public boolean test(ItemStack itemStack) { return brewingRecipe.isInput(itemStack); } } public static class BrewingIngredientIngredient implements IRecipeIngredient<ItemStack, ItemHandlerRecipeTarget> { protected final IBrewingRecipe brewingRecipe; public BrewingIngredientIngredient(IBrewingRecipe brewingRecipe) { this.brewingRecipe = brewingRecipe; } @Override public RecipeComponent<ItemStack, ItemHandlerRecipeTarget> getComponent() { return RecipeComponent.ITEMSTACK; } @Override public List<ItemStack> getMatchingInstances() { return Collections.emptyList(); } @Override public boolean test(ItemStack itemStack) { return brewingRecipe.isIngredient(itemStack); } } }
package org.apache.wicket.bean.validation; import static org.junit.Assert.*; import javax.validation.constraints.NotNull; import org.apache.wicket.MarkupContainer; import org.apache.wicket.markup.IMarkupResourceStreamProvider; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.mock.MockApplication; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.util.resource.IResourceStream; import org.apache.wicket.util.resource.StringResourceStream; import org.apache.wicket.util.tester.WicketTester; import org.apache.wicket.util.tester.WicketTesterScope; import org.junit.Rule; import org.junit.Test; public class PropertyValidatorRequiredTest { @Rule public WicketTesterScope scope = new WicketTesterScope() { protected WicketTester create() { return new WicketTester(new TestApplication()); }; }; @Test public void test() { TestPage page = scope.getTester().startPage(TestPage.class); // no group assertTrue(page.input1.isRequired()); assertFalse(page.input2.isRequired()); assertFalse(page.input3.isRequired()); assertFalse(page.input4.isRequired()); // group1 assertFalse(page.input5.isRequired()); assertTrue(page.input6.isRequired()); assertFalse(page.input7.isRequired()); assertTrue(page.input8.isRequired()); // group2 assertFalse(page.input9.isRequired()); assertFalse(page.input10.isRequired()); assertTrue(page.input11.isRequired()); assertTrue(page.input12.isRequired()); // group1+group2 assertFalse(page.input13.isRequired()); assertTrue(page.input14.isRequired()); assertTrue(page.input15.isRequired()); assertTrue(page.input16.isRequired()); // group3 assertFalse(page.input17.isRequired()); assertFalse(page.input18.isRequired()); assertFalse(page.input19.isRequired()); assertFalse(page.input20.isRequired()); } public static class TestApplication extends MockApplication { @Override protected void init() { super.init(); new BeanValidationConfiguration().configure(this); } } public static class TestPage extends WebPage implements IMarkupResourceStreamProvider { private TestBean bean = new TestBean(); private FormComponent<String> input1, input2, input3, input4, input5, input6, input7, input8, input9, input10, input11, input12, input13, input14, input15, input16, input17, input18, input19, input20; public TestPage() { Form<?> form = new Form<Void>("form"); add(form); input1 = new TextField<String>("input1", new PropertyModel<String>( this, "bean.property")) .add(new PropertyValidator<String>()); input2 = new TextField<String>("input2", new PropertyModel<String>( this, "bean.propertyOne")) .add(new PropertyValidator<String>()); input3 = new TextField<String>("input3", new PropertyModel<String>( this, "bean.propertyTwo")) .add(new PropertyValidator<String>()); input4 = new TextField<String>("input4", new PropertyModel<String>( this, "bean.propertyOneTwo")) .add(new PropertyValidator<String>()); input5 = new TextField<String>("input5", new PropertyModel<String>( this, "bean.property")).add(new PropertyValidator<String>( GroupOne.class)); input6 = new TextField<String>("input6", new PropertyModel<String>( this, "bean.propertyOne")) .add(new PropertyValidator<String>(GroupOne.class)); input7 = new TextField<String>("input7", new PropertyModel<String>( this, "bean.propertyTwo")) .add(new PropertyValidator<String>(GroupOne.class)); input8 = new TextField<String>("input8", new PropertyModel<String>( this, "bean.propertyOneTwo")) .add(new PropertyValidator<String>(GroupOne.class)); input9 = new TextField<String>("input9", new PropertyModel<String>( this, "bean.property")).add(new PropertyValidator<String>( GroupTwo.class)); input10 = new TextField<String>("input10", new PropertyModel<String>(this, "bean.propertyOne")) .add(new PropertyValidator<String>(GroupTwo.class)); input11 = new TextField<String>("input11", new PropertyModel<String>(this, "bean.propertyTwo")) .add(new PropertyValidator<String>(GroupTwo.class)); input12 = new TextField<String>("input12", new PropertyModel<String>(this, "bean.propertyOneTwo")) .add(new PropertyValidator<String>(GroupTwo.class)); input13 = new TextField<String>("input13", new PropertyModel<String>(this, "bean.property")) .add(new PropertyValidator<String>(GroupOne.class, GroupTwo.class)); input14 = new TextField<String>("input14", new PropertyModel<String>(this, "bean.propertyOne")) .add(new PropertyValidator<String>(GroupOne.class, GroupTwo.class)); input15 = new TextField<String>("input15", new PropertyModel<String>(this, "bean.propertyTwo")) .add(new PropertyValidator<String>(GroupOne.class, GroupTwo.class)); input16 = new TextField<String>("input16", new PropertyModel<String>(this, "bean.propertyOneTwo")) .add(new PropertyValidator<String>(GroupOne.class, GroupTwo.class)); input17 = new TextField<String>("input17", new PropertyModel<String>(this, "bean.property")) .add(new PropertyValidator<String>(GroupThree.class)); input18 = new TextField<String>("input18", new PropertyModel<String>(this, "bean.propertyOne")) .add(new PropertyValidator<String>(GroupThree.class)); input19 = new TextField<String>("input19", new PropertyModel<String>(this, "bean.propertyTwo")) .add(new PropertyValidator<String>(GroupThree.class)); input20 = new TextField<String>("input20", new PropertyModel<String>(this, "bean.propertyOneTwo")) .add(new PropertyValidator<String>(GroupThree.class)); form.add(input1, input2, input3, input4, input5, input6, input7, input8, input9, input10, input11, input12, input13, input14, input15, input16, input17, input18, input19, input20); } @Override public IResourceStream getMarkupResourceStream( MarkupContainer container, Class<?> containerClass) { return new StringResourceStream( "<form wicket:id='form'><input wicket:id='input1'/><input wicket:id='input2'/><input wicket:id='input3'/><input wicket:id='input4'/><input wicket:id='input5'/><input wicket:id='input6'/><input wicket:id='input7'/><input wicket:id='input8'/><input wicket:id='input9'/><input wicket:id='input10'/><input wicket:id='input11'/><input wicket:id='input12'/><input wicket:id='input13'/><input wicket:id='input14'/><input wicket:id='input15'/><input wicket:id='input16'/><input wicket:id='input17'/><input wicket:id='input18'/><input wicket:id='input19'/><input wicket:id='input20'/></form>"); } } public static interface GroupOne { } public static interface GroupTwo { } public static interface GroupThree { } public static class TestBean { @NotNull String property; @NotNull(groups = { GroupOne.class }) String propertyOne; @NotNull(groups = { GroupTwo.class }) String propertyTwo; @NotNull(groups = { GroupOne.class, GroupTwo.class }) String propertyOneTwo; } }
package org.elasticsearch.xpack.ml.integration; import org.apache.lucene.util.Constants; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.xpack.core.ml.action.GetJobsStatsAction; import org.elasticsearch.xpack.core.ml.job.config.AnalysisConfig; import org.elasticsearch.xpack.core.ml.job.config.AnalysisLimits; import org.elasticsearch.xpack.core.ml.job.config.DataDescription; import org.elasticsearch.xpack.core.ml.job.config.Detector; import org.elasticsearch.xpack.core.ml.job.config.Job; import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.ModelSizeStats; import org.junit.After; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThan; /** * A set of tests that ensure we comply to the model memory limit */ public class AutodetectMemoryLimitIT extends MlNativeAutodetectIntegTestCase { @After public void cleanUpTest() { cleanUp(); } public void testTooManyPartitions() throws Exception { assumeFalse("AwaitsFix(bugUrl = \"https://github.com/elastic/elasticsearch/issues/32033\")", Constants.WINDOWS); Detector.Builder detector = new Detector.Builder("count", null); detector.setPartitionFieldName("user"); TimeValue bucketSpan = TimeValue.timeValueHours(1); AnalysisConfig.Builder analysisConfig = new AnalysisConfig.Builder(Collections.singletonList(detector.build())); analysisConfig.setBucketSpan(bucketSpan); DataDescription.Builder dataDescription = new DataDescription.Builder(); dataDescription.setTimeFormat("epoch"); Job.Builder job = new Job.Builder("autodetect-memory-limit-test-too-many-partitions"); job.setAnalysisConfig(analysisConfig); job.setDataDescription(dataDescription); // Set the memory limit to 30MB AnalysisLimits limits = new AnalysisLimits(30L, null); job.setAnalysisLimits(limits); registerJob(job); putJob(job); openJob(job.getId()); long now = Instant.now().getEpochSecond(); long timestamp = now - 8 * bucketSpan.seconds(); List<String> data = new ArrayList<>(); while (timestamp < now) { for (int i = 0; i < 11000; i++) { // It's important that the values used here are either always represented in less than 16 UTF-8 bytes or // always represented in more than 22 UTF-8 bytes. Otherwise platform differences in when the small string // optimisation is used will make the results of this test very different for the different platforms. data.add(createJsonRecord(createRecord(timestamp, String.valueOf(i), ""))); } timestamp += bucketSpan.seconds(); } postData(job.getId(), data.stream().collect(Collectors.joining())); closeJob(job.getId()); // Assert we haven't violated the limit too much GetJobsStatsAction.Response.JobStats jobStats = getJobStats(job.getId()).get(0); ModelSizeStats modelSizeStats = jobStats.getModelSizeStats(); assertThat(modelSizeStats.getModelBytes(), lessThan(31500000L)); assertThat(modelSizeStats.getModelBytes(), greaterThan(24000000L)); assertThat(modelSizeStats.getMemoryStatus(), equalTo(ModelSizeStats.MemoryStatus.HARD_LIMIT)); } public void testTooManyByFields() throws Exception { Detector.Builder detector = new Detector.Builder("count", null); detector.setByFieldName("user"); TimeValue bucketSpan = TimeValue.timeValueHours(1); AnalysisConfig.Builder analysisConfig = new AnalysisConfig.Builder(Collections.singletonList(detector.build())); analysisConfig.setBucketSpan(bucketSpan); DataDescription.Builder dataDescription = new DataDescription.Builder(); dataDescription.setTimeFormat("epoch"); Job.Builder job = new Job.Builder("autodetect-memory-limit-test-too-many-by-fields"); job.setAnalysisConfig(analysisConfig); job.setDataDescription(dataDescription); // Set the memory limit to 30MB AnalysisLimits limits = new AnalysisLimits(30L, null); job.setAnalysisLimits(limits); registerJob(job); putJob(job); openJob(job.getId()); long now = Instant.now().getEpochSecond(); long timestamp = now - 8 * bucketSpan.seconds(); List<String> data = new ArrayList<>(); while (timestamp < now) { for (int i = 0; i < 10000; i++) { // It's important that the values used here are either always represented in less than 16 UTF-8 bytes or // always represented in more than 22 UTF-8 bytes. Otherwise platform differences in when the small string // optimisation is used will make the results of this test very different for the different platforms. data.add(createJsonRecord(createRecord(timestamp, String.valueOf(i), ""))); } timestamp += bucketSpan.seconds(); } postData(job.getId(), data.stream().collect(Collectors.joining())); closeJob(job.getId()); // Assert we haven't violated the limit too much GetJobsStatsAction.Response.JobStats jobStats = getJobStats(job.getId()).get(0); ModelSizeStats modelSizeStats = jobStats.getModelSizeStats(); assertThat(modelSizeStats.getModelBytes(), lessThan(35000000L)); assertThat(modelSizeStats.getModelBytes(), greaterThan(25000000L)); assertThat(modelSizeStats.getMemoryStatus(), equalTo(ModelSizeStats.MemoryStatus.HARD_LIMIT)); } public void testTooManyByAndOverFields() throws Exception { Detector.Builder detector = new Detector.Builder("count", null); detector.setByFieldName("department"); detector.setOverFieldName("user"); TimeValue bucketSpan = TimeValue.timeValueHours(1); AnalysisConfig.Builder analysisConfig = new AnalysisConfig.Builder(Collections.singletonList(detector.build())); analysisConfig.setBucketSpan(bucketSpan); DataDescription.Builder dataDescription = new DataDescription.Builder(); dataDescription.setTimeFormat("epoch"); Job.Builder job = new Job.Builder("autodetect-memory-limit-test-too-many-by-and-over-fields"); job.setAnalysisConfig(analysisConfig); job.setDataDescription(dataDescription); // Set the memory limit to 30MB AnalysisLimits limits = new AnalysisLimits(30L, null); job.setAnalysisLimits(limits); registerJob(job); putJob(job); openJob(job.getId()); long now = Instant.now().getEpochSecond(); long timestamp = now - 8 * bucketSpan.seconds(); while (timestamp < now) { for (int department = 0; department < 10; department++) { List<String> data = new ArrayList<>(); for (int user = 0; user < 10000; user++) { // It's important that the values used here are either always represented in less than 16 UTF-8 bytes or // always represented in more than 22 UTF-8 bytes. Otherwise platform differences in when the small string // optimisation is used will make the results of this test very different for the different platforms. data.add(createJsonRecord(createRecord( timestamp, String.valueOf(department) + "_" + String.valueOf(user), String.valueOf(department)))); } postData(job.getId(), data.stream().collect(Collectors.joining())); } timestamp += bucketSpan.seconds(); } closeJob(job.getId()); // Assert we haven't violated the limit too much GetJobsStatsAction.Response.JobStats jobStats = getJobStats(job.getId()).get(0); ModelSizeStats modelSizeStats = jobStats.getModelSizeStats(); assertThat(modelSizeStats.getModelBytes(), lessThan(33000000L)); assertThat(modelSizeStats.getModelBytes(), greaterThan(24000000L)); assertThat(modelSizeStats.getMemoryStatus(), equalTo(ModelSizeStats.MemoryStatus.HARD_LIMIT)); } public void testManyDistinctOverFields() throws Exception { Detector.Builder detector = new Detector.Builder("sum", "value"); detector.setOverFieldName("user"); TimeValue bucketSpan = TimeValue.timeValueHours(1); AnalysisConfig.Builder analysisConfig = new AnalysisConfig.Builder(Collections.singletonList(detector.build())); analysisConfig.setBucketSpan(bucketSpan); DataDescription.Builder dataDescription = new DataDescription.Builder(); dataDescription.setTimeFormat("epoch"); Job.Builder job = new Job.Builder("autodetect-memory-limit-test-too-many-distinct-over-fields"); job.setAnalysisConfig(analysisConfig); job.setDataDescription(dataDescription); // Set the memory limit to 110MB AnalysisLimits limits = new AnalysisLimits(110L, null); job.setAnalysisLimits(limits); registerJob(job); putJob(job); openJob(job.getId()); long now = Instant.now().getEpochSecond(); long timestamp = now - 15 * bucketSpan.seconds(); int user = 0; while (timestamp < now) { List<String> data = new ArrayList<>(); for (int i = 0; i < 10000; i++) { // It's important that the values used here are either always represented in less than 16 UTF-8 bytes or // always represented in more than 22 UTF-8 bytes. Otherwise platform differences in when the small string // optimisation is used will make the results of this test very different for the different platforms. Map<String, Object> record = new HashMap<>(); record.put("time", timestamp); record.put("user", user++); record.put("value", 42.0); data.add(createJsonRecord(record)); } postData(job.getId(), data.stream().collect(Collectors.joining())); timestamp += bucketSpan.seconds(); } closeJob(job.getId()); // Assert we haven't violated the limit too much GetJobsStatsAction.Response.JobStats jobStats = getJobStats(job.getId()).get(0); ModelSizeStats modelSizeStats = jobStats.getModelSizeStats(); assertThat(modelSizeStats.getModelBytes(), lessThan(117000000L)); assertThat(modelSizeStats.getModelBytes(), greaterThan(90000000L)); assertThat(modelSizeStats.getMemoryStatus(), equalTo(ModelSizeStats.MemoryStatus.HARD_LIMIT)); } private static Map<String, Object> createRecord(long timestamp, String user, String department) { Map<String, Object> record = new HashMap<>(); record.put("time", timestamp); record.put("user", user); record.put("department", department); return record; } }
package org.xwiki.rendering.internal.macro.ctsreport; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.xwiki.text.XWikiToStringBuilder; /** * Represents a parsed JUnit test result (see {@link TestParser} for more). * * @version $Id$ * @since 4.1M2 */ public class Result { /** * The syntax being tested and in which the syntax data is written in (eg "xwiki/2.0"). */ public String syntaxId; /** * True if this test is an input test, ie the syntax data represents an input, false otherwise. */ public boolean isSyntaxInputTest; /** * Test Data (test name, syntax extension, cts extension, state). */ public Test test; @Override public String toString() { return new XWikiToStringBuilder(this) .append("syntaxId", this.syntaxId) .append("test", this.test) .append("isSyntaxInputTest", this.isSyntaxInputTest) .toString(); } @Override public boolean equals(Object object) { if (!(object instanceof Result)){ return false; } if (object == this) { return true; } Result rhs = (Result) object; return new EqualsBuilder() .append(this.syntaxId, rhs.syntaxId) .append(this.test, rhs.test) .append(this.isSyntaxInputTest, rhs.isSyntaxInputTest) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(3, 17) .append(this.syntaxId) .append(this.test) .append(this.isSyntaxInputTest) .toHashCode(); } }
package org.yamcs.studio.product.utility; import org.eclipse.core.runtime.IExtension; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.ICoolBarManager; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.action.ToolBarContributionItem; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchCommandConstants; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction; import org.eclipse.ui.application.ActionBarAdvisor; import org.eclipse.ui.application.IActionBarConfigurer; import org.eclipse.ui.internal.OpenPreferencesAction; import org.eclipse.ui.internal.WorkbenchPlugin; import org.eclipse.ui.internal.registry.ActionSetRegistry; import org.eclipse.ui.internal.registry.IActionSetDescriptor; import org.eclipse.ui.part.CoolItemGroupMarker; import org.yamcs.studio.core.ui.ConnectionStringStatusLineContributionItem; import org.yamcs.studio.core.ui.MissionTimeStatusLineContributionItem; import org.yamcs.studio.core.ui.ProcessorStatusLineContributionItem; /** * Forked from org.csstudio.utility.product.ApplicationActionBarAdvisor * <p> * {@link ActionBarAdvisor} that can be called by CSS application startup code to create the menu * and tool bar. * <p> * The menu bar is mostly empty, only providing the "additions" section that is used by the * contributions in plugin.xml. * <p> * The toolbar also mostly defines sections used by contributions from plugin.xml. * <p> * Some actions are created for Eclipse command names in the help menu that have no default * implementation. */ @SuppressWarnings("restriction") public class YamcsStudioActionBarAdvisor extends ActionBarAdvisor { public static final String COOL_GROUP_PROCESSOR_INFO = "processorinfo"; public static final String COOL_GROUP_BOOKMARK_SHORTCUTS = "bookmarkshortcuts"; public static final String COOL_GROUP_PROCESSOR_CONTROLS = "processorcontrols"; private static final String TOOLBAR_USER = "user"; final private IWorkbenchWindow window; private IWorkbenchAction save; private IWorkbenchAction saveAll; private IWorkbenchAction resetPerspectiveAction; private IWorkbenchAction preferencesAction; private IWorkbenchAction helpContentsAction; private IWorkbenchAction onlineHelpAction; private IWorkbenchAction raiseIssueAction; private IWorkbenchAction aboutAction; public YamcsStudioActionBarAdvisor(IActionBarConfigurer configurer) { super(configurer); window = configurer.getWindowConfigurer().getWindow(); // Remove menu items that are not suitable in CS-Studio removeActionById("org.eclipse.ui.edit.text.actionSet.navigation"); removeActionById("org.eclipse.ui.edit.text.actionSet.convertLineDelimitersTo"); removeActionById("org.eclipse.ui.edit.text.actionSet.annotationNavigation"); // Redefined in our own plugin.xml for improved customization removeActionById("org.csstudio.opibuilder.actionSet"); } /** * Create actions. * <p> * Some of these actions are created to programmatically add them to the toolbar. Other actions * like save_as are not used at all in here, but they need to be created because the plugin.xml * registers their command ID in the menu bar, and the action actually implements the handler. * The actions also provide the dynamic enablement. */ @Override protected void makeActions(final IWorkbenchWindow window) { save = ActionFactory.SAVE.create(window); register(save); saveAll = ActionFactory.SAVE_ALL.create(window); register(saveAll); register(ActionFactory.SAVE_AS.create(window)); if (window.getWorkbench().getIntroManager().hasIntro()) register(ActionFactory.INTRO.create(window)); onlineHelpAction = new OnlineHelpAction(); register(onlineHelpAction); raiseIssueAction = new RaiseIssueAction(); register(raiseIssueAction); // Not using this, because we hide that default action id. CSS's advisor puts // it under Edit menu, which is quite confusing. // preferencesAction = ActionFactory.PREFERENCES.create(window); preferencesAction = (new ActionFactory("preferences-2", IWorkbenchCommandConstants.WINDOW_PREFERENCES) { @Override public IWorkbenchAction create(IWorkbenchWindow window) { if (window == null) throw new IllegalArgumentException(); IWorkbenchAction action = new OpenPreferencesAction(window); action.setId(getId()); return action; } }).create(window); register(preferencesAction); resetPerspectiveAction = ActionFactory.RESET_PERSPECTIVE.create(window); register(resetPerspectiveAction); helpContentsAction = ActionFactory.HELP_CONTENTS.create(window); register(helpContentsAction); aboutAction = ActionFactory.ABOUT.create(window); register(aboutAction); } @Override protected void fillMenuBar(final IMenuManager menubar) { menubar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); IMenuManager windowMenu = new MenuManager("Window", IWorkbenchActionConstants.M_WINDOW); menubar.add(windowMenu); windowMenu.add(resetPerspectiveAction); windowMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); windowMenu.add(new Separator()); windowMenu.add(preferencesAction); // plugin.xml in css menu.app defines a non-brandable icon. // through plugin.xml in this bundle, that help menu is hidden, and // we replace it here with another one (shorter) version IMenuManager helpMenu = new MenuManager("Help", "help-2"); menubar.add(helpMenu); helpMenu.add(onlineHelpAction); helpMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); helpMenu.add(new Separator()); helpMenu.add(raiseIssueAction); helpMenu.add(new Separator()); helpMenu.add(aboutAction); } @Override protected void fillCoolBar(ICoolBarManager coolbar) { ///coolbar.setLockLayout(true); // Specific to Yamcs Studio IToolBarManager studioBar = new ToolBarManager(); studioBar.add(new CoolItemGroupMarker(COOL_GROUP_PROCESSOR_INFO)); studioBar.add(new CoolItemGroupMarker(COOL_GROUP_BOOKMARK_SHORTCUTS)); studioBar.add(new CoolItemGroupMarker(COOL_GROUP_PROCESSOR_CONTROLS)); studioBar.add(new CoolItemGroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); coolbar.add(new ToolBarContributionItem(studioBar, "studiocoolbar")); // 'File' section of the cool bar IToolBarManager fileBar = new ToolBarManager(); // File 'new' and 'save' actions fileBar.add(ActionFactory.NEW.create(window)); fileBar.add(save); fileBar.add(saveAll); fileBar.add(new CoolItemGroupMarker(IWorkbenchActionConstants.FILE_END)); coolbar.add(new ToolBarContributionItem(fileBar, IWorkbenchActionConstants.M_FILE)); // 'User' section of the cool bar final IToolBarManager user_bar = new ToolBarManager(); coolbar.add(new ToolBarContributionItem(user_bar, TOOLBAR_USER)); // After a restart, merging of persisted model, PerspectiveSpacer, contributions resulted in re-arranged toolbar with E4. coolbar.add(new CoolItemGroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); coolbar.add(new CoolItemGroupMarker(IWorkbenchActionConstants.GROUP_EDITOR)); } @Override protected void fillStatusLine(IStatusLineManager statusLine) { statusLine.add(new ConnectionStringStatusLineContributionItem("ystudio.status.conn")); statusLine.add(new ProcessorStatusLineContributionItem("ystudio.status.processor")); statusLine.add(new MissionTimeStatusLineContributionItem("ystudio.status.missionTime", true)); } private void removeActionById(String actionSetId) { // Use of an internal API is required to remove actions that are provided // by including Eclipse bundles. ActionSetRegistry reg = WorkbenchPlugin.getDefault().getActionSetRegistry(); IActionSetDescriptor[] actionSets = reg.getActionSets(); for (int i = 0; i < actionSets.length; i++) { if (actionSets[i].getId().equals(actionSetId)) { IExtension ext = actionSets[i].getConfigurationElement().getDeclaringExtension(); reg.removeExtension(ext, new Object[] { actionSets[i] }); return; } } } }
package org.fundacionjala.automation.scenario.steps.admin.service; import org.fundacionjala.automation.framework.pages.admin.conferencerooms.ConferenceRoomsPage; import org.fundacionjala.automation.framework.pages.admin.emailserver.AddEmailServerPage; import org.fundacionjala.automation.framework.pages.admin.emailserver.EmailServerPage; import org.fundacionjala.automation.framework.pages.admin.login.LoginPage; import org.fundacionjala.automation.framework.utils.common.PropertiesReader; import org.testng.Assert; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.MongoClient; import cucumber.api.java.en.Then; public class ServiceThenSteps { @Then("^Service infomation is saved with description \"([^\"]*)\"$") public void service_infomation_is_saved_with_description( String myExpectedDescription) throws Throwable { EmailServerPage emailServer = new EmailServerPage(); emailServer .leftMenu .clickOnIssuesButton() .clickOnEmailServerButton(); String myActualDescription = emailServer .clickOnServerButton() .getEmailServerDescription(); Assert.assertEquals(myActualDescription, myExpectedDescription); } @Then("^The changes: user name \"([^\"]*)\" and password \"([^\"]*)\" are saved$") public void the_changes_user_name_and_password_are_saved( String newUserName, String newPassword) throws Throwable { EmailServerPage emailServer = new EmailServerPage(); String myActualUserName = emailServer.getUserName(); Assert.assertEquals(myActualUserName, newUserName); LoginPage login = new LoginPage(); EmailServerPage server = login .setUserName(PropertiesReader.getUserName()) .setPassword(PropertiesReader.getPassword()) .clickOnSigInButton().leftMenu.clickOnIssuesButton() .clickOnEmailServerButton(); server.clickOnServerButton().clickOnEditCredentialButton() .setUserName(PropertiesReader.getUserName()) .setPassword(PropertiesReader.getPassword()) .clickOnAcceptButton(true); } @Then("^An error message is displayed$") public void an_error_message_is_displayed() throws Throwable { String expectedErrorMessage = "Credentials don't have authorization, " + "please try with another"; EmailServerPage emailServer = new EmailServerPage(); String myActualErrorMessage = emailServer.getErrorMessage(); Assert.assertEquals(myActualErrorMessage, expectedErrorMessage); } @Then("^All Conference rooms are added from Exchange service$") public void all_Conference_rooms_are_added_from_Exchange_service() throws Throwable { EmailServerPage emailServer = new EmailServerPage(); ConferenceRoomsPage rooms; rooms = emailServer.leftMenu.clickOnIssuesButton() .clickOnConferenceRoomsButton(); Assert.assertEquals(rooms.verifyTotalItems(), 210); } @Then("^There is no rooms$") public void there_is_no_rooms() throws Throwable { EmailServerPage emailServer = new EmailServerPage(); boolean areConferenceRoomsPresent = emailServer.verifyIfThereAreRooms(); Assert.assertFalse(areConferenceRoomsPresent); LoginPage login = new LoginPage(); EmailServerPage server = login .setUserName(PropertiesReader.getUserName()) .setPassword(PropertiesReader.getPassword()) .clickOnSigInButton().leftMenu.clickOnIssuesButton() .clickOnEmailServerButton(); if (server.isAddButtonPresent()) { AddEmailServerPage addEmailServer = server.clickOnAddButton(); server = addEmailServer .setDomainServer(PropertiesReader.getExchangeHostname()) .setUserName(PropertiesReader.getExchangeConnectUserName()) .setPassword(PropertiesReader.getExchangeConnectPassword()) .clickSaveButton(); } } @Then("^Service information details are deleted$") public void service_information_details_are_deleted() throws Throwable { MongoClient mongoClient = new MongoClient( PropertiesReader.getHostIPAddress(), PropertiesReader.getMongoDBConnectionPort()); DB db = mongoClient.getDB(PropertiesReader.getDBName()); DBCollection table = db.getCollection(PropertiesReader .getServicesTableName()); DBCursor cursor = table.find(); long actualServiceSize = cursor.getCollection().count(); long expectedServiceSize = 0; Assert.assertEquals(actualServiceSize, expectedServiceSize); LoginPage login = new LoginPage(); EmailServerPage server = login .setUserName(PropertiesReader.getUserName()) .setPassword(PropertiesReader.getPassword()) .clickOnSigInButton().leftMenu.clickOnIssuesButton() .clickOnEmailServerButton(); if (server.isAddButtonPresent()) { AddEmailServerPage addEmailServer = server.clickOnAddButton(); server = addEmailServer .setDomainServer(PropertiesReader.getExchangeHostname()) .setUserName(PropertiesReader.getExchangeConnectUserName()) .setPassword(PropertiesReader.getExchangeConnectPassword()) .clickSaveButton(); } } @Then("^The meetings are deleted$") public void the_meetings_are_deleted() throws Throwable { MongoClient mongoClient = new MongoClient( PropertiesReader.getHostIPAddress(), PropertiesReader.getMongoDBConnectionPort()); DB db = mongoClient.getDB(PropertiesReader.getDBName()); DBCollection table = db.getCollection(PropertiesReader .getMongoDBMeetingTable()); DBCursor cursor = table.find(); long actualMeetingsSize = cursor.getCollection().count(); long expectedMeetingsSize = 0; Assert.assertEquals(actualMeetingsSize, expectedMeetingsSize); LoginPage login = new LoginPage(); EmailServerPage server = login .setUserName(PropertiesReader.getUserName()) .setPassword(PropertiesReader.getPassword()) .clickOnSigInButton().leftMenu.clickOnIssuesButton() .clickOnEmailServerButton(); if (server.isAddButtonPresent()) { AddEmailServerPage addEmailServer = server.clickOnAddButton(); server = addEmailServer .setDomainServer(PropertiesReader.getExchangeHostname()) .setUserName(PropertiesReader.getExchangeConnectUserName()) .setPassword(PropertiesReader.getExchangeConnectPassword()) .clickSaveButton(); } } @Then("^The out-of-orders are deleted$") public void the_out_of_orders_are_deleted() throws Throwable { MongoClient mongoClient = new MongoClient( PropertiesReader.getHostIPAddress(), PropertiesReader.getMongoDBConnectionPort()); DB db = mongoClient.getDB(PropertiesReader.getDBName()); DBCollection table = db.getCollection(PropertiesReader .getMongoDBOutOfOrderTable()); DBCursor cursor = table.find(); long actualOutOfOrdersSize = cursor.getCollection().count(); long expectedOutOfOrdersSize = 0; Assert.assertEquals(actualOutOfOrdersSize, expectedOutOfOrdersSize); LoginPage login = new LoginPage(); EmailServerPage server = login .setUserName(PropertiesReader.getUserName()) .setPassword(PropertiesReader.getPassword()) .clickOnSigInButton().leftMenu.clickOnIssuesButton() .clickOnEmailServerButton(); if (server.isAddButtonPresent()) { AddEmailServerPage addEmailServer = server.clickOnAddButton(); server = addEmailServer .setDomainServer(PropertiesReader.getExchangeHostname()) .setUserName(PropertiesReader.getExchangeConnectUserName()) .setPassword(PropertiesReader.getExchangeConnectPassword()) .clickSaveButton(); } } }
package com.arjinmc.recyclerviewdecoration; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.NinePatch; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PathEffect; import android.graphics.Rect; import android.support.annotation.ColorInt; import android.support.annotation.DrawableRes; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import java.util.regex.Pattern; public class RecyclerViewItemDecoration extends RecyclerView.ItemDecoration { /** * default decoration color */ private static final String DEFAULT_COLOR = "#bdbdbd"; /** * image resource id for R.java */ private int mDrawableRid = 0; /** * decoration color */ private int mColor = Color.parseColor(DEFAULT_COLOR); /** * decoration thickness */ private int mThickness; /** * decoration dash with */ private int mDashWidth = 0; /** * decoration dash gap */ private int mDashGap = 0; private boolean mFirstLineVisible; private boolean mLastLineVisible; private int mPaddingStart = 0; private int mPaddingEnd = 0; /** * border line for grid mode */ private boolean mGridLeftVisible; private boolean mGridRightVisible; private boolean mGridTopVisible; private boolean mGridBottomVisible; /** * spacing for grid mode */ public int mGridHorizontalSpacing; public int mGridVerticalSpacing; /** * direction mode for decoration */ private int mMode; private Paint mPaint; private Bitmap mBmp; private NinePatch mNinePatch; /** * choose the real thickness for image or thickness */ private int mCurrentThickness; /** * sign for if the resource image is a ninepatch image */ private boolean hasNinePatch = false; /** * sign for if has get the parent RecyclerView LayoutManager mode */ private boolean hasGetParentLayoutMode = false; private Context mContext; public RecyclerViewItemDecoration() { } public void setParams(Context context, Param params) { this.mContext = context; this.mDrawableRid = params.drawableRid; this.mColor = params.color; this.mThickness = params.thickness; this.mDashGap = params.dashGap; this.mDashWidth = params.dashWidth; this.mPaddingStart = params.paddingStart; this.mPaddingEnd = params.paddingEnd; this.mFirstLineVisible = params.firstLineVisible; this.mLastLineVisible = params.lastLineVisible; this.mGridLeftVisible = params.gridLeftVisible; this.mGridRightVisible = params.gridRightVisible; this.mGridTopVisible = params.gridTopVisible; this.mGridBottomVisible = params.gridBottomVisible; this.mGridHorizontalSpacing = params.gridHorizontalSpacing; this.mGridVerticalSpacing = params.gridVerticalSpacing; } private void initPaint(Context context) { this.mBmp = BitmapFactory.decodeResource(context.getResources(), mDrawableRid); if (mBmp != null) { if (mBmp.getNinePatchChunk() != null) { hasNinePatch = true; mNinePatch = new NinePatch(mBmp, mBmp.getNinePatchChunk(), null); } if (mMode == RVItemDecorationConst.MODE_HORIZONTAL) mCurrentThickness = mThickness == 0 ? mBmp.getHeight() : mThickness; if (mMode == RVItemDecorationConst.MODE_VERTICAL) mCurrentThickness = mThickness == 0 ? mBmp.getWidth() : mThickness; } mPaint = new Paint(); mPaint.setColor(mColor); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(mThickness); } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { if (parent.getChildCount() == 0) return; mPaint.setColor(mColor); if (mMode == RVItemDecorationConst.MODE_HORIZONTAL) { drawHorinzontal(c, parent); } else if (mMode == RVItemDecorationConst.MODE_VERTICAL) { drawVertical(c, parent); } else if (mMode == RVItemDecorationConst.MODE_GRID) { drawGrid(c, parent); } } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { if (!hasGetParentLayoutMode) { compatibleWithLayoutManager(parent); hasGetParentLayoutMode = true; } int viewPosition = parent.getChildLayoutPosition(view); if (mMode == RVItemDecorationConst.MODE_HORIZONTAL) { if (!(!mLastLineVisible && viewPosition == parent.getAdapter().getItemCount() - 1)) { if (mDrawableRid != 0) { outRect.set(0, 0, 0, mCurrentThickness); } else { outRect.set(0, 0, 0, mThickness); } } if (mFirstLineVisible && viewPosition == 0) { if (mDrawableRid != 0) { outRect.set(0, mCurrentThickness, 0, mCurrentThickness); } else { outRect.set(0, mThickness, 0, mThickness); } } } else if (mMode == RVItemDecorationConst.MODE_VERTICAL) { if (!(!mLastLineVisible && viewPosition == parent.getAdapter().getItemCount() - 1)) { if (mDrawableRid != 0) { outRect.set(0, 0, mCurrentThickness, 0); } else { outRect.set(0, 0, mThickness, 0); } } if (mFirstLineVisible && viewPosition == 0) { if (mDrawableRid != 0) { outRect.set(mCurrentThickness, 0, mCurrentThickness, 0); } else { outRect.set(mThickness, 0, mThickness, 0); } } } else if (mMode == RVItemDecorationConst.MODE_GRID) { int columnSize = ((GridLayoutManager) parent.getLayoutManager()).getSpanCount(); int itemSize = parent.getAdapter().getItemCount(); if (mDrawableRid != 0) { setGridOffsets(outRect, viewPosition, columnSize, itemSize, 0); } else { setGridOffsets(outRect, viewPosition, columnSize, itemSize, 1); } } } /** * judge is a color string like #xxxxxx or #xxxxxxxx * * @param colorStr * @return */ public static boolean isColorString(String colorStr) { return Pattern.matches("^#([0-9a-fA-F]{6}||[0-9a-fA-F]{8})$", colorStr); } private boolean isPureLine() { if (mDashGap == 0 && mDashWidth == 0) return true; return false; } /** * draw horizontal decoration * * @param c * @param parent */ private void drawHorinzontal(Canvas c, RecyclerView parent) { int childrenCount = parent.getChildCount(); if (mDrawableRid != 0) { if (mFirstLineVisible) { View childView = parent.getChildAt(0); int myY = childView.getTop(); if (hasNinePatch) { Rect rect = new Rect(mPaddingStart, myY - mCurrentThickness , parent.getWidth() - mPaddingEnd, myY); mNinePatch.draw(c, rect); } else { c.drawBitmap(mBmp, mPaddingStart, myY - mCurrentThickness, mPaint); } } for (int i = 0; i < childrenCount; i++) { if (!mLastLineVisible && i == childrenCount - 1) break; View childView = parent.getChildAt(i); int myY = childView.getBottom(); if (hasNinePatch) { Rect rect = new Rect(mPaddingStart, myY , parent.getWidth() - mPaddingEnd, myY + mCurrentThickness); mNinePatch.draw(c, rect); } else { c.drawBitmap(mBmp, mPaddingStart, myY, mPaint); } } } else { boolean isPureLine = isPureLine(); if (!isPureLine) { PathEffect effects = new DashPathEffect(new float[]{0, 0, mDashWidth, mThickness}, mDashGap); mPaint.setPathEffect(effects); } if (mFirstLineVisible) { View childView = parent.getChildAt(0); int myY = childView.getTop() - mThickness / 2; if (isPureLine) { c.drawLine(mPaddingStart, myY, parent.getWidth() - mPaddingEnd, myY, mPaint); } else { Path path = new Path(); path.moveTo(mPaddingStart, myY); path.lineTo(parent.getWidth() - mPaddingEnd, myY); c.drawPath(path, mPaint); } } for (int i = 0; i < childrenCount; i++) { if (!mLastLineVisible && i == childrenCount - 1) break; View childView = parent.getChildAt(i); int myY = childView.getBottom() + mThickness / 2; if (isPureLine) { c.drawLine(mPaddingStart, myY, parent.getWidth() - mPaddingEnd, myY, mPaint); } else { Path path = new Path(); path.moveTo(mPaddingStart, myY); path.lineTo(parent.getWidth() - mPaddingEnd, myY); c.drawPath(path, mPaint); } } } } /** * draw vertival decoration * * @param c * @param parent */ private void drawVertical(Canvas c, RecyclerView parent) { int childrenCount = parent.getChildCount(); if (mDrawableRid != 0) { if (mFirstLineVisible) { View childView = parent.getChildAt(0); int myX = childView.getLeft(); if (hasNinePatch) { Rect rect = new Rect(myX - mCurrentThickness, mPaddingStart , myX, parent.getHeight() - mPaddingEnd); mNinePatch.draw(c, rect); } else { c.drawBitmap(mBmp, myX - mCurrentThickness, mPaddingStart, mPaint); } } for (int i = 0; i < childrenCount; i++) { if (!mLastLineVisible && i == childrenCount - 1) break; View childView = parent.getChildAt(i); int myX = childView.getRight(); if (hasNinePatch) { Rect rect = new Rect(myX, mPaddingStart, myX + mCurrentThickness , parent.getHeight() - mPaddingEnd); mNinePatch.draw(c, rect); } else { c.drawBitmap(mBmp, myX, mPaddingStart, mPaint); } } } else { boolean isPureLine = isPureLine(); if (!isPureLine) { PathEffect effects = new DashPathEffect(new float[]{0, 0, mDashWidth, mThickness}, mDashGap); mPaint.setPathEffect(effects); } if (mFirstLineVisible) { View childView = parent.getChildAt(0); int myX = childView.getLeft() - mThickness / 2; if (isPureLine) { c.drawLine(myX, mPaddingStart, myX, parent.getHeight() - mPaddingEnd, mPaint); } else { Path path = new Path(); path.moveTo(myX, mPaddingStart); path.lineTo(myX, parent.getHeight() - mPaddingEnd); c.drawPath(path, mPaint); } } for (int i = 0; i < childrenCount; i++) { if (!mLastLineVisible && i == childrenCount - 1) break; View childView = parent.getChildAt(i); int myX = childView.getRight() + mThickness / 2; if (isPureLine) { c.drawLine(myX, mPaddingStart, myX, parent.getHeight() - mPaddingEnd, mPaint); } else { Path path = new Path(); path.moveTo(myX, mPaddingStart); path.lineTo(myX, parent.getHeight() - mPaddingEnd); c.drawPath(path, mPaint); } } } } /** * draw grid decoration * * @param c * @param parent */ private void drawGrid(Canvas c, RecyclerView parent) { int childrenCount = parent.getChildCount(); int columnSize = ((GridLayoutManager) parent.getLayoutManager()).getSpanCount(); int adapterChildrenCount = parent.getAdapter().getItemCount(); if (mDrawableRid != 0) { if (hasNinePatch) { for (int i = 0; i < childrenCount; i++) { View childView = parent.getChildAt(i); //horizontal if (mGridBottomVisible && isLastGridRow(i, adapterChildrenCount, columnSize)) { Rect rect = new Rect(0 , childView.getBottom() , childView.getRight() + mBmp.getHeight() , childView.getBottom() + mBmp.getHeight()); mNinePatch.draw(c, rect); } if (mGridTopVisible && isFirstGridRow(i, columnSize)) { Rect rect = new Rect(0 , 0 , childView.getRight() + mBmp.getWidth() , childView.getBottom() + mBmp.getHeight()); mNinePatch.draw(c, rect); } else if (!isLastGridRow(i, adapterChildrenCount, columnSize)) { Rect rect = new Rect( childView.getLeft() , childView.getBottom() , childView.getRight() , childView.getBottom() + mBmp.getHeight()); mNinePatch.draw(c, rect); } //vertical if (isLastGridRow(i, adapterChildrenCount, columnSize) && !isLastGridColumn(i, childrenCount, columnSize)) { Rect rect = new Rect( childView.getRight() , childView.getTop() , childView.getRight() + mBmp.getWidth() , childView.getBottom()); mNinePatch.draw(c, rect); } else if (!isLastGridColumn(i, childrenCount, columnSize)) { Rect rect = new Rect( childView.getRight() , childView.getTop() , childView.getRight() + mBmp.getWidth() , childView.getBottom() + mBmp.getHeight()); mNinePatch.draw(c, rect); } if (mGridLeftVisible && (isFirstGridColumn(i, columnSize) || isLastGridRow(i, adapterChildrenCount, columnSize))) { Rect rect = new Rect( childView.getLeft() - mBmp.getWidth() , childView.getTop() , childView.getRight() + mBmp.getWidth() , childView.getBottom() + mBmp.getHeight()); mNinePatch.draw(c, rect); } if (mGridRightVisible && isLastGridColumn(i, childrenCount, columnSize)) { Rect rect = new Rect( childView.getRight() , childView.getTop() - mBmp.getHeight() , childView.getRight() + mBmp.getWidth() , childView.getBottom() + mBmp.getHeight()); mNinePatch.draw(c, rect); } } } else { for (int i = 0; i < childrenCount; i++) { View childView = parent.getChildAt(i); int myX = childView.getRight(); int myY = childView.getBottom(); //horizontal if (mGridBottomVisible && isLastGridRow(i, adapterChildrenCount, columnSize)) { c.drawBitmap(mBmp, childView.getLeft(), myY, mPaint); } else if (!isLastGridRow(i, adapterChildrenCount, columnSize)) { c.drawBitmap(mBmp, childView.getLeft(), myY, mPaint); } if (mGridTopVisible && isFirstGridRow(i, columnSize)) { c.drawBitmap(mBmp, childView.getLeft(), childView.getTop() - mBmp.getHeight(), mPaint); } //vertical if (!isLastGridColumn(i, childrenCount, columnSize)) { c.drawBitmap(mBmp, myX, childView.getTop(), mPaint); } if (mGridLeftVisible && (isFirstGridColumn(i, columnSize) || isLastGridRow(i, adapterChildrenCount, columnSize))) { c.drawBitmap(mBmp, childView.getLeft() - mBmp.getWidth(), childView.getTop(), mPaint); } if (mGridRightVisible && isLastGridColumn(i, childrenCount, columnSize)) { c.drawBitmap(mBmp, childView.getRight(), childView.getTop(), mPaint); } } } } else if (mDashWidth == 0 && mDashGap == 0) { for (int i = 0; i < childrenCount; i++) { View childView = parent.getChildAt(i); int myL, myT, myR, myB; myR = childView.getRight(); myL = childView.getLeft(); myB = childView.getBottom(); myT = childView.getTop(); int viewPosition = parent.getChildLayoutPosition(childView); //when columnSize/spanCount is One if (columnSize == 1) { if (isFirstGridRow(viewPosition, columnSize)) { if (mGridLeftVisible) { mPaint.setStrokeWidth(mThickness); c.drawLine(myL - mThickness / 2 , myT , myL - mThickness / 2 , myB , mPaint); } if (mGridTopVisible) { mPaint.setStrokeWidth(mThickness); c.drawLine(myL - mThickness , myT - mThickness / 2 , myR + mThickness , myT - mThickness / 2 , mPaint); } if (mGridRightVisible) { mPaint.setStrokeWidth(mThickness); c.drawLine(myR + mThickness / 2 , myT , myR + mThickness / 2 , myB , mPaint); } //not first row } else { if (mGridLeftVisible) { mPaint.setStrokeWidth(mThickness); c.drawLine(myL - mThickness / 2 , myT - (mGridVerticalSpacing == 0 ? mThickness : mGridVerticalSpacing) , myL - mThickness / 2 , myB , mPaint); } if (mGridRightVisible) { mPaint.setStrokeWidth(mThickness); c.drawLine(myR + mThickness / 2 , myT , myR + mThickness / 2 , myB , mPaint); } } if (isLastGridRow(viewPosition, adapterChildrenCount, columnSize)) { if (mGridBottomVisible) { mPaint.setStrokeWidth(mThickness); c.drawLine(myL - mThickness , myB + mThickness / 2 , myR + mThickness , myB + mThickness / 2 , mPaint); } } else { mPaint.setStrokeWidth(mThickness); if (mGridVerticalSpacing != 0) { mPaint.setStrokeWidth(mGridVerticalSpacing); } c.drawLine(myL , myB + (mGridVerticalSpacing == 0 ? mThickness : mGridVerticalSpacing) / 2 , myR + mThickness , myB + (mGridVerticalSpacing == 0 ? mThickness : mGridVerticalSpacing) / 2 , mPaint); } //when columnSize/spanCount is Not One } else { if (isFirstGridColumn(viewPosition, columnSize) && isFirstGridRow(viewPosition, columnSize)) { if (mGridLeftVisible) { mPaint.setStrokeWidth(mThickness); c.drawLine(myL - mThickness / 2 , myT - mThickness , myL - mThickness / 2 , myB , mPaint); } if (mGridTopVisible) { mPaint.setStrokeWidth(mThickness); c.drawLine(myL , myT - mThickness / 2 , myR , myT - mThickness / 2 , mPaint); } if (adapterChildrenCount == 1) { if (mGridRightVisible) { mPaint.setStrokeWidth(mThickness); c.drawLine(myR + mThickness / 2 , myT - mThickness , myR + mThickness / 2 , myB , mPaint); } } else { if (mGridHorizontalSpacing != 0) { mPaint.setStrokeWidth(mGridHorizontalSpacing); } c.drawLine(myR + (mGridHorizontalSpacing == 0 ? mThickness : mGridHorizontalSpacing) / 2 , myT - mThickness , myR + (mGridHorizontalSpacing == 0 ? mThickness : mGridHorizontalSpacing) / 2 , myB , mPaint); } } else if (isFirstGridRow(viewPosition, columnSize)) { if (mGridTopVisible) { mPaint.setStrokeWidth(mThickness); c.drawLine(myL , myT - mThickness / 2 , myR , myT - mThickness / 2 , mPaint); } if (isLastGridColumn(viewPosition, adapterChildrenCount, columnSize)) { mPaint.setStrokeWidth(mThickness); if (mGridRightVisible) { c.drawLine(myR + mThickness / 2 , myT - mThickness , myR + mThickness / 2 , myB , mPaint); } } else { if (mGridHorizontalSpacing != 0) { mPaint.setStrokeWidth(mGridHorizontalSpacing); } c.drawLine(myR + (mGridHorizontalSpacing == 0 ? mThickness : mGridHorizontalSpacing) / 2 , myT - mThickness , myR + (mGridHorizontalSpacing == 0 ? mThickness : mGridHorizontalSpacing) / 2 , myB , mPaint); } } else if (isFirstGridColumn(viewPosition, columnSize)) { if (mGridLeftVisible) { mPaint.setStrokeWidth(mThickness); c.drawLine(myL - mThickness / 2 , myT , myL - mThickness / 2 , myB , mPaint); } mPaint.setStrokeWidth(mThickness); if (mGridHorizontalSpacing != 0) { mPaint.setStrokeWidth(mGridHorizontalSpacing); } c.drawLine(myR + (mGridHorizontalSpacing == 0 ? mThickness : mGridHorizontalSpacing) / 2 , myT , myR + (mGridHorizontalSpacing == 0 ? mThickness : mGridHorizontalSpacing) / 2 , myB , mPaint); } else { mPaint.setStrokeWidth(mThickness); if (isLastGridColumn(viewPosition, adapterChildrenCount, columnSize)) { if (mGridRightVisible) { c.drawLine(myR + mThickness / 2 , myT - (mGridVerticalSpacing == 0 ? mThickness : mGridVerticalSpacing) , myR + mThickness / 2 , myB , mPaint); } } else { if (mGridHorizontalSpacing != 0) { mPaint.setStrokeWidth(mGridHorizontalSpacing); } c.drawLine(myR + (mGridHorizontalSpacing == 0 ? mThickness : mGridHorizontalSpacing) / 2 , myT , myR + (mGridHorizontalSpacing == 0 ? mThickness : mGridHorizontalSpacing) / 2 , myB , mPaint); } } //bottom line if (isLastGridRow(viewPosition, adapterChildrenCount, columnSize)) { if (mGridBottomVisible) { mPaint.setStrokeWidth(mThickness); if (adapterChildrenCount == 1) { c.drawLine(myL - mThickness , myB + mThickness / 2 , myR + mThickness , myB + mThickness / 2 , mPaint); } else if (isLastGridColumn(viewPosition, adapterChildrenCount, columnSize)) { c.drawLine(myL - (mGridHorizontalSpacing == 0 ? mThickness : mGridHorizontalSpacing) , myB + mThickness / 2 , myR + mThickness , myB + mThickness / 2 , mPaint); } else { c.drawLine(myL - (mGridHorizontalSpacing == 0 ? mThickness : mGridHorizontalSpacing) , myB + mThickness / 2 , myR + (mGridHorizontalSpacing == 0 ? mThickness : mGridHorizontalSpacing) , myB + mThickness / 2 , mPaint); } } } else { mPaint.setStrokeWidth(mThickness); if (mGridVerticalSpacing != 0) { mPaint.setStrokeWidth(mGridVerticalSpacing); } c.drawLine(myL - (mGridHorizontalSpacing == 0 ? mThickness : mGridHorizontalSpacing) , myB + (mGridVerticalSpacing == 0 ? mThickness : mGridVerticalSpacing) / 2 , myR , myB + (mGridVerticalSpacing == 0 ? mThickness : mGridVerticalSpacing) / 2 , mPaint); } } } } else { PathEffect effects = new DashPathEffect(new float[]{0, 0, mDashWidth, mThickness}, mDashGap); mPaint.setPathEffect(effects); for (int i = 0; i < childrenCount; i++) { View childView = parent.getChildAt(i); int myT, myB, myL, myR; if (mGridHorizontalSpacing != 0) { myR = childView.getRight() + mGridHorizontalSpacing / 2; myL = childView.getLeft() - mGridHorizontalSpacing / 2; } else { myR = childView.getRight() + mThickness / 2; myL = childView.getLeft() - mThickness / 2; } if (mGridVerticalSpacing != 0) { myB = childView.getBottom() + mGridVerticalSpacing / 2; myT = childView.getTop() - mGridVerticalSpacing / 2; } else { myB = childView.getBottom() + mThickness / 2; myT = childView.getTop() - mThickness / 2; } int layoutPosition = parent.getChildLayoutPosition(childView); if (!isLastGridRow(layoutPosition, adapterChildrenCount, columnSize)) { if (mGridVerticalSpacing != 0) mPaint.setStrokeWidth(mGridVerticalSpacing); else mPaint.setStrokeWidth(mThickness); Path path = new Path(); path.moveTo(mThickness, myB); path.lineTo(childView.getRight(), myB); c.drawPath(path, mPaint); } if (!isFirstGridColumn(layoutPosition, columnSize)) { if (mGridHorizontalSpacing != 0) mPaint.setStrokeWidth(mGridHorizontalSpacing); else mPaint.setStrokeWidth(mThickness); if (isLastGridRow(layoutPosition, adapterChildrenCount, columnSize)) { Path path = new Path(); path.moveTo(myL, myT); if (mGridVerticalSpacing != 0) { path.lineTo(myL, myB - mGridVerticalSpacing / 2); } else { path.lineTo(myL, myB - mThickness / 2); } c.drawPath(path, mPaint); } else { Path path = new Path(); path.moveTo(myL, myT); path.lineTo(myL, myB); c.drawPath(path, mPaint); } } // if (adapterChildrenCount > columnSize && isLastItem(layoutPosition, adapterChildrenCount) // && !isLastGridColumn(layoutPosition, adapterChildrenCount, columnSize)) { // if (mGridHorizontalSpacing != 0) // mPaint.setStrokeWidth(mGridHorizontalSpacing); // else // mPaint.setStrokeWidth(mThickness); // Path path = new Path(); // path.moveTo(myR, myT); // path.lineTo(myR, myB); // c.drawPath(path, mPaint); if (mGridTopVisible && isFirstGridRow(layoutPosition, columnSize)) { mPaint.setStrokeWidth(mThickness); int tempT = childView.getTop() - mThickness / 2; Path path = new Path(); path.moveTo(childView.getLeft(), tempT); path.lineTo(childView.getRight(), tempT); c.drawPath(path, mPaint); } if (mGridBottomVisible && isLastGridRow(layoutPosition, adapterChildrenCount, columnSize)) { mPaint.setStrokeWidth(mThickness); int tempB = childView.getBottom() + mThickness / 2; Path path = new Path(); path.moveTo(mThickness, tempB); path.lineTo(childView.getRight(), tempB); c.drawPath(path, mPaint); } if (mGridLeftVisible && (isFirstGridColumn(layoutPosition, columnSize) || isLastGridRow(layoutPosition, adapterChildrenCount, columnSize))) { mPaint.setStrokeWidth(mThickness); int tempT = childView.getTop() - mThickness / 2; int tempB = childView.getBottom() + mThickness / 2; int tempL = childView.getLeft() - mThickness / 2; Path path = new Path(); path.moveTo(tempL, tempT); path.lineTo(tempL, tempB); c.drawPath(path, mPaint); } if (mGridRightVisible) { // if (isLastSecondGridRowNotDivided(layoutPosition, adapterChildrenCount, columnSize)) { // mPaint.setStrokeWidth(mThickness); // int tempT = childView.getTop() - mThickness / 2; // int tempB = childView.getBottom() + (mGridVerticalSpacing != 0 ? mGridVerticalSpacing : mThickness) / 2; // int tempR = childView.getRight() + mThickness / 2; // Path path = new Path(); // path.moveTo(tempR, tempT); // path.lineTo(tempR, tempB); // c.drawPath(path, mPaint); // } else if (isLastGridColumn(layoutPosition, adapterChildrenCount, columnSize)) { mPaint.setStrokeWidth(mThickness); int tempT = childView.getTop() - mThickness / 2; int tempB = childView.getBottom() + mThickness / 2; int tempR = childView.getRight() + mThickness / 2; Path path = new Path(); path.moveTo(tempR, tempT); path.lineTo(tempR, tempB); c.drawPath(path, mPaint); } } } } } /** * set offsets for grid mode * * @param outRect * @param viewPosition * @param columnSize * @param itemSize * @param tag 0 for drawable */ public void setGridOffsets(Rect outRect, int viewPosition, int columnSize , int itemSize, int tag) { int x; int y; int borderThickness = mThickness; if (tag == 0) { x = mBmp.getWidth(); y = mBmp.getHeight(); } else { if (mGridHorizontalSpacing != 0) x = mGridHorizontalSpacing; else x = mThickness; if (mGridVerticalSpacing != 0) y = mGridVerticalSpacing; else y = mThickness; } //when columnSize/spanCount is One if (columnSize == 1) { if (isFirstGridRow(viewPosition, columnSize)) { if (isLastGridRow(viewPosition, itemSize, columnSize)) { outRect.set((mGridLeftVisible ? borderThickness : 0) , (mGridTopVisible ? borderThickness : 0) , (mGridRightVisible ? borderThickness : 0) , (mGridBottomVisible ? borderThickness : y)); } else { outRect.set((mGridLeftVisible ? borderThickness : 0) , (mGridTopVisible ? borderThickness : 0) , (mGridRightVisible ? borderThickness : 0) , y); } } else { if (isLastGridRow(viewPosition, itemSize, columnSize)) { outRect.set((mGridLeftVisible ? borderThickness : 0) , 0 , (mGridRightVisible ? borderThickness : 0) , (mGridBottomVisible ? borderThickness : 0)); } else { outRect.set((mGridLeftVisible ? borderThickness : 0) , 0 , (mGridRightVisible ? borderThickness : 0) , y); } } } else { if (isFirstGridColumn(viewPosition, columnSize) && isFirstGridRow(viewPosition, columnSize)) { outRect.set((mGridLeftVisible ? borderThickness : 0) , (mGridTopVisible ? borderThickness : 0) , (itemSize == 1 ? borderThickness : x) , (isLastGridRow(viewPosition, itemSize, columnSize) ? borderThickness : y)); } else if (isFirstGridRow(viewPosition, columnSize)) { if (isLastGridColumn(viewPosition, itemSize, columnSize)) { outRect.set(0 , (mGridTopVisible ? borderThickness : 0) , (mGridRightVisible ? borderThickness : 0) , (isLastGridRow(viewPosition, itemSize, columnSize) ? borderThickness : y)); } else { outRect.set(0 , (mGridTopVisible ? borderThickness : 0) , x , (isLastGridRow(viewPosition, itemSize, columnSize) ? borderThickness : y)); } } else if (isFirstGridColumn(viewPosition, columnSize)) { outRect.set((mGridLeftVisible ? borderThickness : 0) , 0 , (isLastGridColumn(viewPosition, itemSize, columnSize) ? borderThickness : x) , (isLastGridRow(viewPosition, itemSize, columnSize) ? borderThickness : y)); } else { if (isLastGridColumn(viewPosition, itemSize, columnSize)) { outRect.set(0 , 0 , (mGridRightVisible ? borderThickness : 0) , (isLastGridRow(viewPosition, itemSize, columnSize) ? borderThickness : y)); } else { outRect.set(0 , 0 , x , (isLastGridRow(viewPosition, itemSize, columnSize) ? borderThickness : y)); } } } } /** * check if is one of the first columns * * @param position * @param columnSize * @return */ private boolean isFirstGridColumn(int position, int columnSize) { return position % columnSize == 0; } /** * check if is one of the last columns * * @param position * @param columnSize * @return */ private boolean isLastGridColumn(int position, int itemSize, int columnSize) { boolean isLast = false; if ((position + 1) % columnSize == 0) { isLast = true; } return isLast; } /** * check if is the first row of th grid * * @param position * @param columnSize * @return */ private boolean isFirstGridRow(int position, int columnSize) { return position < columnSize; } /** * check if is the last row of the grid * * @param position * @param itemSize * @param columnSize * @return */ private boolean isLastGridRow(int position, int itemSize, int columnSize) { int temp = itemSize % columnSize; if (temp == 0 && position >= itemSize - columnSize) { return true; } else if (position >= itemSize / columnSize * columnSize) { return true; } return false; } /** * compatible with recyclerview layoutmanager * * @param parent */ private void compatibleWithLayoutManager(RecyclerView parent) { if (parent.getLayoutManager() != null) { if (parent.getLayoutManager() instanceof GridLayoutManager) { mMode = RVItemDecorationConst.MODE_GRID; } else if (parent.getLayoutManager() instanceof LinearLayoutManager) { if (((LinearLayoutManager) parent.getLayoutManager()).getOrientation() == LinearLayout.HORIZONTAL) { mMode = RVItemDecorationConst.MODE_VERTICAL; } else { mMode = RVItemDecorationConst.MODE_HORIZONTAL; } } } else { mMode = RVItemDecorationConst.MODE_UNKNOWN; } initPaint(mContext); } public static class Builder { private Param params; private Context context; public Builder(Context context) { params = new Param(); this.context = context; } public RecyclerViewItemDecoration create() { RecyclerViewItemDecoration recyclerViewItemDecoration = new RecyclerViewItemDecoration(); recyclerViewItemDecoration.setParams(context, params); return recyclerViewItemDecoration; } public Builder drawableID(@DrawableRes int drawableID) { params.drawableRid = drawableID; return this; } public Builder color(@ColorInt int color) { params.color = color; return this; } public Builder color(String color) { if (isColorString(color)) { params.color = Color.parseColor(color); } return this; } public Builder thickness(int thickness) { params.thickness = thickness; return this; } public Builder dashWidth(int dashWidth) { params.dashWidth = dashWidth; return this; } public Builder dashGap(int dashGap) { params.dashGap = dashGap; return this; } public Builder lastLineVisible(boolean visible) { params.lastLineVisible = visible; return this; } public Builder firstLineVisible(boolean visible) { params.firstLineVisible = visible; return this; } public Builder paddingStart(int padding) { params.paddingStart = padding; return this; } public Builder paddingEnd(int padding) { params.paddingEnd = padding; return this; } public Builder gridLeftVisible(boolean visible) { params.gridLeftVisible = visible; return this; } public Builder gridRightVisible(boolean visible) { params.gridRightVisible = visible; return this; } public Builder gridTopVisible(boolean visible) { params.gridTopVisible = visible; return this; } public Builder gridBottomVisible(boolean visible) { params.gridBottomVisible = visible; return this; } public Builder gridHorizontalSpacing(int spacing) { params.gridHorizontalSpacing = spacing; return this; } public Builder gridVerticalSpacing(int spacing) { params.gridVerticalSpacing = spacing; return this; } } private static class Param { public int drawableRid = 0; public int color = Color.parseColor(DEFAULT_COLOR); public int thickness; public int dashWidth = 0; public int dashGap = 0; public boolean lastLineVisible; public boolean firstLineVisible; public int paddingStart; public int paddingEnd; public boolean gridLeftVisible; public boolean gridRightVisible; public boolean gridTopVisible; public boolean gridBottomVisible; public int gridHorizontalSpacing; public int gridVerticalSpacing; } }
package org.eclipse.birt.report.designer.ui.cubebuilder.dialog; import java.util.ArrayList; import java.util.List; import org.eclipse.birt.report.designer.core.commands.DeleteCommand; import org.eclipse.birt.report.designer.internal.ui.dialogs.helper.IDialogHelper; import org.eclipse.birt.report.designer.internal.ui.dialogs.helper.IDialogHelperProvider; import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.internal.ui.util.WidgetUtil; import org.eclipse.birt.report.designer.ui.cubebuilder.nls.Messages; import org.eclipse.birt.report.designer.ui.cubebuilder.provider.CubeExpressionProvider; import org.eclipse.birt.report.designer.ui.cubebuilder.util.BuilderConstants; import org.eclipse.birt.report.designer.ui.cubebuilder.util.OlapUtil; import org.eclipse.birt.report.designer.ui.cubebuilder.util.UIHelper; import org.eclipse.birt.report.designer.ui.newelement.DesignElementFactory; import org.eclipse.birt.report.designer.ui.util.ExceptionUtil; import org.eclipse.birt.report.designer.ui.views.ElementAdapterManager; import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.Expression; import org.eclipse.birt.report.model.api.ResultSetColumnHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.command.NameException; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.metadata.IChoice; import org.eclipse.birt.report.model.api.olap.DimensionHandle; import org.eclipse.birt.report.model.api.olap.HierarchyHandle; import org.eclipse.birt.report.model.api.olap.LevelHandle; import org.eclipse.birt.report.model.api.olap.TabularCubeHandle; import org.eclipse.birt.report.model.api.olap.TabularHierarchyHandle; import org.eclipse.birt.report.model.api.olap.TabularLevelHandle; import org.eclipse.birt.report.model.elements.interfaces.IHierarchyModel; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTreeViewer; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.TreeItem; public class GroupDialog extends TitleAreaDialog { private boolean isNew; public GroupDialog( boolean isNew ) { super( UIUtil.getDefaultShell( ) ); setShellStyle( getShellStyle( ) | SWT.RESIZE | SWT.MAX ); this.isNew = isNew; } private ResultSetColumnHandle dataField; private TabularHierarchyHandle hierarchy; private IDialogHelper helper; private List levelList = new ArrayList( ); public void setInput( TabularHierarchyHandle hierarchy, ResultSetColumnHandle dataField ) { dimension = (DimensionHandle) hierarchy.getContainer( ); this.dataField = dataField; this.hierarchy = hierarchy; TabularLevelHandle[] levels = (TabularLevelHandle[]) hierarchy.getContents( IHierarchyModel.LEVELS_PROP ) .toArray( new TabularLevelHandle[0] ); for ( int i = 0; i < levels.length; i++ ) { if ( levels[i].getDateTimeLevelType( ) != null ) levelList.add( levels[i].getDateTimeLevelType( ) ); } dateTypeSelectedList.addAll( levelList ); } protected Control createDialogArea( Composite parent ) { UIUtil.bindHelp( parent, IHelpContextIds.CUBE_BUILDER_GROUP_DIALOG ); setTitle( Messages.getString( "DateGroupDialog.Title" ) ); //$NON-NLS-1$ getShell( ).setText( Messages.getString( "DateGroupDialog.Shell.Title" ) ); //$NON-NLS-1$ setMessage( Messages.getString( "DateGroupDialog.Message" ) ); //$NON-NLS-1$ Composite area = (Composite) super.createDialogArea( parent ); Composite contents = new Composite( area, SWT.NONE ); GridLayout layout = new GridLayout( ); layout.marginWidth = 20; contents.setLayout( layout ); GridData data = new GridData( GridData.FILL_BOTH ); data.widthHint = convertWidthInCharsToPixels( 80 ); data.heightHint = 300; contents.setLayoutData( data ); createGroupTypeArea( contents ); createContentArea( contents ); WidgetUtil.createGridPlaceholder( contents, 1, true ); initDialog( ); parent.layout( ); return contents; } private void createGroupTypeArea( Composite contents ) { regularButton = new Button( contents, SWT.RADIO ); regularButton.setText( Messages.getString( "GroupDialog.Button.RegularGroup" ) ); //$NON-NLS-1$ regularButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { handleButtonSelection( regularButton ); } } ); dateButton = new Button( contents, SWT.RADIO ); dateButton.setText( Messages.getString( "GroupDialog.Button.DateGroup" ) ); //$NON-NLS-1$ dateButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { handleButtonSelection( dateButton ); } } ); } protected void handleButtonSelection( Button button ) { if ( button == regularButton ) { regularButton.setSelection( true ); dateButton.setSelection( false ); WidgetUtil.setExcludeGridData( levelViewer.getTree( ), true ); setMessage( "" ); //$NON-NLS-1$ isRegularButton = true; } else { regularButton.setSelection( false ); dateButton.setSelection( true ); if ( dataField != null ) { WidgetUtil.setExcludeGridData( levelViewer.getTree( ), false ); setMessage( Messages.getString( "DateGroupDialog.Message" ) ); //$NON-NLS-1$ } else { WidgetUtil.setExcludeGridData( levelViewer.getTree( ), true ); setMessage( "" ); //$NON-NLS-1$ } isRegularButton = false; } levelViewer.getTree( ).getParent( ).layout( ); checkOKButtonStatus( ); } private void initDialog( ) { nameText.setText( hierarchy.getContainer( ).getName( ) ); if ( !isNew ) { if ( ( (DimensionHandle) hierarchy.getContainer( ) ).isTimeType( ) ) { dateButton.setSelection( true ); handleButtonSelection( dateButton ); } else { regularButton.setSelection( true ); handleButtonSelection( regularButton ); } } else { dateButton.setSelection( true ); handleButtonSelection( dateButton ); } if ( !isNew ) { WidgetUtil.setExcludeGridData( regularButton, true ); WidgetUtil.setExcludeGridData( dateButton, true ); } if ( !isNew && !( (DimensionHandle) hierarchy.getContainer( ) ).isTimeType( ) ) levelViewer.getTree( ).setVisible( false ); levelViewer.setInput( getDateTypeNames( getLevelTypesByDateType( ) ) ); levelViewer.expandAll( ); if ( levelViewer.getTree( ).getItemCount( ) > 0 ) { TreeItem topNode = levelViewer.getTree( ).getItem( 0 ); do { if ( levelList.contains( topNode.getData( ) ) ) topNode.setChecked( true ); topNode = topNode.getItem( 0 ); } while ( topNode.getItemCount( ) > 0 ); if ( levelList.contains( topNode.getData( ) ) ) topNode.setChecked( true ); } checkOKButtonStatus( ); } private TreeItem getItem( String text ) { TreeItem topNode = levelViewer.getTree( ).getItem( 0 ); do { if ( text.equals( topNode.getData( ) ) ) return topNode; topNode = topNode.getItem( 0 ); } while ( topNode.getItemCount( ) > 0 ); if ( text.equals( topNode.getData( ) ) ) return topNode; else return null; } private List getDateTypeNames( IChoice[] choices ) { List dateTypeList = new ArrayList( ); if ( choices == null ) return dateTypeList; for ( int i = 0; i < choices.length; i++ ) { dateTypeList.add( choices[i].getName( ) ); } return dateTypeList; } private String getDateTypeDisplayName( String name ) { return ChoiceSetFactory.getDisplayNameFromChoiceSet( name, OlapUtil.getDateTimeLevelTypeChoiceSet( ) ); } class DateLevelProvider extends LabelProvider implements ITreeContentProvider { public Object[] getChildren( Object parentElement ) { int index = getDateTypeNames( getLevelTypesByDateType( ) ).indexOf( parentElement ); return new Object[]{ getDateTypeNames( getLevelTypesByDateType( ) ).get( index + 1 ) }; } public Object getParent( Object element ) { int index = getDateTypeNames( getLevelTypesByDateType( ) ).indexOf( element ); if ( index == 0 ) return null; else return getDateTypeNames( getLevelTypesByDateType( ) ).get( index - 1 ); } public boolean hasChildren( Object element ) { int index = getDateTypeNames( getLevelTypesByDateType( ) ).indexOf( element ); if ( index >= getDateTypeNames( getLevelTypesByDateType( ) ).size( ) - 1 ) return false; return true; } public Object[] getElements( Object inputElement ) { if ( getLevelTypesByDateType( ) != null && getLevelTypesByDateType( ).length > 0 ) return new Object[]{ getDateTypeNames( getLevelTypesByDateType( ) ).get( 0 ) }; return new Object[0]; } public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { // TODO Auto-generated method stub } public Image getImage( Object element ) { return UIHelper.getImage( BuilderConstants.IMAGE_LEVEL ); } public String getText( Object element ) { return getDateTypeDisplayName( element.toString( ) ); } } protected void okPressed( ) { try { dimension.setName( nameText.getText( ).trim( ) ); } catch ( NameException e1 ) { ExceptionUtil.handle( e1 ); } if ( helper != null ) { try { helper.validate( ); dimension.setExpressionProperty( DimensionHandle.ACL_EXPRESSION_PROP, (Expression) helper.getProperty( BuilderConstants.SECURITY_EXPRESSION_PROPERTY ) ); } catch ( SemanticException e ) { ExceptionUtil.handle( e ); } } if ( regularButton.getSelection( ) ) { try { if ( ( (DimensionHandle) hierarchy.getContainer( ) ).isTimeType( ) ) { while ( hierarchy.getContentCount( IHierarchyModel.LEVELS_PROP ) > 0 ) { hierarchy.dropAndClear( IHierarchyModel.LEVELS_PROP, 0 ); } } ( (DimensionHandle) hierarchy.getContainer( ) ).setTimeType( false ); if ( isNew ) { TabularLevelHandle level = DesignElementFactory.getInstance( ) .newTabularLevel( (DimensionHandle) hierarchy.getContainer( ), OlapUtil.getDataFieldDisplayName( dataField ) ); level.setColumnName( dataField.getColumnName( ) ); DataSetHandle dataset = hierarchy.getDataSet( ); if ( dataset == null ) { dataset = ( (TabularCubeHandle) hierarchy.getContainer( ) .getContainer( ) ).getDataSet( ); } level.setDataType( dataField.getDataType( ) ); hierarchy.add( IHierarchyModel.LEVELS_PROP, level ); } } catch ( SemanticException e ) { ExceptionUtil.handle( e ); return; } } else { try { if ( !( (DimensionHandle) hierarchy.getContainer( ) ).isTimeType( ) ) { while ( hierarchy.getContentCount( IHierarchyModel.LEVELS_PROP ) > 0 ) { hierarchy.dropAndClear( IHierarchyModel.LEVELS_PROP, 0 ); } } ( (DimensionHandle) hierarchy.getContainer( ) ).setTimeType( true ); } catch ( SemanticException e ) { ExceptionUtil.handle( e ); } // remove unused level if ( levelList.size( ) > 0 ) { for ( int i = 0; i < OlapUtil.getDateTimeLevelTypeChoices( ).length; i++ ) { String dateType = OlapUtil.getDateTimeLevelTypeChoices( )[i].getName( ); if ( levelList.contains( dateType ) && !dateTypeSelectedList.contains( dateType ) ) { LevelHandle level = hierarchy.getLevel( levelList.indexOf( dateType ) ); boolean hasExecuted = OlapUtil.enableDrop( level ); if ( hasExecuted ) { new DeleteCommand( level ).execute( ); levelList.remove( dateType ); } } } } // New if ( levelList.size( ) == 0 ) { sortDataType( ); for ( int i = 0; i < dateTypeSelectedList.size( ); i++ ) { String dateType = (String) dateTypeSelectedList.get( i ); TabularLevelHandle level = DesignElementFactory.getInstance( ) .newTabularLevel( (DimensionHandle) hierarchy.getContainer( ), getDateTypeDisplayName( dateType ) ); try { hierarchy.add( HierarchyHandle.LEVELS_PROP, level ); level.setColumnName( dataField.getColumnName( ) ); level.setDataType( DesignChoiceConstants.COLUMN_DATA_TYPE_INTEGER ); level.setDateTimeLevelType( dateType ); } catch ( SemanticException e ) { ExceptionUtil.handle( e ); } } } // Edit else { int j = 0; sortDataType( ); for ( int i = 0; i < dateTypeSelectedList.size( ); i++ ) { String dateType = (String) dateTypeSelectedList.get( i ); if ( !levelList.contains( dateType ) ) { boolean exit = false; // in the old level list: month in (year,day) for ( ; j < levelList.size( ); j++ ) { if ( getDateTypeNames( getLevelTypesByDateType( ) ).indexOf( dateType ) < getDateTypeNames( getLevelTypesByDateType( ) ).indexOf( levelList.get( j ) ) ) { TabularLevelHandle level = DesignElementFactory.getInstance( ) .newTabularLevel( (DimensionHandle) hierarchy.getContainer( ), getDateTypeDisplayName( dateType ) ); try { hierarchy.add( HierarchyHandle.LEVELS_PROP, level, j ); level.setColumnName( dataField.getColumnName( ) ); level.setDataType( DesignChoiceConstants.COLUMN_DATA_TYPE_INTEGER ); level.setDateTimeLevelType( dateType ); levelList.add( j, dateType ); exit = true; break; } catch ( SemanticException e ) { ExceptionUtil.handle( e ); } } } if ( exit ) continue; // out of old level list:month out (year,quarter) TabularLevelHandle level = DesignElementFactory.getInstance( ) .newTabularLevel( (DimensionHandle) hierarchy.getContainer( ), getDateTypeDisplayName( dateType ) ); try { hierarchy.add( HierarchyHandle.LEVELS_PROP, level ); level.setColumnName( dataField.getColumnName( ) ); level.setDataType( DesignChoiceConstants.COLUMN_DATA_TYPE_INTEGER ); level.setDateTimeLevelType( dateType ); levelList.add( j++, dateType ); } catch ( SemanticException e ) { ExceptionUtil.handle( e ); } } } } } super.okPressed( ); } private void sortDataType( ) { List list = new ArrayList( ); List typeNames = getDateTypeNames( getLevelTypesByDateType( ) ); for ( int i = 0; i < typeNames.size( ); i++ ) { Object typeName = typeNames.get( i ); for ( int j = 0; j < dateTypeSelectedList.size( ); j++ ) { if ( dateTypeSelectedList.get( j ).equals( typeName ) ) { list.add( typeName ); break; } } } dateTypeSelectedList.clear( ); dateTypeSelectedList.addAll( list ); } private List dateTypeSelectedList = new ArrayList( ); private Text nameText; private CheckboxTreeViewer levelViewer; private Button regularButton; private Button dateButton; private boolean isRegularButton = false; private DimensionHandle dimension; private void createContentArea( Composite parent ) { Composite content = new Composite( parent, SWT.NONE ); content.setLayoutData( new GridData( GridData.FILL_BOTH ) ); GridLayout layout = new GridLayout( ); layout.numColumns = 3; content.setLayout( layout ); Composite nameContainer = new Composite( content, SWT.NONE ); layout = new GridLayout( ); layout.numColumns = 2; layout.marginWidth = layout.marginHeight = 0; nameContainer.setLayout( layout ); GridData gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalSpan = 3; nameContainer.setLayoutData( gd ); new Label( nameContainer, SWT.NONE ).setText( Messages.getString( "DateGroupDialog.Name" ) ); //$NON-NLS-1$ nameText = new Text( nameContainer, SWT.BORDER ); gd = new GridData( GridData.FILL_HORIZONTAL ); nameText.setLayoutData( gd ); nameText.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { checkOKButtonStatus( ); } } ); levelViewer = new CheckboxTreeViewer( content, SWT.SINGLE | SWT.BORDER ); gd = new GridData( GridData.FILL_BOTH ); gd.horizontalSpan = 3; levelViewer.getTree( ).setLayoutData( gd ); DateLevelProvider provider = new DateLevelProvider( ); levelViewer.setContentProvider( provider ); levelViewer.setLabelProvider( provider ); /** * The two listener behaviors are so special behaviors, because they are * used to fix the bug 205934 */ levelViewer.addCheckStateListener( new ICheckStateListener( ) { public void checkStateChanged( CheckStateChangedEvent event ) { String itemText = (String) event.getElement( ); TreeItem item = getItem( itemText ); checkItem( item ); } } ); levelViewer.getTree( ).addMouseListener( new MouseAdapter( ) { public void mouseDown( MouseEvent e ) { TreeItem item = levelViewer.getTree( ).getItem( new Point( e.x, e.y ) ); checkItem( item ); } } ); levelViewer.getTree( ).addKeyListener( new KeyAdapter( ) { public void keyPressed( KeyEvent e ) { if ( e.character == ' ' ) { TreeItem[] item = levelViewer.getTree( ).getSelection( ); if ( item != null && item.length == 1 ) checkItem( item[0] ); } } } ); createSecurityPart( content ); } private void createSecurityPart( Composite parent ) { Object[] helperProviders = ElementAdapterManager.getAdapters( dimension, IDialogHelperProvider.class ); if ( helperProviders != null ) { for ( int i = 0; i < helperProviders.length; i++ ) { IDialogHelperProvider helperProvider = (IDialogHelperProvider) helperProviders[i]; if ( helperProvider != null && helper == null ) { helper = helperProvider.createHelper( this, BuilderConstants.SECURITY_HELPER_KEY ); if ( helper != null ) { helper.setProperty( BuilderConstants.SECURITY_EXPRESSION_LABEL, Messages.getString( "GroupDialog.Access.Control.List.Expression" ) ); //$NON-NLS-1$ helper.setProperty( BuilderConstants.SECURITY_EXPRESSION_CONTEXT, dimension ); helper.setProperty( BuilderConstants.SECURITY_EXPRESSION_PROVIDER, new CubeExpressionProvider( dimension ) ); helper.setProperty( BuilderConstants.SECURITY_EXPRESSION_PROPERTY, dimension.getACLExpression( ) ); helper.createContent( parent ); helper.addListener( SWT.Modify, new Listener( ) { public void handleEvent( Event event ) { helper.update( false ); } } ); helper.update( true ); } } } } } protected void checkOKButtonStatus( ) { if ( nameText.getText( ).trim( ).length( ) == 0 ) { if ( getButton( IDialogConstants.OK_ID ) != null ) getButton( IDialogConstants.OK_ID ).setEnabled( false ); setMessage( null ); setErrorMessage( Messages.getString( "DateGroupDialog.Message.BlankName" ) ); //$NON-NLS-1$ } else if ( !UIUtil.validateDimensionName( nameText.getText( ) ) ) { if ( getButton( IDialogConstants.OK_ID ) != null ) getButton( IDialogConstants.OK_ID ).setEnabled( false ); setMessage( null ); setErrorMessage( Messages.getString( "DateGroupDialog.Message.NumericName" ) ); //$NON-NLS-1$ } else { if ( dateButton.getSelection( ) && dateTypeSelectedList.size( ) == 0 && ( isNew || dataField != null ) ) { if ( getButton( IDialogConstants.OK_ID ) != null ) getButton( IDialogConstants.OK_ID ).setEnabled( false ); setErrorMessage( null ); setMessage( Messages.getString( "DateGroupDialog.Message" ) ); //$NON-NLS-1$ } else if ( getButton( IDialogConstants.OK_ID ) != null ) { getButton( IDialogConstants.OK_ID ).setEnabled( true ); if ( isRegularButton ) { setErrorMessage( null ); setMessage( Messages.getString( "DateGroupDialog.Message.Regular" ) ); //$NON-NLS-1$ } else { setErrorMessage( null ); setMessage( Messages.getString( "DateGroupDialog.Message" ) ); //$NON-NLS-1$ } } } } protected void createButtonsForButtonBar( Composite parent ) { super.createButtonsForButtonBar( parent ); checkOKButtonStatus( ); } public void setInput( TabularHierarchyHandle hierarchy ) { if ( hierarchy.getLevelCount( ) == 0 ) setInput( hierarchy, null ); else { if ( !isDateType( hierarchy, ( (TabularLevelHandle) hierarchy.getLevel( 0 ) ).getColumnName( ) ) ) setInput( hierarchy, null ); else { DataSetHandle dataset = hierarchy.getDataSet( ); if ( dataset == null ) { dataset = ( (TabularCubeHandle) hierarchy.getContainer( ) .getContainer( ) ).getDataSet( ); } setInput( hierarchy, OlapUtil.getDataField( dataset, ( (TabularLevelHandle) hierarchy.getLevel( 0 ) ).getColumnName( ) ) ); } } } private IChoice[] getLevelTypesByDateType( ) { if ( hierarchy == null || dataField == null ) return null; String dataType = dataField.getDataType( ); if ( dataType.equals( DesignChoiceConstants.COLUMN_DATA_TYPE_DATETIME ) ) return OlapUtil.getDateTimeLevelTypeChoices( ); else if ( dataType.equals( DesignChoiceConstants.COLUMN_DATA_TYPE_DATE ) ) return OlapUtil.getDateLevelTypeChoices( ); else return OlapUtil.getTimeLevelTypeChoices( ); } private boolean isDateType( TabularHierarchyHandle hierarchy, String columnName ) { ResultSetColumnHandle column = OlapUtil.getDataField( OlapUtil.getHierarchyDataset( hierarchy ), columnName ); if ( column == null ) return false; String dataType = column.getDataType( ); return dataType.equals( DesignChoiceConstants.COLUMN_DATA_TYPE_DATETIME ) || dataType.equals( DesignChoiceConstants.COLUMN_DATA_TYPE_DATE ) || dataType.equals( DesignChoiceConstants.COLUMN_DATA_TYPE_TIME ); } private void checkItem( TreeItem item ) { if ( item != null ) { item.setChecked( !item.getChecked( ) ); levelViewer.getTree( ).setSelection( item ); if ( item.getChecked( ) ) { if ( !dateTypeSelectedList.contains( item.getData( ) ) ) { dateTypeSelectedList.add( item.getData( ) ); } } else { if ( dateTypeSelectedList.contains( item.getData( ) ) ) dateTypeSelectedList.remove( item.getData( ) ); } checkOKButtonStatus( ); } } }
package gov.nih.nci.caintegrator2.application.study.deployment; import gov.nih.nci.caintegrator2.application.arraydata.ArrayDataService; import gov.nih.nci.caintegrator2.application.arraydata.ArrayDataValues; import gov.nih.nci.caintegrator2.application.arraydata.PlatformHelper; import gov.nih.nci.caintegrator2.application.study.GenomicDataSourceConfiguration; import gov.nih.nci.caintegrator2.application.study.ValidationException; import gov.nih.nci.caintegrator2.common.Cai2Util; import gov.nih.nci.caintegrator2.data.CaIntegrator2Dao; import gov.nih.nci.caintegrator2.domain.genomic.AbstractReporter; import gov.nih.nci.caintegrator2.domain.genomic.ArrayData; import gov.nih.nci.caintegrator2.domain.genomic.ReporterList; import gov.nih.nci.caintegrator2.domain.genomic.Sample; import gov.nih.nci.caintegrator2.external.ConnectionException; import gov.nih.nci.caintegrator2.external.DataRetrievalException; import gov.nih.nci.caintegrator2.external.caarray.CaArrayFacade; import gov.nih.nci.caintegrator2.external.caarray.GenericMultiSamplePerFileParser; import gov.nih.nci.caintegrator2.external.caarray.SupplementalDataFile; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * Reads and retrieves copy number data from a caArray instance. */ @Transactional (propagation = Propagation.REQUIRED) class GenericSupplementalMultiSamplePerFileHandler extends AbstractGenericSupplementalMappingFileHandler { private final List<Sample> samples = new ArrayList<Sample>(); private final Map<String, SupplementalDataFile> supplementalDataFiles = new HashMap<String, SupplementalDataFile>(); private final Map<String, File> dataFiles = new HashMap<String, File>(); private static final Logger LOGGER = Logger.getLogger(GenericSupplementalMultiSamplePerFileHandler.class); private static final int ONE_THOUSAND = 1000; GenericSupplementalMultiSamplePerFileHandler(GenomicDataSourceConfiguration genomicSource, CaArrayFacade caArrayFacade, ArrayDataService arrayDataService, CaIntegrator2Dao dao) { super(genomicSource, caArrayFacade, arrayDataService, dao); } void mappingSample(String subjectIdentifier, String sampleName, SupplementalDataFile supplementalDataFile) throws FileNotFoundException, ValidationException, ConnectionException, DataRetrievalException { samples.add(getSample(sampleName, subjectIdentifier)); if (!supplementalDataFiles.containsKey(supplementalDataFile.getFileName())) { supplementalDataFiles.put(supplementalDataFile.getFileName(), supplementalDataFile); dataFiles.put(supplementalDataFile.getFileName(), getDataFile(supplementalDataFile.getFileName())); } } List<ArrayDataValues> loadArrayDataValue() throws DataRetrievalException { PlatformHelper platformHelper = new PlatformHelper(getDao().getPlatform( getGenomicSource().getPlatformName())); Set<ReporterList> reporterLists = platformHelper.getReporterLists(getReporterType()); return createArrayDataByBucket(platformHelper, reporterLists); } private List<ArrayDataValues> createArrayDataByBucket(PlatformHelper platformHelper, Set<ReporterList> reporterLists) throws DataRetrievalException { List<ArrayDataValues> arrayDataValuesList = new ArrayList<ArrayDataValues>(); for (List<String> sampleBucket : createSampleBuckets(reporterLists, getSampleList())) { Map<String, Map<String, List<Float>>> dataMap = extractData(sampleBucket); loadArrayData(arrayDataValuesList, platformHelper, reporterLists, dataMap); } return arrayDataValuesList; } private List<List<String>> createSampleBuckets(Set<ReporterList> reporterLists, List<String> sampleList) { List<List<String>> sampleBuckets = new ArrayList<List<String>>(); long sampleBucketSize = computeBucketSize(reporterLists); int sampleCount = 0; List<String> sampleBucket = new ArrayList<String>(); for (String sample : sampleList) { if (sampleCount++ % sampleBucketSize == 0) { sampleBucket = new ArrayList<String>(); sampleBuckets.add(sampleBucket); } sampleBucket.add(sample); } return sampleBuckets; } private long computeBucketSize(Set<ReporterList> reporterLists) { int numReporters = 0; for (ReporterList reporterList : reporterLists) { numReporters += reporterList.getReporters().size(); } return (ONE_THOUSAND * Cai2Util.getHeapSizeMB()) / numReporters; } private Map<String, Map<String, List<Float>>> extractData(List<String> mappedSampleBucket) throws DataRetrievalException { Map<String, Map<String, List<Float>>> dataMap = new HashMap<String, Map<String, List<Float>>>(); for (SupplementalDataFile dataFile : supplementalDataFiles.values()) { GenericMultiSamplePerFileParser parser = new GenericMultiSamplePerFileParser( dataFiles.get(dataFile.getFileName()), dataFile.getProbeNameHeader(), dataFile.getSampleHeader(), mappedSampleBucket); parser.loadData(dataMap); } validateSampleMapping(dataMap, mappedSampleBucket); return dataMap; } private void validateSampleMapping(Map<String, Map<String, List<Float>>> dataMap, List<String> sampleList) throws DataRetrievalException { StringBuffer errorMsg = new StringBuffer(); for (String sampleName : sampleList) { if (!dataMap.containsKey(sampleName)) { if (errorMsg.length() > 0) { errorMsg.append(", "); } errorMsg.append(sampleName); } } if (errorMsg.length() > 0) { throw new DataRetrievalException("Sample not found error: " + errorMsg.toString()); } } private List<String> getSampleList() { List<String> sampleNames = new ArrayList<String>(); for (Sample sample : samples) { sampleNames.add(sample.getName()); } return sampleNames; } private Sample getSample(String sampleName) { for (Sample sample : samples) { if (sampleName.equals(sample.getName())) { return sample; } } return null; } private void loadArrayData(List<ArrayDataValues> arrayDataValuesList, PlatformHelper platformHelper, Set<ReporterList> reporterLists, Map<String, Map<String, List<Float>>> dataMap) throws DataRetrievalException { for (String sampleName : dataMap.keySet()) { LOGGER.info("Start LoadArrayData for : " + sampleName); ArrayData arrayData = createArrayData(getSample(sampleName), reporterLists, getDataType()); getDao().save(arrayData); ArrayDataValues values = new ArrayDataValues(platformHelper .getAllReportersByType(getReporterType())); arrayDataValuesList.add(values); Map<String, List<Float>> reporterMap = dataMap.get(sampleName); for (String probeName : reporterMap.keySet()) { AbstractReporter reporter = platformHelper.getReporter(getReporterType(), probeName); if (reporter == null) { LOGGER.warn("Reporter with name " + probeName + " was not found in platform " + platformHelper.getPlatform().getName()); } else { values.setFloatValue(arrayData, reporter, getDataValueType(), reporterMap .get(probeName), getCentralTendencyCalculator()); } } getArrayDataService().save(values); LOGGER.info("Done LoadArrayData for : " + sampleName); } } }
package edu.ucdenver.ccp.nlp.wrapper.conceptmapper.dictionary.obo; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Test; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import edu.ucdenver.ccp.common.collections.CollectionsUtil; import edu.ucdenver.ccp.common.file.CharacterEncoding; import edu.ucdenver.ccp.common.file.FileComparisonUtil; import edu.ucdenver.ccp.common.file.FileComparisonUtil.ColumnOrder; import edu.ucdenver.ccp.common.file.FileComparisonUtil.LineOrder; import edu.ucdenver.ccp.common.file.FileComparisonUtil.LineTrim; import edu.ucdenver.ccp.common.file.FileComparisonUtil.ShowWhiteSpace; import edu.ucdenver.ccp.common.io.ClassPathUtil; import edu.ucdenver.ccp.common.test.DefaultTestCase; import edu.ucdenver.ccp.datasource.fileparsers.obo.OntologyUtil; import edu.ucdenver.ccp.datasource.fileparsers.obo.OntologyUtil.SynonymType; /** * @author Colorado Computational Pharmacology, UC Denver; * ccpsupport@ucdenver.edu * */ public class OboToDictionaryTest extends DefaultTestCase { private static final String SAMPLE_SO_OBO_FILE_NAME = "sample.so.obo"; private static final String SAMPLE_CL_OBO_FILE_NAME = "sample.cl.obo"; @Test public void testExactSynonymOnly_SO_OBO() throws IOException, OWLOntologyCreationException { File oboFile = ClassPathUtil.copyClasspathResourceToDirectory(getClass(), SAMPLE_SO_OBO_FILE_NAME, folder.newFolder("input")); OntologyUtil ontUtil = new OntologyUtil(oboFile); File outputFile = folder.newFile("dict.xml"); OboToDictionary.buildDictionary(outputFile, ontUtil, null, SynonymType.EXACT); /* @formatter:off */ List<String> expectedLines = CollectionsUtil.createList( "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>", "<synonym>", "<token id=\"http://purl.obolibrary.org/obo/SO_0000012\" canonical=\"scRNA_primary_transcript\">", "<variant base=\"scRNA_primary_transcript\"/>", "<variant base=\"scRNA primary transcript\"/>", "<variant base=\"scRNA transcript\"/>", "<variant base=\"small cytoplasmic RNA transcript\"/>", "</token>", "</synonym>"); /* @formatter:on */ assertTrue(FileComparisonUtil.hasExpectedLines(outputFile, CharacterEncoding.UTF_8, expectedLines, null, LineOrder.ANY_ORDER, ColumnOrder.AS_IN_FILE, LineTrim.ON, ShowWhiteSpace.ON)); } @Test public void testExactSynonymOnly_CL_OBO() throws IOException, OWLOntologyCreationException { File oboFile = ClassPathUtil.copyClasspathResourceToDirectory(getClass(), SAMPLE_CL_OBO_FILE_NAME, folder.newFolder("input")); OntologyUtil ontUtil = new OntologyUtil(oboFile); File outputFile = folder.newFile("dict.xml"); OboToDictionary.buildDictionary(outputFile, ontUtil, null, SynonymType.EXACT); /* @formatter:off */ List<String> expectedLines = CollectionsUtil.createList( "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>", "<synonym>", "<token id=\"http://purl.obolibrary.org/obo/CL_0000000\" canonical=\"cell\">", "<variant base=\"cell\"/>", "</token>", "<token id=\"http://purl.obolibrary.org/obo/CL_0000009\" canonical=\"fusiform initial\">", "<variant base=\"fusiform initial\"/>", "</token>", "<token id=\"http://purl.obolibrary.org/obo/CL_0000041\" canonical=\"mature eosinophil\">", "<variant base=\"mature eosinophil\"/>", "<variant base=\"mature eosinocyte\"/>", "<variant base=\"mature eosinophil leucocyte\"/>", "<variant base=\"mature eosinophil leukocyte\"/>", "</token>", "</synonym>"); /* @formatter:on */ assertTrue(FileComparisonUtil.hasExpectedLines(outputFile, CharacterEncoding.UTF_8, expectedLines, null, LineOrder.ANY_ORDER, ColumnOrder.AS_IN_FILE, LineTrim.ON, ShowWhiteSpace.ON)); } @Test public void testIncludeAllSynonyms_CL_OBO() throws IOException, OWLOntologyCreationException { File oboFile = ClassPathUtil.copyClasspathResourceToDirectory(getClass(), SAMPLE_CL_OBO_FILE_NAME, folder.newFolder("input")); OntologyUtil ontUtil = new OntologyUtil(oboFile); File outputFile = folder.newFile("dict.xml"); OboToDictionary.buildDictionary(outputFile, ontUtil, null, SynonymType.ALL); /* @formatter:off */ List<String> expectedLines = CollectionsUtil.createList( "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>", "<synonym>", "<token id=\"http://purl.obolibrary.org/obo/CL_0000000\" canonical=\"cell\">", "<variant base=\"cell\"/>", "</token>", "<token id=\"http://purl.obolibrary.org/obo/CL_0000009\" canonical=\"fusiform initial\">", "<variant base=\"fusiform initial\"/>", "<variant base=\"xylem initial\"/>", "<variant base=\"xylem mother cell\"/>", "<variant base=\"xylem mother cell activity\"/>", "</token>", "<token id=\"http://purl.obolibrary.org/obo/CL_0000041\" canonical=\"mature eosinophil\">", "<variant base=\"mature eosinophil\"/>", "<variant base=\"mature eosinocyte\"/>", "<variant base=\"mature eosinophil leucocyte\"/>", "<variant base=\"mature eosinophil leukocyte\"/>", "<variant base=\"polymorphonuclear leucocyte\"/>", "<variant base=\"polymorphonuclear leukocyte\"/>", "</token>", "</synonym>"); /* @formatter:on */ assertTrue(FileComparisonUtil.hasExpectedLines(outputFile, CharacterEncoding.UTF_8, expectedLines, null, LineOrder.ANY_ORDER, ColumnOrder.AS_IN_FILE, LineTrim.ON, ShowWhiteSpace.ON)); } @Test public void testIncludeAllSynonyms_CL_OBO_WithExternalSyns() throws IOException, OWLOntologyCreationException { File oboFile = ClassPathUtil.copyClasspathResourceToDirectory(getClass(), SAMPLE_CL_OBO_FILE_NAME, folder.newFolder("input")); OntologyUtil ontUtil = new OntologyUtil(oboFile); File outputFile = folder.newFile("dict.xml"); Map<String, Set<String>> id2synsMap = new HashMap<String, Set<String>>(); id2synsMap.put("CL:0000009", CollectionsUtil.createSet("fusi init", "fusi fusi")); id2synsMap.put("CL:0000041", CollectionsUtil.createSet("mat eo", "mature eos")); OboToDictionary.buildDictionary(outputFile, ontUtil, null, SynonymType.ALL, id2synsMap); /* @formatter:off */ List<String> expectedLines = CollectionsUtil.createList( "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>", "<synonym>", "<token id=\"http://purl.obolibrary.org/obo/CL_0000000\" canonical=\"cell\">", "<variant base=\"cell\"/>", "</token>", "<token id=\"http://purl.obolibrary.org/obo/CL_0000009\" canonical=\"fusiform initial\">", "<variant base=\"fusiform initial\"/>", "<variant base=\"xylem initial\"/>", "<variant base=\"xylem mother cell\"/>", "<variant base=\"xylem mother cell activity\"/>", "<variant base=\"fusi init\"/>", "<variant base=\"fusi fusi\"/>", "</token>", "<token id=\"http://purl.obolibrary.org/obo/CL_0000041\" canonical=\"mature eosinophil\">", "<variant base=\"mature eosinophil\"/>", "<variant base=\"mature eosinocyte\"/>", "<variant base=\"mature eosinophil leucocyte\"/>", "<variant base=\"mature eosinophil leukocyte\"/>", "<variant base=\"polymorphonuclear leucocyte\"/>", "<variant base=\"polymorphonuclear leukocyte\"/>", "<variant base=\"mat eo\"/>", "<variant base=\"mature eos\"/>", "</token>", "</synonym>"); /* @formatter:on */ assertTrue(FileComparisonUtil.hasExpectedLines(outputFile, CharacterEncoding.UTF_8, expectedLines, null, LineOrder.ANY_ORDER, ColumnOrder.AS_IN_FILE, LineTrim.ON, ShowWhiteSpace.ON)); } }
package org.deegree.securityproxy.authorization.wcs; import java.util.Collection; import javax.servlet.http.HttpServletRequest; import org.deegree.securityproxy.authentication.wcs.WcsPermission; import org.deegree.securityproxy.commons.WcsOperationType; import org.deegree.securityproxy.request.WcsRequest; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; public class WcsRequestAuthorizationManager implements AccessDecisionManager { @Override public void decide( Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes ) throws AccessDeniedException, InsufficientAuthenticationException { WcsRequest wcsRequest = (WcsRequest) object; if ( authentication == null ) throw new AccessDeniedException( "Not authenticated!" ); Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); for ( GrantedAuthority authority : authorities ) { if ( isAuthorized( authority, wcsRequest ) ) { return; } } throw new AccessDeniedException( "Unauthorized" ); } private boolean isAuthorized( GrantedAuthority authority, WcsRequest wcsRequest ) { if ( authority instanceof WcsPermission ) { WcsPermission wcsPermission = (WcsPermission) authority; if ( isGetCoverageRequest( wcsRequest ) ) { if ( !isLayerNameAuthorized( wcsRequest, wcsPermission ) ) return false; } if ( isOperationTypeAuthorized( wcsRequest, wcsPermission ) && isServiceVersionAuthorized( wcsRequest, wcsPermission ) && isServiceNameAuthorized( wcsRequest, wcsPermission ) ) { return true; } } return false; } private boolean isGetCoverageRequest( WcsRequest wcsRequest ) { return WcsOperationType.GETCOVERAGE.equals( wcsRequest.getOperationType() ); } private boolean isOperationTypeAuthorized( WcsRequest wcsRequest, WcsPermission wcsPermission ) { if ( wcsRequest.getOperationType() != null ) return wcsRequest.getOperationType().equals( wcsPermission.getOperationType() ); else return false; } private boolean isServiceVersionAuthorized( WcsRequest wcsRequest, WcsPermission wcsPermission ) { if ( wcsRequest.getServiceVersion() != null ) return wcsRequest.getServiceVersion().equals( wcsPermission.getServiceVersion() ); else return false; } private boolean isServiceNameAuthorized( WcsRequest wcsRequest, WcsPermission wcsPermission ) { if ( wcsRequest.getServiceName() != null ) return wcsRequest.getServiceName().equals( wcsPermission.getServiceName() ); else return false; } private boolean isLayerNameAuthorized( WcsRequest wcsRequest, WcsPermission wcsPermission ) { if ( wcsRequest.getLayerName() != null ) return wcsRequest.getLayerName().equals( wcsPermission.getLayerName() ); else return false; } @Override public boolean supports( ConfigAttribute attribute ) { // Not needed in this implementation. return true; } @Override public boolean supports( Class<?> clazz ) { return WcsRequest.class.equals( clazz ); } }
package at.tuwien.ss17.dp.lab3.datascience.service.impl; import at.tuwien.ss17.dp.lab3.datascience.exception.DataModelInstanceValidationException; import at.tuwien.ss17.dp.lab3.datascience.model.dmp.javax.*; import at.tuwien.ss17.dp.lab3.datascience.model.dmp.json.LinkDataArray; import at.tuwien.ss17.dp.lab3.datascience.model.dmp.json.NodeDataArray; import at.tuwien.ss17.dp.lab3.datascience.service.DMPModelService; import javax.xml.XMLConstants; import javax.xml.transform.stream.StreamSource; import org.springframework.stereotype.Service; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.net.URL; import java.util.LinkedList; import java.util.List; import javax.xml.validation.Schema; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import at.tuwien.ss17.dp.lab3.datascience.model.dmp.json.DmpModel; @Service(value="DMPModelService") public class DMPModelServiceImpl implements DMPModelService { private final String XSD_LOCATION = "classpath:dmp.xsd"; private SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); private static final String TEMPLATE_XSD_FILE_NAME = new String("dmp.xsd"); @Override public DmpModel validateAndUnmarshalModelInstance(String xml) throws DataModelInstanceValidationException { // VALIDATE try{ URL schemaFile = new URL(XSD_LOCATION); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(schemaFile); Validator validator = schema.newValidator(); final List<SAXParseException> exceptions = new LinkedList<SAXParseException>(); validator.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { exceptions.add(exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { exceptions.add(exception); } @Override public void error(SAXParseException exception) throws SAXException { exceptions.add(exception); } }); validator.validate(new StreamSource(new StringReader(xml))); //if validation errors found -> throw exception if (!exceptions.isEmpty()){ String concat = ""; for (SAXParseException exception : exceptions) { concat += exception + "\n"; } throw new DataModelInstanceValidationException(concat); } } catch (SAXException e) { throw new DataModelInstanceValidationException(e.getMessage()); } catch (IOException e) { e.printStackTrace(); } // UNMARSHAL DataManagementPlan dmp = null; try { ClassLoader classLoader = getClass().getClassLoader(); Schema schema = sf.newSchema(new File(classLoader.getResource(TEMPLATE_XSD_FILE_NAME).getFile())); JAXBContext jc = JAXBContext.newInstance(DataManagementPlan.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); unmarshaller.setSchema(schema); //unmarshal xml StringReader reader = new StringReader(xml); dmp = (DataManagementPlan) unmarshaller.unmarshal(reader); }catch(Exception e){ e.printStackTrace(); } // CREATE MODEL // TODO transform unmarshalled xml to "at.tuwien.ss17.dp.lab3.datascience.model.dmp.json" and return it return transform(dmp); } private DmpModel transform(DataManagementPlan dmpXml){ int id = 0; int locX = 120; int locY = 120; int lvl0RootId = 0; int lvl1RootId = 0; int lvl2RootId = 0; final int X_OFFSET = 140; final int Y_OFFSET = 140; DmpModel dmpJson = new DmpModel(); if (dmpXml != null){ dmpJson.setNodeKeyProperty("id"); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX)+" "+String.valueOf(locY), "DataManagementPlan")); lvl0RootId = id++; if (dmpXml.getDataRepository() != null){ DataRepositoryType dataRepositoryType = dmpXml.getDataRepository(); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX)+" "+String.valueOf(locY+=Y_OFFSET), "dataRepository")); dmpJson.addLinkDataArray(new LinkDataArray(lvl0RootId, id, "has", -20)); lvl1RootId = id++; if (dataRepositoryType.getDoi() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX)+" "+String.valueOf(locY+Y_OFFSET), dataRepositoryType.getDoi())); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id++, "has", -20)); } if (dataRepositoryType.getRepositoryURI() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), dataRepositoryType.getRepositoryURI())); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id++, "has", -20)); } } if (dmpXml.getEthicsPrivacy() != null && !dmpXml.getEthicsPrivacy().isEmpty()){ List<EthicsPrivacyType> ethicsPrivacyTypeList = dmpXml.getEthicsPrivacy(); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+X_OFFSET)+" "+String.valueOf(locY), "ethicsPrivacy")); dmpJson.addLinkDataArray(new LinkDataArray(lvl0RootId, id, "has", -20)); lvl1RootId = id++; for (EthicsPrivacyType ethicsPrivacyType : ethicsPrivacyTypeList) { if (ethicsPrivacyType.getIssue() != null && ethicsPrivacyType.getSolution() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), ethicsPrivacyType.getIssue())); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id++, "has", -20)); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), ethicsPrivacyType.getSolution())); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id++, "has", -20)); } } } if (dmpXml.getRolesAndResponsibilities() != null && !dmpXml.getRolesAndResponsibilities().isEmpty()){ List<RolesAndResponsibilitiesType> rolesAndResponsibilities = dmpXml.getRolesAndResponsibilities(); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+X_OFFSET)+" "+String.valueOf(locY), "rolesAndResponsibilities")); dmpJson.addLinkDataArray(new LinkDataArray(lvl0RootId, id, "has", -20)); lvl1RootId = id++; for (RolesAndResponsibilitiesType responsibilitiesType : rolesAndResponsibilities) { if (responsibilitiesType.getRoleName() != null && responsibilitiesType.getResponsibilitiesDescription() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), responsibilitiesType.getRoleName())); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id++, "has", -20)); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), responsibilitiesType.getResponsibilitiesDescription())); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id++, "has", -20)); } } } if (dmpXml.getBudget() != null && !dmpXml.getBudget().isEmpty()){ List<BudgetType> budgetTypeList = dmpXml.getBudget(); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+X_OFFSET)+" "+String.valueOf(locY), "budget")); dmpJson.addLinkDataArray(new LinkDataArray(lvl0RootId, id, "has", -20)); lvl1RootId = id++; for (BudgetType budgetType : budgetTypeList) { if (budgetType.getPosition() != null && budgetType.getCurrency() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), budgetType.getPosition())); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id++, "has", -20)); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), String.valueOf(budgetType.getCosts()))); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id++, "has", -20)); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), budgetType.getCurrency())); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id++, "has", -20)); } } } if (dmpXml.getExperimentFile() != null){ ExperimentFile experimentFile = dmpXml.getExperimentFile(); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+X_OFFSET)+" "+String.valueOf(locY), "experimentFile")); dmpJson.addLinkDataArray(new LinkDataArray(lvl0RootId, id, "has", -20)); lvl1RootId = id++; if (experimentFile.getMetadata() != null){ MetadataType metadataType = experimentFile.getMetadata(); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+X_OFFSET)+" "+String.valueOf(locY+=Y_OFFSET), "metadata")); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id, "has", -20)); lvl2RootId = id++; if (metadataType.getDcFormat() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), metadataType.getDcFormat())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (metadataType.getDcMimeType() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), metadataType.getDcMimeType())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (metadataType.getDcEncoding() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), metadataType.getDcEncoding())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (metadataType.getDcTitle() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), metadataType.getDcTitle())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (metadataType.getDcDescription() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), metadataType.getDcDescription())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (metadataType.getDcCreator() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), metadataType.getDcCreator())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (metadataType.getDcSource() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), metadataType.getDcSource())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (metadataType.getDcDate() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), metadataType.getDcDate().toString())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } } if (experimentFile.getPreservation() != null){ PreservationType preservationType = experimentFile.getPreservation(); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+X_OFFSET)+" "+String.valueOf(locY), "preservation")); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id, "has", -20)); lvl2RootId = id++; if (preservationType.getBackupStorageURI() != null && !preservationType.getBackupStorageURI().isEmpty()){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), preservationType.getBackupStorageURI())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (preservationType.getBackupsInCronFormat() != null && !preservationType.getBackupsInCronFormat().isEmpty()){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), preservationType.getBackupsInCronFormat())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), String.valueOf(preservationType.getRetentionDurationInDays()))); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (experimentFile.getDataVolume() != null){ DataVolumeType dataVolumeType = experimentFile.getDataVolume(); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+X_OFFSET)+" "+String.valueOf(locY), "dataVolume")); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id, "has", -20)); lvl2RootId = id++; if (dataVolumeType.getUnit() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), dataVolumeType.getUnit().value())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), String.valueOf(dataVolumeType.getAmount()))); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } locY-=Y_OFFSET; } if (dmpXml.getSourceCode() != null){ SourceCode sourceCode = dmpXml.getSourceCode(); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+X_OFFSET)+" "+String.valueOf(locY), "sourceCode")); dmpJson.addLinkDataArray(new LinkDataArray(lvl0RootId, id, "has", -20)); lvl1RootId = id++; if (sourceCode.getMetadata() != null){ MetadataType metadataType = sourceCode.getMetadata(); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+X_OFFSET)+" "+String.valueOf(locY+=Y_OFFSET), "metadata")); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id, "has", -20)); lvl2RootId = id++; if (metadataType.getDcFormat() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), metadataType.getDcFormat())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (metadataType.getDcMimeType() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), metadataType.getDcMimeType())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (metadataType.getDcEncoding() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), metadataType.getDcEncoding())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (metadataType.getDcTitle() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), metadataType.getDcTitle())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (metadataType.getDcDescription() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), metadataType.getDcDescription())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (metadataType.getDcCreator() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), metadataType.getDcCreator())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (metadataType.getDcSource() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), metadataType.getDcSource())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (metadataType.getDcDate() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), metadataType.getDcDate().toString())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } } if (sourceCode.getPreservation() != null){ PreservationType preservationType = sourceCode.getPreservation(); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+X_OFFSET)+" "+String.valueOf(locY), "preservation")); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id, "has", -20)); lvl2RootId = id++; if (preservationType.getBackupStorageURI() != null && !preservationType.getBackupStorageURI().isEmpty()){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), preservationType.getBackupStorageURI())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (preservationType.getBackupsInCronFormat() != null && !preservationType.getBackupsInCronFormat().isEmpty()){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), preservationType.getBackupsInCronFormat())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), String.valueOf(preservationType.getRetentionDurationInDays()))); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (sourceCode.getDataVolume() != null){ DataVolumeType dataVolumeType = sourceCode.getDataVolume(); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+X_OFFSET)+" "+String.valueOf(locY), "dataVolume")); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id, "has", -20)); lvl2RootId = id++; if (dataVolumeType.getUnit() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), dataVolumeType.getUnit().value())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), String.valueOf(dataVolumeType.getAmount()))); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (sourceCode.getDocumentation() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+X_OFFSET)+" "+String.valueOf(locY), "documentation")); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id, "has", -20)); lvl2RootId = id++; dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), sourceCode.getDocumentation().getType())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+=X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), sourceCode.getDocumentation().getLocation())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } if (sourceCode.getIntellectualPropertyRights() != null){ dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+X_OFFSET)+" "+String.valueOf(locY), "intellectualPropertyRights")); dmpJson.addLinkDataArray(new LinkDataArray(lvl1RootId, id, "has", -20)); lvl2RootId = id++; dmpJson.addNodeDataArray(new NodeDataArray(id, String.valueOf(locX+X_OFFSET)+" "+String.valueOf(locY+Y_OFFSET), sourceCode.getIntellectualPropertyRights().getLicense())); dmpJson.addLinkDataArray(new LinkDataArray(lvl2RootId, id++, "has", -20)); } } } return dmpJson; } private void addMetaData(MetadataType metadataType, DmpModel dmpJson){ // TODO impl } private void addPreservaion(MetadataType metadataType, DmpModel dmpJson){ // TODO impl } private void addDataVolume(MetadataType metadataType, DmpModel dmpJson){ // TODO impl } }
package org.eclipse.persistence.testing.tests.queries.report; import java.math.BigDecimal; import java.util.Vector; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.expressions.ExpressionBuilder; import org.eclipse.persistence.queries.ReadAllQuery; import org.eclipse.persistence.queries.ReportQuery; import org.eclipse.persistence.queries.ReportQueryResult; import org.eclipse.persistence.testing.framework.AutoVerifyTestCase; import org.eclipse.persistence.testing.framework.TestErrorException; import org.eclipse.persistence.testing.framework.TestWarningException; import org.eclipse.persistence.testing.models.employee.domain.Employee; /** * This test assumes the following to be true of the * org.eclipse.persistence.testing.models.employee.domain.Employee class: * * - salary is an int. * - id is a BigDecimal. * * It also assumes that report queries in general work properly. That is, if I * asked for a report item, I'll get one back in the report query result. The * verify does not check. */ public class ReportQueryFunctionTypeTestCase extends AutoVerifyTestCase { Vector<ReportQueryResult> results; // shouldHaveReadAllQueryInDescriptor == true added for Bug 290311: ReadAllQuery executed instead of ReportQuery boolean shouldHaveReadAllQueryInDescriptor; boolean hasSetReadAllQueryIntoDescriptor; public ReportQueryFunctionTypeTestCase() { this(false); } public ReportQueryFunctionTypeTestCase(boolean shouldHaveReadAllQueryInDescriptor) { this.shouldHaveReadAllQueryInDescriptor = shouldHaveReadAllQueryInDescriptor; String suffix = shouldHaveReadAllQueryInDescriptor ? " ReadAllQuery in descriptor." : ""; setDescription("Tests the result types of report query that uses functions." + suffix); setName(getName() + suffix); } public void test() { // This is currently where DataDirect is installed on DB2. If this URL // changes then this test will fail since DataDirect on DB2 returns // an Integer for the average function. In fact all the return // types on DataDirect for DB2 are not what is expected in the verify. // Every other platform seems to adhere to these types though so aside // from the Oracle specific variance function these tests should pass // on all platforms. if (getSession().getLogin().getDriverClassName().equals("com.oracle.ias.jdbc.db2.DB2Driver")) { throw new TestWarningException("This test is not supported on DB2 DataDirect"); } else { ReportQuery reportQuery = new ReportQuery(); reportQuery.setReferenceClass(Employee.class); ExpressionBuilder builder = reportQuery.getExpressionBuilder(); reportQuery .addAverage("salary-ave", builder.get("salary")); // Oracle specific function. if (getSession().getDatasourcePlatform().isOracle()) { reportQuery .addVariance("salary-var", builder.get("salary")); } //Sybase and TimesTen doesn't support if(!(getSession().getDatasourcePlatform().isSybase() || getSession().getDatasourcePlatform().isTimesTen() || getSession().getDatasourcePlatform().isDerby())) { reportQuery .addStandardDeviation("salary-std", builder.get("salary")); } reportQuery .addSum("id-sum", builder.get("id")); reportQuery .addMinimum("id-min", builder.get("id")); reportQuery .addMaximum("id-max", builder.get("id")); if(this.shouldHaveReadAllQueryInDescriptor) { ClassDescriptor desc = getSession().getDescriptor(Employee.class); if(!desc.getQueryManager().hasReadAllQuery()) { desc.getQueryManager().setReadAllQuery(new ReadAllQuery()); hasSetReadAllQueryIntoDescriptor = true; } } results = (Vector<ReportQueryResult>) getSession().executeQuery(reportQuery); } } protected void verify() { if (results.isEmpty()) { throw new TestErrorException("No results were returned from the report query."); } else { ReportQueryResult result = results.firstElement(); Object value; // Types are not as expected for Derby. if (getSession().getDatasourcePlatform().isDerby()) { return; } //To fix bug 6217517, AVG(t1.SALARY) returns an Integer value with DB2 if (getSession().getDatasourcePlatform().isOracle()) { value = result.get("salary-ave"); if (value instanceof Integer) { throw new TestErrorException("Incorrect result type for average function of report query."); } value = result.get("salary-var"); if (value instanceof Integer) { throw new TestErrorException("Incorrect result type for variance function of report query."); } value = result.get("id-sum"); if (!(value instanceof BigDecimal)) { throw new TestErrorException("Incorrect result type for sum function of report query."); } value = result.get("id-min"); if (!(value instanceof BigDecimal)) { throw new TestErrorException("Incorrect result type for min function of report query."); } value = result.get("id-max"); if (!(value instanceof BigDecimal)) { throw new TestErrorException("Incorrect result type for max function of report query."); } } value = result.get("salary-std"); if (value instanceof Integer) { throw new TestErrorException("Incorrect result type for standard deviation function of report query."); } } } public void reset() { if(this.hasSetReadAllQueryIntoDescriptor) { ClassDescriptor desc = getSession().getDescriptor(Employee.class); desc.getQueryManager().setReadAllQuery(null); } } }
package util; public class BattleHandler { private static String Exception; /* * takes in the EntityPlayer object and the EntityCreature object, using the existing methods inside, applies the damage to creature * * this takes care of changing the health */ public static void playerTurn (EntityPlayer player, EntityCreature creature){ creature.damageCreature(player); if (creature.getHealth() <= 0){ player.leveling(creature); } } /* * This uses the EntityPLayer object and the EntityCreature object, using the existing methods inside, applies the damage to player * * This takes care of changing the player health, and takes into effect of the speed, there is a chance nothing will happen at all. * * if missed, the message will be stored to static variable "exception" */ public static String creatureTurn (EntityPlayer player, EntityCreature creature){ if (player.speedX > creature.hitChance()) { player.health = player.getHealth(); Exception = " But it Missed!!!!!"; return Exception; } else { player.damagePlayer(creature); Exception = "And you took damage!!!"; return Exception; } /* * if this method is invoked, it calculates the propbabiliy of runing away * * takes into acco unt the chance if its a hit or miss */ } public static String Run(EntityPlayer player, EntityCreature creature){ if (player.getSpeed() * 2 < creature.hitChance()){ return creatureTurn(player, creature); }else { Exception = "Your ran away!!!!!"; return Exception; } } }
// EditDistance.java import java.io.*; /** Computes minimum edit distance between two strings. */ public class EditDistance { public static void main(String[] args) throws IOException { String a = args.length > 0 ? args[0] : getString("First string? "); String b = args.length > 1 ? args[1] : getString("Second string? "); System.out.println("Distance = " + getEditDistance(a, b)); } public static int getEditDistance(String s, String t) { // Leveshtein algorithm if (s == null) s = ""; if (t == null) t = ""; char[] a = s.toCharArray(); char[] b = t.toCharArray(); int[] w = new int[b.length + 1]; int cur = 0, next = 0; for (int i=0; i<a.length; i++) { cur = i + 1; for (int j=0; j<b.length; j++) { next = min( w[j + 1] + 1, cur + 1, w[j] + (a[i] == b[j] ? 0 : 1) ); w[j] = cur; cur = next; } w[b.length] = next; } return next; } private static int min(int a, int b, int c) { if (a < b && a < c) return a; return (b < c ? b : c); } private static String getString(String msg) throws IOException { System.out.print(msg); return new BufferedReader(new InputStreamReader(System.in)).readLine(); } }
package controllers.api; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.sun.syndication.feed.synd.*; import com.sun.syndication.io.FeedException; import com.sun.syndication.io.SyndFeedOutput; import org.joda.time.DateTime; import play.mvc.Result; import uk.gov.openregister.config.ApplicationConf; import uk.gov.openregister.config.Register; import uk.gov.openregister.domain.Record; import uk.gov.openregister.domain.RecordVersionInfo; import uk.gov.openregister.linking.Curie; import uk.gov.openregister.linking.CurieResolver; import uk.gov.openregister.model.Field; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static play.mvc.Results.ok; public class AtomRepresentation implements Representation { public static final String TEXT_ATOM = "application/atom+xml; charset=utf-8"; private final CurieResolver curieResolver; public AtomRepresentation() { curieResolver = new CurieResolver(ApplicationConf.getRegisterServiceTemplateUrl()); } @Override public Result toListOfRecords(Register register, List<Record> records, Map<String, String[]> requestParams, Map<String, String> representationsMap, String previousPageLink, String nextPageLink) { SyndFeed atomFeed = createSyndFeed(register); atomFeed.setEntries( records.stream() .map(r -> renderRecord(r, register)) .collect(Collectors.toList())); return ok(toOutput(atomFeed)).as(TEXT_ATOM); } @Override public Result toRecord(Register register, Record record, Map<String, String[]> requestParams, Map<String, String> representationsMap, List<RecordVersionInfo> history) { SyndFeed atomFeed = createSyndFeed(register); atomFeed.setEntries( new ArrayList<SyndEntry>(){{ add(renderRecord(record, register)); }} ); return ok(toOutput(atomFeed)).as(TEXT_ATOM); } @Override public boolean isPaginated() { return false; } private SyndFeed createSyndFeed(Register register) { SyndFeed atomFeed = new SyndFeedImpl(); atomFeed.setFeedType("atom_1.0"); atomFeed.setTitle("Latest updates to the " + register.friendlyName() + " register."); atomFeed.setLink("http://" + register.name() + ".openregister.org"); atomFeed.setDescription("This feed contains that latest updates to data in the " + register.friendlyName() + " register."); return atomFeed; } private String toOutput(final SyndFeed feed) { try { Writer writer = new StringWriter(); SyndFeedOutput output = new SyndFeedOutput(); output.output(feed, writer); return writer.toString(); } catch (IOException|FeedException e) { e.printStackTrace(); } return ""; } private SyndEntry renderRecord(Record record, Register register) { URI hashUri = curieResolver.resolve(new Curie(register.name() + "_hash", record.getHash())); SyndEntry entry = new SyndEntryImpl(); Map<String, String> keyValue = register.fields().stream() .map(field -> new HashMap.SimpleEntry<String, String>(field.getName(), renderValue(record, field))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); entry.setTitle(keyValue.get("name")); entry.setLink(hashUri.toString()); DateTime publishedDateTime = renderCreationTime(record); entry.setPublishedDate(publishedDateTime.toDate()); SyndContent description = new SyndContentImpl(); description.setType("text/plain"); description.setValue("This " + register.name() + " was updated on " + friendlyFormatDateTime(renderCreationTime(record))); entry.setDescription(description); return entry; } private String renderValue(Record record, Field field) { JsonNode jsonNode = record.getEntry().get(field.getName()); if (jsonNode == null) { return "\"\""; } switch (field.getCardinality()) { case ONE: return renderScalar(field, jsonNode); case MANY: return renderList(field, jsonNode); default: throw new IllegalStateException("Invalid Cardinality: " + field.getCardinality()); } } private String renderScalar(Field field, JsonNode jsonNode) { if (field.getRegister().isPresent()) { Curie curie = new Curie(field.getRegister().get(), jsonNode.asText()); return String.format("<%s>", curieResolver.resolve(curie)); } return jsonNode.toString(); } private String renderList(Field field, JsonNode jsonNode) { ArrayNode arrayNode = (ArrayNode) jsonNode; return StreamSupport.stream(arrayNode.spliterator(),false) .map(val -> renderScalar(field, val)) .collect(Collectors.joining(", ")); } private DateTime renderCreationTime(Record record) { return record.getMetadata().isPresent() ? record.getMetadata().get().creationTime : null; } private static final String FRIENDLY_DATETIME_PATTERN = "yyyy-MM-dd 'at' HH:mm"; private String friendlyFormatDateTime(DateTime dateTime) { return dateTime.toString(FRIENDLY_DATETIME_PATTERN); } public static Representation instance = new AtomRepresentation(); }
package no.rmz.gtp.gtpsim; import static org.junit.Assert.assertEquals; import org.junit.Test; public class GtpPacketTest { private GtpPacket newBytePacket(final byte b) { return new GtpPacket(new byte[]{b}); } private GtpPacket newBytePacket(final int... bytes) { final byte[] byteArray = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) { byteArray[i] = (byte) bytes[i]; } return new GtpPacket(byteArray); } @Test public void testGetVersion() { final GtpPacket bp = newBytePacket(0b00000010); assertEquals(0b010, bp.getVersion()); } @Test public void testSetVersion() { final GtpPacket bp = newBytePacket(0b00000000); assertEquals(0b000, bp.getVersion()); bp.setVersion(0b010); assertEquals(0b010, bp.getVersion()); } @Test public void testGetProtocolType() { final GtpPacket bp = newBytePacket(0b00001000); assertEquals(0b1, bp.getProtocolType()); } @Test public void testSetProtocolType() { final GtpPacket bp = newBytePacket(0b00000000); bp.setProtocolType(1); assertEquals(0b1, bp.getProtocolType()); } @Test public void testGetReserved() { final GtpPacket bp = newBytePacket(0b00010000); assertEquals(0b1, bp.getReserved()); } @Test public void testSetReserved() { final GtpPacket bp = newBytePacket(0b0000000); bp.setReserved(); assertEquals(0b1, bp.getReserved()); } @Test public void testGetHdrLen() { final GtpPacket bp = newBytePacket(0b00100000); assertEquals(0b1, bp.getExtensionHeaderFlag()); } @Test public void testSetHdrLen() { final GtpPacket bp = newBytePacket(0b00000000); bp.setExtensionHeaderFlag(1); assertEquals(0b1, bp.getExtensionHeaderFlag()); } @Test public void testGetSeqNoFlag() { final GtpPacket bp = newBytePacket(0b01000000); assertEquals(0b1, bp.getSeqNoFlag()); } @Test public void testSetSeqNoFlag() { final GtpPacket bp = newBytePacket(0b00000000); bp.setSeqNoFlag(1); assertEquals(0b1, bp.getSeqNoFlag()); } @Test public void testGetGtpMessageType() { final GtpPacket bp = newBytePacket(0b01000000, 152); assertEquals(152, bp.getMessageType()); } @Test public void testSetGtpMessageType() { final GtpPacket bp = newBytePacket(0, 0); bp.setMessageType(152); assertEquals(152, bp.getMessageType()); } }