answer
stringlengths
17
10.2M
package org.jfree.chart.urls; import java.util.ArrayList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import java.util.List; import org.jfree.chart.TestUtils; import org.jfree.chart.util.PublicCloneable; import org.junit.Test; /** * Tests for the {@link CustomXYURLGenerator} class. */ public class CustomXYURLGeneratorTest { /** * Some checks for the equals() method. */ @Test public void testEquals() { CustomXYURLGenerator g1 = new CustomXYURLGenerator(); CustomXYURLGenerator g2 = new CustomXYURLGenerator(); assertTrue(g1.equals(g2)); List<String> u1 = new ArrayList<>(); u1.add("URL A1"); u1.add("URL A2"); u1.add("URL A3"); g1.addURLSeries(u1); assertFalse(g1.equals(g2)); List<String> u2 = new ArrayList<>(); u2.add("URL A1"); u2.add("URL A2"); u2.add("URL A3"); g2.addURLSeries(u2); assertTrue(g1.equals(g2)); } /** * Confirm that cloning works. * @throws java.lang.CloneNotSupportedException */ @Test public void testCloning() throws CloneNotSupportedException { CustomXYURLGenerator g1 = new CustomXYURLGenerator(); List<String> u1 = new ArrayList<>(); u1.add("URL A1"); u1.add("URL A2"); u1.add("URL A3"); g1.addURLSeries(u1); CustomXYURLGenerator g2 = (CustomXYURLGenerator) g1.clone(); assertTrue(g1 != g2); assertTrue(g1.getClass() == g2.getClass()); assertTrue(g1.equals(g2)); // check independence List<String> u2 = new ArrayList<>(); u2.add("URL XXX"); g1.addURLSeries(u2); assertFalse(g1.equals(g2)); g2.addURLSeries(new java.util.ArrayList(u2)); assertTrue(g1.equals(g2)); } /** * Checks that the class implements PublicCloneable. */ @Test public void testPublicCloneable() { CustomXYURLGenerator g1 = new CustomXYURLGenerator(); assertTrue(g1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { List<String> u1 = new ArrayList<>(); u1.add("URL A1"); u1.add("URL A2"); u1.add("URL A3"); List<String> u2 = new ArrayList<>(); u2.add("URL B1"); u2.add("URL B2"); u2.add("URL B3"); CustomXYURLGenerator g1 = new CustomXYURLGenerator(); g1.addURLSeries(u1); g1.addURLSeries(u2); CustomXYURLGenerator g2 = (CustomXYURLGenerator) TestUtils.serialised(g1); assertEquals(g1, g2); } /** * Some checks for the addURLSeries() method. */ @Test public void testAddURLSeries() { CustomXYURLGenerator g1 = new CustomXYURLGenerator(); // you can add a null list - it would have been better if this // required EMPTY_LIST g1.addURLSeries(null); assertEquals(1, g1.getListCount()); assertEquals(0, g1.getURLCount(0)); List<String> list1 = new ArrayList<>(); list1.add("URL1"); g1.addURLSeries(list1); assertEquals(2, g1.getListCount()); assertEquals(0, g1.getURLCount(0)); assertEquals(1, g1.getURLCount(1)); assertEquals("URL1", g1.getURL(1, 0)); // if we modify the original list, it's best if the URL generator is // not affected list1.clear(); assertEquals("URL1", g1.getURL(1, 0)); } }
package org.onedatashare.server.system; import com.google.gson.Gson; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.stubbing.Answer; import org.onedatashare.server.controller.LoginController.LoginControllerRequest; import org.onedatashare.server.controller.RegistrationController.RegistrationControllerRequest; import org.onedatashare.server.model.core.ODSConstants; import org.onedatashare.server.model.core.User; import org.onedatashare.server.repository.UserRepository; import org.onedatashare.server.service.CaptchaService; import org.onedatashare.server.service.EmailService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.lang.String.format; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static reactor.core.publisher.Mono.empty; import static reactor.core.publisher.Mono.just; @SpringBootTest @RunWith(SpringRunner.class) //@AutoConfigureMockMvc(secure = false, addFilters = false) @ContextConfiguration @WebAppConfiguration public class UserActionTest { private static final String TEST_USER_EMAIL = "bigstuff@bigwhoopcorp.com"; private static final String TEST_USER_NAME = "test_user"; private static final String TEST_USER_PASSWORD = "IamTheWalrus"; @Autowired private WebApplicationContext context; private MockMvc mvc; @MockBean private UserRepository userRepository; @MockBean private CaptchaService captchaService; @MockBean private EmailService emailService; private Map<String, User> users = new HashMap<>(); private Map<String, String> inbox = new HashMap<>(); @Before public void setup() { mvc = MockMvcBuilders .webAppContextSetup(context) .apply(springSecurity()) .build(); // User repo mocked methods when(userRepository.insert((User) any())).thenAnswer(addToUsers()); when(userRepository.findById(anyString())).thenAnswer(getFromUsers()); when(userRepository.save(any())).thenAnswer(updateUser()); // Service mocked methods when(captchaService.verifyValue(any())).thenReturn(just(true)); doAnswer(addToEmails()).when(emailService).sendEmail(any(), any(), any()); doCallRealMethod().when(emailService).isValidEmail(any()); users.clear(); inbox.clear(); } @Test @WithMockUser(TEST_USER_EMAIL) public void givenUserDoesNotExist_WhenRegistered_ShouldBeAddedToUserRepository() throws Exception { registerUserAndChangePassword(TEST_USER_EMAIL, TEST_USER_PASSWORD, TEST_USER_NAME); assertEquals(users.size(), 1); assertEquals((getFirstUser()).getEmail(), TEST_USER_EMAIL); } @Test @WithMockUser(TEST_USER_EMAIL) public void givenUserAlreadyExists_WhenRegistered_ShouldNotDuplicateUser() throws Exception { registerUserAndChangePassword(TEST_USER_EMAIL, TEST_USER_PASSWORD, TEST_USER_NAME); long firstRegistrationTimestamp = getFirstUser().getRegisterMoment(); // Try registering the same user again registerUserAndChangePassword(TEST_USER_EMAIL, TEST_USER_PASSWORD, TEST_USER_NAME); assertEquals(users.size(), 1); assertEquals(getFirstUser().getEmail(), TEST_USER_EMAIL); assertEquals(getFirstUser().getRegisterMoment(), firstRegistrationTimestamp); } @Test @WithMockUser(TEST_USER_EMAIL) public void givenUserRegistered_WhenCodeIsVerified_ShouldValidateUser() throws Exception { registerUserAndChangePassword(TEST_USER_EMAIL, TEST_USER_PASSWORD, TEST_USER_NAME); assertTrue(users.get(TEST_USER_EMAIL).isValidated()); } @Test @WithMockUser(TEST_USER_EMAIL) public void givenUserVerified_WhenLoggingIn_ShouldSucceed() throws Exception { registerUserAndChangePassword(TEST_USER_EMAIL, TEST_USER_PASSWORD, TEST_USER_NAME); boolean wasSuccessful = loginUser(TEST_USER_EMAIL, TEST_USER_PASSWORD); assertTrue(wasSuccessful); } @Test @WithMockUser(TEST_USER_EMAIL) public void givenUserNotVerified_WhenLoggingIn_ShouldFail() throws Exception { // does not perform verification by email registerUser(TEST_USER_EMAIL, TEST_USER_NAME); boolean loginSuccessful = loginUser(TEST_USER_EMAIL, TEST_USER_PASSWORD); assertFalse(loginSuccessful); } @Test @WithMockUser(TEST_USER_EMAIL) public void givenUserChangedPassword_WhenLoggingInWithNewPassword_ShouldSucceed() throws Exception { String oldPassword = TEST_USER_PASSWORD; String new_password = "new_password"; registerUserAndChangePassword(TEST_USER_EMAIL, oldPassword, TEST_USER_NAME); resetUserPassword(TEST_USER_EMAIL, oldPassword, new_password); boolean loginSuccessful = loginUser(TEST_USER_EMAIL, new_password); assertTrue(loginSuccessful); } @Test @WithMockUser(TEST_USER_EMAIL) public void givenUserChangedPassword_WhenLoggingInWithOldPassword_ShouldFail() throws Exception { String oldPassword = TEST_USER_PASSWORD; String new_password = "new_password"; registerUserAndChangePassword(TEST_USER_EMAIL, oldPassword, TEST_USER_NAME); resetUserPassword(TEST_USER_EMAIL, oldPassword, new_password); boolean loginSuccessful = loginUser(TEST_USER_EMAIL, oldPassword); assertFalse(loginSuccessful); } @Test @WithMockUser(TEST_USER_EMAIL) public void givenIncorrectOldPassword_WhenResettingPassword_ShouldFail() throws Exception { String oldPassword = TEST_USER_PASSWORD; String new_password = "new_password"; String wrongPassword = "random_guess"; registerUserAndChangePassword(TEST_USER_EMAIL, oldPassword, TEST_USER_NAME); resetUserPassword(TEST_USER_EMAIL, wrongPassword, new_password); boolean loginSuccessful = loginUser(TEST_USER_EMAIL, wrongPassword); assertFalse(loginSuccessful); loginSuccessful = loginUser(TEST_USER_EMAIL, oldPassword); assertTrue(loginSuccessful); } private void resetUserPassword(String userEmail, String oldPassword, String newPassword) throws Exception { LoginControllerRequest requestData = new LoginControllerRequest(); requestData.setEmail(userEmail); requestData.setPassword(oldPassword); requestData.setNewPassword(newPassword); requestData.setConfirmPassword(newPassword); processWithRequestData(ODSConstants.UPDATE_PASSWD_ENDPOINT, requestData); } private void setUserPassword(String userEmail, String userPassword, String authToken) throws Exception { LoginControllerRequest requestData = new LoginControllerRequest(); requestData.setEmail(userEmail); requestData.setPassword(userPassword); requestData.setConfirmPassword(userPassword); requestData.setCode(authToken); processWithRequestData(ODSConstants.RESET_PASSWD_ENDPOINT, requestData); } private boolean loginUser(String userEmail, String password) throws Exception { LoginControllerRequest requestData = new LoginControllerRequest(); requestData.setEmail(userEmail); requestData.setPassword(password); long timeBeforeLoggingIn = System.currentTimeMillis(); processWithRequestData(ODSConstants.AUTH_ENDPOINT, requestData); Long lastActivity = users.get(userEmail).getLastActivity(); return lastActivity != null && lastActivity > timeBeforeLoggingIn; } private void registerUserAndChangePassword(String userEmail, String userPassword, String username) throws Exception { registerUser(userEmail, username); String verificationCodeEmail = inbox.get(userEmail); String verificationCode = extractVerificationCode(verificationCodeEmail); verifyCode(userEmail, verificationCode); String authToken = users.get(userEmail).getAuthToken(); setUserPassword(userEmail, userPassword, authToken); } private void verifyCode(String userEmail, String verificationCode) throws Exception { RegistrationControllerRequest requestData = new RegistrationControllerRequest(); requestData.setEmail(userEmail); requestData.setCode(verificationCode); processWithRequestData(ODSConstants.EMAIL_VERIFICATION_ENDPOINT, requestData); } private void registerUser(String userEmail, String firstName) throws Exception { RegistrationControllerRequest requestData = new RegistrationControllerRequest(); requestData.setFirstName(firstName); requestData.setEmail(userEmail); processWithRequestData(ODSConstants.REGISTRATION_ENDPOINT, requestData); } private String extractVerificationCode(String verificationCodeEmail) { return verificationCodeEmail.substring(verificationCodeEmail.lastIndexOf(" ")).trim(); } private User getFirstUser() { return (User) users.values().toArray()[0]; } private void processWithRequestData(String url, Object requestData) throws Exception { mvc.perform(post(url).with(csrf()).content(toJson(requestData)) .contentType(MediaType.APPLICATION_JSON)); } private String toJson(Object userRequestData) { return new Gson().toJson(userRequestData); } private Answer<Mono<User>> updateUser() { return invocation -> { User user = invocation.getArgument(0); users.put(user.getEmail(), user); return just(user); }; } private Answer<?> addToEmails() { return invocation -> { String recipient = invocation.getArgument(0); String body = invocation.getArgument(2); inbox.put(recipient, body); return null; }; } private Answer<Mono<User>> getFromUsers() { return invocation -> { User user = users.get(invocation.getArgument(0)); return user != null ? just(user) : empty(); }; } private Answer<Mono<User>> addToUsers() { return invocation -> { User user = invocation.getArgument(0); users.put(user.getEmail(), user); return just(user); }; } @SuppressWarnings("unused") private String encodeIntoCookie(Map<String, String> entries) { if (entries.isEmpty()) return ""; StringBuilder cookie = new StringBuilder(); List<String> properties = new ArrayList<>(); entries.forEach((key, value) -> properties.add(format("%s=%s", key, value))); cookie.append(properties.get(0)); for (int i = 1; i < properties.size(); i++) { cookie.append(";").append(properties.get(i)); } return cookie.toString(); } }
package org.traccar.protocol; import org.junit.Test; import org.traccar.ProtocolTest; import org.traccar.model.Position; public class Pt502ProtocolDecoderTest extends ProtocolTest { @Test public void testDecode() throws Exception { Pt502ProtocolDecoder decoder = new Pt502ProtocolDecoder(null); verifyNull(decoder, binary( "24504844302c3936302cffd8ffdb008400140e0f120f0d14121012171514181e32211e1c1c1e3d2c2e243249404c4b47404645505a736250556d5645466488656d777b8182814e608d978c7d96737e817c011517171e1a1e3b21213b7c5346537c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7cffc000110800f0014003012100021101031101ffdd0004000affc401a20000010501010101010100000000000000000102030405060708090a0b100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9fa0100030101010101010101010000000000000102030405060708090a0b1100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00e5292800ef450020a2800a2801d49400b450014b40052e2800a69340094a05007fffd0e5d14b10055b51b00c76a00527273494005250014500251400525001450015347c25003a928010d25007ffd1e52909a00290d0014b40052d0014500145002e297b50018a280109a6d002d2e2803fffd2e7a04da3777a94fbd0025140052500145002514005250014940054e381400b494008690d007fffd3e4f345001486800a5a005a2800a2801680280168a002909e280100cd028016a48937bfb5007fffd4c5038a42280128a004a280128a003ad2500251400945002a8cb0a9a80133450026692803ffd5e4e8a004a2801694500145002d18a005c5140052e280109a69a0029680140abb147b139eb401ffd6c62290d00251400949400114940052500252d002525003e31c93525002521a004a4a00ffd7e4a8a00281400a29d40094b40053ba500252d0018a31400d3cd250018cd2d005ab58777ccdd074ab645007ffd0c72290d00348a2801280")); verifyNull(decoder, buffer( "$POS,718005258,121930.000,V,0514.0960,S,14547.3245,E,0.0,0.0,151020,,/00000,00000/0,0,0,0/106945600//f00//")); verifyPosition(decoder, buffer( "$PHO3821-1,1156802639,022125.000,A,0707.0014,N,07307.3725,W,0.0,0.1,110418,,,A/00000,00000/0,0,0,0/500//fd4//")); verifyPosition(decoder, buffer( "$POS,1360000277,182241.000,A,0846.0896,N,07552.1738,W,13.58,26.88,291017,,,A/00000,00000/142,0,0,0/62792900//f65// verifyPosition(decoder, buffer( "$PHO0-1,1360000260,123012.000,A,0913.9644,N,07548.8345,W,0.0,309.8,111017,,,A/00000,10000/0,0,0,0/64551600//f98//")); verifyPosition(decoder, buffer( "$POS,865328026243864,151105.000,A,1332.7096,N,204.6787,E,0.0,10.00,050517,,,A/00000,10/1,0/234//FD9/")); verifyNull(decoder, buffer( "$FUS865328026243864,510-V1.12,A11-V3.0")); verifyPosition(decoder, buffer( "$HDA,20007,134657.000,A,0626.1607,N,00330.2245,E,33.38,81.79,041016,,,A/00010,00000/270,0,0,0/19948900//fa4//")); verifyPosition(decoder, buffer( "$HDB,20007,134708.000,A,0626.1759,N,00330.3192,E,26.55,80.37,041016,,,A/00010,00000/23b,0,0,0/19949100//fa4//")); verifyPosition(decoder, buffer( "$POS,20007,134704.000,A,0626.1698,N,00330.2870,E,31.23,79.58,041016,,,A/00010,00000/26c,0,0,0/19949100//fa4// verifyPosition(decoder, buffer( "$PHO6608,115099,133140.000,A,1307.1238,N,05936.4194,W,0.00,21.50,290816,,,A/00010,00000/0,0,0,0/185100//f59/")); verifyPosition(decoder, buffer( "$DFR,40456789,083125.000,A,2232.0971,N,11400.9504,E,0.0,5.00,090714,,,A/00000,00/0,0/200076//FE7/")); verifyPosition(decoder, buffer( "$FDA,40456789,083125.000,A,2232.0971,N,11400.9504,E,0.0,5.00,090714,,,A/00000,00/0,0/200076//FE7/")); verifyAttribute(decoder, buffer( "$CPA,40456789,083125.000,A,2232.0971,N,11400.9504,E,7.62,265.24,291117,,,A/00000,00000/0/1200//#"), Position.KEY_ALARM, Position.ALARM_POWER_CUT); verifyPosition(decoder, buffer( "$POS,216769295715,163237.000,A,3258.1738,S,02755.4350,E,0.00,215.88,100915,,,A/0000,0//232300//5b3/"), position("2015-09-10 16:32:37.000", true, -32.96956, 27.92392)); verifyPosition(decoder, buffer( "$POS,11023456,033731.000,A,0335.2617,N,09841.1587,E,0.00,88.12,210615,,,A/0000,0/1f8/388900//f33//")); verifyPosition(decoder, buffer( "$POS,6094,205523.000,A,1013.6223,N,06728.4248,W,0.0,99.3,011112,,,A/00000,00000/0/23895000 verifyPosition(decoder, buffer( "$POS,6120,233326.000,V,0935.1201,N,06914.6933,W,0.00,,151112,,,A/00000,00000/0/0/")); verifyPosition(decoder, buffer( "$POS,6002,233257.000,A,0931.0430,N,06912.8707,W,0.05,146.98,141112,,,A/00010,00000/0/5360872")); verifyPosition(decoder, buffer( "$POS,6095,233344.000,V,0933.0451,N,06912.3360,W,,,151112,,,N/00000,00000/0/1677600/")); verifyPosition(decoder, buffer( "$PHO0,6091,233606.000,A,0902.9855,N,06944.3654,W,0.0,43.8,141112,,,A/00010,00000/0/224000 verifyPosition(decoder, buffer( "$POS,353451000164,082405.000,A,1254.8501,N,10051.6752,E,0.00,237.99,160513,,,A/0000,0/0/55000//a71/")); verifyPosition(decoder, buffer( "$POS,012896008586486,154215.000,A,0118.0143,S,03646.9144,E,0.00,83.29,180714,,,A/0000,0/0/29200//644/")); verifyPosition(decoder, buffer( "$POS,1151000,205326.000,A,0901.3037,N,07928.2751,W,48.79,30.55,170814,,,A/00010,10000/0,0,0,0/15986500//fb8/")); } }
package nl.us2.cloudpelican.stormprocessor; import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.StormSubmitter; import backtype.storm.spout.SchemeAsMultiScheme; import backtype.storm.topology.TopologyBuilder; import backtype.storm.tuple.Fields; import com.google.gson.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import storm.kafka.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; public class Main { public static String KAFKA_SPOUT = "kafka_spout"; public static String MATCH_BOLT = "match_bolt"; public static String SUPERVISOR_RESULT_WRITER = "supervisor_result_writer"; public static String ROLLUP_STATS = "rollup_stats"; public static String SUPERVISOR_STATS_WRITER = "supervisor_stats_writer"; public static String ERROR_CLASSIFIER_BOLT = "error_classifier"; public static String OUTLIER_DETECTION = "outlier_detection"; public static String OUTLIER_COLLECTOR = "outlier_collector"; private static boolean isRunning = true; private static final Logger LOG = LoggerFactory.getLogger(Main.class); public static final int GLOBAL_CONCURRENCY = 6; public static void main(String [] args) throws Exception { ArrayList<String> argList = new ArrayList<String>(); for (String arg : args) { argList.add(arg); } // Config HashMap<String, String> argsMap = new HashMap<String, String>(); for (String arg : argList) { String[] split = arg.split("=", 2); if (split.length == 2 && split[0].trim().length() > 0 && split[1].trim().length() > 0) { if (split[0].equals("-zookeeper")) { argsMap.put("zookeeper_nodes", split[1]); } else if (split[0].equals("-grep")) { argsMap.put("match_regex", split[1]); } else if (split[0].equals("-topic")) { argsMap.put("kafka_topic", split[1]); } else if (split[0].equals("-supervisor-host")) { argsMap.put("supervisor_host", split[1]); } else if (split[0].equals("-supervisor-username")) { argsMap.put("supervisor_username", split[1]); } else if (split[0].equals("-supervisor-password")) { argsMap.put("supervisor_password", split[1]); } else if (split[0].equals("-conf")) { argsMap.put("conf_path", split[1]); } else if (split[0].startsWith("-")) { // Default argsMap.put(split[0].substring(1), split[1]); } } } // Default settings if (!argsMap.containsKey("kafka_consumer_id")) { argsMap.put("kafka_consumer_id", "cloudpelican_lsd_consumer"); } // Settings object Settings settings = new Settings(); JsonObject settingsData = new JsonObject(); // Add light settings to json for (Map.Entry<String, String> kv : argsMap.entrySet()) { settingsData.addProperty(kv.getKey(), kv.getValue()); } // Debug & load LOG.info(settingsData.toString()); settings.load(settingsData); // Topology TopologyBuilder builder = new TopologyBuilder(); // Time TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC")); // Read from kafka BrokerHosts hosts = new ZkHosts(settings.get("zookeeper_nodes")); SpoutConfig spoutConfig = new SpoutConfig(hosts, settings.get("kafka_topic"), "/" + settings.get("kafka_topic"), settings.get("kafka_consumer_id")); spoutConfig.startOffsetTime = kafka.api.OffsetRequest.EarliestTime(); spoutConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); KafkaSpout kafkaSpout = new KafkaSpout(spoutConfig); builder.setSpout(KAFKA_SPOUT, kafkaSpout, Integer.parseInt(settings.getOrDefault("kafka_partitions", "3"))); // Match bolt builder.setBolt(MATCH_BOLT, new MatchBolt(settings), GLOBAL_CONCURRENCY * 6).shuffleGrouping(KAFKA_SPOUT); // No local to prevent hotspots // Error classifier bolt builder.setBolt(ERROR_CLASSIFIER_BOLT, new ErrorClassifierBolt(settings), GLOBAL_CONCURRENCY * 1).fieldsGrouping(MATCH_BOLT, new Fields("filter_id")); // Supervisor result writer bolt builder.setBolt(SUPERVISOR_RESULT_WRITER, new SupervisorResultWriterBolt(settings), GLOBAL_CONCURRENCY * 1).fieldsGrouping(MATCH_BOLT, new Fields("filter_id")); // Supervisor stats writer bolt builder.setBolt(ROLLUP_STATS, new RollupStatsBolt(settings), concurrency(1, 2)).fieldsGrouping(MATCH_BOLT, "match_stats", new Fields("filter_id")).fieldsGrouping(ERROR_CLASSIFIER_BOLT, "error_stats", new Fields("filter_id")); builder.setBolt(SUPERVISOR_STATS_WRITER, new SupervisorStatsWriterBolt(settings), concurrency(1, 4)).fieldsGrouping(ROLLUP_STATS, "rollup_stats", new Fields("filter_id")); // Outlier detection bolts (sharded by filter ID) builder.setBolt(OUTLIER_DETECTION, new OutlierDetectionBolt(settings), GLOBAL_CONCURRENCY * 2).fieldsGrouping(MATCH_BOLT, "dispatch_outlier_checks", new Fields("filter_id")); builder.setBolt(OUTLIER_COLLECTOR, new OutlierCollectorBolt(settings), concurrency(1, 10)).shuffleGrouping(OUTLIER_DETECTION, "outliers"); // Sink if (settings.get("sinks") != null) { String[] sinkIds = settings.get("sinks").split(","); for (String sinkId : sinkIds) { // Type String sinkType = settings.get("sinks." + sinkId + ".type"); AbstractSinkBolt sinkBolt = null; // @todo Sink factory if we have multiple types if (sinkType == null) { throw new Exception("Sink '" + sinkId + "' invalid"); } else if (sinkType.equalsIgnoreCase("bigquery")) { // Google BigQuery sink sinkBolt = new BigQuerySinkBolt(sinkId, settings); } else { throw new Exception("Sink type '" + sinkType + "' not supported"); } // Add to topology if (sinkBolt != null) { String sinkName = "sink_" + sinkType + "_" + sinkId; LOG.info("Setting up sink '" + sinkName + "'"); if (!sinkBolt.isValid()) { LOG.error("Sink '" + sinkName + "' not valid"); } builder.setBolt(sinkName, sinkBolt, GLOBAL_CONCURRENCY * 1).fieldsGrouping(MATCH_BOLT, new Fields("filter_id")); } } } // Debug on for testing Config conf = new Config(); conf.setDebug(false); conf.setMessageTimeoutSecs(60); // Default is 30 seconds, which might be too short under peak load spikes, or when we run the outlier detection String topologyName = settings.getOrDefault("topology_name", "cloudpelican_stormprocessor"); if (argList.contains("-submit")) { conf.setNumWorkers(GLOBAL_CONCURRENCY); conf.setNumAckers(concurrency(2, 10)); conf.setMaxSpoutPending(50000); StormSubmitter.submitTopologyWithProgressBar(topologyName, conf, builder.createTopology()); } else { LocalCluster cluster = new LocalCluster(); cluster.submitTopology(topologyName, conf, builder.createTopology()); // Keep running until interrupt Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run( ){ LOG.info("Shutting down"); isRunning = false; } }); while (isRunning) { Thread.sleep(100); } cluster.killTopology(topologyName); cluster.shutdown(); } } public static int concurrency(int min, int part) { return Math.max(Math.round(GLOBAL_CONCURRENCY / part), min); } }
package kbasesearchengine.test.events; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.time.Instant; import java.util.Arrays; import java.util.Set; import static kbasesearchengine.test.common.TestCommon.set; import org.junit.Test; import kbasesearchengine.events.ObjectEventQueue; import kbasesearchengine.events.StatusEvent; import kbasesearchengine.events.StatusEventID; import kbasesearchengine.events.StatusEventProcessingState; import kbasesearchengine.events.StatusEventType; import kbasesearchengine.events.StoredStatusEvent; public class ObjectEventQueueTest { /* this assert does not mutate the queue state */ private void assertQueueState( final ObjectEventQueue queue, final Set<StoredStatusEvent> ready, final Set<StoredStatusEvent> processing, final int size) { assertThat("incorrect ready", queue.getReadyForProcessing(), is(ready)); assertThat("incorrect get processing", queue.getProcessing(), is(processing)); assertThat("incorrect is processing", queue.isProcessing(), is(!processing.isEmpty())); assertThat("incorrect size", queue.size(), is(size)); } /* this assert does not mutate the queue state */ private void assertEmpty(final ObjectEventQueue queue) { assertQueueState(queue, set(), set(), 0); assertMoveToReadyCorrect(queue, set()); assertMoveToProcessingCorrect(queue, set()); } /* note this assert may change the queue state. */ private void assertMoveToProcessingCorrect( final ObjectEventQueue queue, final Set<StoredStatusEvent> moveToProcessing) { assertThat("incorrect move", queue.moveReadyToProcessing(), is(moveToProcessing)); } /* note this assert may change the queue state. */ private void assertMoveToReadyCorrect( final ObjectEventQueue queue, final Set<StoredStatusEvent> moveToReady) { assertThat("incorrect move", queue.moveToReady(), is(moveToReady)); } @Test public void constructEmpty() { assertEmpty(new ObjectEventQueue()); } @Test public void loadOneObjectLevelEventAndProcess() { final ObjectEventQueue q = new ObjectEventQueue(); final StoredStatusEvent sse = new StoredStatusEvent(StatusEvent.getBuilder( "bar", Instant.ofEpochMilli(10000), StatusEventType.DELETE_ALL_VERSIONS) .build(), new StatusEventID("foo"), StatusEventProcessingState.UNPROC, null, null); assertEmpty(q); q.load(sse); assertQueueState(q, set(), set(), 1); assertMoveToReadyCorrect(q, set(sse)); //mutates queue assertQueueState(q, set(sse), set(), 1); assertMoveToProcessingCorrect(q, set(sse)); //mutates queue assertQueueState(q, set(), set(sse), 1); q.setProcessingComplete(sse); assertEmpty(q); } @Test public void loadMultipleObjectLevelEventsAndProcess() { final ObjectEventQueue q = new ObjectEventQueue(); final StoredStatusEvent sse = new StoredStatusEvent(StatusEvent.getBuilder( "bar", Instant.ofEpochMilli(10000), StatusEventType.DELETE_ALL_VERSIONS) .build(), new StatusEventID("foo"), StatusEventProcessingState.UNPROC, null, null); final StoredStatusEvent sse1 = new StoredStatusEvent(StatusEvent.getBuilder( "bar1", Instant.ofEpochMilli(20000), StatusEventType.NEW_ALL_VERSIONS) .build(), new StatusEventID("foo1"), StatusEventProcessingState.UNPROC, null, null); final StoredStatusEvent sse2 = new StoredStatusEvent(StatusEvent.getBuilder( "bar2", Instant.ofEpochMilli(30000), StatusEventType.RENAME_ALL_VERSIONS) .build(), new StatusEventID("foo2"), StatusEventProcessingState.UNPROC, null, null); assertEmpty(q); q.load(sse2); q.load(sse1); q.load(sse); assertQueueState(q, set(), set(), 3); assertMoveToReadyCorrect(q, set(sse)); assertQueueState(q, set(sse), set(), 3); //check queue is blocked assertMoveToReadyCorrect(q, set()); assertMoveToProcessingCorrect(q, set(sse)); assertQueueState(q, set(), set(sse), 3); //check queue is blocked assertMoveToReadyCorrect(q, set()); assertMoveToProcessingCorrect(q, set()); q.setProcessingComplete(sse); // calls move to ready assertQueueState(q, set(sse1), set(), 2); //check queue is blocked assertMoveToReadyCorrect(q, set()); assertMoveToProcessingCorrect(q, set(sse1)); assertQueueState(q, set(), set(sse1), 2); //check queue is blocked assertMoveToReadyCorrect(q, set()); assertMoveToProcessingCorrect(q, set()); q.setProcessingComplete(sse1); assertQueueState(q, set(sse2), set(), 1); //check queue is blocked assertMoveToReadyCorrect(q, set()); assertMoveToProcessingCorrect(q, set(sse2)); assertQueueState(q, set(), set(sse2), 1); //check queue is blocked assertMoveToReadyCorrect(q, set()); assertMoveToProcessingCorrect(q, set()); q.setProcessingComplete(sse2); assertEmpty(q); } @Test public void loadOneVersionLevelEventAndProcess() { final ObjectEventQueue q = new ObjectEventQueue(); final StoredStatusEvent sse = new StoredStatusEvent(StatusEvent.getBuilder( "bar", Instant.ofEpochMilli(10000), StatusEventType.NEW_VERSION) .build(), new StatusEventID("foo"), StatusEventProcessingState.UNPROC, null, null); assertEmpty(q); q.load(sse); assertQueueState(q, set(), set(), 1); assertMoveToReadyCorrect(q, set(sse)); assertQueueState(q, set(sse), set(), 1); assertMoveToProcessingCorrect(q, set(sse)); assertQueueState(q, set(), set(sse), 1); q.setProcessingComplete(sse); assertEmpty(q); } @Test public void loadMultipleVersionLevelEventsAndProcess() { final ObjectEventQueue q = new ObjectEventQueue(); final StoredStatusEvent sse = new StoredStatusEvent(StatusEvent.getBuilder( "bar", Instant.ofEpochMilli(10000), StatusEventType.NEW_VERSION) .build(), new StatusEventID("foo"), StatusEventProcessingState.UNPROC, null, null); final StoredStatusEvent sse1 = new StoredStatusEvent(StatusEvent.getBuilder( "bar1", Instant.ofEpochMilli(20000), StatusEventType.NEW_VERSION) .build(), new StatusEventID("foo1"), StatusEventProcessingState.UNPROC, null, null); final StoredStatusEvent sse2 = new StoredStatusEvent(StatusEvent.getBuilder( "bar2", Instant.ofEpochMilli(30000), StatusEventType.NEW_VERSION) .build(), new StatusEventID("foo2"), StatusEventProcessingState.UNPROC, null, null); assertEmpty(q); q.load(sse2); q.load(sse); assertQueueState(q, set(), set(), 2); assertMoveToReadyCorrect(q, set(sse, sse2)); //mutates queue assertQueueState(q, set(sse, sse2), set(), 2); assertMoveToProcessingCorrect(q, set(sse, sse2)); //mutates queue assertQueueState(q, set(), set(sse, sse2), 2); q.load(sse1); assertQueueState(q, set(), set(sse, sse2), 3); q.setProcessingComplete(sse2); // calls move to ready assertQueueState(q, set(sse1), set(sse), 2); assertMoveToReadyCorrect(q, set()); // does not mutate queue assertQueueState(q, set(sse1), set(sse), 2); assertMoveToProcessingCorrect(q, set(sse1)); //mutates queue assertQueueState(q, set(), set(sse, sse1), 2); q.setProcessingComplete(sse1); assertQueueState(q, set(), set(sse), 1); q.setProcessingComplete(sse); assertEmpty(q); } @Test public void blockVersionEventsWithObjectLevelEvent() { final ObjectEventQueue q = new ObjectEventQueue(); final StoredStatusEvent sse = new StoredStatusEvent(StatusEvent.getBuilder( "bar", Instant.ofEpochMilli(10000), StatusEventType.NEW_VERSION) .build(), new StatusEventID("foo"), StatusEventProcessingState.UNPROC, null, null); final StoredStatusEvent sse1 = new StoredStatusEvent(StatusEvent.getBuilder( "bar1", Instant.ofEpochMilli(20000), StatusEventType.NEW_VERSION) .build(), new StatusEventID("foo1"), StatusEventProcessingState.UNPROC, null, null); final StoredStatusEvent sse2 = new StoredStatusEvent(StatusEvent.getBuilder( "bar2", Instant.ofEpochMilli(30000), StatusEventType.NEW_VERSION) .build(), new StatusEventID("foo2"), StatusEventProcessingState.UNPROC, null, null); final StoredStatusEvent sse3 = new StoredStatusEvent(StatusEvent.getBuilder( "bar3", Instant.ofEpochMilli(40000), StatusEventType.NEW_VERSION) .build(), new StatusEventID("foo4"), StatusEventProcessingState.UNPROC, null, null); final StoredStatusEvent blocking = new StoredStatusEvent(StatusEvent.getBuilder( "blocker", Instant.ofEpochMilli(25000), StatusEventType.DELETE_ALL_VERSIONS) .build(), new StatusEventID("blk"), StatusEventProcessingState.UNPROC, null, null); assertEmpty(q); q.load(sse3); q.load(sse2); q.load(sse1); q.load(sse); q.load(blocking); assertQueueState(q, set(), set(), 5); assertMoveToReadyCorrect(q, set(sse, sse1)); assertQueueState(q, set(sse, sse1), set(), 5); // check the queue is now blocked assertMoveToReadyCorrect(q, set()); assertQueueState(q, set(sse, sse1), set(), 5); assertMoveToProcessingCorrect(q, set(sse, sse1)); assertQueueState(q, set(), set(sse, sse1), 5); // check queue is still blocked assertMoveToReadyCorrect(q, set()); assertMoveToProcessingCorrect(q, set()); q.setProcessingComplete(sse1); assertQueueState(q, set(), set(sse), 4); // check queue is still blocked assertMoveToReadyCorrect(q, set()); assertMoveToProcessingCorrect(q, set()); q.setProcessingComplete(sse); // calls move to ready assertQueueState(q, set(blocking), set(), 3); // check queue is blocked assertMoveToReadyCorrect(q, set()); assertQueueState(q, set(blocking), set(), 3); assertMoveToProcessingCorrect(q, set(blocking)); assertQueueState(q, set(), set(blocking), 3); //check queue is still blocked assertMoveToReadyCorrect(q, set()); assertMoveToProcessingCorrect(q, set()); assertQueueState(q, set(), set(blocking), 3); q.setProcessingComplete(blocking); // calls move to ready assertQueueState(q, set(sse2, sse3), set(), 2); assertMoveToReadyCorrect(q, set()); assertMoveToProcessingCorrect(q, set(sse2, sse3)); assertQueueState(q, set(), set(sse2, sse3), 2); q.setProcessingComplete(sse2); q.setProcessingComplete(sse3); assertEmpty(q); } @Test public void initializeWithReadyObjectLevelEvent() { for (final StatusEventType type: Arrays.asList(StatusEventType.DELETE_ALL_VERSIONS, StatusEventType.NEW_ALL_VERSIONS, StatusEventType.PUBLISH_ALL_VERSIONS, StatusEventType.RENAME_ALL_VERSIONS, StatusEventType.UNDELETE_ALL_VERSIONS)) { assertSingleReadyEvent(type); } } private void assertSingleReadyEvent(final StatusEventType type) { final StoredStatusEvent sse = new StoredStatusEvent(StatusEvent.getBuilder( "bar", Instant.ofEpochMilli(10000), type) .build(), new StatusEventID("foo"), StatusEventProcessingState.READY, null, null); final ObjectEventQueue q = new ObjectEventQueue(sse); assertQueueState(q, set(sse), set(), 1); } @Test public void initializeWithProcessingObjectLevelEvent() { for (final StatusEventType type: Arrays.asList(StatusEventType.DELETE_ALL_VERSIONS, StatusEventType.NEW_ALL_VERSIONS, StatusEventType.PUBLISH_ALL_VERSIONS, StatusEventType.RENAME_ALL_VERSIONS, StatusEventType.UNDELETE_ALL_VERSIONS)) { assertSingleProcessingEvent(type); } } private void assertSingleProcessingEvent(final StatusEventType type) { final StoredStatusEvent sse = new StoredStatusEvent(StatusEvent.getBuilder( "bar", Instant.ofEpochMilli(10000), type) .build(), new StatusEventID("foo"), StatusEventProcessingState.PROC, null, null); final ObjectEventQueue q = new ObjectEventQueue(sse); assertQueueState(q, set(), set(sse), 1); } //TODO TEST returned sets are immutable }
package hudson.model; import hudson.FilePath; import hudson.Functions; import hudson.tasks.Shell; import hudson.tasks.BatchFile; import hudson.Launcher; import org.jvnet.hudson.test.Email; import org.jvnet.hudson.test.HudsonTestCase; import org.jvnet.hudson.test.TestBuilder; import java.io.IOException; /** * @author Kohsuke Kawaguchi */ public class DirectoryBrowserSupportTest extends HudsonTestCase { /** * Double dots that appear in file name is OK. */ @Email("http: public void testDoubleDots() throws Exception { // create a problematic file name in the workspace FreeStyleProject p = createFreeStyleProject(); if(Functions.isWindows()) p.getBuildersList().add(new BatchFile("echo > abc..def")); else p.getBuildersList().add(new Shell("touch abc..def")); p.scheduleBuild2(0).get(); // can we see it? new WebClient().goTo("job/"+p.getName()+"/ws/abc..def","application/octet-stream"); // TODO: implement negative check to make sure we aren't serving unexpected directories. // the following trivial attempt failed. Someone in between is normalizing. // // but this should fail // try { // new WebClient().goTo("job/" + p.getName() + "/ws/abc/../", "application/octet-stream"); // } catch (FailingHttpStatusCodeException e) { // assertEquals(400,e.getStatusCode()); } /** * <strike>Also makes sure '\\' in the file name for Unix is handled correctly</strike>. * * To prevent directory traversal attack, we now treat '\\' just like '/'. */ @Email("http: public void testDoubleDots2() throws Exception { if(Functions.isWindows()) return; // can't test this on Windows // create a problematic file name in the workspace FreeStyleProject p = createFreeStyleProject(); p.getBuildersList().add(new Shell("mkdir abc; touch abc/def.bin")); p.scheduleBuild2(0).get(); // can we see it? new WebClient().goTo("job/"+p.getName()+"/ws/abc%5Cdef.bin","application/octet-stream"); } public void testNonAsciiChar() throws Exception { // create a problematic file name in the workspace FreeStyleProject p = createFreeStyleProject(); p.getBuildersList().add(new TestBuilder() { public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { build.getWorkspace().child("\u6F22\u5B57.bin").touch(0); // Kanji return true; } }); // Kanji p.scheduleBuild2(0).get(); // can we see it? new WebClient().goTo("job/"+p.getName()+"/ws/%e6%bc%a2%e5%ad%97.bin","application/octet-stream"); } public void testGlob() throws Exception { FreeStyleProject p = createFreeStyleProject(); p.getBuildersList().add(new TestBuilder() { @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { FilePath ws = build.getWorkspace(); ws.child("pom.xml").touch(0); ws.child("src/main/java/p").mkdirs(); ws.child("src/main/java/p/X.java").touch(0); ws.child("src/main/resources/p").mkdirs(); ws.child("src/main/resources/p/x.txt").touch(0); ws.child("src/test/java/p").mkdirs(); ws.child("src/test/java/p/XTest.java").touch(0); return true; } }); assertEquals(Result.SUCCESS, p.scheduleBuild2(0).get().getResult()); String text = new WebClient().goTo("job/"+p.getName()+"/ws*.java").asText(); assertTrue(text, text.contains("X.java")); assertTrue(text, text.contains("XTest.java")); assertFalse(text, text.contains("pom.xml")); assertFalse(text, text.contains("x.txt")); } }
package com.intellij.ui.jcef; import com.intellij.application.options.RegistryManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.registry.Registry; import com.intellij.ui.JBColor; import com.intellij.util.ArrayUtil; import com.jetbrains.cef.JCefAppConfig; import org.cef.CefApp; import org.cef.CefSettings; import org.cef.CefSettings.LogSeverity; import org.cef.browser.CefBrowser; import org.cef.browser.CefFrame; import org.cef.callback.CefSchemeHandlerFactory; import org.cef.callback.CefSchemeRegistrar; import org.cef.handler.CefAppHandlerAdapter; import org.cef.handler.CefResourceHandler; import org.cef.network.CefRequest; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import static com.intellij.ui.jcef.JBCefFileSchemeHandler.FILE_SCHEME_NAME; /** * A wrapper over {@link CefApp}. * <p> * Use {@link #getInstance()} to get the app (triggers CEF startup on first call). * Use {@link #createClient()} to create a client. * * @author tav */ @ApiStatus.Experimental public final class JBCefApp { private static final Logger LOG = Logger.getInstance(JBCefApp.class); // [tav] todo: retrieve the version at compile time from the "jcef" maven lib private static final int MIN_SUPPORTED_CEF_MAJOR_VERSION = 80; @NotNull private final CefApp myCefApp; @NotNull private final Disposable myDisposable = new Disposable() { @Override public void dispose() { myCefApp.dispose(); } }; private static volatile AtomicBoolean ourSupported; private static final Object ourSupportedLock = new Object(); private static final AtomicBoolean ourInitialized = new AtomicBoolean(false); private static final List<JBCefCustomSchemeHandlerFactory> ourCustomSchemeHandlerFactoryList = Collections.synchronizedList(new ArrayList<>()); private JBCefApp(@NotNull JCefAppConfig config) { CefApp.startup(ArrayUtil.EMPTY_STRING_ARRAY); CefSettings settings = config.getCefSettings(); settings.windowless_rendering_enabled = false; settings.log_severity = getLogLevel(); Color bg = JBColor.background(); settings.background_color = settings.new ColorType(bg.getAlpha(), bg.getRed(), bg.getGreen(), bg.getBlue()); if (ApplicationManager.getApplication().isInternal()) { settings.remote_debugging_port = Registry.intValue("ide.browser.jcef.debug.port"); } CefApp.addAppHandler(new MyCefAppHandler(config.getAppArgs())); myCefApp = CefApp.getInstance(settings); Disposer.register(ApplicationManager.getApplication(), myDisposable); } private static LogSeverity getLogLevel() { String level = System.getProperty("ide.browser.jcef.log.level", "disable").toLowerCase(Locale.ENGLISH); switch (level) { case "disable": return LogSeverity.LOGSEVERITY_DISABLE; case "verbose": return LogSeverity.LOGSEVERITY_VERBOSE; case "info": return LogSeverity.LOGSEVERITY_INFO; case "warning": return LogSeverity.LOGSEVERITY_WARNING; case "error": return LogSeverity.LOGSEVERITY_ERROR; case "fatal": return LogSeverity.LOGSEVERITY_FATAL; case "default": default: return LogSeverity.LOGSEVERITY_DEFAULT; } } @NotNull Disposable getDisposable() { return myDisposable; } @NotNull public static JBCefApp getInstance() { if (Holder.INSTANCE == null) { throw new IllegalStateException("JCEF is not supported in this env or failed to initialize"); } return Holder.INSTANCE; } private static class Holder { @Nullable static final JBCefApp INSTANCE; static { ourInitialized.set(true); JCefAppConfig config = null; if (isSupported(true)) { try { config = JCefAppConfig.getInstance(); } catch (Exception e) { LOG.error(e); } } INSTANCE = config != null ? new JBCefApp(config) : null; } } /** * Returns whether JCEF is supported. For that: * <ul> * <li> It should be available in the running JBR. * <li> It should have a compatible version. * </ul> * In order to assuredly meet the above requirements the IDE should run with a bundled JBR. */ public static boolean isSupported() { return isSupported(false); } private static boolean isSupported(boolean logging) { if (ourSupported != null) { return ourSupported.get(); } synchronized (ourSupportedLock) { if (ourSupported != null) { return ourSupported.get(); } Function<String, Boolean> unsupported = (msg) -> { ourSupported = new AtomicBoolean(false); if (logging) { LOG.warn(msg + (!msg.contains("disabled") ? " (Use JBR bundled with the IDE)" : "")); } return false; }; // warn: do not change to Registry.is(), the method used at startup if (!RegistryManager.getInstance().is("ide.browser.jcef.enabled")) { return unsupported.apply("JCEF is manually disabled via 'ide.browser.jcef.enabled'"); } String version; try { version = JCefAppConfig.getVersion(); } catch (NoSuchMethodError e) { return unsupported.apply("JCEF runtime version is not supported"); } if (version == null) { return unsupported.apply("JCEF runtime version is not available"); } String[] split = version.split("\\."); if (split.length == 0) { return unsupported.apply("JCEF runtime version has wrong format: " + version); } try { int majorVersion = Integer.parseInt(split[0]); if (MIN_SUPPORTED_CEF_MAJOR_VERSION > majorVersion) { return unsupported.apply("JCEF minimum supported major version is " + MIN_SUPPORTED_CEF_MAJOR_VERSION + ", current is " + majorVersion); } } catch (NumberFormatException e) { return unsupported.apply("JCEF runtime version has wrong format: " + version); } String path = JCefAppConfig.class.getResource("JCefAppConfig.class").toString(); String name = JCefAppConfig.class.getName().replace('.', '/'); boolean isJbrModule = path != null && path.contains("/jcef/" + name); if (!isJbrModule) { return unsupported.apply("JCEF runtime library is not a JBR module"); } ourSupported = new AtomicBoolean(true); return true; } } @NotNull public JBCefClient createClient() { return new JBCefClient(myCefApp.createClient()); } @SuppressWarnings("unused") /*public*/ static void addCefCustomSchemeHandlerFactory(@NotNull JBCefApp.JBCefCustomSchemeHandlerFactory factory) { if (ourInitialized.get()) { throw new IllegalStateException("JBCefApp has already been initialized!"); } ourCustomSchemeHandlerFactoryList.add(factory); } public interface JBCefCustomSchemeHandlerFactory extends CefSchemeHandlerFactory { /** * A callback to register the custom scheme handler via calling: * {@link CefSchemeRegistrar#addCustomScheme(String, boolean, boolean, boolean, boolean, boolean, boolean, boolean)}. */ void registerCustomScheme(@NotNull CefSchemeRegistrar registrar); /** * Returns the custom scheme name. */ @NotNull String getSchemeName(); /** * Returns a domain name restricting the scheme. * An empty string should be returned when all domains are permitted. */ @NotNull String getDomainName(); } private static class MyCefAppHandler extends CefAppHandlerAdapter { MyCefAppHandler(String @Nullable[] args) { super(args); } @Override public boolean onBeforeTerminate() { // Do not let JCEF auto-terminate by Cmd+Q (or an alternative), // so that IDE (user) has an option to decide return true; } @Override public void onRegisterCustomSchemes(CefSchemeRegistrar registrar) { for (JBCefCustomSchemeHandlerFactory f : ourCustomSchemeHandlerFactoryList) { f.registerCustomScheme(registrar); } } @Override public void onContextInitialized() { for (JBCefCustomSchemeHandlerFactory f : ourCustomSchemeHandlerFactoryList) { getInstance().myCefApp.registerSchemeHandlerFactory(f.getSchemeName(), f.getDomainName(), f); } ourCustomSchemeHandlerFactoryList.clear(); // no longer needed getInstance().myCefApp.registerSchemeHandlerFactory(FILE_SCHEME_NAME, "", new CefSchemeHandlerFactory() { @Override public CefResourceHandler create(CefBrowser browser, CefFrame frame, String schemeName, CefRequest request) { return FILE_SCHEME_NAME.equals(schemeName) ? new JBCefFileSchemeHandler(browser, frame) : null; } }); } } }
package com.intellij.util.text; import com.intellij.CommonBundle; import com.intellij.jna.JnaLoader; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Clock; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.win32.StdCallLibrary; import org.jetbrains.annotations.NotNull; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class DateFormatUtil { private static final Logger LOG = Logger.getInstance("com.intellij.util.text.DateFormatUtil"); public static final long SECOND = 1000; public static final long MINUTE = SECOND * 60; public static final long HOUR = MINUTE * 60; public static final long DAY = HOUR * 24; public static final long WEEK = DAY * 7; public static final long MONTH = DAY * 30; public static final long YEAR = DAY * 365; public static final long DAY_FACTOR = 24L * 60 * 60 * 1000; // do not expose these constants - they are very likely to be changed in future private static final SyncDateFormat DATE_FORMAT; private static final SyncDateFormat TIME_FORMAT; private static final SyncDateFormat TIME_WITH_SECONDS_FORMAT; private static final SyncDateFormat DATE_TIME_FORMAT; private static final SyncDateFormat ABOUT_DATE_FORMAT; private static final SyncDateFormat ISO8601_FORMAT; static { SyncDateFormat[] formats = getDateTimeFormats(); DATE_FORMAT = formats[0]; TIME_FORMAT = formats[1]; TIME_WITH_SECONDS_FORMAT = formats[2]; DATE_TIME_FORMAT = formats[3]; ABOUT_DATE_FORMAT = new SyncDateFormat(DateFormat.getDateInstance(DateFormat.LONG, Locale.US)); @SuppressWarnings("SpellCheckingInspection") DateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); iso8601.setTimeZone(TimeZone.getTimeZone("UTC")); ISO8601_FORMAT = new SyncDateFormat(iso8601); } private static final long[] DENOMINATORS = {YEAR, MONTH, WEEK, DAY, HOUR, MINUTE}; private enum Period {YEAR, MONTH, WEEK, DAY, HOUR, MINUTE} private static final Period[] PERIODS = {Period.YEAR, Period.MONTH, Period.WEEK, Period.DAY, Period.HOUR, Period.MINUTE}; private DateFormatUtil() { } public static long getDifferenceInDays(@NotNull Date startDate, @NotNull Date endDate) { return (endDate.getTime() - startDate.getTime() + DAY_FACTOR - 1000) / DAY_FACTOR; } @NotNull public static SyncDateFormat getDateFormat() { return DATE_FORMAT; } @NotNull public static SyncDateFormat getTimeFormat() { return TIME_FORMAT; } @NotNull public static SyncDateFormat getTimeWithSecondsFormat() { return TIME_WITH_SECONDS_FORMAT; } @NotNull public static SyncDateFormat getDateTimeFormat() { return DATE_TIME_FORMAT; } @NotNull public static SyncDateFormat getIso8601Format() { return ISO8601_FORMAT; } @NotNull public static String formatTime(@NotNull Date time) { return formatTime(time.getTime()); } @NotNull public static String formatTime(long time) { return getTimeFormat().format(time); } @NotNull public static String formatTimeWithSeconds(@NotNull Date time) { return formatTimeWithSeconds(time.getTime()); } @NotNull public static String formatTimeWithSeconds(long time) { return getTimeWithSecondsFormat().format(time); } @NotNull public static String formatDate(@NotNull Date time) { return formatDate(time.getTime()); } @NotNull public static String formatDate(long time) { return getDateFormat().format(time); } @NotNull public static String formatPrettyDate(@NotNull Date date) { return formatPrettyDate(date.getTime()); } @NotNull public static String formatPrettyDate(long time) { return doFormatPretty(time, false); } @NotNull public static String formatDateTime(Date date) { return formatDateTime(date.getTime()); } @NotNull public static String formatDateTime(long time) { return getDateTimeFormat().format(time); } @NotNull public static String formatPrettyDateTime(@NotNull Date date) { return formatPrettyDateTime(date.getTime()); } @NotNull public static String formatPrettyDateTime(long time) { return doFormatPretty(time, true); } @NotNull private static String doFormatPretty(long time, boolean formatTime) { long currentTime = Clock.getTime(); Calendar c = Calendar.getInstance(); c.setTimeInMillis(currentTime); int currentYear = c.get(Calendar.YEAR); int currentDayOfYear = c.get(Calendar.DAY_OF_YEAR); c.setTimeInMillis(time); int year = c.get(Calendar.YEAR); int dayOfYear = c.get(Calendar.DAY_OF_YEAR); if (LOG.isTraceEnabled()) { LOG.trace("now=" + currentTime + " t=" + time + " z=" + c.getTimeZone()); } if (formatTime) { long delta = currentTime - time; if (delta >= 0 && delta <= HOUR + MINUTE) { return CommonBundle.message("date.format.minutes.ago", (int)Math.rint(delta / (double)MINUTE)); } } boolean isToday = currentYear == year && currentDayOfYear == dayOfYear; if (isToday) { String result = CommonBundle.message("date.format.today"); return formatTime ? result + " " + TIME_FORMAT.format(time) : result; } boolean isYesterdayOnPreviousYear = (currentYear == year + 1) && currentDayOfYear == 1 && dayOfYear == c.getActualMaximum(Calendar.DAY_OF_YEAR); boolean isYesterday = isYesterdayOnPreviousYear || (currentYear == year && currentDayOfYear == dayOfYear + 1); if (isYesterday) { String result = CommonBundle.message("date.format.yesterday"); return formatTime ? result + " " + TIME_FORMAT.format(time) : result; } return formatTime ? DATE_TIME_FORMAT.format(time) : DATE_FORMAT.format(time); } @NotNull public static String formatFrequency(long time) { return CommonBundle.message("date.frequency", formatBetweenDates(time, 0)); } @NotNull public static String formatBetweenDates(long d1, long d2) { long delta = Math.abs(d1 - d2); if (delta == 0) return CommonBundle.message("date.format.right.now"); int n = -1; int i; for (i = 0; i < DENOMINATORS.length; i++) { long denominator = DENOMINATORS[i]; if (delta >= denominator) { n = (int)(delta / denominator); break; } } if (d2 > d1) { if (n <= 0) { return CommonBundle.message("date.format.a.few.moments.ago"); } else { return someTimeAgoMessage(PERIODS[i], n); } } else if (d2 < d1) { if (n <= 0) { return CommonBundle.message("date.format.in.a.few.moments"); } else { return composeInSomeTimeMessage(PERIODS[i], n); } } return ""; } @NotNull public static String formatAboutDialogDate(@NotNull Date date) { return formatAboutDialogDate(date.getTime()); } @NotNull public static String formatAboutDialogDate(long time) { return ABOUT_DATE_FORMAT.format(time); } //<editor-fold desc="Helpers."> private static String someTimeAgoMessage(final Period period, final int n) { switch (period) { case DAY: return CommonBundle.message("date.format.n.days.ago", n); case MINUTE: return CommonBundle.message("date.format.n.minutes.ago", n); case HOUR: return CommonBundle.message("date.format.n.hours.ago", n); case MONTH: return CommonBundle.message("date.format.n.months.ago", n); case WEEK: return CommonBundle.message("date.format.n.weeks.ago", n); default: return CommonBundle.message("date.format.n.years.ago", n); } } private static String composeInSomeTimeMessage(final Period period, final int n) { switch (period) { case DAY: return CommonBundle.message("date.format.in.n.days", n); case MINUTE: return CommonBundle.message("date.format.in.n.minutes", n); case HOUR: return CommonBundle.message("date.format.in.n.hours", n); case MONTH: return CommonBundle.message("date.format.in.n.months", n); case WEEK: return CommonBundle.message("date.format.in.n.weeks", n); default: return CommonBundle.message("date.format.in.n.years", n); } } private static SyncDateFormat[] getDateTimeFormats() { DateFormat[] formats = null; try { if (SystemInfo.isMac && JnaLoader.isLoaded()) { formats = getMacFormats(); } else if (SystemInfo.isUnix) { formats = getUnixFormats(); } else if (SystemInfo.isWin7OrNewer && JnaLoader.isLoaded() ) { formats = getWindowsFormats(); } } catch (Throwable t) { LOG.error(t); } if (formats == null) { formats = new DateFormat[]{ DateFormat.getDateInstance(DateFormat.SHORT), DateFormat.getTimeInstance(DateFormat.SHORT), DateFormat.getTimeInstance(DateFormat.MEDIUM), DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT) }; } if (LOG.isTraceEnabled()) { LOG.trace("formats (OS=" + SystemInfo.OS_NAME + " JNA=" + JnaLoader.isLoaded() + ")"); for (DateFormat format: formats) { LOG.trace("'" + (format instanceof SimpleDateFormat ? ((SimpleDateFormat)format).toPattern() : format.toString()) + "'"); } } SyncDateFormat[] synced = new SyncDateFormat[4]; for (int i = 0; i < formats.length; i++) { synced[i] = new SyncDateFormat(formats[i]); } return synced; } private interface CF extends Library { long kCFDateFormatterNoStyle = 0; long kCFDateFormatterShortStyle = 1; long kCFDateFormatterMediumStyle = 2; @Structure.FieldOrder({"location", "length"}) class CFRange extends Structure implements Structure.ByValue { public long location; public long length; public CFRange(long location, long length) { this.location = location; this.length = length; } } Pointer CFLocaleCopyCurrent(); Pointer CFDateFormatterCreate(Pointer allocator, Pointer locale, long dateStyle, long timeStyle); Pointer CFDateFormatterGetFormat(Pointer formatter); long CFStringGetLength(Pointer str); void CFStringGetCharacters(Pointer str, CFRange range, char[] buffer); void CFRelease(Pointer p); } // platform-specific patterns: http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns private static DateFormat[] getMacFormats() { CF cf = Native.load("CoreFoundation", CF.class); Pointer locale = cf.CFLocaleCopyCurrent(); try { return new DateFormat[]{ getMacFormat(cf, locale, CF.kCFDateFormatterShortStyle, CF.kCFDateFormatterNoStyle), // short date getMacFormat(cf, locale, CF.kCFDateFormatterNoStyle, CF.kCFDateFormatterShortStyle), // short time getMacFormat(cf, locale, CF.kCFDateFormatterNoStyle, CF.kCFDateFormatterMediumStyle), // medium time getMacFormat(cf, locale, CF.kCFDateFormatterShortStyle, CF.kCFDateFormatterShortStyle) // short date/time }; } finally { cf.CFRelease(locale); } } private static DateFormat getMacFormat(CF cf, Pointer locale, long dateStyle, long timeStyle) { Pointer formatter = cf.CFDateFormatterCreate(null, locale, dateStyle, timeStyle); if (formatter == null) throw new IllegalStateException("CFDateFormatterCreate: null"); try { Pointer format = cf.CFDateFormatterGetFormat(formatter); int length = (int)cf.CFStringGetLength(format); char[] buffer = new char[length]; cf.CFStringGetCharacters(format, new CF.CFRange(0, length), buffer); return formatFromString(new String(buffer)); } finally { cf.CFRelease(formatter); } } private static DateFormat[] getUnixFormats() { String localeStr = System.getenv("LC_TIME"); if (LOG.isTraceEnabled()) LOG.trace("LC_TIME=" + localeStr); if (localeStr == null) return null; localeStr = localeStr.trim(); int p = localeStr.indexOf('.'); if (p > 0) localeStr = localeStr.substring(0, p); p = localeStr.indexOf('@'); if (p > 0) localeStr = localeStr.substring(0, p); Locale locale; p = localeStr.indexOf('_'); if (p < 0) { locale = new Locale(localeStr); } else { locale = new Locale(localeStr.substring(0, p), localeStr.substring(p + 1)); } return new DateFormat[]{ DateFormat.getDateInstance(DateFormat.SHORT, locale), DateFormat.getTimeInstance(DateFormat.SHORT, locale), DateFormat.getTimeInstance(DateFormat.MEDIUM, locale), DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale) }; } @SuppressWarnings("SpellCheckingInspection") private interface Kernel32 extends StdCallLibrary { int LOCALE_SSHORTDATE = 0x0000001F; int LOCALE_SSHORTTIME = 0x00000079; int LOCALE_STIMEFORMAT = 0x00001003; int GetLocaleInfoEx(String localeName, int lcType, char[] lcData, int dataSize); int GetLastError(); } private static DateFormat[] getWindowsFormats() { Kernel32 kernel32 = Native.load("Kernel32", Kernel32.class); int bufferSize = 128, rv; char[] buffer = new char[bufferSize]; rv = kernel32.GetLocaleInfoEx(null, Kernel32.LOCALE_SSHORTDATE, buffer, bufferSize); if (rv < 2) throw new IllegalStateException("GetLocaleInfoEx: " + kernel32.GetLastError()); String shortDate = fixWindowsFormat(new String(buffer, 0, rv - 1)); rv = kernel32.GetLocaleInfoEx(null, Kernel32.LOCALE_SSHORTTIME, buffer, bufferSize); if (rv < 2) throw new IllegalStateException("GetLocaleInfoEx: " + kernel32.GetLastError()); String shortTime = fixWindowsFormat(new String(buffer, 0, rv - 1)); rv = kernel32.GetLocaleInfoEx(null, Kernel32.LOCALE_STIMEFORMAT, buffer, bufferSize); if (rv < 2) throw new IllegalStateException("GetLocaleInfoEx: " + kernel32.GetLastError()); String mediumTime = fixWindowsFormat(new String(buffer, 0, rv - 1)); return new DateFormat[]{ formatFromString(shortDate), formatFromString(shortTime), formatFromString(mediumTime), formatFromString(shortDate + " " + shortTime) }; } private static String fixWindowsFormat(String format) { format = format.replaceAll("g+", "G"); format = StringUtil.replace(format, "tt", "a"); return format; } private static DateFormat formatFromString(String format) { try { return new SimpleDateFormat(format.trim()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("unrecognized format string '" + format + "'"); } } //</editor-fold> }
package info.tregmine.listeners; import info.tregmine.Tregmine; import info.tregmine.api.TregminePlayer; import info.tregmine.database.ConnectionPool; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import java.util.TimeZone; import org.bukkit.ChatColor; //import org.bukkit.GameMode; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; //import org.bukkit.entity.Player; import org.bukkit.entity.Player; import org.bukkit.event.block.Action; //import org.bukkit.event.player.PlayerEvent; import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.player.PlayerBucketFillEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerListener; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerLoginEvent.Result; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerPreLoginEvent; import org.bukkit.event.player.PlayerQuitEvent; public class TregminePlayerListener extends PlayerListener { private final static String[] quitMessages = new String[] { ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " deserted from the battlefield with a hearty good bye!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " stole the cookies and ran!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " was eaten by a teenage mutant ninja platypus!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " parachuted of the plane and into the unknown!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " stole the cookies and ran!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " was eaten by a teenage mutant ninja creeper!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " jumped off the plane with a cobble stone parachute!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " built Rome in one day and now deserves a break!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " will come back soon because Tregmine is awesome!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " leaves the light and enter darkness.", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " disconnects from a better life.", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " already miss the best friends in the world!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " will build something epic next time.", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " is not banned yet!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " has left our world!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " went to browse Tregmine's forums instead!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " was scared away by einand! :(", ChatColor.YELLOW + "Quit - " + "%s" + "'s" + ChatColor.YELLOW + " CPU was killed by the Rendermen!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " fell off the map!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " logged out on accident!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " found the IRL warp!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " left the game due to IRL chunk error issues!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " left the Matrix. Say hi to Morpheus!", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " <reserved space for ads. Contact a Senior Admin. Only 200k!>", ChatColor.YELLOW + "Quit - " + "%s" + ChatColor.YELLOW + " disconnected? What is this!? Impossibru!" }; private final Tregmine plugin; public TregminePlayerListener(Tregmine instance) { plugin = instance; plugin.getServer(); } public void onPlayerBucketFill(PlayerBucketFillEvent event) { if (event.getBucket() == Material.LAVA_BUCKET) { event.setCancelled(true); } if (event.getBlockClicked().getType() == Material.LAVA) { event.setCancelled(true); } if (event.getBlockClicked().getType() == Material.STATIONARY_LAVA) { event.setCancelled(true); } } public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event){ if (event.getBucket() == Material.LAVA_BUCKET) { event.setCancelled(true); } } public void onPlayerInteract(PlayerInteractEvent event) { info.tregmine.api.TregminePlayer tregminePlayer = this.plugin.tregminePlayer.get(event.getPlayer().getName()); if (!tregminePlayer.isTrusted()) { event.setCancelled(true); } if (tregminePlayer.isAdmin()) { event.setCancelled(false); } if (event.getPlayer().getItemInHand().getTypeId() == Material.PAPER.getId() && event.getAction() == Action.RIGHT_CLICK_BLOCK ) { Location block = event.getClickedBlock().getLocation(); java.util.zip.CRC32 crc32 = new java.util.zip.CRC32(); String pos = block.getX() + "," + block.getY() + "," + block.getZ(); crc32.update(pos.getBytes()); long checksum = crc32.getValue(); String timezone = tregminePlayer.getTimezone(); SimpleDateFormat dfm = new SimpleDateFormat("dd/MM/yy hh:mm:ss a"); dfm.setTimeZone(TimeZone.getTimeZone(timezone)); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = ConnectionPool.getConnection(); stmt = conn.prepareStatement("SELECT * FROM stats_blocks WHERE checksum = ? " + "ORDER BY time DESC LIMIT 5"); stmt.setLong(1, checksum); stmt.execute(); rs = stmt.getResultSet(); //TODO : Reverse the sorting order while (rs.next()) { Date date = new Date(rs.getLong("time")); long blockid = rs.getLong("blockid"); String player = rs.getString("player"); boolean placed = rs.getBoolean("status"); Material mat = Material.getMaterial((int) blockid); if (placed == true) { event.getPlayer().sendMessage(ChatColor.DARK_AQUA + mat.name().toLowerCase() + " placed by " + player + " at " + dfm.format(date)); } else { event.getPlayer().sendMessage(ChatColor.DARK_AQUA + mat.name().toLowerCase() + " delete by " + player + " at " + dfm.format(date)); } } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } } } public void onPlayerJoin(PlayerJoinEvent event) { event.setJoinMessage(null); if (!event.getPlayer().isOp()) { event.getPlayer().setGameMode(GameMode.SURVIVAL); } } public void onPlayerLogin(PlayerLoginEvent event) { Player player = event.getPlayer(); String playerName = player.getName(); TregminePlayer tregPlayer = new TregminePlayer(player, playerName); if(tregPlayer.exists()) { tregPlayer.load(); } else { tregPlayer.create(); tregPlayer.load(); } if (tregPlayer.isBanned()) { event.setKickMessage("You are not allowed on this server!"); event.disallow(Result.KICK_BANNED, "You shall not pass!"); } else { this.plugin.tregminePlayer.put(playerName, tregPlayer); } } public void onPlayerQuit(PlayerQuitEvent event) { event.setQuitMessage(null); TregminePlayer tregP = this.plugin.tregminePlayer.get(event.getPlayer().getName()); if(!event.getPlayer().isOp()) { Random rand = new Random(); int msgIndex = rand.nextInt(quitMessages.length); String message = String.format(quitMessages[msgIndex], tregP.getChatName()); this.plugin.getServer().broadcastMessage(message); } this.plugin.tregminePlayer.remove(event.getPlayer().getName()); this.plugin.log.info("Unloaded settings for " + event.getPlayer().getName() + "."); } public void onPlayerPreLogin(PlayerPreLoginEvent event) { Player player = this.plugin.getServer().getPlayer(event.getName()); if (player != null) { player.kickPlayer("Sorry, we don't allow clones on this server."); } } public void onPlayerMove(PlayerMoveEvent event) { // if player move } public void onPlayerTeleport(PlayerMoveEvent event) { // if player teleport } public void onPlayerPickupItem (PlayerPickupItemEvent event){ TregminePlayer tregminePlayer; try { tregminePlayer = this.plugin.tregminePlayer.get(event.getPlayer().getName()); } catch (Exception e) { e.printStackTrace(); event.setCancelled(true); return; } if (tregminePlayer.isAdmin()) { return; } if (!tregminePlayer.isTrusted()) { event.setCancelled(true); return; } } public void onPlayerDropItem (PlayerDropItemEvent event) { TregminePlayer tregminePlayer = this.plugin.tregminePlayer.get(event.getPlayer().getName()); if (tregminePlayer.isAdmin()) { return; } if (!tregminePlayer.isTrusted()) { event.setCancelled(true); return; } } public void onPlayerKick(PlayerKickEvent event) { event.setLeaveMessage(null); } }
package com.google.sps.utils; // Imports the Google Cloud client library import com.google.cloud.dialogflow.v2.QueryInput; import com.google.cloud.dialogflow.v2.QueryResult; import com.google.gson.Gson; import com.google.protobuf.ByteString; import com.google.protobuf.Struct; import com.google.protobuf.Value; import com.google.sps.utils.TextUtils; import com.google.sps.utils.SpeechUtils; import com.google.sps.data.Location; import com.google.sps.data.Output; import com.google.sps.agents.*; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Map; import java.util.stream.Collectors; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; /** * Identifies agent from Dialogflow API Query result and creates Output object */ public class AgentUtils { public static Output getOutput(QueryResult queryResult, String languageCode) { String fulfillment = null; String display = null; String redirect = null; byte[] byteStringToByteArray = null; Agent object = null; String detectedIntent = queryResult.getIntent().getDisplayName(); String agentName = getAgentName(detectedIntent); String intentName = getIntentName(detectedIntent); // Retrieve detected input from DialogFlow result. String inputDetected = queryResult.getQueryText(); inputDetected = inputDetected.equals("") ? " (null) " : inputDetected; Map<String, Value> parameterMap = getParameterMap(queryResult); Agent object = null; // Case where response is pre-defined in Dialogflow if (!queryResult.getFulfillmentText().isEmpty()){ fulfillment = queryResult.getFulfillmentText(); }else{ object = getAgent(agentName, intentName, parameterMap); if (object != null){ try{ fulfillment = object.getOutput(); display = object.getDisplay(); redirect = object.getRedirect(); }catch (Exception e){ e.printStackTrace(); } } else { fulfillment = queryResult.getFulfillmentText(); fulfillment = fulfillment.equals("") ? "I didn't hear you. Can you repeat that?" : fulfillment; } } fulfillment = fulfillment == null ? "I didn't hear you. Can you repeat that?" : fulfillment; byteStringToByteArray = getByteStringToByteArray(fulfillment, languageCode); Output output = new Output(inputDetected, fulfillment, byteStringToByteArray, display, redirect); return output; } private static Agent getAgent(String agentName, String intentName, Map<String, Value> parameterMap) { switch(agentName) { case "calculator": return new Tip(intentName, parameterMap); case "currency": return new Currency(intentName, parameterMap); case "language": return new Language(intentName, parameterMap); case "name": return new Name(intentName, parameterMap); case "reminders": return new Reminders(intentName, parameterMap); case "time": return new Time(intentName, parameterMap); case "translate": return new TranslateAgent(intentName, parameterMap); case "units": return new UnitConverter(intentName, parameterMap); case "weather": return new Weather(intentName, parameterMap); case "web": return new WebSearch(intentName, parameterMap); default: return null; } } private static String getAgentName(String detectedIntent) { String[] intentList = detectedIntent.split("\\.", 2); return intentList[0]; } private static String getIntentName(String detectedIntent) { String[] intentList = detectedIntent.split("\\.", 2); String intentName = detectedIntent; if (intentList.length > 1){ intentName = intentList[1]; } return intentName; } public static Map<String, Value> getParameterMap(QueryResult queryResult) { Struct paramStruct = queryResult.getParameters(); Map<String, Value> parameters = paramStruct.getFieldsMap(); return parameters; } public static byte[] getByteStringToByteArray(String fulfillment, String languageCode){ byte[] byteArray = null; try { ByteString audioResponse = SpeechUtils.synthesizeText(fulfillment, languageCode); byteArray = audioResponse.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return byteArray; } public static String getLanguageCode(String language) { if (language == null) { return "en-US"; } switch(language) { case "Chinese": return "zh-CN"; case "English": return "en-US"; case "French": return "fr"; case "German": return "de"; case "Hindi": return "hi"; case "Italian": return "it"; case "Japanese": return "ja"; case "Korean": return "ko"; case "Portuguese": return "pt"; case "Russian": return "ru"; case "Spanish": return "es"; case "Swedish": return "sv"; default: return null; } } }
package com.opengamma.util; import java.util.Map; /** * Contains utility methods for checking inputs to methods. */ public final class ArgumentChecker { /** * Restrictive constructor. */ private ArgumentChecker() { } public static void isTrue(boolean trueIfValid, String message) { if (trueIfValid == false) { throw new IllegalArgumentException(message); } } public static void isFalse(boolean falseIfValid, String message) { if (falseIfValid) { throw new IllegalArgumentException(message); } } public static void notNull(Object parameter, String name) { if (parameter == null) { throw new IllegalArgumentException("Input parameter '" + name + "' must not be null"); } } public static void notNullInjected(Object parameter, String name) { if (parameter == null) { throw new IllegalArgumentException("Injected input parameter '" + name + "' must not be null"); } } public static void notEmpty(String parameter, String name) { notNull(parameter, name); if (parameter.length() == 0) { throw new IllegalArgumentException("Input parameter '" + name + "' must not be zero length"); } } public static void notEmpty(Object[] parameter, String name) { notNull(parameter, name); if (parameter.length == 0) { throw new IllegalArgumentException("Input parameter array '" + name + "' must not be zero length"); } } public static void notEmpty(Object[][] parameter, String name) { notNull(parameter, name); if (parameter.length == 0) { throw new IllegalArgumentException("Input parameter array '" + name + "' must not be zero length"); } } public static void notEmpty(double[] parameter, String name) { notNull(parameter, name); if (parameter.length == 0) { throw new IllegalArgumentException("Input parameter array '" + name + "' must not be zero length"); } } public static void notEmpty(long[] parameter, String name) { notNull(parameter, name); if (parameter.length == 0) { throw new IllegalArgumentException("Input parameter array '" + name + "' must not be zero length"); } } public static void notEmpty(Iterable<?> parameter, String name) { notNull(parameter, name); if (parameter.iterator().hasNext() == false) { throw new IllegalArgumentException("Input parameter collection '" + name + "' must not be zero length"); } } public static void notEmpty(Map<?, ?> parameter, String name) { notNull(parameter, name); if (parameter.size() == 0) { throw new IllegalArgumentException("Input parameter map '" + name + "' must not be zero length"); } } public static void noNulls(Object[] parameter, String name) { notNull(parameter, name); for (int i = 0; i < parameter.length; i++) { if (parameter[i] == null) { throw new IllegalArgumentException("Input parameter array '" + name + "' must not contain null at index " + i); } } } public static void noNulls(Iterable<?> parameter, String name) { notNull(parameter, name); for (Object obj : parameter) { if (obj == null) { throw new IllegalArgumentException("Input parameter collection '" + name + "' must not contain null"); } } } public static void notNegative(int parameter, String name) { if (parameter < 0) { throw new IllegalArgumentException("Input parameter '" + name + "' must not be negative"); } } public static void notNegative(double parameter, String name) { if (parameter < 0) { throw new IllegalArgumentException("Input parameter '" + name + "' must not be negative"); } } public static void notNegativeOrZero(int parameter, String name) { if (parameter <= 0) { throw new IllegalArgumentException("Input parameter '" + name + "' must not be negative or zero"); } } public static void notNegativeOrZero(double parameter, String name) { if (parameter <= 0) { throw new IllegalArgumentException("Input parameter '" + name + "' must not be negative or zero"); } } public static void notZero(double x, double eps, String name) { if (CompareUtils.closeEquals(x, 0, eps)) { throw new IllegalArgumentException("Input parameter '" + name + "' must not be zero"); } } public static boolean hasNullElement(Iterable<?> iterable) { notNull(iterable, "collection"); for (Object o : iterable) { if (o == null) { return true; } } return false; } public static boolean hasNegativeElement(Iterable<Double> iterable) { notNull(iterable, "collection"); for (Double d : iterable) { if (d < 0) { return true; } } return false; } /** * Checks that a value is within the range low < x < high. * * @param low Low value of the range * @param high High value of the range * @param x the value * @return true if low < x < high */ public static boolean isInRangeExclusive(double low, double high, double x) { if (x > low && x < high) { return true; } return false; } /** * Checks that a value is within the range low <= x <= high. * * @param low the low value of the range * @param high the high value of the range * @param x the value * @return true if low <= x <= high */ public static boolean isInRangeInclusive(double low, double high, double x) { if (x >= low && x <= high) { return true; } return false; } /** * Checks that a value is within the range low < x <= high. * * @param low the low value of the range * @param high the high value of the range * @param x the value * @return true if low < x <= high */ public static boolean isInRangeExcludingLow(double low, double high, double x) { if (x > low && x <= high) { return true; } return false; } /** * Checks that a value is within the range low <= x < high. * * @param low the low value of the range * @param high the high value of the range * @param x the value * @return true if low <= x < high */ public static boolean isInRangeExcludingHigh(double low, double high, double x) { if (x >= low && x < high) { return true; } return false; } }
package org.batfish.main; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Verify.verify; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.regex.Pattern.CASE_INSENSITIVE; import static java.util.stream.Collectors.toMap; import static org.batfish.bddreachability.BDDMultipathInconsistency.computeMultipathInconsistencies; import static org.batfish.bddreachability.BDDReachabilityUtils.constructFlows; import static org.batfish.common.BfConsts.RELPATH_CHECKPOINT_SHOW_ACCESS_RULEBASE; import static org.batfish.common.BfConsts.RELPATH_CHECKPOINT_SHOW_GATEWAYS_AND_SERVERS; import static org.batfish.common.BfConsts.RELPATH_CHECKPOINT_SHOW_NAT_RULEBASE; import static org.batfish.common.BfConsts.RELPATH_CHECKPOINT_SHOW_PACKAGE; import static org.batfish.common.runtime.SnapshotRuntimeData.EMPTY_SNAPSHOT_RUNTIME_DATA; import static org.batfish.common.util.CompletionMetadataUtils.getFilterNames; import static org.batfish.common.util.CompletionMetadataUtils.getInterfaces; import static org.batfish.common.util.CompletionMetadataUtils.getIps; import static org.batfish.common.util.CompletionMetadataUtils.getLocationCompletionMetadata; import static org.batfish.common.util.CompletionMetadataUtils.getMlagIds; import static org.batfish.common.util.CompletionMetadataUtils.getNodes; import static org.batfish.common.util.CompletionMetadataUtils.getPrefixes; import static org.batfish.common.util.CompletionMetadataUtils.getRoutingPolicyNames; import static org.batfish.common.util.CompletionMetadataUtils.getStructureNames; import static org.batfish.common.util.CompletionMetadataUtils.getVrfs; import static org.batfish.common.util.CompletionMetadataUtils.getZones; import static org.batfish.common.util.isp.IspModelingUtils.INTERNET_HOST_NAME; import static org.batfish.datamodel.acl.AclLineMatchExprs.not; import static org.batfish.main.ReachabilityParametersResolver.resolveReachabilityParameters; import static org.batfish.main.StreamDecoder.decodeStreamAndAppendNewline; import static org.batfish.specifier.LocationInfoUtils.computeLocationInfo; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Throwables; import com.google.common.cache.Cache; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import com.google.common.collect.Table; import com.google.common.hash.Hashing; import com.google.errorprone.annotations.MustBeClosed; import io.opentracing.References; import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.SpanContext; import io.opentracing.util.GlobalTracer; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.sf.javabdd.BDD; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.apache.commons.configuration2.ImmutableConfiguration; import org.apache.commons.lang3.SerializationUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.batfish.bddreachability.BDDLoopDetectionAnalysis; import org.batfish.bddreachability.BDDReachabilityAnalysis; import org.batfish.bddreachability.BDDReachabilityAnalysisFactory; import org.batfish.bddreachability.BidirectionalReachabilityAnalysis; import org.batfish.bddreachability.IpsRoutedOutInterfacesFactory; import org.batfish.common.Answerer; import org.batfish.common.BatfishException; import org.batfish.common.BatfishException.BatfishStackTrace; import org.batfish.common.BatfishLogger; import org.batfish.common.BfConsts; import org.batfish.common.CleanBatfishException; import org.batfish.common.CompletionMetadata; import org.batfish.common.CoordConsts; import org.batfish.common.CoordConstsV2; import org.batfish.common.ErrorDetails; import org.batfish.common.NetworkSnapshot; import org.batfish.common.Warning; import org.batfish.common.Warnings; import org.batfish.common.bdd.BDDPacket; import org.batfish.common.plugin.BgpTablePlugin; import org.batfish.common.plugin.DataPlanePlugin; import org.batfish.common.plugin.DataPlanePlugin.ComputeDataPlaneResult; import org.batfish.common.plugin.ExternalBgpAdvertisementPlugin; import org.batfish.common.plugin.IBatfish; import org.batfish.common.plugin.PluginClientType; import org.batfish.common.plugin.PluginConsumer; import org.batfish.common.plugin.TracerouteEngine; import org.batfish.common.runtime.SnapshotRuntimeData; import org.batfish.common.topology.Layer1Edge; import org.batfish.common.topology.Layer1Topology; import org.batfish.common.topology.TopologyContainer; import org.batfish.common.topology.TopologyProvider; import org.batfish.common.util.BatfishObjectMapper; import org.batfish.common.util.CommonUtil; import org.batfish.common.util.isp.IspModelingUtils; import org.batfish.common.util.isp.IspModelingUtils.ModeledNodes; import org.batfish.config.Settings; import org.batfish.datamodel.AbstractRoute; import org.batfish.datamodel.AnnotatedRoute; import org.batfish.datamodel.BgpAdvertisement; import org.batfish.datamodel.Bgpv4Route; import org.batfish.datamodel.Configuration; import org.batfish.datamodel.ConfigurationFormat; import org.batfish.datamodel.DataPlane; import org.batfish.datamodel.DeviceType; import org.batfish.datamodel.Edge; import org.batfish.datamodel.EvpnRoute; import org.batfish.datamodel.Fib; import org.batfish.datamodel.Flow; import org.batfish.datamodel.FlowDisposition; import org.batfish.datamodel.ForwardingAnalysis; import org.batfish.datamodel.GenericRib; import org.batfish.datamodel.IntegerSpace; import org.batfish.datamodel.Interface; import org.batfish.datamodel.Interface.Dependency; import org.batfish.datamodel.Interface.DependencyType; import org.batfish.datamodel.InterfaceType; import org.batfish.datamodel.NetworkConfigurations; import org.batfish.datamodel.Prefix; import org.batfish.datamodel.SubRange; import org.batfish.datamodel.SwitchportMode; import org.batfish.datamodel.Topology; import org.batfish.datamodel.acl.AclLineMatchExpr; import org.batfish.datamodel.answers.Answer; import org.batfish.datamodel.answers.AnswerElement; import org.batfish.datamodel.answers.AnswerMetadataUtil; import org.batfish.datamodel.answers.AnswerStatus; import org.batfish.datamodel.answers.AnswerSummary; import org.batfish.datamodel.answers.ConvertConfigurationAnswerElement; import org.batfish.datamodel.answers.ConvertStatus; import org.batfish.datamodel.answers.DataPlaneAnswerElement; import org.batfish.datamodel.answers.InitInfoAnswerElement; import org.batfish.datamodel.answers.InitStepAnswerElement; import org.batfish.datamodel.answers.ParseAnswerElement; import org.batfish.datamodel.answers.ParseEnvironmentBgpTablesAnswerElement; import org.batfish.datamodel.answers.ParseStatus; import org.batfish.datamodel.answers.ParseVendorConfigurationAnswerElement; import org.batfish.datamodel.answers.RunAnalysisAnswerElement; import org.batfish.datamodel.collections.BgpAdvertisementsByVrf; import org.batfish.datamodel.collections.NodeInterfacePair; import org.batfish.datamodel.eigrp.EigrpMetricValues; import org.batfish.datamodel.eigrp.EigrpTopologyUtils; import org.batfish.datamodel.flow.Trace; import org.batfish.datamodel.flow.TraceWrapperAsAnswerElement; import org.batfish.datamodel.isp_configuration.IspConfiguration; import org.batfish.datamodel.ospf.OspfTopologyUtils; import org.batfish.datamodel.questions.InvalidReachabilityParametersException; import org.batfish.datamodel.questions.Question; import org.batfish.datamodel.vxlan.Layer2Vni; import org.batfish.dataplane.TracerouteEngineImpl; import org.batfish.grammar.BatfishCombinedParser; import org.batfish.grammar.BatfishParseException; import org.batfish.grammar.BatfishParseTreeWalker; import org.batfish.grammar.BgpTableFormat; import org.batfish.grammar.GrammarSettings; import org.batfish.grammar.NopFlattener; import org.batfish.grammar.ParseTreePrettyPrinter; import org.batfish.grammar.VendorConfigurationFormatDetector; import org.batfish.grammar.flattener.Flattener; import org.batfish.grammar.juniper.JuniperCombinedParser; import org.batfish.grammar.juniper.JuniperFlattener; import org.batfish.grammar.palo_alto_nested.PaloAltoNestedCombinedParser; import org.batfish.grammar.palo_alto_nested.PaloAltoNestedFlattener; import org.batfish.grammar.vyos.VyosCombinedParser; import org.batfish.grammar.vyos.VyosFlattener; import org.batfish.identifiers.AnalysisId; import org.batfish.identifiers.AnswerId; import org.batfish.identifiers.IdResolver; import org.batfish.identifiers.NetworkId; import org.batfish.identifiers.NodeRolesId; import org.batfish.identifiers.QuestionId; import org.batfish.identifiers.SnapshotId; import org.batfish.identifiers.StorageBasedIdResolver; import org.batfish.job.BatfishJobExecutor; import org.batfish.job.ConvertConfigurationJob; import org.batfish.job.ParseEnvironmentBgpTableJob; import org.batfish.job.ParseResult; import org.batfish.job.ParseVendorConfigurationJob; import org.batfish.job.ParseVendorConfigurationResult; import org.batfish.question.ReachabilityParameters; import org.batfish.question.ResolvedReachabilityParameters; import org.batfish.question.SrcNattedConstraint; import org.batfish.question.bidirectionalreachability.BidirectionalReachabilityResult; import org.batfish.question.differentialreachability.DifferentialReachabilityParameters; import org.batfish.question.differentialreachability.DifferentialReachabilityResult; import org.batfish.question.multipath.MultipathConsistencyParameters; import org.batfish.referencelibrary.ReferenceLibrary; import org.batfish.representation.aws.AwsConfiguration; import org.batfish.representation.host.HostConfiguration; import org.batfish.representation.iptables.IptablesVendorConfiguration; import org.batfish.role.InferRoles; import org.batfish.role.NodeRoleDimension; import org.batfish.role.NodeRolesData; import org.batfish.role.NodeRolesData.Type; import org.batfish.role.RoleMapping; import org.batfish.specifier.AllInterfaceLinksLocationSpecifier; import org.batfish.specifier.AllInterfacesLocationSpecifier; import org.batfish.specifier.InferFromLocationIpSpaceSpecifier; import org.batfish.specifier.IpSpaceAssignment; import org.batfish.specifier.Location; import org.batfish.specifier.LocationInfo; import org.batfish.specifier.SpecifierContext; import org.batfish.specifier.SpecifierContextImpl; import org.batfish.specifier.UnionLocationSpecifier; import org.batfish.storage.FileBasedStorage; import org.batfish.storage.StorageProvider; import org.batfish.symbolic.IngressLocation; import org.batfish.topology.TopologyProviderImpl; import org.batfish.vendor.ConversionContext; import org.batfish.vendor.VendorConfiguration; import org.batfish.vendor.check_point_management.AccessLayer; import org.batfish.vendor.check_point_management.CheckpointManagementConfiguration; import org.batfish.vendor.check_point_management.Domain; import org.batfish.vendor.check_point_management.GatewaysAndServers; import org.batfish.vendor.check_point_management.ManagementDomain; import org.batfish.vendor.check_point_management.ManagementPackage; import org.batfish.vendor.check_point_management.ManagementServer; import org.batfish.vendor.check_point_management.NatRulebase; import org.batfish.vendor.check_point_management.Package; import org.batfish.vendor.check_point_management.Uid; import org.batfish.version.BatfishVersion; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.jgrapht.Graph; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.SimpleDirectedGraph; import org.jgrapht.traverse.TopologicalOrderIterator; /** This class encapsulates the main control logic for Batfish. */ public class Batfish extends PluginConsumer implements IBatfish { private static final Pattern MANAGEMENT_INTERFACES = Pattern.compile( "(\\Amgmt)|(\\Amanagement)|(\\Afxp0)|(\\Aem0)|(\\Ame0)|(\\Avme)|(\\Awlan-ap)", CASE_INSENSITIVE); private static final Pattern MANAGEMENT_VRFS = Pattern.compile("(\\Amgmt)|(\\Amanagement)", CASE_INSENSITIVE); static void checkTopology(Map<String, Configuration> configurations, Topology topology) { for (Edge edge : topology.getEdges()) { if (!configurations.containsKey(edge.getNode1())) { throw new BatfishException( String.format("Topology contains a non-existent node '%s'", edge.getNode1())); } if (!configurations.containsKey(edge.getNode2())) { throw new BatfishException( String.format("Topology contains a non-existent node '%s'", edge.getNode2())); } // nodes are valid, now checking corresponding interfaces Configuration config1 = configurations.get(edge.getNode1()); Configuration config2 = configurations.get(edge.getNode2()); if (!config1.getAllInterfaces().containsKey(edge.getInt1())) { throw new BatfishException( String.format( "Topology contains a non-existent interface '%s' on node '%s'", edge.getInt1(), edge.getNode1())); } if (!config2.getAllInterfaces().containsKey(edge.getInt2())) { throw new BatfishException( String.format( "Topology contains a non-existent interface '%s' on node '%s'", edge.getInt2(), edge.getNode2())); } } } public static @Nonnull Flattener flatten( String input, BatfishLogger logger, GrammarSettings settings, Warnings warnings, ConfigurationFormat format, String header) { switch (format) { case PALO_ALTO_NESTED: { PaloAltoNestedCombinedParser parser = new PaloAltoNestedCombinedParser(input, settings); ParserRuleContext tree = parse(parser, logger, settings); PaloAltoNestedFlattener flattener = new PaloAltoNestedFlattener( VendorConfigurationFormatDetector.BATFISH_FLATTENED_PALO_ALTO_HEADER); ParseTreeWalker walker = new BatfishParseTreeWalker(parser); try { walker.walk(flattener, tree); } catch (BatfishParseException e) { warnings.setErrorDetails(e.getErrorDetails()); throw new BatfishException( String.format("Error flattening %s config", format.getVendorString()), e); } return flattener; } case JUNIPER: { JuniperCombinedParser parser = new JuniperCombinedParser(input, settings); ParserRuleContext tree = parse(parser, logger, settings); JuniperFlattener flattener = new JuniperFlattener( VendorConfigurationFormatDetector.BATFISH_FLATTENED_JUNIPER_HEADER, input); ParseTreeWalker walker = new BatfishParseTreeWalker(parser); try { walker.walk(flattener, tree); } catch (BatfishParseException e) { warnings.setErrorDetails(e.getErrorDetails()); throw new BatfishException( String.format("Error flattening %s config", format.getVendorString()), e); } return flattener; } case VYOS: { VyosCombinedParser parser = new VyosCombinedParser(input, settings); ParserRuleContext tree = parse(parser, logger, settings); VyosFlattener flattener = new VyosFlattener(VendorConfigurationFormatDetector.BATFISH_FLATTENED_VYOS_HEADER); ParseTreeWalker walker = new BatfishParseTreeWalker(parser); try { walker.walk(flattener, tree); } catch (BatfishParseException e) { warnings.setErrorDetails(e.getErrorDetails()); throw new BatfishException( String.format("Error flattening %s config", format.getVendorString()), e); } return flattener; } // $CASES-OMITTED$ default: return new NopFlattener(input); } } private void initLocalSettings(Settings settings) { if (settings == null || settings.getStorageBase() == null || settings.getContainer() == null) { // This should only happen in tests. return; } _snapshot = settings.getTestrig(); if (_snapshot == null) { throw new CleanBatfishException("Must supply argument to -" + BfConsts.ARG_TESTRIG); } _referenceSnapshot = settings.getDeltaTestrig(); } /** * Reads the snapshot input objects corresponding to the provided keys, and returns a map from * each object's key to its contents. */ private @Nonnull SortedMap<String, String> readAllInputObjects( Stream<String> keys, NetworkSnapshot snapshot) { return keys.map( key -> { _logger.debugf("Reading: \"%s\"\n", key); try (InputStream inputStream = _storage.loadSnapshotInputObject( snapshot.getNetwork(), snapshot.getSnapshot(), key)) { return new SimpleEntry<>(key, decodeStreamAndAppendNewline(inputStream)); } catch (IOException e) { throw new UncheckedIOException(e); } }) .collect( ImmutableSortedMap.toImmutableSortedMap( Ordering.natural(), SimpleEntry::getKey, SimpleEntry::getValue)); } public static void logWarnings(BatfishLogger logger, Warnings warnings) { for (Warning warning : warnings.getRedFlagWarnings()) { logger.redflag(logWarningsHelper(warning)); } for (Warning warning : warnings.getUnimplementedWarnings()) { logger.unimplemented(logWarningsHelper(warning)); } for (Warning warning : warnings.getPedanticWarnings()) { logger.pedantic(logWarningsHelper(warning)); } } private static String logWarningsHelper(Warning warning) { return " " + warning.getTag() + ": " + warning.getText() + "\n"; } /** * Returns the parse tree for the given parser, logging to the given logger and using the given * settings to control the parse tree printing, if applicable. */ public static ParserRuleContext parse( BatfishCombinedParser<?, ?> parser, BatfishLogger logger, GrammarSettings settings) { ParserRuleContext tree; try { tree = parser.parse(); } catch (BatfishException e) { throw new ParserBatfishException("Parser error", e); } List<String> errors = parser.getErrors(); int numErrors = errors.size(); if (numErrors > 0) { throw new ParserBatfishException("Parser error(s)", errors); } else if (!settings.getPrintParseTree()) { logger.info("OK\n"); } else { logger.info("OK, PRINTING PARSE TREE:\n"); logger.info( ParseTreePrettyPrinter.print(tree, parser, settings.getPrintParseTreeLineNums()) + "\n\n"); } return tree; } private final Map<String, AnswererCreator> _answererCreators; private SnapshotId _snapshot; private SortedMap<BgpTableFormat, BgpTablePlugin> _bgpTablePlugins; private final Cache<NetworkSnapshot, SortedMap<String, Configuration>> _cachedConfigurations; private final Cache<NetworkSnapshot, DataPlane> _cachedDataPlanes; private final Map<NetworkSnapshot, SortedMap<String, BgpAdvertisementsByVrf>> _cachedEnvironmentBgpTables; private final Cache<NetworkSnapshot, Map<String, VendorConfiguration>> _cachedVendorConfigurations; private SnapshotId _referenceSnapshot; private Set<ExternalBgpAdvertisementPlugin> _externalBgpAdvertisementPlugins; private IdResolver _idResolver; private BatfishLogger _logger; private Settings _settings; private final StorageProvider _storage; // this variable is used communicate with parent thread on how the job // finished (null if job finished successfully) private String _terminatingExceptionMessage; private Map<String, DataPlanePlugin> _dataPlanePlugins; private final TopologyProvider _topologyProvider; public Batfish( Settings settings, Cache<NetworkSnapshot, SortedMap<String, Configuration>> cachedConfigurations, Cache<NetworkSnapshot, DataPlane> cachedDataPlanes, Map<NetworkSnapshot, SortedMap<String, BgpAdvertisementsByVrf>> cachedEnvironmentBgpTables, Cache<NetworkSnapshot, Map<String, VendorConfiguration>> cachedVendorConfigurations, @Nullable StorageProvider alternateStorageProvider, @Nullable IdResolver alternateIdResolver) { _settings = settings; _bgpTablePlugins = new TreeMap<>(); _cachedConfigurations = cachedConfigurations; _cachedDataPlanes = cachedDataPlanes; _cachedEnvironmentBgpTables = cachedEnvironmentBgpTables; _cachedVendorConfigurations = cachedVendorConfigurations; _externalBgpAdvertisementPlugins = new TreeSet<>(); initLocalSettings(settings); _logger = _settings.getLogger(); _terminatingExceptionMessage = null; _answererCreators = new HashMap<>(); _dataPlanePlugins = new HashMap<>(); _storage = alternateStorageProvider != null ? alternateStorageProvider : new FileBasedStorage(_settings.getStorageBase(), _logger, this::newBatch); _idResolver = alternateIdResolver != null ? alternateIdResolver : new StorageBasedIdResolver(_storage); _topologyProvider = new TopologyProviderImpl(this, _storage); loadPlugins(); } private Answer analyze() { try { Answer answer = new Answer(); AnswerSummary summary = new AnswerSummary(); AnalysisId analysisName = _settings.getAnalysisName(); NetworkId containerName = _settings.getContainer(); RunAnalysisAnswerElement ae = new RunAnalysisAnswerElement(); _idResolver .listQuestions(containerName, analysisName) .forEach( questionName -> { Optional<QuestionId> questionIdOpt = _idResolver.getQuestionId(questionName, containerName, analysisName); checkArgument( questionIdOpt.isPresent(), "Question '%s' for analysis '%s' for network '%s' was deleted in the middle of" + " this operation", questionName, containerName, analysisName); _settings.setQuestionName(questionIdOpt.get()); Answer currentAnswer; Span span = GlobalTracer.get().buildSpan("Getting answer to analysis question").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning span.setTag("analysis-name", analysisName.getId()); currentAnswer = answer(); } finally { span.finish(); } // Ensuring that question was parsed successfully if (currentAnswer.getQuestion() != null) { try { // TODO: This can be represented much cleanly and easily with a Json _logger.infof( "Ran question:%s from analysis:%s in container:%s; work-id:%s, status:%s, " + "computed dataplane:%s, parameters:%s\n", questionName, analysisName, containerName, getTaskId(), currentAnswer.getSummary().getNumFailed() > 0 ? "failed" : "passed", currentAnswer.getQuestion().getDataPlane(), BatfishObjectMapper.writeString( currentAnswer.getQuestion().getInstance().getVariables())); } catch (JsonProcessingException e) { throw new BatfishException( String.format( "Error logging question %s in analysis %s", questionName, analysisName), e); } } try { outputAnswer(currentAnswer); outputAnswerMetadata(currentAnswer); ae.getAnswers().put(questionName, currentAnswer); } catch (Exception e) { Answer errorAnswer = new Answer(); errorAnswer.addAnswerElement( new BatfishStackTrace(new BatfishException("Failed to output answer", e))); ae.getAnswers().put(questionName, errorAnswer); } ae.getAnswers().put(questionName, currentAnswer); summary.combine(currentAnswer.getSummary()); }); answer.addAnswerElement(ae); answer.setSummary(summary); return answer; } finally { // ensure question name is null so logger does not try to write analysis answer into a // question's answer folder _settings.setQuestionName(null); } } public Answer answer() { Question question = null; // return right away if we cannot parse the question successfully Span span = GlobalTracer.get().buildSpan("Parse question span").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning String rawQuestionStr; try { rawQuestionStr = _storage.loadQuestion( _settings.getContainer(), _settings.getQuestionName(), _settings.getAnalysisName()); } catch (Exception e) { Answer answer = new Answer(); BatfishException exception = new BatfishException("Could not read question", e); answer.setStatus(AnswerStatus.FAILURE); answer.addAnswerElement(exception.getBatfishStackTrace()); return answer; } try { question = Question.parseQuestion(rawQuestionStr); } catch (Exception e) { Answer answer = new Answer(); BatfishException exception = new BatfishException("Could not parse question", e); answer.setStatus(AnswerStatus.FAILURE); answer.addAnswerElement(exception.getBatfishStackTrace()); return answer; } } finally { span.finish(); } LOGGER.info("Answering question {}", question.getClass().getSimpleName()); if (GlobalTracer.get().scopeManager().activeSpan() != null) { Span activeSpan = GlobalTracer.get().scopeManager().activeSpan(); activeSpan .setTag("container-name", getContainerName().getId()) .setTag("testrig_name", getSnapshot().getSnapshot().getId()); if (question.getInstance() != null) { activeSpan.setTag("question-name", question.getInstance().getInstanceName()); } } if (_settings.getDifferential()) { question.setDifferential(true); } boolean dp = question.getDataPlane(); boolean diff = question.getDifferential(); _settings.setDiffQuestion(diff); // Ensures configurations are parsed and ready loadConfigurations(getSnapshot()); if (diff) { loadConfigurations(getReferenceSnapshot()); } Span initQuestionSpan = GlobalTracer.get().buildSpan("Init question env").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning prepareToAnswerQuestions(diff, dp); } finally { initQuestionSpan.finish(); } AnswerElement answerElement = null; BatfishException exception = null; Span getAnswerSpan = GlobalTracer.get().buildSpan("Get answer").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning if (question.getDifferential()) { answerElement = Answerer.create(question, this).answerDiff(getSnapshot(), getReferenceSnapshot()); } else { answerElement = Answerer.create(question, this).answer(getSnapshot()); } } catch (Exception e) { exception = new BatfishException("Failed to answer question", e); } finally { getAnswerSpan.finish(); } Answer answer = new Answer(); answer.setQuestion(question); if (exception == null) { LOGGER.info("Question answered successfully"); // success answer.setStatus(AnswerStatus.SUCCESS); answer.addAnswerElement(answerElement); } else { LOGGER.warn("Question execution failed", exception); // failure answer.setStatus(AnswerStatus.FAILURE); answer.addAnswerElement(exception.getBatfishStackTrace()); } return answer; } private static void computeAggregatedInterfaceBandwidths(Map<String, Interface> interfaces) { // Set bandwidths for aggregate interfaces interfaces.values().stream() .filter(iface -> iface.getInterfaceType() == InterfaceType.AGGREGATED) .forEach( iface -> { /* If interface has dependencies, bandwidth should be sum of their bandwidths. */ if (!iface.getDependencies().isEmpty()) { iface.setBandwidth( iface.getDependencies().stream() .map(dependency -> interfaces.get(dependency.getInterfaceName())) .filter(Objects::nonNull) .filter(Interface::getActive) .map(Interface::getBandwidth) .filter(Objects::nonNull) .mapToDouble(Double::doubleValue) .sum()); } else { /* Bandwidth should be sum of bandwidth of channel-group members. */ iface.setBandwidth( iface.getChannelGroupMembers().stream() .mapToDouble(ifaceName -> interfaces.get(ifaceName).getBandwidth()) .sum()); } }); // Now that aggregate interfaces have bandwidths, set bandwidths for aggregate child interfaces interfaces.values().stream() .filter(iface -> iface.getInterfaceType() == InterfaceType.AGGREGATE_CHILD) .forEach( iface -> { /* Bandwidth for aggregate child interfaces (e.g. units) should be inherited from parent. */ double bandwidth = iface.getDependencies().stream() .filter(d -> d.getType() == DependencyType.BIND) .findFirst() .map(Dependency::getInterfaceName) .map(interfaces::get) .map(Interface::getBandwidth) .orElse(0.0); iface.setBandwidth(bandwidth); }); } private static void computeRedundantInterfaceBandwidths(Map<String, Interface> interfaces) { // Set bandwidths for redundant interfaces interfaces.values().stream() .filter(iface -> iface.getInterfaceType() == InterfaceType.REDUNDANT) .forEach( iface -> { /* If interface has dependencies, bandwidth should be bandwidth of any active dependency. */ iface.setBandwidth( iface.getDependencies().stream() .map(dependency -> interfaces.get(dependency.getInterfaceName())) .filter(Objects::nonNull) .filter(Interface::getActive) .map(Interface::getBandwidth) .filter(Objects::nonNull) .mapToDouble(Double::doubleValue) .min() .orElse(0.0)); }); // Now that redundant interfaces have bandwidths, set bandwidths for redundant child interfaces interfaces.values().stream() .filter(iface -> iface.getInterfaceType() == InterfaceType.REDUNDANT_CHILD) .forEach( iface -> { /* Bandwidth for redundant child interfaces (e.g. units) should be inherited from parent. */ double bandwidth = iface.getDependencies().stream() .filter(d -> d.getType() == DependencyType.BIND) .findFirst() .map(Dependency::getInterfaceName) .map(interfaces::get) .map(Interface::getBandwidth) .orElse(0.0); iface.setBandwidth(bandwidth); }); } public static Warnings buildWarnings(Settings settings) { return Warnings.forLogger(settings.getLogger()); } private static final NetworkSnapshot DUMMY_SNAPSHOT = new NetworkSnapshot( new NetworkId("__BATFISH_DUMMY_NETWORK"), new SnapshotId("__BATFISH_DUMMY_SNAPSHOT")); private static final DataPlane DUMMY_DATAPLANE = new DataPlane() { @Override public Table<String, String, Set<Bgpv4Route>> getBgpRoutes() { throw new UnsupportedOperationException(); } @Override public Table<String, String, Set<Bgpv4Route>> getBgpBackupRoutes() { throw new UnsupportedOperationException(); } @Override public Table<String, String, Set<EvpnRoute<?, ?>>> getEvpnRoutes() { throw new UnsupportedOperationException(); } @Override public Table<String, String, Set<EvpnRoute<?, ?>>> getEvpnBackupRoutes() { throw new UnsupportedOperationException(); } @Override public Map<String, Map<String, Fib>> getFibs() { throw new UnsupportedOperationException(); } @Override public ForwardingAnalysis getForwardingAnalysis() { throw new UnsupportedOperationException(); } @Override public SortedMap<String, SortedMap<String, GenericRib<AnnotatedRoute<AbstractRoute>>>> getRibs() { throw new UnsupportedOperationException(); } @Override public SortedMap<String, SortedMap<String, Map<Prefix, Map<String, Set<String>>>>> getPrefixTracingInfoSummary() { throw new UnsupportedOperationException(); } @Override public Table<String, String, Set<Layer2Vni>> getLayer2Vnis() { throw new UnsupportedOperationException(); } }; @Override public DataPlaneAnswerElement computeDataPlane(NetworkSnapshot snapshot) { // If already present, invalidate a dataplane for this snapshot. // (unlikely, only when devs force recomputation) _cachedDataPlanes.invalidate(snapshot); // Reserve space for the new dataplane in the in-memory cache by inserting and invalidating a // dummy value. _cachedDataPlanes.put(DUMMY_SNAPSHOT, DUMMY_DATAPLANE); _cachedDataPlanes.invalidate(DUMMY_SNAPSHOT); ComputeDataPlaneResult result = getDataPlanePlugin().computeDataPlane(snapshot); DataPlaneAnswerElement answerElement = result._answerElement; DataPlane dataplane = result._dataPlane; TopologyContainer topologyContainer = result._topologies; result = null; // let it be garbage collected. saveDataPlane(snapshot, dataplane, topologyContainer); return answerElement; } /* Write the dataplane to disk and cache, and write the answer element to disk. */ private void saveDataPlane( NetworkSnapshot snapshot, DataPlane dataplane, TopologyContainer topologies) { _cachedDataPlanes.put(snapshot, dataplane); _logger.resetTimer(); newBatch("Writing data plane to disk", 0); Span writeDataplane = GlobalTracer.get().buildSpan("Writing data plane").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(writeDataplane)) { assert scope != null; // avoid unused warning LOGGER.info("Storing DataPlane"); _storage.storeDataPlane(dataplane, snapshot); LOGGER.info("Storing BGP Topology"); _storage.storeBgpTopology(topologies.getBgpTopology(), snapshot); LOGGER.info("Storing EIGRP Topology"); _storage.storeEigrpTopology(topologies.getEigrpTopology(), snapshot); LOGGER.info("Storing L3 Adjacencies"); _storage.storeL3Adjacencies(topologies.getL3Adjacencies(), snapshot); LOGGER.info("Storing Layer3 Topology"); _storage.storeLayer3Topology(topologies.getLayer3Topology(), snapshot); LOGGER.info("Storing OSPF Topology"); _storage.storeOspfTopology(topologies.getOspfTopology(), snapshot); LOGGER.info("Storing VxLAN Topology"); _storage.storeVxlanTopology(topologies.getVxlanTopology(), snapshot); } catch (IOException e) { throw new BatfishException("Failed to save data plane", e); } finally { writeDataplane.finish(); } _logger.printElapsedTime(); } private Map<String, Configuration> convertConfigurations( Map<String, VendorConfiguration> vendorConfigurations, ConversionContext conversionContext, SnapshotRuntimeData runtimeData, ConvertConfigurationAnswerElement answerElement) { _logger.info("\n*** CONVERTING VENDOR CONFIGURATIONS TO INDEPENDENT FORMAT ***\n"); _logger.resetTimer(); Map<String, Configuration> configurations = new TreeMap<>(); List<ConvertConfigurationJob> jobs = new ArrayList<>(); for (Entry<String, VendorConfiguration> config : vendorConfigurations.entrySet()) { VendorConfiguration vc = config.getValue(); ConvertConfigurationJob job = new ConvertConfigurationJob( _settings, conversionContext, runtimeData, vc, config.getKey()); jobs.add(job); } BatfishJobExecutor.runJobsInExecutor( _settings, _logger, jobs, configurations, answerElement, _settings.getHaltOnConvertError(), "Convert configurations to vendor-independent format"); _logger.printElapsedTime(); return configurations; } @Override public boolean debugFlagEnabled(String flag) { return _settings.debugFlagEnabled(flag); } @Override public Map<Location, LocationInfo> getLocationInfo(NetworkSnapshot snapshot) { return computeLocationInfo( getTopologyProvider().getIpOwners(snapshot), loadConfigurations(snapshot)); } private void disableUnusableVlanInterfaces(Map<String, Configuration> configurations) { for (Configuration c : configurations.values()) { String hostname = c.getHostname(); Map<Integer, Interface> vlanInterfaces = new HashMap<>(); Map<Integer, Integer> vlanMemberCounts = new HashMap<>(); Set<Interface> nonVlanInterfaces = new HashSet<>(); Integer vlanNumber = null; // Populate vlanInterface and nonVlanInterfaces, and initialize // vlanMemberCounts: for (Interface iface : c.getActiveInterfaces().values()) { if ((iface.getInterfaceType() == InterfaceType.VLAN) && ((vlanNumber = CommonUtil.getInterfaceVlanNumber(iface.getName())) != null)) { vlanInterfaces.put(vlanNumber, iface); vlanMemberCounts.put(vlanNumber, 0); } else { nonVlanInterfaces.add(iface); } } // Update vlanMemberCounts: for (Interface iface : nonVlanInterfaces) { IntegerSpace.Builder vlans = IntegerSpace.builder(); if (iface.getSwitchportMode() == SwitchportMode.TRUNK) { // vlan trunked interface IntegerSpace allowed = iface.getAllowedVlans(); if (!allowed.isEmpty()) { // Explicit list of allowed VLANs vlans.including(allowed); } else { // No explicit list, so all VLANs are allowed. vlanInterfaces.keySet().forEach(vlans::including); } // Add the native VLAN as well. vlanNumber = iface.getNativeVlan(); if (vlanNumber != null) { vlans.including(vlanNumber); } } else if (iface.getSwitchportMode() == SwitchportMode.ACCESS) { // access mode ACCESS vlanNumber = iface.getAccessVlan(); if (vlanNumber != null) { vlans.including(vlanNumber); } // Any other Switch Port mode is unsupported } else if (iface.getSwitchportMode() != SwitchportMode.NONE) { _logger.warnf( "WARNING: Unsupported switch port mode %s, assuming no VLANs allowed: \"%s:%s\"\n", iface.getSwitchportMode(), hostname, iface.getName()); } vlans.build().stream() .forEach( vlanId -> vlanMemberCounts.compute(vlanId, (k, v) -> (v == null) ? 1 : (v + 1))); } // Disable all "normal" vlan interfaces with zero member counts: SubRange normalVlanRange = c.getNormalVlanRange(); for (Map.Entry<Integer, Integer> entry : vlanMemberCounts.entrySet()) { if (entry.getValue() == 0) { vlanNumber = entry.getKey(); if ((vlanNumber >= normalVlanRange.getStart()) && (vlanNumber <= normalVlanRange.getEnd())) { Interface iface = vlanInterfaces.get(vlanNumber); if ((iface != null) && iface.getAutoState()) { _logger.warnf( "Disabling unusable vlan interface because no switch port is assigned to it: %s", NodeInterfacePair.of(iface)); iface.blacklist(); } } } } } } /** Returns a map of hostname to VI {@link Configuration} */ public Map<String, Configuration> getConfigurations( Map<String, VendorConfiguration> vendorConfigurations, ConversionContext conversionContext, SnapshotRuntimeData runtimeData, ConvertConfigurationAnswerElement answerElement) { Map<String, Configuration> configurations = convertConfigurations(vendorConfigurations, conversionContext, runtimeData, answerElement); identifyDeviceTypes(configurations.values()); return configurations; } @Override public NetworkId getContainerName() { return _settings.getContainer(); } @Override public DataPlanePlugin getDataPlanePlugin() { DataPlanePlugin plugin = _dataPlanePlugins.get(_settings.getDataPlaneEngineName()); if (plugin == null) { throw new BatfishException( String.format( "Dataplane engine %s is unavailable or unsupported", _settings.getDataPlaneEngineName())); } return plugin; } private SortedMap<String, BgpAdvertisementsByVrf> getEnvironmentBgpTables( NetworkSnapshot snapshot, ParseEnvironmentBgpTablesAnswerElement answerElement) { _logger.info("\n*** READING Environment BGP Tables ***\n"); SortedMap<String, String> inputData; try (Stream<String> keys = _storage.listInputEnvironmentBgpTableKeys(snapshot)) { inputData = readAllInputObjects(keys, snapshot); } catch (IOException e) { throw new UncheckedIOException(e); } SortedMap<String, BgpAdvertisementsByVrf> bgpTables = parseEnvironmentBgpTables(snapshot, inputData, answerElement); return bgpTables; } @Override public BatfishLogger getLogger() { return _logger; } /** * Gets the {@link NodeRolesData} for the testrig * * @return The {@link NodeRolesData} object. */ @Override public NodeRolesData getNodeRolesData() { try { NetworkId networkId = _settings.getContainer(); Optional<NodeRolesId> networkNodeRolesIdOpt = _idResolver.getNetworkNodeRolesId(networkId); if (!networkNodeRolesIdOpt.isPresent()) { return null; } return BatfishObjectMapper.mapper() .readValue( _storage.loadNodeRoles(networkId, networkNodeRolesIdOpt.get()), NodeRolesData.class); } catch (IOException e) { _logger.errorf("Could not read roles data: %s", e); return null; } } /** * Gets the {@link NodeRoleDimension} object given dimension name. If {@code dimension} is null, * returns the default dimension. * * @param dimension The dimension name * @return An {@link Optional} that has the requested NodeRoleDimension or empty otherwise. */ @Override public Optional<NodeRoleDimension> getNodeRoleDimension(@Nullable String dimension) { NodeRolesData nodeRolesData = getNodeRolesData(); return nodeRolesData.nodeRoleDimensionFor(dimension); } @Override public Map<String, String> getQuestionTemplates(boolean verbose) { if (_settings.getCoordinatorHost() == null) { throw new BatfishException("Cannot get question templates: coordinator host is not set"); } String url = String.format( "http://%s:%s%s/%s", _settings.getCoordinatorHost(), _settings.getCoordinatorPoolPort(), CoordConsts.SVC_CFG_POOL_MGR, CoordConsts.SVC_RSC_POOL_GET_QUESTION_TEMPLATES); Map<String, String> params = new HashMap<>(); params.put(CoordConsts.SVC_KEY_VERSION, BatfishVersion.getVersionStatic()); params.put(CoordConstsV2.QP_VERBOSE, String.valueOf(verbose)); JSONObject response = (JSONObject) CoordinatorClient.talkToCoordinator(url, params, _settings, _logger); if (response == null) { throw new BatfishException("Could not get question templates: Got null response"); } if (!response.has(CoordConsts.SVC_KEY_QUESTION_LIST)) { throw new BatfishException("Could not get question templates: Response lacks question list"); } try { Map<String, String> templates = BatfishObjectMapper.mapper() .readValue( response.get(CoordConsts.SVC_KEY_QUESTION_LIST).toString(), new TypeReference<Map<String, String>>() {}); return templates; } catch (JSONException | IOException e) { throw new BatfishException("Could not cast response to Map: ", e); } } /** Gets the {@link ReferenceLibrary} for the network */ @Override public @Nullable ReferenceLibrary getReferenceLibraryData() { try { return _storage .loadReferenceLibrary(_settings.getContainer()) .orElse(new ReferenceLibrary(null)); } catch (IOException e) { _logger.errorf( "Could not read reference library data for network %s: %s", _settings.getContainer(), e); return null; } } public Settings getSettings() { return _settings; } @Override public ImmutableConfiguration getSettingsConfiguration() { return _settings.getImmutableConfiguration(); } @Override public NetworkSnapshot getSnapshot() { return new NetworkSnapshot(_settings.getContainer(), _snapshot); } @Override public NetworkSnapshot getReferenceSnapshot() { return new NetworkSnapshot(_settings.getContainer(), _referenceSnapshot); } @Override public String getTaskId() { return _settings.getTaskId(); } public String getTerminatingExceptionMessage() { return _terminatingExceptionMessage; } @Nonnull @Override public TopologyProvider getTopologyProvider() { return _topologyProvider; } @Override public PluginClientType getType() { return PluginClientType.BATFISH; } @Override public InitInfoAnswerElement initInfo( NetworkSnapshot snapshot, boolean summary, boolean verboseError) { LOGGER.info("Getting snapshot initialization info"); ParseVendorConfigurationAnswerElement parseAnswer = loadParseVendorConfigurationAnswerElement(snapshot); InitInfoAnswerElement answerElement = mergeParseAnswer(summary, verboseError, parseAnswer); ConvertConfigurationAnswerElement convertAnswer = loadConvertConfigurationAnswerElementOrReparse(snapshot); mergeConvertAnswer(summary, verboseError, convertAnswer, answerElement); _logger.info(answerElement.toString()); return answerElement; } @Override public InitInfoAnswerElement initInfoBgpAdvertisements( NetworkSnapshot snapshot, boolean summary, boolean verboseError) { ParseEnvironmentBgpTablesAnswerElement parseAnswer = loadParseEnvironmentBgpTablesAnswerElement(snapshot); InitInfoAnswerElement answerElement = mergeParseAnswer(summary, verboseError, parseAnswer); _logger.info(answerElement.toString()); return answerElement; } private void prepareToAnswerQuestions(NetworkSnapshot snapshot, boolean dp) { try { if (!_storage.hasParseEnvironmentBgpTablesAnswerElement(snapshot)) { computeEnvironmentBgpTables(snapshot); } if (dp && _cachedDataPlanes.getIfPresent(snapshot) == null) { if (!_storage.hasDataPlane(snapshot)) { computeDataPlane(snapshot); } } } catch (IOException e) { throw new UncheckedIOException(e); } } private void prepareToAnswerQuestions(boolean diff, boolean dp) { prepareToAnswerQuestions(getSnapshot(), dp); if (diff) { prepareToAnswerQuestions(getReferenceSnapshot(), dp); } } @Override public SortedMap<String, Configuration> loadConfigurations(NetworkSnapshot snapshot) { Span span = GlobalTracer.get().buildSpan("Load configurations").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning _logger.debugf("Loading configurations for %s\n", snapshot); // Do we already have configurations in the cache? SortedMap<String, Configuration> configurations = _cachedConfigurations.getIfPresent(snapshot); if (configurations != null) { return configurations; } _logger.debugf("Loading configurations for %s, cache miss", snapshot); // Next, see if we have an up-to-date configurations on disk. configurations = _storage.loadConfigurations(snapshot.getNetwork(), snapshot.getSnapshot()); if (configurations != null) { _logger.debugf("Loaded configurations for %s off disk", snapshot); } else { // Otherwise, we have to parse the configurations. Fall back to old, hacky code. configurations = actuallyParseConfigurations(snapshot); } // Apply things like blacklist and aggregations before installing in the cache. postProcessSnapshot(snapshot, configurations); _cachedConfigurations.put(snapshot, configurations); return configurations; } finally { span.finish(); } } @Nonnull private SortedMap<String, Configuration> actuallyParseConfigurations(NetworkSnapshot snapshot) { _logger.infof("Repairing configurations for testrig %s", snapshot.getSnapshot()); repairConfigurations(snapshot); SortedMap<String, Configuration> configurations = _storage.loadConfigurations(snapshot.getNetwork(), snapshot.getSnapshot()); verify( configurations != null, "Configurations should not be null when loaded immediately after repair."); assert configurations != null; return configurations; } @Override public ConvertConfigurationAnswerElement loadConvertConfigurationAnswerElementOrReparse( NetworkSnapshot snapshot) { ConvertConfigurationAnswerElement ccae = _storage.loadConvertConfigurationAnswerElement( snapshot.getNetwork(), snapshot.getSnapshot()); if (ccae != null) { return ccae; } repairConfigurations(snapshot); ccae = _storage.loadConvertConfigurationAnswerElement( snapshot.getNetwork(), snapshot.getSnapshot()); if (ccae != null) { return ccae; } else { throw new BatfishException( "Version error repairing configurations for convert configuration answer element"); } } @Override public DataPlane loadDataPlane(NetworkSnapshot snapshot) { Span span = GlobalTracer.get().buildSpan("Load data plane").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning DataPlane dp = _cachedDataPlanes.getIfPresent(snapshot); if (dp == null) { newBatch("Loading data plane from disk", 0); dp = _storage.loadDataPlane(snapshot); _cachedDataPlanes.put(snapshot, dp); } return dp; } catch (IOException e) { throw new UncheckedIOException(e); } finally { span.finish(); } } @Override public SortedMap<String, BgpAdvertisementsByVrf> loadEnvironmentBgpTables( NetworkSnapshot snapshot) { SortedMap<String, BgpAdvertisementsByVrf> environmentBgpTables = _cachedEnvironmentBgpTables.get(snapshot); if (environmentBgpTables == null) { loadParseEnvironmentBgpTablesAnswerElement(snapshot); try { environmentBgpTables = ImmutableSortedMap.copyOf(_storage.loadEnvironmentBgpTables(snapshot)); } catch (IOException e) { throw new UncheckedIOException(e); } _cachedEnvironmentBgpTables.put(snapshot, environmentBgpTables); } return environmentBgpTables; } public ParseEnvironmentBgpTablesAnswerElement loadParseEnvironmentBgpTablesAnswerElement( NetworkSnapshot snapshot) { return loadParseEnvironmentBgpTablesAnswerElement(snapshot, true); } private ParseEnvironmentBgpTablesAnswerElement loadParseEnvironmentBgpTablesAnswerElement( NetworkSnapshot snapshot, boolean firstAttempt) { try { if (!_storage.hasParseEnvironmentBgpTablesAnswerElement(snapshot)) { repairEnvironmentBgpTables(snapshot); } } catch (IOException e) { throw new UncheckedIOException(e); } try { return _storage.loadParseEnvironmentBgpTablesAnswerElement(snapshot); } catch (Exception e) { /* Do nothing, this is expected on serialization or other errors. */ _logger.warn("Unable to load prior parse data"); } if (firstAttempt) { repairEnvironmentBgpTables(snapshot); return loadParseEnvironmentBgpTablesAnswerElement(snapshot, false); } else { throw new BatfishException( "Version error repairing environment BGP tables for parse environment BGP tables " + "answer element"); } } @Override public ParseVendorConfigurationAnswerElement loadParseVendorConfigurationAnswerElement( NetworkSnapshot snapshot) { return loadParseVendorConfigurationAnswerElement(snapshot, true); } private ParseVendorConfigurationAnswerElement loadParseVendorConfigurationAnswerElement( NetworkSnapshot snapshot, boolean firstAttempt) { try { if (_storage.hasParseVendorConfigurationAnswerElement(snapshot)) { try { return _storage.loadParseVendorConfigurationAnswerElement(snapshot); } catch (Exception e) { /* Do nothing, this is expected on serialization or other errors. */ _logger.warn("Unable to load prior parse data"); } } } catch (IOException e) { throw new UncheckedIOException(e); } if (firstAttempt) { repairVendorConfigurations(snapshot); return loadParseVendorConfigurationAnswerElement(snapshot, false); } else { throw new BatfishException( "Version error repairing vendor configurations for parse configuration answer element"); } } @Override public Map<String, VendorConfiguration> loadVendorConfigurations(NetworkSnapshot snapshot) { Span span = GlobalTracer.get().buildSpan("Load vendor configurations").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning _logger.debugf("Loading vendor configurations for %s\n", snapshot); // Do we already have configurations in the cache? Map<String, VendorConfiguration> vendorConfigurations = _cachedVendorConfigurations.getIfPresent(snapshot); if (vendorConfigurations == null) { _logger.debugf("Loading vendor configurations for %s, cache miss", snapshot); loadParseVendorConfigurationAnswerElement(snapshot); try { vendorConfigurations = _storage.loadVendorConfigurations(snapshot); } catch (IOException e) { throw new UncheckedIOException(e); } _cachedVendorConfigurations.put(snapshot, vendorConfigurations); } return vendorConfigurations; } finally { span.finish(); } } private void mergeConvertAnswer( boolean summary, boolean verboseError, ConvertConfigurationAnswerElement convertAnswer, InitInfoAnswerElement answerElement) { mergeInitStepAnswer(answerElement, convertAnswer, summary, verboseError); convertAnswer.getConvertStatus().entrySet().stream() .filter(s -> s.getValue() == ConvertStatus.FAILED) .forEach(s -> answerElement.getParseStatus().put(s.getKey(), ParseStatus.FAILED)); } private void mergeInitStepAnswer( InitInfoAnswerElement initInfoAnswerElement, InitStepAnswerElement initStepAnswerElement, boolean summary, boolean verboseError) { if (!summary) { if (verboseError) { SortedMap<String, List<BatfishStackTrace>> errors = initInfoAnswerElement.getErrors(); initStepAnswerElement .getErrors() .forEach( (hostname, initStepErrors) -> errors.computeIfAbsent(hostname, k -> new ArrayList<>()).add(initStepErrors)); } SortedMap<String, Warnings> warnings = initInfoAnswerElement.getWarnings(); initStepAnswerElement .getWarnings() .forEach( (hostname, initStepWarnings) -> { Warnings combined = warnings.computeIfAbsent(hostname, h -> buildWarnings(_settings)); combined.getParseWarnings().addAll(initStepWarnings.getParseWarnings()); combined.getPedanticWarnings().addAll(initStepWarnings.getPedanticWarnings()); combined.getRedFlagWarnings().addAll(initStepWarnings.getRedFlagWarnings()); combined .getUnimplementedWarnings() .addAll(initStepWarnings.getUnimplementedWarnings()); }); } } private InitInfoAnswerElement mergeParseAnswer( boolean summary, boolean verboseError, ParseAnswerElement parseAnswer) { InitInfoAnswerElement answerElement = new InitInfoAnswerElement(); mergeInitStepAnswer(answerElement, parseAnswer, summary, verboseError); answerElement.setParseStatus(parseAnswer.getParseStatus()); answerElement.setParseTrees(parseAnswer.getParseTrees()); return answerElement; } @Override public AtomicInteger newBatch(String description, int jobs) { return BatchManager.get().newBatch(_settings, description, jobs); } private void outputAnswer(Answer answer) { outputAnswer(answer, /* log */ false); } void outputAnswerWithLog(Answer answer) { outputAnswer(answer, /* log */ true); } private void outputAnswer(Answer answer, boolean writeLog) { try { // Write answer to work json log if caller requested. // Summarize that answer if all of the following are true: // - answering a question // - question successful // - client did not request full successful answers String answerString = BatfishObjectMapper.writeString(answer); boolean summarizeWorkJsonLogAnswer = writeLog && _settings.getQuestionName() != null && !_settings.getAlwaysIncludeAnswerInWorkJsonLog() && answer.getStatus() == AnswerStatus.SUCCESS; String workJsonLogAnswerString; if (summarizeWorkJsonLogAnswer) { Answer summaryAnswer = new Answer(); summaryAnswer.setQuestion(answer.getQuestion()); summaryAnswer.setStatus(answer.getStatus()); summaryAnswer.setSummary(answer.getSummary()); // do not include answer elements workJsonLogAnswerString = BatfishObjectMapper.writeString(summaryAnswer); } else { workJsonLogAnswerString = answerString; } _logger.debug(answerString); writeJsonAnswerWithLog(answerString, workJsonLogAnswerString, writeLog); } catch (Exception e) { BatfishException be = new BatfishException("Error in sending answer", e); try { Answer failureAnswer = Answer.failureAnswer(e.toString(), answer.getQuestion()); failureAnswer.addAnswerElement(be.getBatfishStackTrace()); String answerString = BatfishObjectMapper.writeString(failureAnswer); _logger.error(answerString); // write "answer" to work json log if caller requested writeJsonAnswerWithLog(answerString, answerString, writeLog); } catch (Exception e1) { _logger.errorf( "Could not serialize failure answer. %s", Throwables.getStackTraceAsString(e1)); } throw be; } } void outputAnswerMetadata(Answer answer) throws IOException { QuestionId questionId = _settings.getQuestionName(); if (questionId == null) { return; } SnapshotId referenceSnapshot = _settings.getDiffQuestion() ? _referenceSnapshot : null; NetworkId networkId = _settings.getContainer(); AnalysisId analysisId = _settings.getAnalysisName(); NodeRolesId networkNodeRolesId = _idResolver .getNetworkNodeRolesId(networkId) .orElse(NodeRolesId.DEFAULT_NETWORK_NODE_ROLES_ID); AnswerId baseAnswerId = _idResolver.getAnswerId( networkId, _snapshot, questionId, networkNodeRolesId, referenceSnapshot, analysisId); _storage.storeAnswerMetadata( networkId, _snapshot, AnswerMetadataUtil.computeAnswerMetadata(answer, _logger), baseAnswerId); } /** Parse AWS configurations for a single account (possibly with multiple regions) */ @VisibleForTesting @Nonnull public static AwsConfiguration parseAwsConfigurations( Map<String, String> configurationData, ParseVendorConfigurationAnswerElement pvcae) { AwsConfiguration config = new AwsConfiguration(); for (Entry<String, String> configFile : configurationData.entrySet()) { // Using path for convenience for now to handle separators and key hierarchcially gracefully Path path = Paths.get(configFile.getKey()); // Find the place in the path where "aws_configs" starts int awsRootIndex = 0; for (Path value : path) { if (value.toString().equals(BfConsts.RELPATH_AWS_CONFIGS_DIR)) { break; } awsRootIndex++; } int pathLength = path.getNameCount(); String regionName; String accountName; if (pathLength == 2) { // Currently happens for tests, but probably shouldn't be allowed regionName = AwsConfiguration.DEFAULT_REGION_NAME; accountName = AwsConfiguration.DEFAULT_ACCOUNT_NAME; } else if (pathLength == 3) { // If we are processing old-style packaging, just put everything in to one "default" // account. regionName = path.getName(pathLength - 2).toString(); // parent dir name accountName = AwsConfiguration.DEFAULT_ACCOUNT_NAME; } else if (pathLength > 3) { regionName = path.getName(pathLength - 2).toString(); // parent dir name accountName = path.getName(pathLength - 3).toString(); // account dir name } else { pvcae.addRedFlagWarning( BfConsts.RELPATH_AWS_CONFIGS_FILE, new Warning(String.format("Unexpected AWS configuration path: %s", path), "AWS")); continue; } String fileName = path.subpath(awsRootIndex, pathLength).toString(); pvcae.getFileMap().put(BfConsts.RELPATH_AWS_CONFIGS_FILE, fileName); try { JsonNode json = BatfishObjectMapper.mapper().readTree(configFile.getValue()); config.addConfigElement(regionName, json, fileName, pvcae, accountName); } catch (IOException e) { pvcae.addRedFlagWarning( BfConsts.RELPATH_AWS_CONFIGS_FILE, new Warning(String.format("Unexpected content in AWS file %s", fileName), "AWS")); } } return config; } private @Nonnull List<AccessLayer> getAccessLayers(Map<String, String> packageFiles) throws JsonProcessingException { return packageFiles.containsKey(RELPATH_CHECKPOINT_SHOW_ACCESS_RULEBASE) ? BatfishObjectMapper.ignoreUnknownMapper() .readValue( packageFiles.get(RELPATH_CHECKPOINT_SHOW_ACCESS_RULEBASE), new TypeReference<List<AccessLayer>>() {}) : ImmutableList.of(); } private @Nullable NatRulebase getNatRulebase( Package pakij, Map<String, String> packageFiles, ParseVendorConfigurationAnswerElement pvcae, String serverName) throws JsonProcessingException { if (!pakij.hasNatPolicy()) { return null; } List<NatRulebase> natRulebases = packageFiles.containsKey(RELPATH_CHECKPOINT_SHOW_NAT_RULEBASE) ? BatfishObjectMapper.ignoreUnknownMapper() .readValue( packageFiles.get(RELPATH_CHECKPOINT_SHOW_NAT_RULEBASE), new TypeReference<List<NatRulebase>>() {}) : ImmutableList.of(); if (natRulebases.size() != 1) { pvcae.addRedFlagWarning( BfConsts.RELPATH_CHECKPOINT_MANAGEMENT_DIR, new Warning( String.format( "Checkpoint package %s in domain %s on server %s should contain exactly" + " one NAT rulebase, but contains %s", pakij.getName(), pakij.getDomain().getName(), serverName, natRulebases.size()), "Checkpoint")); } return natRulebases.isEmpty() ? null : natRulebases.get(0); } private @Nonnull CheckpointManagementConfiguration parseCheckpointManagementData( @Nonnull Map<String, String> cpManagementData, @Nonnull ParseVendorConfigurationAnswerElement pvcae) throws IOException { /* Organize server data into maps */ // server -> domain -> filename -> file contents Map<String, Map<String, Map<String, String>>> domainFileMap = new HashMap<>(); // server -> domain -> -> package -> filename -> file contents Map<String, Map<String, Map<String, Map<String, String>>>> packageFileMap = new HashMap<>(); cpManagementData.forEach( (filePath, fileContent) -> { String[] parts = filePath.split("/"); if (parts.length == 4) { // checkpoint_management/SERVER_NAME/DOMAIN_NAME/foo.json String serverName = parts[1]; String domainName = parts[2]; String fileName = parts[3]; domainFileMap .computeIfAbsent(serverName, n -> new HashMap<>()) .computeIfAbsent(domainName, n -> new HashMap<>()) .put(fileName, fileContent); } else if (parts.length == 5) { // checkpoint_management/SERVER_NAME/DOMAIN_NAME/PACKAGE_NAME/foo.json String serverName = parts[1]; String domainName = parts[2]; String packageName = parts[3]; String fileName = parts[4]; packageFileMap .computeIfAbsent(serverName, n -> new HashMap<>()) .computeIfAbsent(domainName, n -> new HashMap<>()) .computeIfAbsent(packageName, n -> new HashMap<>()) .put(fileName, fileContent); } }); /* Extract server data into CheckpointManagementConfiguration */ ImmutableMap.Builder<String, ManagementServer> serversMap = ImmutableMap.builder(); for (Entry<String, Map<String, Map<String, Map<String, String>>>> serverEntry : packageFileMap.entrySet()) { String serverName = serverEntry.getKey(); ImmutableMap.Builder<String, ManagementDomain> domainsMap = ImmutableMap.builder(); for (Entry<String, Map<String, Map<String, String>>> domainEntry : serverEntry.getValue().entrySet()) { String domainName = domainEntry.getKey(); String showGatewaysAndServers = domainFileMap .getOrDefault(serverName, ImmutableMap.of()) .getOrDefault(domainName, ImmutableMap.of()) .get(RELPATH_CHECKPOINT_SHOW_GATEWAYS_AND_SERVERS); if (showGatewaysAndServers == null) { pvcae.addRedFlagWarning( BfConsts.RELPATH_CHECKPOINT_MANAGEMENT_DIR, new Warning( String.format( "Checkpoint management domain %s on server %s missing %s", domainName, serverName, RELPATH_CHECKPOINT_SHOW_GATEWAYS_AND_SERVERS), "Checkpoint")); continue; } List<GatewaysAndServers> gatewaysAndServersList = BatfishObjectMapper.ignoreUnknownMapper() .readValue( showGatewaysAndServers, new TypeReference<List<GatewaysAndServers>>() {}); GatewaysAndServers gatewaysAndServers = mergeGatewaysAndServersPages(gatewaysAndServersList); ImmutableMap.Builder<Uid, ManagementPackage> packagesBuilder = ImmutableMap.builder(); for (Entry<String, Map<String, String>> packageEntry : domainEntry.getValue().entrySet()) { Map<String, String> packageFiles = packageEntry.getValue(); if (!packageFiles.containsKey(RELPATH_CHECKPOINT_SHOW_PACKAGE)) { pvcae.addRedFlagWarning( BfConsts.RELPATH_CHECKPOINT_MANAGEMENT_DIR, new Warning( String.format( "Checkpoint management package %s in domain %s on server %s missing %s", packageEntry.getKey(), domainName, serverName, RELPATH_CHECKPOINT_SHOW_PACKAGE), "Checkpoint")); continue; } Package pakij = BatfishObjectMapper.ignoreUnknownMapper() .readValue(packageFiles.get(RELPATH_CHECKPOINT_SHOW_PACKAGE), Package.class); ManagementPackage mgmtPackage; List<AccessLayer> accessLayers = getAccessLayers(packageFiles); NatRulebase natRulebase = getNatRulebase(pakij, packageFiles, pvcae, serverName); mgmtPackage = new ManagementPackage(accessLayers, natRulebase, pakij); packagesBuilder.put(mgmtPackage.getPackage().getUid(), mgmtPackage); } Map<Uid, ManagementPackage> packages = packagesBuilder.build(); if (packages.isEmpty()) { pvcae.addRedFlagWarning( BfConsts.RELPATH_CHECKPOINT_MANAGEMENT_DIR, new Warning( String.format( "Ignoring Checkpoint management domain %s on server %s: no packages present", domainName, serverName), "Checkpoint")); continue; } // Use any package to find domain Domain domain = packages.values().iterator().next().getPackage().getDomain(); ManagementDomain mgmtDomain = new ManagementDomain(domain, gatewaysAndServers.getGatewaysAndServers(), packages); domainsMap.put(mgmtDomain.getName(), mgmtDomain); } serversMap.put(serverName, new ManagementServer(domainsMap.build(), serverName)); } return new CheckpointManagementConfiguration(serversMap.build()); } private @Nonnull GatewaysAndServers mergeGatewaysAndServersPages( List<GatewaysAndServers> gatewaysAndServersList) { // TODO: actually merge return gatewaysAndServersList.get(0); } private SortedMap<String, BgpAdvertisementsByVrf> parseEnvironmentBgpTables( NetworkSnapshot snapshot, SortedMap<String, String> inputData, ParseEnvironmentBgpTablesAnswerElement answerElement) { _logger.info("\n*** PARSING ENVIRONMENT BGP TABLES ***\n"); _logger.resetTimer(); SortedMap<String, BgpAdvertisementsByVrf> bgpTables = new TreeMap<>(); List<ParseEnvironmentBgpTableJob> jobs = new ArrayList<>(); SortedMap<String, Configuration> configurations = loadConfigurations(snapshot); for (Entry<String, String> bgpObject : inputData.entrySet()) { String currentKey = bgpObject.getKey(); String objectText = bgpObject.getValue(); String hostname = Paths.get(currentKey).getFileName().toString(); String optionalSuffix = ".bgp"; if (hostname.endsWith(optionalSuffix)) { hostname = hostname.substring(0, hostname.length() - optionalSuffix.length()); } if (!configurations.containsKey(hostname)) { continue; } Warnings warnings = buildWarnings(_settings); ParseEnvironmentBgpTableJob job = new ParseEnvironmentBgpTableJob( _settings, snapshot, objectText, hostname, currentKey, warnings, _bgpTablePlugins); jobs.add(job); } BatfishJobExecutor.runJobsInExecutor( _settings, _logger, jobs, bgpTables, answerElement, _settings.getHaltOnParseError(), "Parse environment BGP tables"); _logger.printElapsedTime(); return bgpTables; } /** * Returns a list of {@link ParseVendorConfigurationJob} to parse each file. * * <p>{@code expectedFormat} specifies the type of files expected in the {@code keyedFileText} * map, or is set to {@link ConfigurationFormat#UNKNOWN} to trigger format detection. */ private List<ParseVendorConfigurationJob> makeParseVendorConfigurationsJobs( NetworkSnapshot snapshot, Map<String, String> keyedFileText, ConfigurationFormat expectedFormat) { List<ParseVendorConfigurationJob> jobs = new ArrayList<>(keyedFileText.size()); for (Entry<String, String> vendorFile : keyedFileText.entrySet()) { @Nullable SpanContext parseVendorConfigurationSpanContext = GlobalTracer.get().activeSpan() == null ? null : GlobalTracer.get().activeSpan().context(); ParseVendorConfigurationJob job = new ParseVendorConfigurationJob( _settings, snapshot, vendorFile.getValue(), vendorFile.getKey(), buildWarnings(_settings), expectedFormat, HashMultimap.create(), parseVendorConfigurationSpanContext); jobs.add(job); } return jobs; } /** * Parses the given configuration files and returns a map keyed by hostname representing the * {@link VendorConfiguration vendor-specific configurations}. * * <p>{@code expectedFormat} specifies the type of files expected in the {@code keyedFileText} * map, or is set to {@link ConfigurationFormat#UNKNOWN} to trigger format detection. */ private SortedMap<String, VendorConfiguration> parseVendorConfigurations( NetworkSnapshot snapshot, Map<String, String> keyedConfigurationText, ParseVendorConfigurationAnswerElement answerElement, ConfigurationFormat expectedFormat) { _logger.info("\n*** PARSING VENDOR CONFIGURATION FILES ***\n"); _logger.resetTimer(); SortedMap<String, VendorConfiguration> vendorConfigurations = new TreeMap<>(); List<ParseVendorConfigurationJob> jobs = makeParseVendorConfigurationsJobs(snapshot, keyedConfigurationText, expectedFormat); BatfishJobExecutor.runJobsInExecutor( _settings, _logger, jobs, vendorConfigurations, answerElement, _settings.getHaltOnParseError(), "Parse configurations"); _logger.printElapsedTime(); return vendorConfigurations; } private void populateChannelGroupMembers( Map<String, Interface> interfaces, String ifaceName, Interface iface) { String portChannelName = iface.getChannelGroup(); if (portChannelName == null) { return; } Interface portChannel = interfaces.get(portChannelName); if (portChannel == null) { return; } portChannel.setChannelGroupMembers( ImmutableSortedSet.<String>naturalOrder() .addAll(portChannel.getChannelGroupMembers()) .add(ifaceName) .build()); } private void postProcessAggregatedInterfaces(Map<String, Configuration> configurations) { configurations .values() .forEach(c -> postProcessAggregatedInterfacesHelper(c.getAllInterfaces())); } private void postProcessAggregatedInterfacesHelper(Map<String, Interface> interfaces) { /* Populate aggregated interfaces with members referring to them. */ interfaces.forEach( (ifaceName, iface) -> populateChannelGroupMembers(interfaces, ifaceName, iface)); /* Compute bandwidth for aggregated interfaces. */ computeAggregatedInterfaceBandwidths(interfaces); } private void postProcessRedundantInterfaces(Map<String, Configuration> configurations) { configurations .values() .forEach( c -> c.getVrfs() .values() .forEach( v -> postProcessRedundantInterfacesHelper(c.getAllInterfaces(v.getName())))); } private void postProcessRedundantInterfacesHelper(Map<String, Interface> interfaces) { /* Compute bandwidth for redundnant interfaces. */ computeRedundantInterfaceBandwidths(interfaces); } private void identifyDeviceTypes(Collection<Configuration> configurations) { for (Configuration c : configurations) { if (c.getDeviceType() != null) { continue; } // Set device type to host iff the configuration format is HOST if (c.getConfigurationFormat() == ConfigurationFormat.HOST) { c.setDeviceType(DeviceType.HOST); } else if (c.getVrfs().values().stream() .anyMatch( vrf -> vrf.getBgpProcess() != null || !vrf.getEigrpProcesses().isEmpty() || vrf.getIsisProcess() != null || !vrf.getOspfProcesses().isEmpty() || vrf.getRipProcess() != null)) { c.setDeviceType(DeviceType.ROUTER); } else { // If device was not a host or router, call it a switch c.setDeviceType(DeviceType.SWITCH); } } } @VisibleForTesting static void postProcessInterfaceDependencies(Map<String, Configuration> configurations) { configurations .values() .forEach( config -> { Map<String, Interface> allInterfaces = config.getAllInterfaces(); Graph<String, DefaultEdge> graph = new SimpleDirectedGraph<>(DefaultEdge.class); allInterfaces.keySet().forEach(graph::addVertex); allInterfaces .values() .forEach( iface -> iface .getDependencies() .forEach( dependency -> { // JGraphT crashes if there is an edge to an undeclared vertex. // We add every edge target as a vertex, and code later will // still disable the child. graph.addVertex(dependency.getInterfaceName()); graph.addEdge( // Reverse edge direction to aid topological sort dependency.getInterfaceName(), iface.getName()); })); // Traverse interfaces in topological order and deactivate if necessary for (TopologicalOrderIterator<String, DefaultEdge> iterator = new TopologicalOrderIterator<>(graph); iterator.hasNext(); ) { String ifaceName = iterator.next(); @Nullable Interface iface = allInterfaces.get(ifaceName); if (iface == null) { // A missing dependency. continue; } deactivateInterfaceIfNeeded(iface); } }); } /** Deactivate an interface if it is blacklisted or its dependencies are not active */ private static void deactivateInterfaceIfNeeded(@Nonnull Interface iface) { Configuration config = iface.getOwner(); Set<Dependency> dependencies = iface.getDependencies(); if (dependencies.stream() // Look at bind dependencies .filter(d -> d.getType() == DependencyType.BIND) .map(d -> config.getAllInterfaces().get(d.getInterfaceName())) // Find any missing or inactive interfaces .anyMatch(parent -> parent == null || !parent.getActive())) { iface.setActive(false); } // Look at aggregate dependencies only now if ((iface.getInterfaceType() == InterfaceType.AGGREGATED || iface.getInterfaceType() == InterfaceType.REDUNDANT) && dependencies.stream() .filter(d1 -> d1.getType() == DependencyType.AGGREGATE) // Extract existing and active interfaces .map(d -> config.getAllInterfaces().get(d.getInterfaceName())) .filter(Objects::nonNull) .noneMatch(Interface::getActive)) { iface.setActive(false); } } private void postProcessEigrpCosts(Map<String, Configuration> configurations) { configurations.values().stream() .flatMap(c -> c.getAllInterfaces().values().stream()) .filter( iface -> iface.getEigrp() != null && (iface.getInterfaceType() == InterfaceType.AGGREGATED || iface.getInterfaceType() == InterfaceType.AGGREGATE_CHILD)) .forEach( iface -> { EigrpMetricValues metricValues = iface.getEigrp().getMetric().getValues(); if (metricValues.getBandwidth() == null) { // only set bandwidth if it's not explicitly configured for EIGRP Double bw = iface.getBandwidth(); assert bw != null; // all bandwidths should be finalized at this point metricValues.setBandwidth(bw.longValue() / 1000); // convert to kbps } }); } private void postProcessOspfCosts(Map<String, Configuration> configurations) { configurations .values() .forEach( c -> c.getVrfs() .values() .forEach( vrf -> { // Compute OSPF interface costs where they are missing vrf.getOspfProcesses().values().forEach(p -> p.initInterfaceCosts(c)); })); } @Override public Set<BgpAdvertisement> loadExternalBgpAnnouncements( NetworkSnapshot snapshot, Map<String, Configuration> configurations) { Set<BgpAdvertisement> advertSet = new LinkedHashSet<>(); for (ExternalBgpAdvertisementPlugin plugin : _externalBgpAdvertisementPlugins) { Set<BgpAdvertisement> currentAdvertisements = plugin.loadExternalBgpAdvertisements(snapshot); advertSet.addAll(currentAdvertisements); } return advertSet; } /** * Builds the {@link Trace}s for a {@link Set} of {@link Flow}s. * * @param flows {@link Set} of {@link Flow} for which {@link Trace}s are to be found * @param ignoreFilters if true, will ignore ACLs * @return {@link SortedMap} of {@link Flow}s to {@link List} of {@link Trace}s */ @Override public SortedMap<Flow, List<Trace>> buildFlows( NetworkSnapshot snapshot, Set<Flow> flows, boolean ignoreFilters) { return getTracerouteEngine(snapshot).computeTraces(flows, ignoreFilters); } @Override public TracerouteEngine getTracerouteEngine(NetworkSnapshot snapshot) { return new TracerouteEngineImpl( loadDataPlane(snapshot), _topologyProvider.getLayer3Topology(snapshot), loadConfigurations(snapshot)); } /** Function that processes an interface blacklist across all configurations */ private static void processInterfaceBlacklist( Set<NodeInterfacePair> interfaceBlacklist, NetworkConfigurations configurations) { interfaceBlacklist.stream() .map(iface -> configurations.getInterface(iface.getHostname(), iface.getInterface())) .filter(Optional::isPresent) .map(Optional::get) .forEach(Interface::blacklist); } @VisibleForTesting static Set<NodeInterfacePair> nodeToInterfaceBlacklist( SortedSet<String> blacklistNodes, NetworkConfigurations configurations) { return blacklistNodes.stream() // Get all valid/present node configs .map(configurations::get) .filter(Optional::isPresent) .map(Optional::get) // All interfaces in each config .flatMap(c -> c.getAllInterfaces().values().stream()) .map(NodeInterfacePair::of) .collect(ImmutableSet.toImmutableSet()); } @VisibleForTesting static void processManagementInterfaces(Map<String, Configuration> configurations) { configurations .values() .forEach( configuration -> { for (Interface iface : configuration.getAllInterfaces().values()) { if (MANAGEMENT_INTERFACES.matcher(iface.getName()).find() || MANAGEMENT_VRFS.matcher(iface.getVrfName()).find()) { iface.blacklist(); } } }); } @Override @Nullable public String readExternalBgpAnnouncementsFile(NetworkSnapshot snapshot) { try { return _storage.loadExternalBgpAnnouncementsFile(snapshot).orElse(null); } catch (IOException e) { throw new UncheckedIOException(e); } } /** * Read Iptable Files for each host in the keyset of {@code hostConfigurations}, and store the * contents in {@code iptablesData}. Each task fails if the Iptables file specified by host does * not exist. * * @throws BatfishException if there is a failed task and either {@link * Settings#getExitOnFirstError()} or {@link Settings#getHaltOnParseError()} is set. */ void readIptablesFiles( NetworkSnapshot snapshot, SortedMap<String, VendorConfiguration> hostConfigurations, SortedMap<String, String> iptablesData, ParseVendorConfigurationAnswerElement answerElement) { List<BatfishException> failureCauses = new ArrayList<>(); for (VendorConfiguration vc : hostConfigurations.values()) { HostConfiguration hostConfig = (HostConfiguration) vc; String iptablesFile = hostConfig.getIptablesFile(); if (iptablesFile == null) { continue; } // ensure that the iptables file is not taking us outside of the // testrig try { if (!_storage.hasSnapshotInputObject(iptablesFile, snapshot)) { String failureMessage = String.format( "Iptables file %s for host %s is not contained within the snapshot", hostConfig.getIptablesFile(), hostConfig.getHostname()); BatfishException bfc; if (answerElement.getErrors().containsKey(hostConfig.getHostname())) { bfc = new BatfishException( failureMessage, answerElement.getErrors().get(hostConfig.getHostname()).getException()); answerElement.getErrors().put(hostConfig.getHostname(), bfc.getBatfishStackTrace()); answerElement .getErrorDetails() .put( hostConfig.getHostname(), new ErrorDetails(Throwables.getStackTraceAsString(bfc))); } else { bfc = new BatfishException(failureMessage); if (_settings.getExitOnFirstError()) { throw bfc; } else { failureCauses.add(bfc); answerElement.getErrors().put(hostConfig.getHostname(), bfc.getBatfishStackTrace()); answerElement.getParseStatus().put(hostConfig.getIptablesFile(), ParseStatus.FAILED); answerElement .getErrorDetails() .put( hostConfig.getHostname(), new ErrorDetails(Throwables.getStackTraceAsString(bfc))); } } } else { try (InputStream inputStream = _storage.loadSnapshotInputObject( snapshot.getNetwork(), snapshot.getSnapshot(), iptablesFile)) { iptablesData.put(iptablesFile, decodeStreamAndAppendNewline(inputStream)); } } } catch (IOException e) { throw new BatfishException("Could not get canonical path", e); } } if (_settings.getHaltOnParseError() && !failureCauses.isEmpty()) { BatfishException e = new BatfishException( "Fatal exception due to at least one Iptables file is" + " not contained within the testrig"); failureCauses.forEach(e::addSuppressed); throw e; } } @Override public void registerAnswerer( String questionName, String questionClassName, BiFunction<Question, IBatfish, Answerer> answererCreator) { AnswererCreator oldAnswererCreator = _answererCreators.putIfAbsent( questionName, new AnswererCreator(questionClassName, answererCreator)); if (oldAnswererCreator != null) { // Error: questionName collision. String oldQuestionClassName = _answererCreators.get(questionClassName).getQuestionClassName(); throw new IllegalArgumentException( String.format( "questionName %s already exists.\n" + " old questionClassName: %s\n" + " new questionClassName: %s", questionName, oldQuestionClassName, questionClassName)); } } @Override public void registerBgpTablePlugin(BgpTableFormat format, BgpTablePlugin bgpTablePlugin) { _bgpTablePlugins.put(format, bgpTablePlugin); } @Override public void registerExternalBgpAdvertisementPlugin( ExternalBgpAdvertisementPlugin externalBgpAdvertisementPlugin) { _externalBgpAdvertisementPlugins.add(externalBgpAdvertisementPlugin); } private void repairConfigurations(NetworkSnapshot snapshot) { // Needed to ensure vendor configs are written loadParseVendorConfigurationAnswerElement(snapshot); serializeIndependentConfigs(snapshot); } /** * Post-process the configuration in the current snapshot. Post-processing includes: * * <ul> * <li>Applying node and interface blacklists. * <li>Process interface dependencies and deactivate interfaces that cannot be up * </ul> */ private void updateBlacklistedAndInactiveConfigs( NetworkSnapshot snapshot, Map<String, Configuration> configurations) { NetworkConfigurations nc = NetworkConfigurations.of(configurations); NetworkId networkId = snapshot.getNetwork(); SnapshotId snapshotId = snapshot.getSnapshot(); SortedSet<String> blacklistedNodes = _storage.loadNodeBlacklist(networkId, snapshotId); if (blacklistedNodes != null) { processInterfaceBlacklist(nodeToInterfaceBlacklist(blacklistedNodes, nc), nc); } // If interface blacklist was provided, it was converted to runtime data file by WorkMgr SnapshotRuntimeData runtimeData = _storage.loadRuntimeData(networkId, snapshotId); if (runtimeData != null) { processInterfaceBlacklist(runtimeData.getBlacklistedInterfaces(), nc); } if (_settings.ignoreManagementInterfaces()) { processManagementInterfaces(configurations); } postProcessInterfaceDependencies(configurations); // We do not process the edge blacklist here. Instead, we rely on these edges being explicitly // deleted from the Topology (aka list of edges) that is used along with configurations in // answering questions. // TODO: take this out once dependencies are *the* definitive way to disable interfaces disableUnusableVlanInterfaces(configurations); } /** * Ensures that the current configurations for the current snapshot are correct by performing some * post-processing on the vendor-independent datamodel. Among other things, this includes: * * <ul> * <li>Invalidating cached configs if the in-memory copy has been changed by question * processing. * <li>Re-loading configurations from disk, including re-parsing if the configs were parsed on a * previous version of Batfish. * <li>Ensuring that blacklists are honored. * </ul> */ private void postProcessSnapshot( NetworkSnapshot snapshot, Map<String, Configuration> configurations) { updateBlacklistedAndInactiveConfigs(snapshot, configurations); postProcessAggregatedInterfaces(configurations); postProcessRedundantInterfaces(configurations); NetworkConfigurations nc = NetworkConfigurations.of(configurations); OspfTopologyUtils.initNeighborConfigs(nc); postProcessOspfCosts(configurations); postProcessEigrpCosts(configurations); // must be after postProcessAggregatedInterfaces EigrpTopologyUtils.initNeighborConfigs(nc); } private void computeAndStoreCompletionMetadata( NetworkSnapshot snapshot, Map<String, Configuration> configurations) { try { _storage.storeCompletionMetadata( computeCompletionMetadata(snapshot, configurations), _settings.getContainer(), snapshot.getSnapshot()); } catch (IOException e) { _logger.errorf("Error storing CompletionMetadata: %s", e); } } private CompletionMetadata computeCompletionMetadata( NetworkSnapshot snapshot, Map<String, Configuration> configurations) { return new CompletionMetadata( getFilterNames(configurations), getInterfaces(configurations), getIps(configurations), getLocationCompletionMetadata(getLocationInfo(snapshot), configurations), getMlagIds(configurations), getNodes(configurations), getPrefixes(configurations), getRoutingPolicyNames(configurations), getStructureNames(configurations), getVrfs(configurations), getZones(configurations)); } @MustBeClosed @Nonnull @Override public InputStream getNetworkObject(NetworkId networkId, String key) throws IOException { return _storage.loadNetworkObject(networkId, key); } @MustBeClosed @Nonnull @Override public InputStream getSnapshotInputObject(NetworkSnapshot snapshot, String key) throws IOException { return _storage.loadSnapshotInputObject(snapshot.getNetwork(), snapshot.getSnapshot(), key); } private void repairEnvironmentBgpTables(NetworkSnapshot snapshot) { try { _storage.deleteParseEnvironmentBgpTablesAnswerElement(snapshot); _storage.deleteEnvironmentBgpTables(snapshot); } catch (IOException e) { throw new UncheckedIOException(e); } computeEnvironmentBgpTables(snapshot); } private void repairVendorConfigurations(NetworkSnapshot snapshot) { try { _storage.deleteParseVendorConfigurationAnswerElement(snapshot); _storage.deleteVendorConfigurations(snapshot); } catch (IOException e) { throw new UncheckedIOException(e); } serializeVendorConfigs(snapshot); } public Answer run(NetworkSnapshot snapshot) { newBatch("Begin job", 0); boolean action = false; Answer answer = new Answer(); if (_settings.getSerializeVendor()) { answer.append(serializeVendorConfigs(snapshot)); action = true; } if (_settings.getSerializeIndependent()) { answer.append(serializeIndependentConfigs(snapshot)); // TODO: compute topology on initialization in cleaner way initializeTopology(snapshot); updateSnapshotNodeRoles(snapshot); action = true; } if (_settings.getInitInfo()) { InitInfoAnswerElement initInfoAnswerElement = initInfo(snapshot, true, false); // In this context we can remove parse trees because they will be returned in preceding answer // element. Note that parse trees are not removed when asking initInfo as its own question. initInfoAnswerElement.setParseTrees(Collections.emptySortedMap()); answer.addAnswerElement(initInfoAnswerElement); action = true; } if (_settings.getAnswer()) { Span span = GlobalTracer.get().buildSpan("Getting answer to question").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning answer.append(answer()); action = true; } finally { span.finish(); } } if (_settings.getAnalyze()) { answer.append(analyze()); action = true; } if (_settings.getDataPlane()) { answer.addAnswerElement(computeDataPlane(snapshot)); action = true; } if (!action) { throw new CleanBatfishException("No task performed! Run with -help flag to see usage\n"); } return answer; } /** Initialize topologies, commit {raw, raw pojo, pruned} layer-3 topologies to storage. */ @VisibleForTesting void initializeTopology(NetworkSnapshot networkSnapshot) { Map<String, Configuration> configurations = loadConfigurations(networkSnapshot); LOGGER.info("Initializing topology"); Topology rawLayer3Topology = _topologyProvider.getRawLayer3Topology(networkSnapshot); checkTopology(configurations, rawLayer3Topology); org.batfish.datamodel.pojo.Topology pojoTopology = org.batfish.datamodel.pojo.Topology.create( _settings.getSnapshotName(), configurations, rawLayer3Topology); try { _storage.storePojoTopology( pojoTopology, networkSnapshot.getNetwork(), networkSnapshot.getSnapshot()); } catch (IOException e) { throw new BatfishException("Could not serialize layer-3 POJO topology", e); } Topology layer3Topology = _topologyProvider.getInitialLayer3Topology(networkSnapshot); try { _storage.storeInitialTopology( layer3Topology, networkSnapshot.getNetwork(), networkSnapshot.getSnapshot()); } catch (IOException e) { throw new BatfishException("Could not serialize layer-3 topology", e); } } /** Returns {@code true} iff AWS configuration data is found. */ private boolean serializeAwsConfigs( NetworkSnapshot snapshot, ParseVendorConfigurationAnswerElement pvcae) { _logger.info("\n*** READING AWS CONFIGS ***\n"); AwsConfiguration awsConfiguration; boolean found = false; Span span = GlobalTracer.get().buildSpan("Parse AWS configs").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning Map<String, String> awsConfigurationData; // Try to parse all accounts as one vendor configuration try (Stream<String> keys = _storage.listInputAwsMultiAccountKeys(snapshot)) { awsConfigurationData = readAllInputObjects(keys, snapshot); } if (awsConfigurationData.isEmpty()) { // No multi-account data, so try to parse as single-account try (Stream<String> keys = _storage.listInputAwsSingleAccountKeys(snapshot)) { awsConfigurationData = readAllInputObjects(keys, snapshot); } } found = !awsConfigurationData.isEmpty(); awsConfiguration = parseAwsConfigurations(awsConfigurationData, pvcae); } catch (IOException e) { throw new UncheckedIOException(e); } finally { span.finish(); } _logger.info("\n*** SERIALIZING AWS CONFIGURATION STRUCTURES ***\n"); _logger.resetTimer(); _logger.debugf("Serializing AWS"); try { _storage.storeVendorConfigurations( ImmutableMap.of(BfConsts.RELPATH_AWS_CONFIGS_FILE, awsConfiguration), snapshot); } catch (IOException e) { throw new UncheckedIOException(e); } _logger.debug("OK\n"); _logger.printElapsedTime(); return found; } private void serializeConversionContext( NetworkSnapshot snapshot, ParseVendorConfigurationAnswerElement pvcae) { // Serialize Checkpoint management servers if present LOGGER.info("\n*** READING CHECKPOINT MANAGEMENT CONFIGS ***\n"); CheckpointManagementConfiguration cpMgmtConfig = null; Span span = GlobalTracer.get().buildSpan("Parse Checkpoint management configs").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning Map<String, String> cpServerData; // Try to parse all accounts as one vendor configuration try (Stream<String> keys = _storage.listInputCheckpointManagementKeys(snapshot)) { cpServerData = readAllInputObjects(keys, snapshot); } if (!cpServerData.isEmpty()) { cpMgmtConfig = parseCheckpointManagementData(cpServerData, pvcae); } } catch (IOException e) { throw new UncheckedIOException(e); } finally { span.finish(); } LOGGER.info("\n*** SERIALIZING CONVERSION CONTEXT ***\n"); ConversionContext conversionContext = new ConversionContext(); conversionContext.setCheckpointManagementConfiguration(cpMgmtConfig); if (!conversionContext.isEmpty()) { try { _storage.storeConversionContext(conversionContext, snapshot); } catch (IOException e) { throw new UncheckedIOException(e); } } } private Answer computeEnvironmentBgpTables(NetworkSnapshot snapshot) { Answer answer = new Answer(); ParseEnvironmentBgpTablesAnswerElement answerElement = new ParseEnvironmentBgpTablesAnswerElement(); answerElement.setVersion(BatfishVersion.getVersionStatic()); answer.addAnswerElement(answerElement); SortedMap<String, BgpAdvertisementsByVrf> bgpTables = getEnvironmentBgpTables(snapshot, answerElement); try { _storage.storeEnvironmentBgpTables(bgpTables, snapshot); _storage.storeParseEnvironmentBgpTablesAnswerElement(answerElement, snapshot); } catch (IOException e) { throw new UncheckedIOException(e); } return answer; } private SortedMap<String, VendorConfiguration> serializeHostConfigs( NetworkSnapshot snapshot, ParseVendorConfigurationAnswerElement answerElement) { _logger.info("\n*** READING HOST CONFIGS ***\n"); Map<String, String> keyedHostText; try (Stream<String> keys = _storage.listInputHostConfigurationsKeys(snapshot)) { keyedHostText = readAllInputObjects(keys, snapshot); } catch (IOException e) { throw new UncheckedIOException(e); } // read the host files SortedMap<String, VendorConfiguration> allHostConfigurations; Span span = GlobalTracer.get().buildSpan("Parse host configs").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning allHostConfigurations = parseVendorConfigurations( snapshot, keyedHostText, answerElement, ConfigurationFormat.HOST); } finally { span.finish(); } if (allHostConfigurations == null) { throw new BatfishException("Exiting due to parser errors"); } _logger.infof( "Testrig:%s in container:%s has total number of host configs:%d", snapshot.getSnapshot(), snapshot.getNetwork(), allHostConfigurations.size()); // split into hostConfigurations and overlayConfigurations SortedMap<String, VendorConfiguration> overlayConfigurations = allHostConfigurations.entrySet().stream() .filter(e -> ((HostConfiguration) e.getValue()).getOverlay()) .collect(toMap(Entry::getKey, Entry::getValue, (v1, v2) -> v1, TreeMap::new)); SortedMap<String, VendorConfiguration> nonOverlayHostConfigurations = allHostConfigurations.entrySet().stream() .filter(e -> !((HostConfiguration) e.getValue()).getOverlay()) .collect(toMap(Entry::getKey, Entry::getValue, (v1, v2) -> v1, TreeMap::new)); // read and associate iptables files for specified hosts SortedMap<String, String> keyedIptablesText = new TreeMap<>(); readIptablesFiles(snapshot, allHostConfigurations, keyedIptablesText, answerElement); SortedMap<String, VendorConfiguration> iptablesConfigurations = parseVendorConfigurations( snapshot, keyedIptablesText, answerElement, ConfigurationFormat.IPTABLES); for (VendorConfiguration vc : allHostConfigurations.values()) { HostConfiguration hostConfig = (HostConfiguration) vc; if (hostConfig.getIptablesFile() != null) { String iptablesKeyFromHost = hostConfig.getIptablesFile(); if (iptablesConfigurations.containsKey(iptablesKeyFromHost)) { hostConfig.setIptablesVendorConfig( (IptablesVendorConfiguration) iptablesConfigurations.get(iptablesKeyFromHost)); } } } // now, serialize _logger.info("\n*** SERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n"); _logger.resetTimer(); try { _storage.storeVendorConfigurations(nonOverlayHostConfigurations, snapshot); } catch (IOException e) { throw new UncheckedIOException(e); } // serialize warnings try { _storage.storeParseVendorConfigurationAnswerElement(answerElement, snapshot); } catch (IOException e) { throw new UncheckedIOException(e); } _logger.printElapsedTime(); return overlayConfigurations; } private Answer serializeIndependentConfigs(NetworkSnapshot snapshot) { Span span = GlobalTracer.get().buildSpan("serializeIndependentConfigs").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning Answer answer = new Answer(); ConvertConfigurationAnswerElement answerElement = new ConvertConfigurationAnswerElement(); answerElement.setVersion(BatfishVersion.getVersionStatic()); if (_settings.getVerboseParse()) { answer.addAnswerElement(answerElement); } ConversionContext conversionContext; try { conversionContext = _storage.loadConversionContext(snapshot); } catch (FileNotFoundException e) { // Not written when it is empty. conversionContext = new ConversionContext(); } catch (IOException e) { throw new UncheckedIOException(e); } SnapshotRuntimeData runtimeData = firstNonNull( _storage.loadRuntimeData(snapshot.getNetwork(), snapshot.getSnapshot()), EMPTY_SNAPSHOT_RUNTIME_DATA); Map<String, VendorConfiguration> vendorConfigs; Map<String, Configuration> configurations; LOGGER.info( "Converting the Vendor-Specific configurations to Vendor-Independent configurations"); Span convertSpan = GlobalTracer.get().buildSpan("convert VS to VI").start(); try (Scope childScope = GlobalTracer.get().scopeManager().activate(span)) { assert childScope != null; // avoid unused warning vendorConfigs = _storage.loadVendorConfigurations(snapshot); configurations = getConfigurations(vendorConfigs, conversionContext, runtimeData, answerElement); } catch (IOException e) { throw new UncheckedIOException(e); } finally { convertSpan.finish(); } Set<Layer1Edge> layer1Edges = vendorConfigs.values().stream() .flatMap(vc -> vc.getLayer1Edges().stream()) .collect(Collectors.toSet()); Warnings internetWarnings = answerElement .getWarnings() .computeIfAbsent(INTERNET_HOST_NAME, i -> buildWarnings(_settings)); ModeledNodes modeledNodes = getInternetAndIspNodes(snapshot, configurations, vendorConfigs, internetWarnings); mergeInternetAndIspNodes(modeledNodes, configurations, layer1Edges, internetWarnings); LOGGER.info("Serializing Vendor-Independent configurations"); Span storeSpan = GlobalTracer.get().buildSpan("store VI configs").start(); try (Scope childScope = GlobalTracer.get().scopeManager().activate(span)) { assert childScope != null; // avoid unused warning try { _storage.storeConfigurations( configurations, answerElement, // we don't write anything if no Layer1 edges were produced // empty topologies are currently dangerous for L1 computation layer1Edges.isEmpty() ? null : new Layer1Topology(layer1Edges), snapshot.getNetwork(), snapshot.getSnapshot()); } catch (IOException e) { throw new BatfishException("Could not store vendor independent configs to disk: %s", e); } } finally { storeSpan.finish(); } LOGGER.info("Post-processing the Vendor-Independent devices"); Span ppSpan = GlobalTracer.get().buildSpan("Post-process vendor-independent configs").start(); try (Scope childScope = GlobalTracer.get().scopeManager().activate(span)) { assert childScope != null; // avoid unused warning postProcessSnapshot(snapshot, configurations); } finally { ppSpan.finish(); } LOGGER.info("Computing completion metadata"); Span metadataSpan = GlobalTracer.get().buildSpan("Compute and store completion metadata").start(); try (Scope childScope = GlobalTracer.get().scopeManager().activate(span)) { assert childScope != null; // avoid unused warning computeAndStoreCompletionMetadata(snapshot, configurations); } finally { metadataSpan.finish(); } return answer; } finally { span.finish(); } } /** * Merges modeled nodes into {@code configurations} and {@code layer1Edges}. Nothing is done if * the input configurations have a node in common with modeled nodes. */ @VisibleForTesting static void mergeInternetAndIspNodes( ModeledNodes modeledNodes, Map<String, Configuration> configurations, Set<Layer1Edge> layer1Edges, Warnings internetWarnings) { Map<String, Configuration> modeledConfigs = modeledNodes.getConfigurations(); Set<String> commonNodes = Sets.intersection(configurations.keySet(), modeledConfigs.keySet()); if (!commonNodes.isEmpty()) { internetWarnings.redFlag( String.format( "Cannot add internet and ISP nodes because nodes with the following names already" + " exist in the snapshot: %s", commonNodes)); return; } configurations.putAll(modeledConfigs); layer1Edges.addAll(modeledNodes.getLayer1Edges()); } /** * Creates and returns ISP and Internet nodes. * * <p>If a node named 'internet' already exists in input {@code configurations} an empty {@link * ModeledNodes} object is returned. */ @Nonnull private ModeledNodes getInternetAndIspNodes( NetworkSnapshot snapshot, Map<String, Configuration> configurations, Map<String, VendorConfiguration> vendorConfigs, Warnings internetWarnings) { if (configurations.containsKey(INTERNET_HOST_NAME)) { internetWarnings.redFlag( "Cannot model internet because a node with the name 'internet' already exists"); return new ModeledNodes(); } ImmutableList.Builder<IspConfiguration> ispConfigurations = new ImmutableList.Builder<>(); IspConfiguration ispConfiguration = _storage.loadIspConfiguration(snapshot.getNetwork(), snapshot.getSnapshot()); if (ispConfiguration != null) { LOGGER.info("Loading Batfish ISP Configuration"); ispConfigurations.add(ispConfiguration); } vendorConfigs.values().stream() .map(VendorConfiguration::getIspConfiguration) .filter(Objects::nonNull) .forEach(ispConfigurations::add); return IspModelingUtils.getInternetAndIspNodes( configurations, ispConfigurations.build(), _logger, internetWarnings); } private void updateSnapshotNodeRoles(NetworkSnapshot snapshot) { // Compute new auto role data and updates existing auto data with it NodeRolesId snapshotNodeRolesId = _idResolver.getSnapshotNodeRolesId(snapshot.getNetwork(), snapshot.getSnapshot()); Set<String> nodeNames = loadConfigurations(snapshot).keySet(); Topology rawLayer3Topology = _topologyProvider.getRawLayer3Topology(snapshot); Optional<RoleMapping> autoRoles = new InferRoles(nodeNames, rawLayer3Topology).inferRoles(); NodeRolesData.Builder snapshotNodeRoles = NodeRolesData.builder(); try { if (autoRoles.isPresent()) { snapshotNodeRoles.setDefaultDimension(NodeRoleDimension.AUTO_DIMENSION_PRIMARY); snapshotNodeRoles.setRoleMappings(ImmutableList.of(autoRoles.get())); snapshotNodeRoles.setType(Type.AUTO); } _storage.storeNodeRoles( snapshot.getNetwork(), snapshotNodeRoles.build(), snapshotNodeRolesId); } catch (IOException e) { _logger.warnf("Could not update node roles: %s", e); } } private ParseVendorConfigurationResult getOrParse( ParseVendorConfigurationJob job, @Nullable SpanContext span, GrammarSettings settings) { String filename = job.getFilename(); String filetext = job.getFileText(); Span parseNetworkConfigsSpan = GlobalTracer.get() .buildSpan("Parse " + job.getFilename()) .addReference(References.FOLLOWS_FROM, span) .start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(parseNetworkConfigsSpan)) { assert scope != null; // avoid unused warning // Short-circuit all cache-related code. if (!_settings.getParseReuse()) { long startTime = System.currentTimeMillis(); ParseResult result = job.parse(); long elapsed = System.currentTimeMillis() - startTime; return job.fromResult(result, elapsed); } String id = Hashing.murmur3_128() .newHasher() .putString("Cached Parse Result", UTF_8) .putString(filename, UTF_8) .putString(filetext, UTF_8) .putBoolean(settings.getDisableUnrecognized()) .putInt(settings.getMaxParserContextLines()) .putInt(settings.getMaxParserContextTokens()) .putInt(settings.getMaxParseTreePrintLength()) .putBoolean(settings.getPrintParseTreeLineNums()) .putBoolean(settings.getPrintParseTree()) .putBoolean(settings.getThrowOnLexerError()) .putBoolean(settings.getThrowOnParserError()) .hash() .toString(); long startTime = System.currentTimeMillis(); boolean cached = false; ParseResult result; try (InputStream in = _storage.loadNetworkBlob(getContainerName(), id)) { result = SerializationUtils.deserialize(in); // sanity-check filenames. In the extremely unlikely event of a collision, we'll lose reuse // for this input. cached = result.getFilename().equals(filename); } catch (FileNotFoundException e) { result = job.parse(); } catch (Exception e) { _logger.warnf( "Error deserializing cached parse result for %s: %s", filename, Throwables.getStackTraceAsString(e)); result = job.parse(); } if (!cached) { try { byte[] serialized = SerializationUtils.serialize(result); _storage.storeNetworkBlob(new ByteArrayInputStream(serialized), getContainerName(), id); } catch (Exception e) { _logger.warnf( "Error caching parse result for %s: %s", filename, Throwables.getStackTraceAsString(e)); } } long elapsed = System.currentTimeMillis() - startTime; return job.fromResult(result, elapsed); } finally { parseNetworkConfigsSpan.finish(); } } /** * Parses configuration files for networking devices from the uploaded user data and produces * {@link VendorConfiguration vendor-specific configurations} serialized to the given output path. * Returns {@code true} iff at least one network configuration was found. * * <p>This function should be named better, but it's called by the {@link * #serializeVendorConfigs(NetworkSnapshot)}, so leaving as-is for now. */ private boolean serializeNetworkConfigs( NetworkSnapshot snapshot, ParseVendorConfigurationAnswerElement answerElement, SortedMap<String, VendorConfiguration> overlayHostConfigurations) { if (!overlayHostConfigurations.isEmpty()) { // Not able to cache with overlays. return oldSerializeNetworkConfigs(snapshot, answerElement, overlayHostConfigurations); } boolean found = false; _logger.info("\n*** READING DEVICE CONFIGURATION FILES ***\n"); List<ParseVendorConfigurationResult> parseResults; Span parseNetworkConfigsSpan = GlobalTracer.get().buildSpan("Parse network configs").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(parseNetworkConfigsSpan)) { assert scope != null; // avoid unused warning List<ParseVendorConfigurationJob> jobs; Span makeJobsSpan = GlobalTracer.get().buildSpan("Read files and make jobs").start(); try (Scope makeJobsScope = GlobalTracer.get().scopeManager().activate(makeJobsSpan)) { assert makeJobsScope != null; // avoid unused warning Map<String, String> keyedConfigText; // user filename (configs/foo) -> text of configs/foo try (Stream<String> keys = _storage.listInputNetworkConfigurationsKeys(snapshot)) { keyedConfigText = readAllInputObjects(keys, snapshot); } catch (IOException e) { throw new UncheckedIOException(e); } if (!keyedConfigText.isEmpty()) { found = true; } jobs = makeParseVendorConfigurationsJobs( snapshot, keyedConfigText, ConfigurationFormat.UNKNOWN); // Java parallel streams are not self-balancing in large networks, so shuffle the jobs. Collections.shuffle(jobs); } finally { makeJobsSpan.finish(); } AtomicInteger batch = newBatch("Parse network configs", jobs.size()); LOGGER.info("Parsing {} configuration files", jobs.size()); parseResults = jobs.parallelStream() .map( j -> { ParseVendorConfigurationResult result = getOrParse(j, parseNetworkConfigsSpan.context(), _settings); int done = batch.incrementAndGet(); if (done % 100 == 0) { LOGGER.info( "Successfully parsed {}/{} configuration files", done, jobs.size()); } return result; }) .collect(ImmutableList.toImmutableList()); LOGGER.info("Done parsing {} configuration files", jobs.size()); } finally { parseNetworkConfigsSpan.finish(); } if (_settings.getHaltOnParseError() && parseResults.stream().anyMatch(r -> r.getFailureCause() != null)) { BatfishException e = new BatfishException("Exiting due to parser errors"); parseResults.stream() .map(ParseVendorConfigurationResult::getFailureCause) .filter(Objects::nonNull) .forEach(e::addSuppressed); throw e; } _logger.infof( "Snapshot %s in network %s has total number of network configs:%d", snapshot.getSnapshot(), snapshot.getNetwork(), parseResults.size()); /* Assemble answer. */ SortedMap<String, VendorConfiguration> vendorConfigurations = new TreeMap<>(); parseResults.forEach(pvcr -> pvcr.applyTo(vendorConfigurations, _logger, answerElement)); LOGGER.info("Serializing Vendor-Specific configurations"); Span serializeNetworkConfigsSpan = GlobalTracer.get().buildSpan("Serialize network configs").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(serializeNetworkConfigsSpan)) { assert scope != null; // avoid unused warning _logger.info("\n*** SERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n"); _logger.resetTimer(); Map<String, VendorConfiguration> output = new TreeMap<>(); vendorConfigurations.forEach( (name, vc) -> { if (name.contains(File.separator)) { // iptables will get a hostname like configs/iptables-save if they // are not set up correctly using host files _logger.errorf("Cannot serialize configuration with bad hostname %s\n", name); answerElement.addRedFlagWarning( name, new Warning( "Cannot serialize network config. Bad hostname " + name.replace("\\", "/"), "MISCELLANEOUS")); } else { output.put(name, vc); } }); _storage.storeVendorConfigurations(output, snapshot); _logger.printElapsedTime(); } catch (IOException e) { throw new UncheckedIOException(e); } finally { serializeNetworkConfigsSpan.finish(); } return found; } /** Returns {@code true} iff at least one network configuration was found. */ private boolean oldSerializeNetworkConfigs( NetworkSnapshot snapshot, ParseVendorConfigurationAnswerElement answerElement, SortedMap<String, VendorConfiguration> overlayHostConfigurations) { boolean found = false; _logger.info("\n*** READING DEVICE CONFIGURATION FILES ***\n"); Map<String, VendorConfiguration> vendorConfigurations; Span parseNetworkConfigsSpan = GlobalTracer.get().buildSpan("Parse network configs").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(parseNetworkConfigsSpan)) { assert scope != null; // avoid unused warning Map<String, String> keyedConfigText; try (Stream<String> keys = _storage.listInputNetworkConfigurationsKeys(snapshot)) { keyedConfigText = readAllInputObjects(keys, snapshot); } catch (IOException e) { throw new UncheckedIOException(e); } if (!keyedConfigText.isEmpty()) { found = true; } vendorConfigurations = parseVendorConfigurations( snapshot, keyedConfigText, answerElement, ConfigurationFormat.UNKNOWN); } finally { parseNetworkConfigsSpan.finish(); } _logger.infof( "Snapshot %s in network %s has total number of network configs:%d", snapshot.getSnapshot(), snapshot.getNetwork(), vendorConfigurations.size()); Span serializeNetworkConfigsSpan = GlobalTracer.get().buildSpan("Serialize network configs").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(serializeNetworkConfigsSpan)) { assert scope != null; // avoid unused warning _logger.info("\n*** SERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n"); _logger.resetTimer(); Map<String, VendorConfiguration> output = new TreeMap<>(); vendorConfigurations.forEach( (name, vc) -> { if (name.contains(File.separator)) { // iptables will get a hostname like configs/iptables-save if they // are not set up correctly using host files _logger.errorf("Cannot serialize configuration with hostname %s\n", name); answerElement.addRedFlagWarning( name, new Warning( "Cannot serialize network config. Bad hostname " + name.replace("\\", "/"), "MISCELLANEOUS")); } else { // apply overlay if it exists VendorConfiguration overlayConfig = overlayHostConfigurations.get(name); if (overlayConfig != null) { vc.setOverlayConfiguration(overlayConfig); overlayHostConfigurations.remove(name); } output.put(name, vc); } }); // warn about unused overlays overlayHostConfigurations.forEach( (name, overlay) -> answerElement.getParseStatus().put(overlay.getFilename(), ParseStatus.ORPHANED)); _storage.storeVendorConfigurations(output, snapshot); _logger.printElapsedTime(); } catch (IOException e) { throw new UncheckedIOException(e); } finally { serializeNetworkConfigsSpan.finish(); } return found; } /** * Parses configuration files from the uploaded user data and produces {@link VendorConfiguration * vendor-specific configurations} serialized to the given output path. * * <p>This function should be named better, but it's called by the {@code -sv} argument to Batfish * so leaving as-is for now. */ private Answer serializeVendorConfigs(NetworkSnapshot snapshot) { Answer answer = new Answer(); boolean configsFound = false; ParseVendorConfigurationAnswerElement answerElement = new ParseVendorConfigurationAnswerElement(); answerElement.setVersion(BatfishVersion.getVersionStatic()); if (_settings.getVerboseParse()) { answer.addAnswerElement(answerElement); } // look for host configs and overlay configs in the `hosts/` subfolder of the upload. SortedMap<String, VendorConfiguration> overlayHostConfigurations = new TreeMap<>(); if (hasHostConfigs(snapshot)) { overlayHostConfigurations.putAll(serializeHostConfigs(snapshot, answerElement)); configsFound = true; } // look for network configs in the `configs/` subfolder of the upload. if (serializeNetworkConfigs(snapshot, answerElement, overlayHostConfigurations)) { configsFound = true; } // look for AWS VPC configs in the `aws_configs/` subfolder of the upload. if (serializeAwsConfigs(snapshot, answerElement)) { configsFound = true; } if (!configsFound) { throw new BatfishException("No valid configurations found in snapshot"); } // serialize any context needed for conversion (this does not include any configs) serializeConversionContext(snapshot, answerElement); // serialize warnings try { _storage.storeParseVendorConfigurationAnswerElement(answerElement, snapshot); } catch (IOException e) { throw new UncheckedIOException(e); } return answer; } private boolean hasHostConfigs(NetworkSnapshot snapshot) { try (Stream<String> keys = _storage.listInputHostConfigurationsKeys(snapshot)) { return keys.findAny().isPresent(); } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public void registerDataPlanePlugin(DataPlanePlugin plugin, String name) { _dataPlanePlugins.put(name, plugin); } public void setTerminatingExceptionMessage(String terminatingExceptionMessage) { _terminatingExceptionMessage = terminatingExceptionMessage; } @Override public SpecifierContext specifierContext(NetworkSnapshot networkSnapshot) { return new SpecifierContextImpl(this, networkSnapshot); } @Override public BidirectionalReachabilityResult bidirectionalReachability( NetworkSnapshot snapshot, BDDPacket bddPacket, ReachabilityParameters parameters) { ResolvedReachabilityParameters params; try { params = resolveReachabilityParameters(this, parameters, snapshot); } catch (InvalidReachabilityParametersException e) { throw new BatfishException("Error resolving reachability parameters", e); } DataPlane dataPlane = loadDataPlane(snapshot); return new BidirectionalReachabilityAnalysis( bddPacket, loadConfigurations(snapshot), dataPlane.getForwardingAnalysis(), new IpsRoutedOutInterfacesFactory(dataPlane.getFibs()), params.getSourceIpAssignment(), params.getHeaderSpace(), params.getForbiddenTransitNodes(), params.getRequiredTransitNodes(), params.getFinalNodes(), params.getActions()) .getResult(); } @Override public AnswerElement standard( NetworkSnapshot snapshot, ReachabilityParameters reachabilityParameters) { return bddSingleReachability(snapshot, reachabilityParameters); } public AnswerElement bddSingleReachability( NetworkSnapshot snapshot, ReachabilityParameters parameters) { Span span = GlobalTracer.get().buildSpan("bddSingleReachability").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning ResolvedReachabilityParameters params; try { params = resolveReachabilityParameters(this, parameters, snapshot); } catch (InvalidReachabilityParametersException e) { return e.getInvalidParametersAnswer(); } checkArgument( params.getSrcNatted() == SrcNattedConstraint.UNCONSTRAINED, "Requiring or forbidding Source NAT is currently unsupported"); BDDPacket pkt = new BDDPacket(); boolean ignoreFilters = params.getIgnoreFilters(); BDDReachabilityAnalysisFactory bddReachabilityAnalysisFactory = getBddReachabilityAnalysisFactory(snapshot, pkt, ignoreFilters); Map<IngressLocation, BDD> reachableBDDs = bddReachabilityAnalysisFactory.getAllBDDs( params.getSourceIpAssignment(), params.getHeaderSpace(), params.getForbiddenTransitNodes(), params.getRequiredTransitNodes(), params.getFinalNodes(), params.getActions()); Set<Flow> flows = constructFlows(pkt, reachableBDDs); return new TraceWrapperAsAnswerElement(buildFlows(snapshot, flows, ignoreFilters)); } finally { span.finish(); } } @Override public Set<Flow> bddLoopDetection(NetworkSnapshot snapshot) { Span span = GlobalTracer.get().buildSpan("bddLoopDetection").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning BDDPacket pkt = new BDDPacket(); // TODO add ignoreFilters parameter boolean ignoreFilters = false; BDDReachabilityAnalysisFactory bddReachabilityAnalysisFactory = getBddReachabilityAnalysisFactory(snapshot, pkt, ignoreFilters); BDDLoopDetectionAnalysis analysis = bddReachabilityAnalysisFactory.bddLoopDetectionAnalysis( getAllSourcesInferFromLocationIpSpaceAssignment(snapshot)); Map<IngressLocation, BDD> loopBDDs = analysis.detectLoops(); Span span1 = GlobalTracer.get().buildSpan("bddLoopDetection.computeResultFlows").start(); try (Scope scope1 = GlobalTracer.get().scopeManager().activate(span)) { assert scope1 != null; // avoid unused warning return loopBDDs.entrySet().stream() .map( entry -> pkt.getFlow(entry.getValue()) .map( fb -> { IngressLocation loc = entry.getKey(); fb.setIngressNode(loc.getNode()); switch (loc.getType()) { case INTERFACE_LINK: fb.setIngressInterface(loc.getInterface()); break; case VRF: fb.setIngressVrf(loc.getVrf()); break; default: throw new BatfishException( "Unknown Location Type: " + loc.getType()); } return fb.build(); })) .flatMap(optional -> optional.map(Stream::of).orElse(Stream.empty())) .collect(ImmutableSet.toImmutableSet()); } finally { span1.finish(); } } finally { span.finish(); } } @Override public Set<Flow> bddMultipathConsistency( NetworkSnapshot snapshot, MultipathConsistencyParameters parameters) { Span span = GlobalTracer.get().buildSpan("bddMultipathConsistency").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning BDDPacket pkt = new BDDPacket(); // TODO add ignoreFilters parameter boolean ignoreFilters = false; BDDReachabilityAnalysisFactory bddReachabilityAnalysisFactory = getBddReachabilityAnalysisFactory(snapshot, pkt, ignoreFilters); IpSpaceAssignment srcIpSpaceAssignment = parameters.getSrcIpSpaceAssignment(); Set<String> finalNodes = parameters.getFinalNodes(); Set<FlowDisposition> failureDispositions = ImmutableSet.of( FlowDisposition.DENIED_IN, FlowDisposition.DENIED_OUT, FlowDisposition.LOOP, FlowDisposition.INSUFFICIENT_INFO, FlowDisposition.NEIGHBOR_UNREACHABLE, FlowDisposition.NO_ROUTE, FlowDisposition.NULL_ROUTED); Set<FlowDisposition> successDispositions = ImmutableSet.of( FlowDisposition.ACCEPTED, FlowDisposition.DELIVERED_TO_SUBNET, FlowDisposition.EXITS_NETWORK); Set<String> forbiddenTransitNodes = parameters.getForbiddenTransitNodes(); Set<String> requiredTransitNodes = parameters.getRequiredTransitNodes(); Map<IngressLocation, BDD> successBdds = bddReachabilityAnalysisFactory.getAllBDDs( srcIpSpaceAssignment, parameters.getHeaderSpace(), forbiddenTransitNodes, requiredTransitNodes, finalNodes, successDispositions); Map<IngressLocation, BDD> failureBdds = bddReachabilityAnalysisFactory.getAllBDDs( srcIpSpaceAssignment, parameters.getHeaderSpace(), forbiddenTransitNodes, requiredTransitNodes, finalNodes, failureDispositions); return ImmutableSet.copyOf(computeMultipathInconsistencies(pkt, successBdds, failureBdds)); } finally { span.finish(); } } @Nonnull public IpSpaceAssignment getAllSourcesInferFromLocationIpSpaceAssignment( NetworkSnapshot snapshot) { SpecifierContextImpl specifierContext = new SpecifierContextImpl(this, snapshot); Set<Location> locations = new UnionLocationSpecifier( AllInterfacesLocationSpecifier.INSTANCE, AllInterfaceLinksLocationSpecifier.INSTANCE) .resolve(specifierContext); return InferFromLocationIpSpaceSpecifier.INSTANCE.resolve(locations, specifierContext); } @Nonnull private BDDReachabilityAnalysisFactory getBddReachabilityAnalysisFactory( NetworkSnapshot snapshot, BDDPacket pkt, boolean ignoreFilters) { Span span = GlobalTracer.get().buildSpan("getBddReachabilityAnalysisFactory").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning DataPlane dataPlane = loadDataPlane(snapshot); return new BDDReachabilityAnalysisFactory( pkt, loadConfigurations(snapshot), dataPlane.getForwardingAnalysis(), new IpsRoutedOutInterfacesFactory(dataPlane.getFibs()), ignoreFilters, false); } finally { span.finish(); } } public BDDReachabilityAnalysis getBddReachabilityAnalysis( NetworkSnapshot snapshot, BDDPacket pkt, IpSpaceAssignment srcIpSpaceAssignment, AclLineMatchExpr initialHeaderSpace, Set<String> forbiddenTransitNodes, Set<String> requiredTransitNodes, Set<String> finalNodes, Set<FlowDisposition> actions, boolean ignoreFilters, boolean useInterfaceRoots) { BDDReachabilityAnalysisFactory factory = getBddReachabilityAnalysisFactory(snapshot, pkt, ignoreFilters); return factory.bddReachabilityAnalysis( srcIpSpaceAssignment, initialHeaderSpace, forbiddenTransitNodes, requiredTransitNodes, finalNodes, actions, useInterfaceRoots); } /** * Return a set of flows (at most 1 per source {@link Location}) for which reachability has been * reduced by the change from base to delta snapshot. */ @Override public DifferentialReachabilityResult bddDifferentialReachability( NetworkSnapshot snapshot, NetworkSnapshot reference, DifferentialReachabilityParameters parameters) { Span span = GlobalTracer.get().buildSpan("bddDifferentialReachability").start(); try (Scope scope = GlobalTracer.get().scopeManager().activate(span)) { assert scope != null; // avoid unused warning checkArgument( !parameters.getFlowDispositions().isEmpty(), "Must specify at least one FlowDisposition"); BDDPacket pkt = new BDDPacket(); AclLineMatchExpr headerSpace = parameters.getInvertSearch() ? not(parameters.getHeaderSpace()) : parameters.getHeaderSpace(); /* * TODO should we have separate parameters for base and delta? * E.g. suppose we add a host subnet in the delta network. This would be a source of * differential reachability, but we currently won't find it because it won't be in the * IpSpaceAssignment. */ Map<IngressLocation, BDD> baseAcceptBDDs = getBddReachabilityAnalysisFactory(snapshot, pkt, parameters.getIgnoreFilters()) .getAllBDDs( parameters.getIpSpaceAssignment(), headerSpace, parameters.getForbiddenTransitNodes(), parameters.getRequiredTransitNodes(), parameters.getFinalNodes(), parameters.getFlowDispositions()); Map<IngressLocation, BDD> deltaAcceptBDDs = getBddReachabilityAnalysisFactory(reference, pkt, parameters.getIgnoreFilters()) .getAllBDDs( parameters.getIpSpaceAssignment(), headerSpace, parameters.getForbiddenTransitNodes(), parameters.getRequiredTransitNodes(), parameters.getFinalNodes(), parameters.getFlowDispositions()); Set<IngressLocation> commonSources = Sets.intersection(baseAcceptBDDs.keySet(), deltaAcceptBDDs.keySet()); Set<Flow> decreasedFlows = getDifferentialFlows(pkt, commonSources, baseAcceptBDDs, deltaAcceptBDDs); Set<Flow> increasedFlows = getDifferentialFlows(pkt, commonSources, deltaAcceptBDDs, baseAcceptBDDs); return new DifferentialReachabilityResult(increasedFlows, decreasedFlows); } finally { span.finish(); } } private static Set<Flow> getDifferentialFlows( BDDPacket pkt, Set<IngressLocation> commonSources, Map<IngressLocation, BDD> includeBDDs, Map<IngressLocation, BDD> excludeBDDs) { return commonSources.stream() .flatMap( source -> { BDD difference = includeBDDs.get(source).diff(excludeBDDs.get(source)); if (difference.isZero()) { return Stream.of(); } Flow.Builder flow = pkt.getFlow(difference) .orElseThrow(() -> new BatfishException("Error getting flow from BDD")); // set flow parameters flow.setIngressNode(source.getNode()); switch (source.getType()) { case VRF: flow.setIngressVrf(source.getVrf()); break; case INTERFACE_LINK: flow.setIngressInterface(source.getInterface()); break; default: throw new BatfishException("Unexpected IngressLocationType: " + source.getType()); } return Stream.of(flow.build()); }) .collect(ImmutableSet.toImmutableSet()); } private void writeJsonAnswer(String structuredAnswerString) throws IOException { SnapshotId referenceSnapshot = _settings.getDiffQuestion() ? _referenceSnapshot : null; NetworkId networkId = _settings.getContainer(); QuestionId questionId = _settings.getQuestionName(); AnalysisId analysisId = _settings.getAnalysisName(); NodeRolesId networkNodeRolesId = _idResolver .getNetworkNodeRolesId(networkId) .orElse(NodeRolesId.DEFAULT_NETWORK_NODE_ROLES_ID); AnswerId baseAnswerId = _idResolver.getAnswerId( networkId, _snapshot, questionId, networkNodeRolesId, referenceSnapshot, analysisId); _storage.storeAnswer(networkId, _snapshot, structuredAnswerString, baseAnswerId); } private void writeJsonAnswerWithLog( String answerOutput, String workJsonLogAnswerString, boolean writeLog) throws IOException { if (writeLog && _settings.getTaskId() != null) { _storage.storeWorkJson( workJsonLogAnswerString, _settings.getContainer(), _settings.getTestrig(), _settings.getTaskId()); } // Write answer if WorkItem was answering a question if (_settings.getQuestionName() != null) { writeJsonAnswer(answerOutput); } } @Override public @Nullable Answerer createAnswerer(@Nonnull Question question) { AnswererCreator creator = _answererCreators.get(question.getName()); return creator != null ? creator.create(question, this) : null; } private static final Logger LOGGER = LogManager.getLogger(Batfish.class); }
package com.intellij.util; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream; import com.intellij.openapi.util.io.FileUtil; import com.intellij.ui.scale.DerivedScaleType; import com.intellij.ui.scale.ScaleContext; import com.intellij.ui.svg.MyTranscoder; import com.intellij.ui.svg.SaxSvgDocumentFactory; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.ui.ImageUtil; import com.intellij.util.ui.JBUI; import org.apache.batik.anim.dom.SVGOMDocument; import org.apache.batik.bridge.BridgeContext; import org.apache.batik.bridge.GVTBuilder; import org.apache.batik.transcoder.TranscoderException; import org.apache.batik.transcoder.TranscoderInput; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.awt.*; import java.awt.geom.Dimension2D; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; /** * @author tav */ public final class SVGLoader { private static final byte[] DEFAULT_THEME = new byte[0]; private static SvgElementColorPatcherProvider ourColorPatcher = null; private static final SVGLoaderCache ourCache = new SVGLoaderCache() { @NotNull @Override protected File getCachesHome() { return new File(PathManager.getSystemPath(), "icons"); } @Override protected void forkIOTask(@NotNull Runnable action) { AppExecutorUtil.getAppExecutorService().execute(action); } }; public static final int ICON_DEFAULT_SIZE = 16; public static Image load(@NotNull URL url, float scale) throws IOException { return load(url, url.openStream(), scale); } public static Image load(@NotNull InputStream stream, float scale) throws IOException { return load(null, stream, scale); } public static Image load(@Nullable URL url, @NotNull InputStream stream, double scale) throws IOException { return load(url, stream, scale, null); } @ApiStatus.Internal public static Image load(@Nullable URL url, @NotNull InputStream stream, double scale, @Nullable ImageLoader.Dimension2DDouble docSize /*OUT*/) throws IOException { byte[] theme = DEFAULT_THEME; byte[] svgBytes = FileUtil.loadBytes(stream); if (ourColorPatcher != null && url != null) { SvgElementColorPatcher subPatcher = ourColorPatcher.forURL(url); if (subPatcher != null) { theme = subPatcher.digest(); } } if (docSize == null) { docSize = new ImageLoader.Dimension2DDouble(0, 0); } BufferedImage image; if (theme != null) { image = ourCache.loadFromCache(theme, svgBytes, scale, docSize); if (image != null) { return image; } } image = loadWithoutCache(url, svgBytes, scale, docSize); if (image != null && theme != null) { ourCache.storeLoadedImage(theme, svgBytes, scale, image, docSize); } return image; } @ApiStatus.Internal public static BufferedImage loadWithoutCache(@Nullable URL url, @NotNull byte[] stream, double scale, @Nullable ImageLoader.Dimension2DDouble docSize /*OUT*/) throws IOException { try { MyTranscoder transcoder = MyTranscoder.createImage(scale, createTranscodeInput(url, new ByteArrayInputStream(stream))); if (docSize != null) { docSize.setSize(transcoder.getOrigDocWidth(), transcoder.getOrigDocHeight()); } return transcoder.getImage(); } catch (TranscoderException ex) { if (docSize != null) { docSize.setSize(0, 0); } throw new IOException(ex); } } /** * Loads an image with the specified {@code width} and {@code height} (in user space). Size specified in svg file is ignored. */ public static Image load(@Nullable URL url, @NotNull InputStream stream, @NotNull ScaleContext ctx, double width, double height) throws IOException { try { double s = ctx.getScale(DerivedScaleType.PIX_SCALE); return MyTranscoder.createImage(1, createTranscodeInput(url, stream), (float)(width * s), (float)(height * s)).getImage(); } catch (TranscoderException ex) { throw new IOException(ex); } } /** * Loads a HiDPI-aware image with the specified {@code width} and {@code height} (in user space). Size specified in svg file is ignored. */ public static <T extends BufferedImage> T loadHiDPI(@Nullable URL url, @NotNull InputStream stream, ScaleContext ctx, double width, double height) throws IOException { BufferedImage image = (BufferedImage)load(url, stream, ctx, width, height); @SuppressWarnings("unchecked") T t = (T)ImageUtil.ensureHiDPI(image, ctx); return t; } /** * Loads a HiDPI-aware image of the size specified in the svg file. */ public static <T extends BufferedImage> T loadHiDPI(@Nullable URL url, @NotNull InputStream stream, ScaleContext ctx) throws IOException { BufferedImage image = (BufferedImage)load(url, stream, ctx.getScale(DerivedScaleType.PIX_SCALE)); @SuppressWarnings("unchecked") T t = (T)ImageUtil.ensureHiDPI(image, ctx); return t; } /** @deprecated Use {@link #loadHiDPI(URL, InputStream, ScaleContext)} */ @Deprecated public static <T extends BufferedImage> T loadHiDPI(@Nullable URL url, @NotNull InputStream stream, JBUI.ScaleContext ctx) throws IOException { return loadHiDPI(url, stream, (ScaleContext)ctx); } public static ImageLoader.Dimension2DDouble getDocumentSize(@Nullable URL url, @NotNull InputStream stream, double scale) throws IOException { // In order to get the size we parse the whole document and build a tree ("GVT"), what might be too expensive. // So, to optimize we extract the svg header (possibly prepended with <?xml> header) and parse only it. // Assumes 8-bit encoding of the input stream (no one in theirs right mind would use wide characters for SVG anyway). BufferExposingByteArrayOutputStream buffer = new BufferExposingByteArrayOutputStream(100); byte[] bytes = new byte[3]; boolean checkClosingBracket = false; int ch; while ((ch = stream.read()) != -1) { buffer.write(ch); if (ch == '<') { int n = stream.read(bytes, 0, 3); if (n == -1) break; buffer.write(bytes, 0, n); checkClosingBracket = n == 3 && bytes[0] == 's' && bytes[1] == 'v' && bytes[2] == 'g'; } else if (checkClosingBracket && ch == '>') { buffer.write(new byte[]{'<', '/', 's', 'v', 'g', '>'}); return getDocumentSize(scale, createTranscodeInput(url, new ByteArrayInputStream(buffer.getInternalBuffer(), 0, buffer.size()))); } } return new ImageLoader.Dimension2DDouble(ICON_DEFAULT_SIZE * scale, ICON_DEFAULT_SIZE * scale); } public static double getMaxZoomFactor(@Nullable URL url, @NotNull InputStream stream, @NotNull ScaleContext ctx) throws IOException { ImageLoader.Dimension2DDouble size = getDocumentSize(ctx.getScale(DerivedScaleType.PIX_SCALE), createTranscodeInput(url, stream)); double iconMaxSize = MyTranscoder.getIconMaxSize(); return Math.min(iconMaxSize / size.getWidth(), iconMaxSize / size.getHeight()); } private SVGLoader() { } @NotNull private static TranscoderInput createTranscodeInput(@Nullable URL url, @NotNull InputStream stream) throws IOException { TranscoderInput myTranscoderInput; String uri = null; try { if (url != null && "jar".equals(url.getProtocol())) { // workaround for BATIK-1217 url = new URL(url.getPath()); } uri = url != null ? url.toURI().toString() : null; } catch (URISyntaxException ignore) { } Document document = new SaxSvgDocumentFactory().createDocument(uri, stream); patchColors(url, document); myTranscoderInput = new TranscoderInput(document); return myTranscoderInput; } private static void patchColors(URL url, Document document) { if (ourColorPatcher != null) { final SvgElementColorPatcher patcher = ourColorPatcher.forURL(url); if (patcher != null) { patcher.patchColors(document.getDocumentElement()); } } } /** * @deprecated use {@link #setColorPatcherProvider(SvgElementColorPatcherProvider)} instead */ @Deprecated public static void setColorPatcher(@Nullable final SvgColorPatcher colorPatcher) { if (colorPatcher == null) { setColorPatcherProvider(null); return; } setColorPatcherProvider(new SvgElementColorPatcherProvider() { @Override public SvgElementColorPatcher forURL(@NotNull final URL url) { return new SvgElementColorPatcher() { @Override public void patchColors(Element svg) { colorPatcher.patchColors(url, svg); } @Nullable @Override public byte[] digest() { return null; } }; } }); } public static void setColorPatcherProvider(@Nullable SvgElementColorPatcherProvider colorPatcher) { ourColorPatcher = colorPatcher; IconLoader.clearCache(); } private static ImageLoader.Dimension2DDouble getDocumentSize(double scale, @NotNull TranscoderInput input) { SVGOMDocument document = (SVGOMDocument)input.getDocument(); BridgeContext ctx = new MyTranscoder(scale).createBridgeContext(document); new GVTBuilder().build(ctx, document); Dimension2D size = ctx.getDocumentSize(); return new ImageLoader.Dimension2DDouble(size.getWidth() * scale, size.getHeight() * scale); } public interface SvgElementColorPatcher { void patchColors(Element svg); /** * @return hash code of the current SVG color patcher or null to disable rendered SVG images caching */ @Nullable byte[] digest(); } public interface SvgElementColorPatcherProvider { @Nullable SvgElementColorPatcher forURL(@NotNull URL url); } /** * @deprecated use {@link SvgElementColorPatcherProvider instead} */ @Deprecated public interface SvgColorPatcher { /** * @deprecated use {@link #patchColors(URL, Element)} */ @Deprecated default void patchColors(@SuppressWarnings("unused") Element svg) {} default void patchColors(URL url, Element svg) { patchColors(svg); } } }
package org.mskcc.portal.servlet; import java.io.IOException; import java.io.PrintWriter; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.Date; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.mskcc.cgds.model.ClinicalData; import org.mskcc.portal.model.*; import org.mskcc.portal.oncoPrintSpecLanguage.OncoPrintLangException; import org.mskcc.portal.oncoPrintSpecLanguage.ParserOutput; import org.mskcc.portal.remote.*; import org.mskcc.portal.util.*; import org.mskcc.portal.r_bridge.SurvivalPlot; import org.mskcc.cgds.model.CancerStudy; import org.mskcc.cgds.model.CaseList; import org.mskcc.cgds.model.GeneticProfile; import org.mskcc.cgds.model.GeneticAlterationType; import org.mskcc.cgds.model.ExtendedMutation; import org.mskcc.cgds.dao.DaoException; import org.mskcc.cgds.util.AccessControl; import org.mskcc.cgds.web_api.ProtocolException; import org.mskcc.cgds.web_api.GetProfileData; import org.owasp.validator.html.PolicyException; /** * Central Servlet for building queries. */ public class QueryBuilder extends HttpServlet { public static final boolean INCLUDE_NETWORKS = true; public static final String CGDS_URL_PARAM = "cgds_url"; public static final String PATHWAY_COMMONS_URL_PARAM = "pathway_commons_url"; public static final String CANCER_TYPES_INTERNAL = "cancer_types"; public static final String PROFILE_LIST_INTERNAL = "profile_list"; public static final String CASE_SETS_INTERNAL = "case_sets"; public static final String CANCER_STUDY_ID = "cancer_study_id"; public static final String CLINICAL_DATA_LIST = "clinical_data_list"; public static final String GENETIC_PROFILE_IDS = "genetic_profile_ids"; public static final String GENE_SET_CHOICE = "gene_set_choice"; public static final String CASE_SET_ID = "case_set_id"; public static final String CASE_IDS = "case_ids"; public static final String GENE_LIST = "gene_list"; public static final String ACTION = "action"; public static final String OUTPUT = "output"; public static final String FORMAT = "format"; public static final String PLOT_TYPE = "plot_type"; public static final String OS_SURVIVAL_PLOT = "os_survival_plot"; public static final String DFS_SURVIVAL_PLOT = "dfs_survival_plot"; public static final String XDEBUG = "xdebug"; public static final String ACTION_SUBMIT = "Submit"; public static final String STEP2_ERROR_MSG = "step2_error_msg"; public static final String STEP3_ERROR_MSG = "step3_error_msg"; public static final String STEP4_ERROR_MSG = "step4_error_msg"; public static final String MERGED_PROFILE_DATA_INTERNAL = "merged_profile_data"; public static final String PROFILE_DATA_SUMMARY = "profile_data_summary"; public static final String WARNING_UNION = "warning_union"; public static final String DOWNLOAD_LINKS = "download_links"; public static final String NETWORK = "network"; public static final String HTML_TITLE = "html_title"; public static final String TAB_INDEX = "tab_index"; public static final String TAB_DOWNLOAD = "tab_download"; public static final String TAB_VISUALIZE = "tab_visualize"; public static final String USER_ERROR_MESSAGE = "user_error_message"; public static final String ATTRIBUTE_URL_BEFORE_FORWARDING = "ATTRIBUTE_URL_BEFORE_FORWARDING"; public static final String Z_SCORE_THRESHOLD = "Z_SCORE_THRESHOLD"; public static final String MRNA_PROFILES_SELECTED = "MRNA_PROFILES_SELECTED"; public static final String COMPUTE_LOG_ODDS_RATIO = "COMPUTE_LOG_ODDS_RATIO"; public static final String MUTATION_MAP = "MUTATION_MAP"; public static final int MUTATION_DETAIL_LIMIT = 10; public static final String MUTATION_DETAIL_LIMIT_REACHED = "MUTATION_DETAIL_LIMIT_REACHED"; public static final int MAX_NUM_GENES = 100; public static final String XDEBUG_OBJECT = "xdebug_object"; public static final String ONCO_PRINT_HTML = "oncoprint_html"; public static final String INDEX_PAGE = "index.do"; private ServletXssUtil servletXssUtil; /** * Initializes the servlet. * * @throws ServletException Serlvet Init Error. */ public void init() throws ServletException { super.init(); String cgdsUrl = getInitParameter(CGDS_URL_PARAM); System.out.println ("Init Query Builder with CGDS URL: " + cgdsUrl); GlobalProperties.setCgdsUrl(cgdsUrl); String pathwayCommonsUrl = getInitParameter(PATHWAY_COMMONS_URL_PARAM); System.out.println ("Init Query Builder with PathwayCommons URL: " + pathwayCommonsUrl); GlobalProperties.setPathwayCommonsUrl(pathwayCommonsUrl); try { servletXssUtil = ServletXssUtil.getInstance(); } catch (PolicyException e) { throw new ServletException (e); } } /** * Handles HTTP GET Request. * * @param httpServletRequest Http Servlet Request Object. * @param httpServletResponse Http Servelt Response Object. * @throws ServletException Servlet Error. * @throws IOException IO Error. */ protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { doPost(httpServletRequest, httpServletResponse); } /** * Handles HTTP POST Request. * * @param httpServletRequest Http Servlet Request Object. * @param httpServletResponse Http Servelt Response Object. * @throws ServletException Servlet Error. * @throws IOException IO Error. */ protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { XDebug xdebug = new XDebug( httpServletRequest ); xdebug.startTimer(); xdebug.logMsg(this, "Attempting to initiate new user query."); if (httpServletRequest.getRequestURL() != null) { httpServletRequest.setAttribute(ATTRIBUTE_URL_BEFORE_FORWARDING, httpServletRequest.getRequestURL().toString()); } // Get User Selected Action String action = servletXssUtil.getCleanInput (httpServletRequest, ACTION); // Get User Selected Cancer Type String cancerTypeId = servletXssUtil.getCleanInput(httpServletRequest, CANCER_STUDY_ID); // Get User Selected Genetic Profiles String geneticProfileIds[] = httpServletRequest.getParameterValues(GENETIC_PROFILE_IDS); HashSet<String> geneticProfileIdSet = new HashSet<String>(); if (geneticProfileIds != null && geneticProfileIds.length > 0) { for (String geneticProfileIdDirty : geneticProfileIds) { String geneticProfileIdClean = servletXssUtil.getCleanInput(geneticProfileIdDirty); geneticProfileIdSet.add(geneticProfileIdClean); } } httpServletRequest.setAttribute(GENETIC_PROFILE_IDS, geneticProfileIdSet); // Get User Defined Gene List String geneList = servletXssUtil.getCleanInput (httpServletRequest, GENE_LIST); xdebug.logMsg(this, "Gene List is set to: " + geneList); // Get all Cancer Types try { ArrayList<CancerStudy> cancerStudyList = GetCancerTypes.getCancerStudies(); if (cancerTypeId == null) { cancerTypeId = cancerStudyList.get(0).getCancerStudyStableId(); } httpServletRequest.setAttribute(CANCER_STUDY_ID, cancerTypeId); httpServletRequest.setAttribute(CANCER_TYPES_INTERNAL, cancerStudyList); // Get Genetic Profiles for Selected Cancer Type ArrayList<GeneticProfile> profileList = GetGeneticProfiles.getGeneticProfiles (cancerTypeId); httpServletRequest.setAttribute(PROFILE_LIST_INTERNAL, profileList); // Get Case Sets for Selected Cancer Type xdebug.logMsg(this, "Using Cancer Study ID: " + cancerTypeId); ArrayList<CaseList> caseSets = GetCaseSets.getCaseSets(cancerTypeId); xdebug.logMsg(this, "Total Number of Case Sets: " + caseSets.size()); CaseList caseSet = new CaseList(); caseSet.setName("User-defined Case List"); caseSet.setDescription("User defined case list."); caseSet.setStableId("-1"); caseSets.add(caseSet); httpServletRequest.setAttribute(CASE_SETS_INTERNAL, caseSets); // Get User Selected Case Set String caseSetId = servletXssUtil.getCleanInput(httpServletRequest, CASE_SET_ID); if (caseSetId != null) { httpServletRequest.setAttribute(CASE_SET_ID, caseSetId); } else { if (caseSets.size() > 0) { CaseList zeroSet = caseSets.get(0); httpServletRequest.setAttribute(CASE_SET_ID, zeroSet.getStableId()); } } String caseIds = servletXssUtil.getCleanInput(httpServletRequest, CASE_IDS); httpServletRequest.setAttribute(XDEBUG_OBJECT, xdebug); boolean errorsExist = validateForm(action, profileList, geneticProfileIdSet, geneList, caseSetId, caseIds, httpServletRequest); if (action != null && action.equals(ACTION_SUBMIT) && (!errorsExist)) { processData(geneticProfileIdSet, profileList, geneList, caseSetId, caseIds, caseSets, getServletContext(), httpServletRequest, httpServletResponse, xdebug); } else { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/index.jsp"); dispatcher.forward(httpServletRequest, httpServletResponse); } } catch (RemoteException e) { xdebug.logMsg(this, "Got Remote Exception: " + e.getMessage()); forwardToErrorPage(httpServletRequest, httpServletResponse, "The Cancer Genomics Data Server is not currently " + "available. <br/><br/>Please check back later.", xdebug); } catch (DaoException e) { xdebug.logMsg(this, "Got Database Exception: " + e.getMessage()); forwardToErrorPage(httpServletRequest, httpServletResponse, "The Cancer Genomics Data Server is not currently " + "available. <br/><br/>Please check back later.", xdebug); } } // This method checks the user information sent in the Authorization // header against the database of users maintained in the users Hashtable. protected boolean allowUser(HttpServletRequest request, HttpServletResponse response) throws IOException { String auth = request.getHeader("Authorization"); if (auth == null) { askForPassword (response); return false; } else { String userInfo = auth.substring(6).trim(); // TODO: replace unsupported library sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder(); String nameAndPassword = new String (decoder.decodeBuffer(userInfo)); if (nameAndPassword != null) { int index = nameAndPassword.indexOf(":"); if (index > -1) { String user = nameAndPassword.substring(0, index); String password = nameAndPassword.substring(index+1); // Check our user list to see if that user and password are "allowed" if (user.equals("tcga_user") && password.equals("tcga123")) { return true; } else { askForPassword(response); return false; } } else { askForPassword(response); return false; } } else { askForPassword(response); return false; } } } private void askForPassword (HttpServletResponse response) throws IOException { response.setHeader("WWW-Authenticate", "BASIC realm=\"users\""); response.sendError(response.SC_UNAUTHORIZED); } /** * process a good request * * @param geneticProfileIdSet User Selected Genetic Profiles * @param profileList Genetic Profiles for Selected Cancer Type * @param geneListStr User Defined Gene List, i.e., input in the 'gene symbols / OQL' text box * @param caseSetId * @param caseIds User Selected Case Set * @param caseSetList Case Sets for Selected Cancer Type * @param servletContext * @param request the HTTP Request * @param response the HTTP Response * @param xdebug * * @throws IOException * @throws ServletException */ private void processData(HashSet<String> geneticProfileIdSet, ArrayList<GeneticProfile> profileList, String geneListStr, String caseSetId, String caseIds, ArrayList<CaseList> caseSetList, ServletContext servletContext, HttpServletRequest request, HttpServletResponse response, XDebug xdebug) throws IOException, ServletException, DaoException { // parse geneList, written in the OncoPrintSpec language (except for changes by XSS clean) double zScore = ZScoreUtil.getZScore(geneticProfileIdSet, profileList, request); ParserOutput theOncoPrintSpecParserOutput = OncoPrintSpecificationDriver.callOncoPrintSpecParserDriver( geneListStr, geneticProfileIdSet, profileList, zScore ); ArrayList<String> geneList = new ArrayList<String>(); geneList.addAll( theOncoPrintSpecParserOutput.getTheOncoPrintSpecification().listOfGenes() ); request.setAttribute(GENE_LIST, geneList); xdebug.logMsg(this, "Using gene list geneList.toString(): " + geneList.toString()); if (!caseSetId.equals("-1")) { for (CaseList caseSet : caseSetList) { if (caseSet.getStableId().equals(caseSetId)) { caseIds = caseSet.getCaseListAsString(); //TODO: why not break? } } } request.setAttribute(CASE_IDS, caseIds); Iterator<String> profileIterator = geneticProfileIdSet.iterator(); ArrayList<ProfileData> profileDataList = new ArrayList<ProfileData>(); Set<String> warningUnion = new HashSet<String>(); ArrayList<DownloadLink> downloadLinkSet = new ArrayList<DownloadLink>(); ArrayList<ExtendedMutation> mutationList = new ArrayList<ExtendedMutation>(); while (profileIterator.hasNext()) { String profileId = profileIterator.next(); GeneticProfile profile = GeneticProfileUtil.getProfile(profileId, profileList); if( null == profile ){ continue; } xdebug.logMsg(this, "Getting data for: " + profile.getProfileName()); Date startTime = new Date(); GetProfileData remoteCall = new GetProfileData(profile, geneList, caseIds); ProfileData pData = remoteCall.getProfileData(); Date stopTime = new Date(); long timeElapsed = stopTime.getTime() - startTime.getTime(); xdebug.logMsg(this, "Total Time for Connection to Web API: " + timeElapsed + " ms."); DownloadLink downloadLink = new DownloadLink(profile, geneList, caseIds, remoteCall.getRawContent()); downloadLinkSet.add(downloadLink); warningUnion.addAll(remoteCall.getWarnings()); if( pData == null ){ System.err.println( "pData == null" ); }else{ if( pData.getGeneList() == null ){ System.err.println( "pData.getGeneList() == null" ); } } if (pData != null) { xdebug.logMsg(this, "Got number of genes: " + pData.getGeneList().size()); xdebug.logMsg(this, "Got number of cases: " + pData.getCaseIdList().size()); } xdebug.logMsg(this, "Number of warnings received: " + remoteCall.getWarnings().size()); profileDataList.add(pData); // Optionally, get Extended Mutation Data. if (profile.getGeneticAlterationType().equals (GeneticAlterationType.MUTATION_EXTENDED)) { if (geneList.size() <= MUTATION_DETAIL_LIMIT) { xdebug.logMsg(this, "Number genes requested is <= " + MUTATION_DETAIL_LIMIT); startTime = new Date(); xdebug.logMsg(this, "Therefore, getting extended mutation data"); GetMutationData remoteCallMutation = new GetMutationData(); ArrayList<ExtendedMutation> tempMutationList = remoteCallMutation.getMutationData(profile, geneList, caseIds, xdebug); xdebug.logMsg(this, "Total number of mutation records retrieved: " + tempMutationList.size()); for (ExtendedMutation mutation: tempMutationList) { xdebug.logMsg(this, "Extended Mutation: " + mutation.getGeneSymbol()); } if (tempMutationList != null && tempMutationList.size() > 0) { mutationList.addAll(tempMutationList); } stopTime = new Date(); timeElapsed = stopTime.getTime() - startTime.getTime(); xdebug.logMsg(this, "Total Time for Connection to Web API: " + timeElapsed + " ms."); } else { request.setAttribute(MUTATION_DETAIL_LIMIT_REACHED, Boolean.TRUE); } } } // Store Extended Mutations ExtendedMutationMap mutationMap = new ExtendedMutationMap(mutationList); request.setAttribute(MUTATION_MAP, mutationMap); // Store download links in session (for possible future retrieval). request.getSession().setAttribute(DOWNLOAD_LINKS, downloadLinkSet); String tabIndex = servletXssUtil.getCleanInput(request, QueryBuilder.TAB_INDEX); if (tabIndex != null && tabIndex.equals(QueryBuilder.TAB_VISUALIZE)) { xdebug.logMsg(this, "Merging Profile Data"); ProfileMerger merger = new ProfileMerger(profileDataList); ProfileData mergedProfile = merger.getMergedProfile(); // Get Clinical Data xdebug.logMsg(this, "Getting Clinical Data:"); ArrayList <ClinicalData> clinicalDataList = GetClinicalData.getClinicalData(caseIds, xdebug); xdebug.logMsg(this, "Got Clinical Data for: " + clinicalDataList.size() + " cases."); request.setAttribute(CLINICAL_DATA_LIST, clinicalDataList); xdebug.logMsg(this, "Merged Profile, Number of genes: " + mergedProfile.getGeneList().size()); xdebug.logMsg(this, "Merged Profile, Number of cases: " + mergedProfile.getCaseIdList().size()); request.setAttribute(MERGED_PROFILE_DATA_INTERNAL, mergedProfile); request.setAttribute(WARNING_UNION, warningUnion); String output = servletXssUtil.getCleanInput(request, OUTPUT); String format = servletXssUtil.getCleanInput(request, FORMAT); double zScoreThreshold = ZScoreUtil.getZScore(geneticProfileIdSet, profileList, request); PrintWriter writer = response.getWriter(); if (output != null) { String showAlteredColumns = servletXssUtil.getCleanInput(request, "showAlteredColumns"); boolean showAlteredColumnsBool = false; if( showAlteredColumns != null && showAlteredColumns.equals("true")) { showAlteredColumnsBool = true; } if (output.equalsIgnoreCase("svg")) { response.setContentType("image/svg+xml"); MakeOncoPrint.OncoPrintType theOncoPrintType = MakeOncoPrint.OncoPrintType.SVG; String out = MakeOncoPrint.makeOncoPrint(geneListStr, mergedProfile, caseSetList, caseSetId, zScoreThreshold, theOncoPrintType, showAlteredColumnsBool, geneticProfileIdSet, profileList, true, true); writer.write(out); writer.flush(); writer.close(); } else if (output.equalsIgnoreCase("html")) { response.setContentType("text/html"); writer.write ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n" + "\"http: "<html xmlns=\"http: writer.write ("<head>\n"); writer.write ("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />\n"); writer.write ("<title>OncoPrint::Results</title>\n"); writer.write ("<link href=\"css/global_portal.css\" type=\"text/css\" rel=\"stylesheet\" />\n"); writer.write ("</head>\n"); writer.write ("<body style=\"background-color:#FFFFFF\">\n"); MakeOncoPrint.OncoPrintType theOncoPrintType = MakeOncoPrint.OncoPrintType.HTML; String out = MakeOncoPrint.makeOncoPrint(geneListStr, mergedProfile, caseSetList, caseSetId, zScoreThreshold, theOncoPrintType, showAlteredColumnsBool, geneticProfileIdSet, profileList, true, true); writer.write(out); writer.write ("</body>\n"); writer.write ("</html>\n"); writer.flush(); writer.close(); } else if (output.equals("text")) { response.setContentType("text/plain"); ProfileDataSummary dataSummary = new ProfileDataSummary( mergedProfile, theOncoPrintSpecParserOutput.getTheOncoPrintSpecification(), zScoreThreshold ); writer.write("" + dataSummary.getPercentCasesAffected()); writer.flush(); writer.close(); } else if (output.equals(OS_SURVIVAL_PLOT)) { ProfileDataSummary dataSummary = new ProfileDataSummary( mergedProfile, theOncoPrintSpecParserOutput.getTheOncoPrintSpecification(), zScoreThreshold ); SurvivalPlot survivalPlot = new SurvivalPlot(SurvivalPlot.SurvivalPlotType.OS, clinicalDataList, dataSummary, format, response); } else if (output.equals(DFS_SURVIVAL_PLOT)) { ProfileDataSummary dataSummary = new ProfileDataSummary( mergedProfile, theOncoPrintSpecParserOutput.getTheOncoPrintSpecification(), zScoreThreshold ); SurvivalPlot survivalPlot = new SurvivalPlot(SurvivalPlot.SurvivalPlotType.DFS, clinicalDataList, dataSummary, format, response); } } else { // Store download links in session (for possible future retrieval). request.getSession().setAttribute(DOWNLOAD_LINKS, downloadLinkSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/visualize.jsp"); dispatcher.forward(request, response); } } else { ShowData.showDataAtSpecifiedIndex(servletContext, request, response, 0, xdebug); } } /** * validate the portal web input form. * @param action * @param profileList * @param geneticProfileIdSet * @param geneList the list of genes, possibly annotated with the OncoPrintSpec language * @param caseSetId * @param caseIds * @param httpServletRequest * @return true, if the form contains fatal error(s) that require it be resubmitted */ private boolean validateForm(String action, ArrayList<GeneticProfile> profileList, HashSet<String> geneticProfileIdSet, String geneList, String caseSetId, String caseIds, HttpServletRequest httpServletRequest) { boolean errorsExist = false; String tabIndex = servletXssUtil.getCleanInput(httpServletRequest, QueryBuilder.TAB_INDEX); if (action != null) { if (action.equals(ACTION_SUBMIT)) { if (geneticProfileIdSet.size() == 0) { if (tabIndex == null || tabIndex.equals(QueryBuilder.TAB_DOWNLOAD)) { httpServletRequest.setAttribute(STEP2_ERROR_MSG, "Please select a genetic profile below. "); } else { httpServletRequest.setAttribute(STEP2_ERROR_MSG, "Please select one or more genetic profiles below. "); } errorsExist = true; } if (geneList != null && geneList.trim().length() == 0) { httpServletRequest.setAttribute(STEP4_ERROR_MSG, "Please enter at least one gene symbol below. "); errorsExist = true; } if (caseSetId.equals("-1") && caseIds.trim().length() == 0) { httpServletRequest.setAttribute(STEP3_ERROR_MSG, "Please enter at least one case ID below. "); errorsExist = true; } if (geneList != null && geneList.trim().length() > 0) { String geneSymbols[] = geneList.split("\\s"); int numGenes = 0; for (String gene : geneSymbols) { if (gene.trim().length() > 0) { numGenes++; } } if (numGenes > MAX_NUM_GENES) { httpServletRequest.setAttribute(STEP4_ERROR_MSG, "Please restrict your request to " + MAX_NUM_GENES + " genes or less."); errorsExist = true; } // output any errors generated by the parser ParserOutput theOncoPrintSpecParserOutput = OncoPrintSpecificationDriver.callOncoPrintSpecParserDriver( geneList, geneticProfileIdSet, profileList, ZScoreUtil.getZScore(geneticProfileIdSet, profileList, httpServletRequest ) ); if( 0<theOncoPrintSpecParserOutput.getSyntaxErrors().size() || 0<theOncoPrintSpecParserOutput.getSemanticsErrors().size() ){ StringBuffer sb = new StringBuffer(); for( String e: theOncoPrintSpecParserOutput.getSyntaxErrors() ){ sb.append(e+"<br>"); } for( OncoPrintLangException e: theOncoPrintSpecParserOutput.getSemanticsErrors() ){ sb.append(e.getMessage()+"<br>"); } httpServletRequest.setAttribute(STEP4_ERROR_MSG, sb.toString() ); errorsExist = true; } } // Additional validation rules // If we have selected mRNA Expression Data Check Box, but failed to // select an mRNA profile, this is an error. String mRNAProfileSelected = servletXssUtil.getCleanInput(httpServletRequest, QueryBuilder.MRNA_PROFILES_SELECTED); if (mRNAProfileSelected != null && mRNAProfileSelected.equalsIgnoreCase("on")) { // Make sure that at least one of the mRNA profiles is selected boolean mRNAProfileRadioSelected = false; for (int i = 0; i < profileList.size(); i++) { GeneticProfile geneticProfile = profileList.get(i); if (geneticProfile.getGeneticAlterationType() == GeneticAlterationType.MRNA_EXPRESSION && geneticProfileIdSet.contains(geneticProfile.getStableId())) { mRNAProfileRadioSelected = true; } } if (mRNAProfileRadioSelected == false) { httpServletRequest.setAttribute(STEP2_ERROR_MSG, "Please select an mRNA profile."); errorsExist = true; } } } } if( errorsExist ){ httpServletRequest.setAttribute( GENE_LIST, geneList ); } return errorsExist; } private void forwardToErrorPage(HttpServletRequest request, HttpServletResponse response, String userMessage, XDebug xdebug) throws ServletException, IOException { request.setAttribute("xdebug_object", xdebug); request.setAttribute(USER_ERROR_MESSAGE, userMessage); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/error.jsp"); dispatcher.forward(request, response); } }
/* vim: set et ts=4 sts=4 sw=4 tw=72 : */ package uk.ac.cam.cl.git; import uk.ac.cam.cl.git.api.Commit; import uk.ac.cam.cl.git.api.EmptyDirectoryExpectedException; import uk.ac.cam.cl.git.configuration.ConfigurationLoader; import uk.ac.cam.cl.git.interfaces.*; import org.eclipse.jgit.treewalk.*; import org.eclipse.jgit.revwalk.*; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.LinkedList; import java.io.File; import java.io.IOException; import java.io.ByteArrayOutputStream; import com.fasterxml.jackson.annotation.*; import org.mongojack.Id; import org.mongojack.ObjectId; import uk.ac.cam.cl.dtg.segue.git.*; /** * @author Isaac Dunn &lt;ird28@cam.ac.uk&gt; * @author Kovacsics Robert &lt;rmk35@cam.ac.uk&gt; * @version 0.1 */ public class Repository implements TesterInterface { private final String parent; private final String parent_hidden; private final String repo; private final String host = ConfigurationLoader.getConfig().getRepoHost(); private final String user = ConfigurationLoader.getConfig().getRepoUser(); private final String owner; private final List<String> read_write; private final List<String> read_only; private String _id; String workingCommit; GitDb handle; @JsonIgnore public Repository ( String name , String crsid , List<String> read_write , List<String> read_only ) { this.parent = null; this.parent_hidden = null; this.repo = name; this.read_write = read_write; this.read_only = read_only; owner = crsid; } @JsonIgnore public Repository ( String name , String crsid , List<String> read_write , List<String> read_only , String parent , String parent_hidden ) { this.parent = parent; this.parent_hidden = parent_hidden; this.repo = name; this.read_write = read_write; this.read_only = read_only; owner = crsid; } @JsonCreator Repository ( @JsonProperty("name") String name , @JsonProperty("owner") String crsid , @JsonProperty("rw") List<String> read_write , @JsonProperty("r") List<String> read_only , @JsonProperty("parent") String parent , @JsonProperty("parent_hidden") String parent_hidden , @JsonProperty("_id") String id ) { this.parent = parent; this.parent_hidden = parent_hidden; this.repo = name; this.read_write = read_write; this.read_only = read_only; owner = crsid; } public void addReadOnlyUser(String user) { read_only.add(user); } /** * Clones repository to specified directory, if it can get * repository access. * <p> * It tries to access the repository with the id_rsa key. * * @param directory The empty directory to which you want to clone * into. * * @throws EmptyDirectoryExpectedException The File given is either * not a directory or not empty. * @throws IOException Something went wrong (typically not * recoverable). */ @JsonIgnore public void cloneTo(File directory) throws EmptyDirectoryExpectedException, IOException { if (directory.listFiles() == null || directory.listFiles().length != 0) throw new EmptyDirectoryExpectedException(); handle = new GitDb( /* src */ getRepoPath() ,/* dest */ directory ,/* bare */ false ,/* branch */ "master" ,/* remote */ "origin" ,/* privateKeyPath */ ConfigurationLoader.getConfig() .getSshPrivateKeyFile()); if (workingCommit == null) workingCommit = handle.getHeadSha(); } /** * Clones parent repository's contents. Use only once, on the * initialisation of the repository. * * @throws IOException Something went wrong during cloning, perhaps * the directory was not empty? */ public void cloneParent() throws IOException { GitDb tmp = new GitDb(ConfigurationLoader.getConfig() .getGitoliteHome() + "/repositories/" + parent + ".git"); /* Now parent is cloned at tmpDir, push back to child */ if (tmp.listCommits() == null) { try { tmp.pushTo(ConfigurationLoader.getConfig() .getGitoliteHome() + "/repositories/" + repo + ".git"); } catch (PushFailedException e) { throw new IOException( "Failed to push parent repo onto child. " + "You will get an empty repository.\n", e); } } } /** * Opens a local repository. * * @param repoName The name of the repository to open. * @throws IOException Something went wrong (typically not * recoverable). */ public void openLocal(String repoName) throws IOException { System.out.println("Opening : " + ConfigurationLoader.getConfig() .getGitoliteHome() + "/repositories/" + repoName + ".git"); handle = new GitDb(ConfigurationLoader.getConfig() .getGitoliteHome() + "/repositories/" + repoName + ".git"); if (workingCommit == null) workingCommit = handle.getHeadSha(); } /** * Opens a local repository with the given commit. * * @param repoName The name of the repository to open. * @param commitID Identification for a commit. * @throws IOException Something went wrong (typically not * recoverable). */ public void openLocal(String repoName, String commitID) throws IOException { System.out.println("Opening : " + ConfigurationLoader.getConfig() .getGitoliteHome() + "/repositories/" + repoName + ".git"); handle = new GitDb(ConfigurationLoader.getConfig() .getGitoliteHome() + "/repositories/" + repoName + ".git"); workingCommit = commitID; } /** * List the commits in the repository. */ public List<Commit> listCommits() { List<Commit> rtn = new LinkedList<Commit>(); for (RevCommit commit : handle.listCommits()) { rtn.add(new Commit (commit.getName() , commit.getAuthorIdent().getName() , commit.getFullMessage() , new Date(commit.getCommitTime()) )); } return rtn; } /** * Resolves a commit reference such as HEAD or a branch name such as * master to a SHA. * * @param name The name to resolve. * @return The SHA of the latest matching commit. */ public String resolveCommit(String name) { return handle.getSha(name); } /* Test team stores test results now. This is a placeholder to say * why code was removed. */ /** * Returns a list of the source files in the repository. * <p> * Repository must first be cloned using cloneTo! * * @return The list of source files */ @JsonIgnore public Collection<String> getSources() throws IOException { List<String> rtn = new LinkedList<String>(); if (handle == null) throw new NullPointerException("Repository unset. Did you clone it?"); if (workingCommit == null) /* Only way above is true if we have an empty repository, as * everything that sets handle also sets workingCommit (to * null, if we have an empty repository). */ return null; TreeWalk tw = handle.getTreeWalk(workingCommit); while (tw.next()) rtn.add(tw.getPathString()); return rtn; } /** * Returns a list of the source files in the repository, filtered * according to filter. * <p> * Repository must first be cloned using cloneTo! * * @param filter Filter files according to this * @return The list of source files * * @throws IOException Something went wrong (typically not * recoverable). */ @JsonIgnore public Collection<String> getSources(String filter) throws IOException { List<String> rtn = new LinkedList<String>(); if (handle == null) throw new NullPointerException("Repository unset. Did you clone it?"); if (workingCommit == null) /* Only way above is true if we have an empty repository, as * everything that sets handle also sets workingCommit (to * null, if we have an empty repository). */ return null; TreeWalk tw = handle.getTreeWalk(workingCommit, filter); while (tw.next()) rtn.add(tw.getPathString()); return rtn; } /** * Outputs the content of the file. * * @param filePath Full path of the file * @return Contents of the file asked for or null if file is not * found. */ @JsonIgnore public String getFile(String filePath) throws IOException { if (handle == null) throw new NullPointerException("Repository unset. Did you clone it?"); if (workingCommit == null) /* Only way above is true if we have an empty repository, as * everything that sets handle also sets workingCommit (to * null, if we have an empty repository). */ return null; ByteArrayOutputStream rtn = handle.getFileByCommitSHA(workingCommit, filePath); if (rtn == null) return null; return rtn.toString(); } /** * Gets the CRSID of the repository owner * * @return CRSID of the repository owner */ @JsonProperty("owner") public String getCRSID() { return owner; } /** * Gets the name of the repository * * @return Name of the repository */ @JsonProperty("name") public String getName() { return this.repo; } /** * Gets the read &amp; write capable users or groups, for * serialization. * * @return Read &amp; write capable users or groups. */ @JsonProperty("rw") public List<String> getReadWrite() { return this.read_write; } /** * Gets the read only capable users or groups, for serialization. * * @return Read only capable users or groups. */ @JsonProperty("r") public List<String> getReadOnly() { return this.read_only; } /** * Gets the parent of this repository, or null if this repository * has no parent. * * @return Parent or null */ @JsonProperty("parent") public String parent() { return this.parent; } /** * For storing this in MongoDB * * @return ID of this object in MongoDB */ @Id @ObjectId protected String get_id() { return this._id; } /** * For storing this in MongoDB * * @param id Object ID to set */ @Id @ObjectId protected void set_id(String id) { _id = id; } /** * Gets the hidden parent of this repository, or null if this * repository has no hidden parent. * * @return Hidden parent or null */ @JsonProperty("parent_hidden") public String parent_hidden() { return this.parent_hidden; } /** * Gives the string representation of the repository, to be used in * conjuction with Gitolite. * * Please do not change this method without appropriately updating * rebuildDatabaseFromGitolite in ConfigDatabase! * * @return Gitolite config compatible string representation of the * repository */ @Override @JsonIgnore public String toString() { StringBuilder strb = new StringBuilder("repo "); strb.append(repo); strb.append("\n"); strb.append(" RW ="); strb.append(" " + owner); /* Usernames or groups */ if (read_write != null) for ( String name : read_write) strb.append(" " + name); strb.append("\n"); if (read_only != null && read_only.size() > 0) { strb.append(" R ="); /* Usernames or groups */ for ( String name : read_only) strb.append(" " + name); strb.append("\n"); } strb.append("# "); // To allow the rebuilding of the database strb.append(parent + " "); // from the gitolite config file strb.append(parent_hidden + "\n"); return strb.toString(); } /** * Gets the parent repository path as an SSH URI. * * @return Parent repository path as an SSH URI. */ @JsonIgnore public String getParentRepoPath() { return "ssh://" + user + "@" + host + "/" + parent + ".git"; } /** * Gets the repository path as an SSH URI. * * @return Repository path as an SSH URI. */ @JsonIgnore public String getRepoPath() { return "ssh://" + user + "@" + host + "/" + repo + ".git"; } /** * Checks if this repository exists on disk. * * @return True if repository exists. */ @JsonIgnore public boolean repoExists() { return new File(ConfigurationLoader.getConfig() .getGitoliteHome() + "/repositories/" + repo + ".git").exists(); } }
package foam.core; public class ContextAgentRunnable implements Runnable { final X x_; final ContextAgent agent_; final String description_; public ContextAgentRunnable(X x, ContextAgent agent, String description) { x_ = x; agent_ = agent; description_ = description; } public String toString() { return description_; } public void run() { agent_.execute(x_); } }
package foam.mlang; import foam.core.X; import static foam.core.ContextAware.maybeContextualize; public class ContextualizingExpr extends ProxyExpr { private final X x_; public ContextualizingExpr(X x, Expr delegate) { super(delegate); x_ = x; } public X getX() { return x_; } @Override public Object f(Object obj) { return maybeContextualize(getX(), super.f(obj)); } }
package foam.util.Emails; import foam.core.X; import foam.dao.DAO; import foam.nanos.app.AppConfig; import foam.nanos.auth.Subject; import foam.nanos.auth.User; import foam.nanos.logger.Logger; import foam.nanos.notification.email.EmailMessage; import foam.nanos.notification.email.EmailPropertyService; import foam.nanos.theme.Theme; import foam.nanos.theme.Themes; import foam.util.SafetyUtil; import java.util.HashMap; import java.util.Map; public class EmailsUtility { /* documentation: Purpose of this function/service is to facilitate the population of an email properties and then to actually send the email. STEP 1) EXIT CASES && VARIABLE SET UP STEP 2) SERVICE CALL: to fill in email properties. STEP 3) SERVICE CALL: passing emailMessage through to actual email service. Note: For email service to work correctly: parameters should be as follows: @param x: Is necessary @param user: Is only necessary to find the right template associated to the group of the user. If null default is * group. @param emailMessage: The obj that gets filled with all the properties that have been passed. eventually becoming the email that is transported out. @param templateName: The template name that is used for this email. It is found and applied based on user.group @param templateArgs: The arguments that are used to fill the template model body. */ public static void sendEmailFromTemplate(X x, User user, EmailMessage emailMessage, String templateName, Map templateArgs) { // EXIT CASES && VARIABLE SET UP if ( x == null ) return; Logger logger = (Logger) x.get("logger"); if ( emailMessage == null ) { if ( SafetyUtil.isEmpty(templateName) ) { logger.error("@EmailsUtility: no email message available to be sent"); return; } emailMessage = new EmailMessage(); } String group = user != null ? user.getGroup() : ""; AppConfig appConfig = (AppConfig) x.get("appConfig"); Theme theme = (Theme) x.get("theme"); if ( theme == null ) { Subject subject = new Subject.Builder(x).setUser(user).build(); theme = ((Themes) x.get("themes")).findTheme(x.put("subject", subject)); appConfig = theme.getAppConfig(); } // Add template name to templateArgs, to avoid extra parameter passing if ( ! SafetyUtil.isEmpty(templateName) ) { if ( templateArgs != null ) { templateArgs.put("template", templateName); } else { templateArgs = new HashMap<>(); templateArgs.put("template", templateName); } templateArgs.put("supportPhone", (theme.getSupportPhone())); templateArgs.put("supportEmail", (theme.getSupportEmail())); // personal support user User psUser = theme.findPersonalSupportUser(x); templateArgs.put("personalSupportPhone", psUser == null ? "" : psUser.getPhoneNumber()); templateArgs.put("personalSupportEmail", psUser == null ? "" : psUser.getEmail()); templateArgs.put("personalSupportFirstName", psUser == null ? "" : psUser.getFirstName()); templateArgs.put("personalSupportFullName", psUser == null ? "" : psUser.getLegalName()); foam.nanos.auth.Address address = theme.getSupportAddress(); templateArgs.put("supportAddress", address == null ? "" : address.toSummary()); templateArgs.put("appName", (theme.getAppName())); templateArgs.put("logo", (appConfig.getUrl() + "/" + theme.getLogo())); templateArgs.put("appLink", (appConfig.getUrl())); emailMessage.setTemplateArguments(templateArgs); } // SERVICE CALL: to fill in email properties. EmailPropertyService cts = (EmailPropertyService) x.get("emailPropertyService"); try { cts.apply(x, group, emailMessage, templateArgs); } catch (Exception e) { logger.error(e); return; } // SERVICE CALL: passing emailMessage through to actual email service. DAO email = (DAO) x.get("localEmailMessageDAO"); emailMessage.setStatus(foam.nanos.notification.email.Status.UNSENT); email.put(emailMessage); } }
package tpe.fruh_razzaq_jando.pue1; import java.math.*; /** * Diese Klasse implementiert einen Bruch * * @author TPE_UIB_01 */ public class Bruch { // Properties private long nenner, zaehler, ganze; // Constructors Bruch(long zaehler, long nenner) { if (nenner == 0) throw new RuntimeException( "Bruch(zaehler, nenner) - nenner darf nicht 0 sein!"); else { this.zaehler = zaehler; this.nenner = nenner; kuerze(); } } Bruch(long zaehler, long nenner, long ganze) { if (nenner == 0) throw new RuntimeException( "Bruch(zaehler, nenner, ganze) - nenner darf nicht 0 sein!"); else { this.zaehler = zaehler; this.nenner = nenner; this.ganze = ganze; kuerze(); } } // Accessors public long getNenner() { return nenner; } public void setNenner(long nenner) { this.nenner = nenner; } public long getZaehler() { return zaehler; } public void setZaehler(long zaehler) { this.zaehler = zaehler; } public long getGanze() { return ganze; } public void setGanze(long ganze) { this.ganze = ganze; } // Methods public void unechterBruch() { if (this.ganze != 0) { this.zaehler = (this.ganze * this.nenner) + this.zaehler; this.ganze = 0; } } public void echterBruch() { while (this.zaehler > this.nenner) { this.ganze++; this.zaehler -= this.nenner; } } public double getDezimalzahl() { return ganze + ((double) zaehler / (double) nenner); } private void kuerze() { long ggt = getGGT(Math.min(zaehler, nenner)); this.zaehler = this.zaehler / ggt; this.nenner = this.nenner / ggt; } private long getGGT(long aktuelleZahl) { if (zaehler % aktuelleZahl == 0 && nenner % aktuelleZahl == 0) return aktuelleZahl; else return getGGT(aktuelleZahl - 1); } @Override public String toString() { if (ganze == 0) return zaehler + "/" + nenner; else if (zaehler == 0 && nenner == 0) return ganze + ""; else return ganze + " " + zaehler + "/" + nenner; } }
package edu.rpi.phil.legup.newgui; import java.awt.FlowLayout; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JToggleButton; import javax.swing.JOptionPane; import edu.rpi.phil.legup.BoardState; import edu.rpi.phil.legup.CaseRule; import edu.rpi.phil.legup.Legup; import edu.rpi.phil.legup.Selection; import javax.swing.*; import java.awt.*; import javax.swing.TransferHandler; import java.awt.datatransfer.*; import java.awt.event.*; import javax.swing.ImageIcon; import javax.swing.JToggleButton; /** * Provides a user interface for users to provide case rule justifications * */ public class CasePanel extends JustificationPanel { private static final long serialVersionUID = -2304281047341398965L; protected final ImageIcon icon = new ImageIcon("images/Case Rules.gif"); protected final String name = "Case Rules"; protected final String toolTip = "Case Rules"; //MouseListener listener = new DragMouseAdapter(); private Vector<CaseRule> caseRules = null; private CaseRule defaultApplication; //NEEDED! Not yet reimplmented! /** * Create a new CasePanel */ CasePanel(JustificationFrame jf) { this.parentFrame = jf; setLayout(new WrapLayout()); } /** * set the case rules displayed by this case rule panel * @param caseRules the vector of CaseRules */ public void setCaseRules(Vector<CaseRule> caseRules) { this.caseRules = caseRules; clearButtons(); buttons = new JToggleButton[caseRules.size()]; for (int x = 0; x < caseRules.size(); ++x) { CaseRule c = caseRules.get(x); buttons[x] = new JToggleButton(c.getImageIcon()); this.parentFrame.getButtonGroup().add(buttons[x]); buttons[x].setToolTipText(c.getName() + ": " + c.getDescription()); buttons[x].addActionListener(this); //removed due to drag-drop being de-prioritized //buttons[x].addMouseListener(listener); //buttons[x].setTransferHandler(new TransferHandler("icon")); add(buttons[x]); } revalidate(); } /** * Check if the given case Rule can be applied to current board state * @param c the case rule to be applied */ private void checkCaseRule(CaseRule c) { Selection sel = Legup.getInstance().getSelections().getFirstSelection(); if (sel.isTransition()) { BoardState state = sel.getState(); state.setCaseSplitJustification(c); String error = c.checkCaseRule(state); JustificationFrame.justificationApplied(state, c); parentFrame.resetJustificationButtons(); if (error == null && LEGUP_Gui.profFlag(LEGUP_Gui.IMD_FEEDBACK)) parentFrame.setStatus(true,"The case rule is applied correctly!"); else if (LEGUP_Gui.profFlag(LEGUP_Gui.IMD_FEEDBACK)) parentFrame.setStatus(false, error); } else { parentFrame.resetJustificationButtons(); parentFrame.setStatus(false, "Case Rules can only be applied to transitions, not states."); sel.getState().setJustification(null); } //parent.rep } /** * Depresses the current rule button for user display * @param c Rule to be pressed * @return Whether or not the rule exists */ public boolean setCaseRule(CaseRule c) { for (int x = 0; x < caseRules.size(); ++x) { if (caseRules.get(x).equals(c)) { buttons[x].setSelected(true); checkCaseRule(c); return true; } } return false; } @Override protected void addJustification(int button) { Selection selection = Legup.getInstance().getSelections().getFirstSelection(); BoardState cur = selection.getState(); if (cur.isModifiable() || cur.getTransitionsFrom().size() > 0) return; if (cur.getCaseRuleJustification() != null) return; CaseRule r = caseRules.get(button); int quantityofcases = Integer.valueOf(JOptionPane.showInputDialog(null,"How many branches?")).intValue(); /*if(quantityofcases > 10)quantityofcases = 10;*/ //some sanity checks on the input, to prevent if(quantityofcases < 2)quantityofcases = 2; //the user from creating 100 nodes or something for (int i = 0; i < quantityofcases; i++) { cur.addTransitionFrom(null); } cur.setCaseSplitJustification(caseRules.get(button)); Legup.getInstance().getSelections().setSelection(new Selection(cur.getTransitionsFrom().get(0), false)); } @Override protected void checkJustification(int button) { checkCaseRule(caseRules.get(button)); } @Override protected void doDefaultApplication(int index, BoardState state) { //We set the current default application so we know which to apply for later CaseRule r = caseRules.get(index); boolean legal = r.startDefaultApplication(state); if (!legal) parentFrame.setStatus(false, "There is not legal default application that can be applied."); else { parentFrame.setStatus(true, r.getApplicationText()); Legup.getInstance().getPuzzleModule().defaultApplication = r; this.defaultApplication = r; } } }
package fr.mikrosimage.gwt.client; import static com.google.gwt.dom.client.Style.Unit.PX; import com.google.gwt.cell.client.AbstractCell; import com.google.gwt.cell.client.Cell.Context; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.dom.client.Style; import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.dom.client.Style.Position; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.cellview.client.AbstractCellTable; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.cellview.client.Header; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Event.NativePreviewEvent; import com.google.gwt.user.client.Event.NativePreviewHandler; public abstract class ResizableHeader<T> extends Header<String> { //TODO Have following strings localized from separate properties file private static final String MOVE = "Move"; private static final String RESIZE = "Resize"; private static final String MOVE_tt = "Click and drag to move column"; private static final String RESIZE_tt = "Click and drag to resize column"; private static final Style.Cursor moveCursor = Cursor.MOVE; private static final Style.Cursor resizeCursor = Cursor.COL_RESIZE; private static final String RESIZE_COLOR = "#A49AED"; private static final String MOVE_COLOR = "gray"; private static final String FOREGROUND_COLOR = "white"; private static final double GHOST_OPACITY = .3; private static final int MINIMUM_COLUMN_WIDTH = 30; private final String title; private final Document document = Document.get(); private final AbstractCellTable<T> table; private final Element tableElement; protected final Column<T, ?> column; public ResizableHeader(String title, AbstractCellTable<T> table, Column<T, ?> column) { super(new HeaderCell()); if (title == null || table == null || column == null) throw new NullPointerException(); this.title = title; this.column = column; this.table = table; this.tableElement = table.getElement(); } @Override public String getValue() { return title; } @Override public void onBrowserEvent(Context context, Element target, NativeEvent event) { new HeaderHelper(target, event); } private static void setCursor(Element element, Cursor cursor) { element.getStyle().setCursor(cursor); } interface IDragCallback { void dragFinished(); } private static final int RESIZE_HANDLE_WIDTH = 34; private static NativeEvent getEventAndPreventPropagation(NativePreviewEvent event) { final NativeEvent nativeEvent = event.getNativeEvent(); nativeEvent.preventDefault(); nativeEvent.stopPropagation(); return nativeEvent; } private static void setLine(Style style, int width, int top, int height, String color) { style.setPosition(Position.ABSOLUTE); style.setTop(top, PX); style.setHeight(height, PX); style.setWidth(width, PX); style.setBackgroundColor(color); style.setZIndex(1000); } private class HeaderHelper implements NativePreviewHandler, IDragCallback { private final HandlerRegistration handler = Event.addNativePreviewHandler(this); final Element mover, left, right; private boolean dragging; private final Element source; public HeaderHelper(Element target, NativeEvent event) { this.source = target; event.preventDefault(); event.stopPropagation(); mover = document.createDivElement(); left = document.createSpanElement(); left.setInnerText(MOVE); left.setAttribute("title", MOVE_tt); mover.appendChild(left); final Style lStyle = left.getStyle(); setCursor(left, moveCursor); lStyle.setPosition(Position.ABSOLUTE); lStyle.setTop(0, PX); lStyle.setBottom(0, PX); lStyle.setZIndex(1000); lStyle.setHeight(target.getOffsetHeight(), PX); lStyle.setTop(target.getOffsetTop(), PX); lStyle.setBackgroundColor(MOVE_COLOR); lStyle.setColor(FOREGROUND_COLOR); lStyle.setLeft(target.getOffsetLeft() + target.getOffsetWidth() - 2*RESIZE_HANDLE_WIDTH, PX); lStyle.setWidth(RESIZE_HANDLE_WIDTH, PX); right = document.createSpanElement(); right.setInnerText(RESIZE); right.setAttribute("title", RESIZE_tt); mover.appendChild(right); final Style rStyle = right.getStyle(); setCursor(right, resizeCursor); rStyle.setPosition(Position.ABSOLUTE); rStyle.setTop(0, PX); rStyle.setBottom(0, PX); rStyle.setZIndex(1000); rStyle.setHeight(target.getOffsetHeight(), PX); rStyle.setTop(target.getOffsetTop(), PX); rStyle.setBackgroundColor(RESIZE_COLOR); rStyle.setColor(FOREGROUND_COLOR); rStyle.setLeft(target.getOffsetLeft() + target.getOffsetWidth() - RESIZE_HANDLE_WIDTH, PX); rStyle.setWidth(RESIZE_HANDLE_WIDTH, PX); target.appendChild(mover); } @Override public void onPreviewNativeEvent(NativePreviewEvent event) { NativeEvent natEvent = event.getNativeEvent(); final Element element = natEvent.getEventTarget().cast(); final String eventType = natEvent.getType(); if (!(element == left || element == right)) { if ("mousedown".equals(eventType)) { //No need to do anything, the event will be passed on to the column sort handler }else if (!dragging && "mouseover".equals(eventType)) { finish(); } return; } final NativeEvent nativeEvent = getEventAndPreventPropagation(event); if ("mousedown".equals(eventType)) { if (element == right) { left.removeFromParent(); new ColumnResizeHelper(this, source, right, nativeEvent); } else new ColumnMoverHelper(this, source, nativeEvent); dragging = true; } } private void finish() { handler.removeHandler(); mover.removeFromParent(); } public void dragFinished() { dragging = false; finish(); } } private class ColumnResizeHelper implements NativePreviewHandler { private final HandlerRegistration handler = Event.addNativePreviewHandler(this); private final DivElement resizeLine = document.createDivElement(); private final Style resizeLineStyle = resizeLine.getStyle(); private final Element header; private final IDragCallback dragCallback; private final Element caret; private ColumnResizeHelper(IDragCallback dragCallback, Element header, Element caret, NativeEvent event) { this.dragCallback = dragCallback; this.header = header; this.caret = caret; setLine(resizeLineStyle, 2, header.getAbsoluteTop() + header.getOffsetHeight(), getTableBodyHeight(), RESIZE_COLOR); moveLine(event.getClientX()); tableElement.appendChild(resizeLine); } @Override public void onPreviewNativeEvent(NativePreviewEvent event) { final NativeEvent nativeEvent = getEventAndPreventPropagation(event); final int clientX = nativeEvent.getClientX(); final String eventType = nativeEvent.getType(); if ("mousemove".equals(eventType)) { moveLine(clientX); } else if ("mouseup".equals(eventType)) { handler.removeHandler(); resizeLine.removeFromParent(); dragCallback.dragFinished(); columnResized(Math.max(clientX - header.getAbsoluteLeft(), MINIMUM_COLUMN_WIDTH)); } } private void moveLine(final int clientX) { final int xPos = clientX - table.getAbsoluteLeft(); caret.getStyle().setLeft(xPos - caret.getOffsetWidth() / 2, PX); resizeLineStyle.setLeft(xPos, PX); resizeLineStyle.setTop(header.getOffsetHeight(), PX); } } private class ColumnMoverHelper implements NativePreviewHandler { private static final int ghostLineWidth = 4; private final HandlerRegistration handler = Event.addNativePreviewHandler(this); private final DivElement ghostLine = document.createDivElement(); private final Style ghostLineStyle = ghostLine.getStyle(); private final DivElement ghostColumn = document.createDivElement(); private final Style ghostColumnStyle = ghostColumn.getStyle(); private final int columnWidth; private final int[] columnXPositions; private final IDragCallback dragCallback; private int fromIndex = -1; private int toIndex; private ColumnMoverHelper(IDragCallback dragCallback, Element target, NativeEvent event) { this.dragCallback = dragCallback; final int clientX = event.getClientX(); columnWidth = target.getOffsetWidth(); final Element tr = target.getParentElement(); final int columns = tr.getChildCount(); columnXPositions = new int[columns + 1]; columnXPositions[0] = tr.getAbsoluteLeft(); for (int i = 0; i < columns; ++i) { final int xPos = columnXPositions[i] + ((Element) tr.getChild(i)).getOffsetWidth(); if (xPos > clientX && fromIndex == -1) fromIndex = i; columnXPositions[i + 1] = xPos; } toIndex = fromIndex; final int top = target.getOffsetHeight(); final int bodyHeight = getTableBodyHeight(); setLine(ghostColumnStyle, columnWidth, top, bodyHeight, MOVE_COLOR); setLine(ghostLineStyle, ghostLineWidth, top, bodyHeight, RESIZE_COLOR); ghostColumnStyle.setOpacity(GHOST_OPACITY); moveColumn(clientX); tableElement.appendChild(ghostColumn); tableElement.appendChild(ghostLine); } @Override public void onPreviewNativeEvent(NativePreviewEvent event) { final NativeEvent nativeEvent = getEventAndPreventPropagation(event); final String eventType = nativeEvent.getType(); if ("mousemove".equals(eventType)) { moveColumn(nativeEvent.getClientX()); } else if ("mouseup".equals(eventType)) { handler.removeHandler(); ghostColumn.removeFromParent(); ghostLine.removeFromParent(); if (fromIndex != toIndex) columnMoved(fromIndex, toIndex); dragCallback.dragFinished(); } } private void moveColumn(final int clientX) { final int pointer = clientX - columnWidth / 2; ghostColumnStyle.setLeft(pointer - table.getAbsoluteLeft(), PX); for (int i = 0; i < columnXPositions.length - 1; ++i) { if (clientX < columnXPositions[i + 1]) { final int adjustedIndex = i > fromIndex ? i + 1 : i; int lineXPos = columnXPositions[adjustedIndex] - table.getAbsoluteLeft(); if (adjustedIndex == columnXPositions.length - 1) //last columns lineXPos -= ghostLineWidth; else if (adjustedIndex > 0) lineXPos -= ghostLineWidth / 2; ghostLineStyle.setLeft(lineXPos, PX); toIndex = i; break; } } } } private static class HeaderCell extends AbstractCell<String> { public HeaderCell() { super("mousemove"); } @Override public void render(Context context, String value, SafeHtmlBuilder sb) { sb.append(SafeHtmlUtils.fromString(value)); } } protected void columnResized(int newWidth) { table.setColumnWidth(column, newWidth + "px"); } protected void columnMoved(int fromIndex, int toIndex) { table.removeColumn(fromIndex); table.insertColumn(toIndex, column, this); } protected abstract int getTableBodyHeight(); };
package systeme; import compte.*; import java.util.LinkedHashSet; import java.util.Set; public class Systeme { public static final String ADRESSE_CORRECTE = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-z]{2,6}$"; private Set<Compte> comptes; private String domaine; public Systeme(String domaine, String passwordRoot) throws Exception { comptes = new LinkedHashSet<Compte>(); this.domaine = domaine; comptes.add(new SuperUtilisateur("root", "root@"+domaine, passwordRoot)); } public Utilisateur connexion(String adresse, String password) { Compte c = obtenirCompte(adresse); if (c != null && c instanceof Utilisateur) { Utilisateur u = (Utilisateur) c; if (password.equals(u.getPassword())) { if (c instanceof SuperUtilisateur) return (SuperUtilisateur) u; else return u; } } return null; } public Compte obtenirCompte(String adresse) { for (Compte c : comptes) { if (c.getAdresse().equals(adresse)) return c; } return null; } public boolean ajouterUtilisateur(Utilisateur utilisateur, Utilisateur superUtilisateur) { if (superUtilisateur instanceof SuperUtilisateur && !comptes.contains(utilisateur)) { if (utilisateur instanceof SuperUtilisateur) { if (superUtilisateur.getLogin().equals("root")) { return comptes.add(utilisateur); } } else { return comptes.add(utilisateur); } } return false; } public boolean supprimerUtilisateur(Utilisateur utilisateur, Utilisateur superUtilisateur) { if (superUtilisateur instanceof SuperUtilisateur) { if (utilisateur instanceof SuperUtilisateur) { if (superUtilisateur.getLogin().equals("root")) { supprimerAbonnement(utilisateur); return comptes.remove(utilisateur); } } else { supprimerAbonnement(utilisateur); return comptes.remove(utilisateur); } } return false; } public boolean ajouterListeDiffusion(ListeDiffusion listeDiffusion) { return comptes.add(listeDiffusion); } public boolean supprimerListeDiffusion(ListeDiffusion listeDiffusion, Utilisateur utilisateur) { if (utilisateur instanceof SuperUtilisateur || listeDiffusion.estCreateur(utilisateur)) { supprimerAbonnement(listeDiffusion); return comptes.remove(listeDiffusion); } return false; } public boolean abonnerCompte(ListeDiffusion listeDiffusion, Compte compte, Utilisateur utilisateur) { if (utilisateur.equals(compte) || utilisateur instanceof SuperUtilisateur || listeDiffusion.estCreateur(utilisateur)) { return listeDiffusion.ajouterCompte(compte); } return false; } public boolean desabonnerCompte(ListeDiffusion listeDiffusion, Compte compte, Utilisateur utilisateur) { if (utilisateur.equals(compte) || utilisateur instanceof SuperUtilisateur || listeDiffusion.estCreateur(utilisateur)) { return listeDiffusion.supprimerCompte(compte); } return false; } public Set<ListeDiffusion> voirAbonnements(Compte compte) { LinkedHashSet<ListeDiffusion> listes = new LinkedHashSet<ListeDiffusion>(); for (Compte c : comptes) { if (c instanceof ListeDiffusion) { ListeDiffusion liste = (ListeDiffusion) c; if (liste.contient(compte)) listes.add(liste); } } return listes; } /** * Supprime tous les abonnements d'un compte. * * @param compte le compte auquel on souhaite supprimer les abonnements */ public void supprimerAbonnement(Compte compte) { Set<ListeDiffusion> listes = voirAbonnements(compte); for (ListeDiffusion liste : listes) { liste.supprimerCompte(compte); } } }
package fr.utc.assos.uvweb.adapters; import android.content.Context; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.SectionIndexer; import android.widget.TextView; import com.emilsjolander.components.stickylistheaders.StickyListHeadersAdapter; import fr.utc.assos.uvweb.R; import fr.utc.assos.uvweb.data.UVwebContent; import fr.utc.assos.uvweb.util.ThreadPreconditionsUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static fr.utc.assos.uvweb.util.LogUtils.makeLogTag; /** * An adapter used all together with the {@link fr.utc.assos.uvweb.ui.UVListFragment}'s ListView. * It relies on a standard ViewHolder pattern implemented in the {@link UVwebHolder} * class and thus allows UVs recycling. * It implements both SectionIndexer and StickyListHeadersAdapter interfaces */ public class UVListAdapter extends UVAdapter implements SectionIndexer, StickyListHeadersAdapter, Filterable { private static final String TAG = makeLogTag(UVListAdapter.class); /** * Size of the French alphabet. We use it to instantiate our data structures and avoid memory * reallocation, since we can fairly surely assume we'll have a section for each letter. */ private static final int ALPHABET_LENGTH = 26; /** * A dummy implementation of the {@link SearchCallbacks} interface that does * nothing. Used only when this fragment is not attached to an activity. */ private static final SearchCallbacks sDummySearchCallbacks = new SearchCallbacks() { @Override public void onItemsFound(List<UVwebContent.UV> results) { } @Override public void onNothingFound() { } }; /** * Custom Filterable interface implementation */ private final UVFilter mFilter = new UVFilter(); /** * Data structures that help us keep track of a comprehensive list of sections and bind these sections * with the ListView's items' positions */ private final SparseArray<Character> mSectionToPosition; private final List<Character> mComprehensiveSectionsList; /** * Set of data */ private List<UVwebContent.UV> mUVs = Collections.emptyList(); private List<UVwebContent.UV> mSavedUVs = Collections.emptyList(); private SearchCallbacks mSearchCallbacks = sDummySearchCallbacks; public UVListAdapter(Context context) { super(context); mComprehensiveSectionsList = new ArrayList<Character>(ALPHABET_LENGTH); mSectionToPosition = new SparseArray<Character>(ALPHABET_LENGTH); } public void setSearchCallbacks(SearchCallbacks callbacks) { mSearchCallbacks = callbacks; } @Override public int getCount() { return mUVs.size(); } public boolean hasUvs() { return mSavedUVs != null && mSavedUVs.size() > 0; } @Override public UVwebContent.UV getItem(int position) { return mUVs.get(position); } public void updateUVs(List<UVwebContent.UV> UVs) { updateUVs(UVs, false); } public List<UVwebContent.UV> getUVs() { return mSavedUVs; } protected void updateUVs(List<UVwebContent.UV> UVs, boolean dueToFilterOperation) { ThreadPreconditionsUtils.checkOnMainThread(); mSectionToPosition.clear(); mComprehensiveSectionsList.clear(); Collections.sort(UVs); int i = 0; for (UVwebContent.UV UV : UVs) { final char section = UV.getLetterCode().charAt(0); mSectionToPosition.append(i, section); if (!mComprehensiveSectionsList.contains(section)) { mComprehensiveSectionsList.add(section); } i++; } mUVs = UVs; notifyDataSetChanged(); if (!dueToFilterOperation) { mSavedUVs = new ArrayList<UVwebContent.UV>(UVs); } } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mLayoutInflater.inflate(R.layout.uv, null); } final TextView code1View = UVwebHolder.get(convertView, R.id.uv_code_letter); final TextView code2View = UVwebHolder.get(convertView, R.id.uv_code_number); final TextView rateView = UVwebHolder.get(convertView, R.id.rate); final TextView descView = UVwebHolder.get(convertView, R.id.desc); final UVwebContent.UV UV = getItem(position); code1View.setText(UV.getLetterCode()); code2View.setText(UV.getNumberCode()); descView.setText(UV.getDescription()); rateView.setText(UV.getFormattedRate()); final View separatorView = UVwebHolder.get(convertView, R.id.list_divider); if (separatorView != null && position < mUVs.size() - 1) { // In tablet mode, we need to remove the last horizontal divider from the section, because these // are manually drawn final long currentHeaderId = getHeaderId(position), nextHeaderId = getHeaderId(position + 1); if (currentHeaderId != nextHeaderId) { separatorView.setVisibility(View.GONE); } else { separatorView.setVisibility(View.VISIBLE); } } return convertView; } /** * SectionIndexer interface's methods */ @Override public int getSectionForPosition(int position) { return 1; } @Override public int getPositionForSection(int section) { final int actualSection = Math.min(section, mComprehensiveSectionsList.size() - 1); // Workaround for the fastScroll issue return mSectionToPosition.indexOfValue(mComprehensiveSectionsList.get(actualSection)); } @Override public Object[] getSections() { return mComprehensiveSectionsList.toArray(new Character[mComprehensiveSectionsList.size()]); } /** * StickyListHeadersAdapter interface's methods */ @Override public View getHeaderView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mLayoutInflater.inflate(R.layout.header_uv_list, null); } // Set header text as first char in name final TextView headerView = UVwebHolder.get(convertView, R.id.header_text); headerView.setText((String.valueOf(getSectionName(position)))); return convertView; } @Override public long getHeaderId(int position) { return getSectionName(position); } /** * @param position the position of a given item in the ListView * @return the name of the corresponding section */ private char getSectionName(int position) { return mSectionToPosition.get(position); } @Override public Filter getFilter() { return mFilter; } /** * A callback interface that each Fragment using this adapter * and using its Filterable interface should implement. * This mechanism allows the querier to be notified and to act accordingly. */ public interface SearchCallbacks { public void onItemsFound(List<UVwebContent.UV> results); public void onNothingFound(); } private final class UVFilter extends Filter { private final FilterResults mFilterResults = new FilterResults(); private final List<UVwebContent.UV> mFoundUVs = new ArrayList<UVwebContent.UV>(); @Override protected FilterResults performFiltering(CharSequence charSequence) { if (charSequence == null || charSequence.length() == 0) { mFilterResults.values = mSavedUVs; mFilterResults.count = mSavedUVs.size(); return mFilterResults; } mFoundUVs.clear(); final String query = charSequence.toString().toUpperCase(); for (UVwebContent.UV UV : mSavedUVs) { if (UV.getName().startsWith(query)) { mFoundUVs.add(UV); } } mFilterResults.values = mFoundUVs; mFilterResults.count = mFoundUVs.size(); return mFilterResults; } @Override @SuppressWarnings("unchecked") protected void publishResults(CharSequence charSequence, FilterResults filterResults) { final List<UVwebContent.UV> results = (List<UVwebContent.UV>) filterResults.values; updateUVs(results, true); if (filterResults.count == 0) { mSearchCallbacks.onNothingFound(); } else { mSearchCallbacks.onItemsFound(results); } } } }
package table; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JPanel; public class DrawPanel extends JPanel { public static final int W = 206; public static final int H = 280; int x1=-1; int x2=-1; int y1 = -1; int y2 = -1; int x3 = -1; int y3 = -1; int i = 0; Toole toole = Toole.getToole(); static boolean isGenerate=false; static boolean isChange = false; static double[][] change = { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } }; double angle = 0.0; static double scale = 1; static double[][] symmetric_X = { { 1, 0, 0 }, { 0, -1, 0 }, { 0, 0, 1 } }; static double[][] symmetric_Y = { { -1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } }; double[][] amplify_big = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } }; double[][] rotate = { { 1, 1, 0 }, { 1, 1, 0 }, { 0, 0, 1 } };; private static MyArray operation(double[][] a, double[][] b) { MyArray result = new MyArray(); for (int i = 0; i < a.length; i++) { for (int j = 0; j < b[0].length; j++) { result.M[i][j] = 0; for (int k = 0; k < b.length; k++) { result.M[i][j] += a[i][k] * b[k][j]; } } } return result; } @Override public synchronized void paintComponent(Graphics g) { super.paintComponent(g); setBackground(Color.WHITE); Graphics2D g2d = (Graphics2D) g; g2d.setStroke(new BasicStroke(3f)); g.setFont(getFont().deriveFont(Font.ITALIC, 20f)); g.drawString("(0),(0)", W, H); int[] xPoints_X = { 2 * W - 3, 2 * W + 8, 2 * W - 3 }; int[] yPoints_X = { H -4, H + 1, H +4 }; int[] xPoints_Y = { W-5, W , W + 5 }; int[] yPoints_Y = { 10, 0, 10 }; g.setColor(Color.BLUE); Font font = new Font("", Font.LAYOUT_LEFT_TO_RIGHT, 20); int mX = getWidth(); int mY = getHeight(); g.drawLine(W, 0, W, 2*H); g.drawLine(0,H,2*W, H); g.fillPolygon(xPoints_X, yPoints_X, yPoints_X.length); g.drawString("X", 2 * W - 10, H-3); g.drawString("max:200", 2 * W-70, H+30); g.fillPolygon(xPoints_Y, yPoints_Y, yPoints_Y.length); g.drawString("Y max:200", W - 25, 20); g.fillOval(W-5, H-5, 10, 10); amplify_big[0][0] = scale; amplify_big[1][1] = scale; rotate[0][0] = Math.cos(angle); rotate[0][1] = Math.sin(angle); rotate[1][0] = -Math.sin(angle); rotate[1][1] = Math.cos(angle); double[][] origination = { { x1 - DrawPanel.W, -y1 + DrawPanel.H, 1 }, { x2 - DrawPanel.W, -y2 + DrawPanel.H, 1 }, { x3 - DrawPanel.W, -y3 + DrawPanel.H, 1 } }; double[][] variant = operation(origination, change).M; g.setColor(Color.BLACK); int[] x = { x1, x2, x3 }; int[] y = { y1, y2, y3 }; if (x2 != -1 && y2 != -1) { g.drawString("P1", x1, y1); g.drawString("P2", x2, y2); g.drawLine(x1, y1, x2, y2); if(isGenerate==false){ toole.x_1.setText(x1 - DrawPanel.W + ""); toole.x_2.setText(x2 - DrawPanel.W + ""); toole.x_3.setText(x3 - DrawPanel.W + ""); toole.y_1.setText(-y1 + DrawPanel.H + ""); toole.y_2.setText(-y2 + DrawPanel.H + ""); toole.y_3.setText(-y3 + DrawPanel.H + ""); } isGenerate=false; } if (x3 != -1 && y3 != -1) { g.drawString("P3", x3, y3); g.drawPolygon(x, y, x.length); System.out.println(x3+" System.out.println(x2+" System.out.println(x1+" } if (isChange) { System.out.println("angle is:" + drawPanel.angle + (int) variant[0][0]); int[] changeX = { (int) variant[0][0] + DrawPanel.W, (int) variant[1][0] + DrawPanel.W, (int) variant[2][0] + DrawPanel.W }; int[] changeY = { (int) -variant[0][1] + DrawPanel.H, (int) -variant[1][1] + DrawPanel.H, (int) -variant[2][1] + DrawPanel.H }; g.drawPolygon(changeX, changeY, changeY.length); isChange = false; } } static DrawPanel drawPanel = new DrawPanel(); public static DrawPanel getDrawPanel() { return drawPanel; } }
package io.flutter.preview; import com.google.common.collect.Maps; import com.intellij.icons.AllIcons; import com.intellij.ide.CommonActionsManager; import com.intellij.ide.DefaultTreeExpander; import com.intellij.ide.TreeExpander; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.Storage; import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.event.CaretEvent; import com.intellij.openapi.editor.event.CaretListener; import com.intellij.openapi.fileEditor.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.SimpleToolWindowPanel; import com.intellij.openapi.ui.Splitter; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ex.ToolWindowEx; import com.intellij.ui.ColoredTreeCellRenderer; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.TreeSpeedSearch; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentFactory; import com.intellij.ui.content.ContentManager; import com.intellij.ui.speedSearch.SpeedSearchUtil; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.messages.MessageBusConnection; import com.jetbrains.lang.dart.assists.AssistUtils; import com.jetbrains.lang.dart.assists.DartSourceEditException; import icons.FlutterIcons; import io.flutter.FlutterInitializer; import io.flutter.FlutterMessages; import io.flutter.FlutterUtils; import io.flutter.dart.FlutterDartAnalysisServer; import io.flutter.dart.FlutterOutlineListener; import io.flutter.inspector.FlutterWidget; import io.flutter.utils.CustomIconMaker; import org.dartlang.analysis.server.protocol.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.*; import java.util.List; @com.intellij.openapi.components.State( name = "FlutterPreviewView", storages = {@Storage("$WORKSPACE_FILE$")} ) public class PreviewView implements PersistentStateComponent<PreviewViewState>, Disposable { public static final String TOOL_WINDOW_ID = "Flutter Preview"; private static final boolean SHOW_PREVIEW_AREA = false; @NotNull private final PreviewViewState state = new PreviewViewState(); @NotNull private final Project project; @NotNull private final FlutterDartAnalysisServer flutterAnalysisServer; private SimpleToolWindowPanel windowPanel; private ActionToolbar windowToolbar; private final Map<String, AnAction> messageToActionMap = new HashMap<>(); private final Map<AnAction, SourceChange> actionToChangeMap = new HashMap<>(); private Splitter splitter; private JScrollPane scrollPane; private OutlineTree tree; private PreviewAreaPanel previewAreaPanel; private final Map<FlutterOutline, DefaultMutableTreeNode> outlineToNodeMap = Maps.newHashMap(); private VirtualFile currentFile; private Editor currentEditor; private FlutterOutline currentOutline; private final FlutterOutlineListener outlineListener = new FlutterOutlineListener() { @Override public void outlineUpdated(@NotNull String filePath, @NotNull FlutterOutline outline) { if (currentFile != null && Objects.equals(currentFile.getPath(), filePath)) { ApplicationManager.getApplication().invokeLater(() -> updateOutline(filePath, outline)); } } }; private final CaretListener caretListener = new CaretListener() { @Override public void caretPositionChanged(CaretEvent e) { final Caret caret = e.getCaret(); if (caret != null) { ApplicationManager.getApplication().invokeLater(() -> applyEditorSelectionToTree(caret)); } } @Override public void caretAdded(CaretEvent e) { } @Override public void caretRemoved(CaretEvent e) { } }; private final TreeSelectionListener treeSelectionListener = this::handleTreeSelectionEvent; public PreviewView(@NotNull Project project) { this.project = project; flutterAnalysisServer = FlutterDartAnalysisServer.getInstance(project); // Show preview for the file selected when the view is being opened. final VirtualFile[] selectedFiles = FileEditorManager.getInstance(project).getSelectedFiles(); if (selectedFiles.length != 0) { setSelectedFile(selectedFiles[0]); } final FileEditor[] selectedEditors = FileEditorManager.getInstance(project).getSelectedEditors(); if (selectedEditors.length != 0) { setSelectedEditor(selectedEditors[0]); } // Listen for selecting files. final MessageBusConnection bus = project.getMessageBus().connect(project); bus.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() { @Override public void selectionChanged(@NotNull FileEditorManagerEvent event) { setSelectedFile(event.getNewFile()); setSelectedEditor(event.getNewEditor()); } }); } @Override public void dispose() { } @NotNull @Override public PreviewViewState getState() { return this.state; } @Override public void loadState(PreviewViewState state) { this.state.copyFrom(state); } public void initToolWindow(@NotNull ToolWindow toolWindow) { final ContentFactory contentFactory = ContentFactory.SERVICE.getInstance(); final ContentManager contentManager = toolWindow.getContentManager(); final DefaultActionGroup toolbarGroup = new DefaultActionGroup(); toolbarGroup.add(new QuickAssistAction("dart.assist.flutter.wrap.center", FlutterIcons.Center, "Center widget")); toolbarGroup.add(new QuickAssistAction("dart.assist.flutter.wrap.padding", FlutterIcons.Padding, "Add padding")); toolbarGroup.add(new QuickAssistAction("dart.assist.flutter.wrap.column", FlutterIcons.Column, "Wrap with Column")); toolbarGroup.add(new QuickAssistAction("dart.assist.flutter.wrap.row", FlutterIcons.Row, "Wrap with Row")); toolbarGroup.addSeparator(); toolbarGroup.add(new QuickAssistAction("dart.assist.flutter.move.up", FlutterIcons.Up, "Move widget up")); toolbarGroup.add(new QuickAssistAction("dart.assist.flutter.move.down", FlutterIcons.Down, "Move widget down")); toolbarGroup.addSeparator(); toolbarGroup.add(new QuickAssistAction("dart.assist.flutter.removeWidget", FlutterIcons.RemoveWidget, "Remove widget")); final Content content = contentFactory.createContent(null, null, false); content.setCloseable(false); windowPanel = new SimpleToolWindowPanel(true, true); content.setComponent(windowPanel); windowToolbar = ActionManager.getInstance().createActionToolbar("PreviewViewToolbar", toolbarGroup, true); windowPanel.setToolbar(windowToolbar.getComponent()); final DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(); tree = new OutlineTree(rootNode); tree.setCellRenderer(new OutlineTreeCellRenderer()); tree.expandAll(); // Add collapse all and expand all buttons. if (toolWindow instanceof ToolWindowEx) { final TreeExpander expander = new DefaultTreeExpander(tree); final CommonActionsManager actions = CommonActionsManager.getInstance(); final AnAction expandAllAction = actions.createExpandAllAction(expander, tree); expandAllAction.getTemplatePresentation().setIcon(AllIcons.General.ExpandAll); final AnAction collapseAllAction = actions.createCollapseAllAction(expander, tree); collapseAllAction.getTemplatePresentation().setIcon(AllIcons.General.CollapseAll); ((ToolWindowEx)toolWindow).setTitleActions(expandAllAction, collapseAllAction); } new TreeSpeedSearch(tree) { @Override protected String getElementText(Object element) { final TreePath path = (TreePath)element; final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); final Object object = node.getUserObject(); if (object instanceof OutlineObject) { return ((OutlineObject)object).getSpeedSearchString(); } return null; } }; tree.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() > 1) { final TreePath selectionPath = tree.getSelectionPath(); if (selectionPath != null) { selectPath(selectionPath, true); } } } }); tree.addTreeSelectionListener(treeSelectionListener); scrollPane = ScrollPaneFactory.createScrollPane(tree); previewAreaPanel = new PreviewAreaPanel(); splitter = new Splitter(true); splitter.setProportion(getState().getSplitterProportion()); getState().addListener(e -> { final float newProportion = getState().getSplitterProportion(); if (splitter.getProportion() != newProportion) { splitter.setProportion(newProportion); } }); //noinspection Convert2Lambda splitter.addPropertyChangeListener("proportion", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { getState().setSplitterProportion(splitter.getProportion()); } }); splitter.setFirstComponent(scrollPane); windowPanel.setContent(splitter); contentManager.addContent(content); contentManager.setSelectedContent(content); } private void handleTreeSelectionEvent(TreeSelectionEvent e) { final TreePath selectionPath = e.getNewLeadSelectionPath(); if (selectionPath != null) { ApplicationManager.getApplication().invokeLater(() -> selectPath(selectionPath, false)); } final List<FlutterOutline> selectedOutlines = getOutlinesSelectedInTree(); updateActionsForOutlines(selectedOutlines); } private void selectPath(TreePath selectionPath, boolean focusEditor) { final FlutterOutline outline = getOutlineOfPath(selectionPath); if (outline == null) { return; } sendAnalyticEvent("jumpToSource"); final int offset = outline.getDartElement() != null ? outline.getDartElement().getLocation().getOffset() : outline.getOffset(); if (currentFile != null) { currentEditor.getCaretModel().removeCaretListener(caretListener); try { new OpenFileDescriptor(project, currentFile, offset).navigate(focusEditor); } finally { currentEditor.getCaretModel().addCaretListener(caretListener); } } if (SHOW_PREVIEW_AREA) { final Element buildMethodElement = getBuildMethodElement(selectionPath); previewAreaPanel.updatePreviewElement(getElementParentFor(buildMethodElement), buildMethodElement); } } private void updateActionsForOutlines(List<FlutterOutline> outlines) { synchronized (actionToChangeMap) { actionToChangeMap.clear(); } final VirtualFile selectionFile = this.currentFile; if (selectionFile != null && !outlines.isEmpty()) { ApplicationManager.getApplication().executeOnPooledThread(() -> { final FlutterOutline firstOutline = outlines.get(0); final FlutterOutline lastOutline = outlines.get(outlines.size() - 1); final int offset = firstOutline.getOffset(); final int length = lastOutline.getOffset() + lastOutline.getLength() - offset; final List<SourceChange> changes = flutterAnalysisServer.edit_getAssists(selectionFile, offset, length); // If the current file or outline are different, ignore the changes. // We will eventually get new changes. final List<FlutterOutline> newOutlines = getOutlinesSelectedInTree(); if (!Objects.equals(this.currentFile, selectionFile) || !outlines.equals(newOutlines)) { return; } // Associate changes with actions. // Actions will be enabled / disabled in background. for (SourceChange change : changes) { final AnAction action = messageToActionMap.get(change.getMessage()); if (action != null) { actionToChangeMap.put(action, change); } } // Update actions immediately. if (windowToolbar != null) { ApplicationManager.getApplication().invokeLater(() -> windowToolbar.updateActionsImmediately()); } }); } } // TODO: Add parent relationship info to FlutterOutline instead of this O(n^2) traversal. private Element getElementParentFor(@Nullable Element element) { if (element == null) { return null; } for (FlutterOutline outline : outlineToNodeMap.keySet()) { final List<FlutterOutline> children = outline.getChildren(); if (children != null) { for (FlutterOutline child : children) { if (child.getDartElement() == element) { return outline.getDartElement(); } } } } return null; } private Element getBuildMethodElement(TreePath path) { for (Object n : path.getPath()) { final DefaultMutableTreeNode node = (DefaultMutableTreeNode)n; final OutlineObject outlineElement = (OutlineObject)node.getUserObject(); if (outlineElement == null) { continue; } final FlutterOutline flutterOutline = outlineElement.outline; final Element element = flutterOutline.getDartElement(); if (element != null && ModelUtils.isBuildMethod(element)) { return element; } } return null; } private DefaultTreeModel getTreeModel() { return (DefaultTreeModel)tree.getModel(); } private DefaultMutableTreeNode getRootNode() { return (DefaultMutableTreeNode)getTreeModel().getRoot(); } private void updateOutline(@NotNull String filePath, @NotNull FlutterOutline outline) { currentOutline = outline; final DefaultMutableTreeNode rootNode = getRootNode(); rootNode.removeAllChildren(); outlineToNodeMap.clear(); if (outline.getChildren() != null) { updateOutlineImpl(rootNode, outline.getChildren()); } getTreeModel().reload(rootNode); tree.expandAll(); if (currentEditor != null) { final Caret caret = currentEditor.getCaretModel().getPrimaryCaret(); applyEditorSelectionToTree(caret); } if (SHOW_PREVIEW_AREA) { if (ModelUtils.containsBuildMethod(outline)) { splitter.setSecondComponent(previewAreaPanel); final Element buildMethodElement = getBuildMethodElement(tree.getSelectionPath()); previewAreaPanel.updatePreviewElement(getElementParentFor(buildMethodElement), buildMethodElement); } else { splitter.setSecondComponent(null); } } } private void updateOutlineImpl(@NotNull DefaultMutableTreeNode parent, @NotNull List<FlutterOutline> outlines) { for (int i = 0; i < outlines.size(); i++) { final FlutterOutline outline = outlines.get(i); final OutlineObject object = new OutlineObject(outline); final DefaultMutableTreeNode node = new DefaultMutableTreeNode(object); outlineToNodeMap.put(outline, node); getTreeModel().insertNodeInto(node, parent, i); if (outline.getChildren() != null) { updateOutlineImpl(node, outline.getChildren()); } } } @NotNull private List<FlutterOutline> getOutlinesSelectedInTree() { final List<FlutterOutline> selectedOutlines = new ArrayList<>(); final DefaultMutableTreeNode[] selectedNodes = tree.getSelectedNodes(DefaultMutableTreeNode.class, null); for (DefaultMutableTreeNode selectedNode : selectedNodes) { final FlutterOutline outline = getOutlineOfNode(selectedNode); selectedOutlines.add(outline); } return selectedOutlines; } static private FlutterOutline getOutlineOfNode(DefaultMutableTreeNode node) { final OutlineObject object = (OutlineObject)node.getUserObject(); return object.outline; } @Nullable private FlutterOutline getOutlineOfPath(@Nullable TreePath path) { if (path == null) { return null; } final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); return getOutlineOfNode(node); } private FlutterOutline findOutlineAtOffset(FlutterOutline outline, int offset) { if (outline == null) { return null; } if (outline.getOffset() <= offset && offset <= outline.getOffset() + outline.getLength()) { if (outline.getChildren() != null) { for (FlutterOutline child : outline.getChildren()) { final FlutterOutline foundChild = findOutlineAtOffset(child, offset); if (foundChild != null) { return foundChild; } } } return outline; } return null; } private void addOutlinesCoveredByRange(List<FlutterOutline> covered, int start, int end, @Nullable FlutterOutline outline) { if (outline == null) { return; } final int outlineStart = outline.getOffset(); final int outlineEnd = outlineStart + outline.getLength(); // The outline ends before, or starts after the selection. if (outlineEnd < start || outlineStart > end) { return; } // The outline is covered by the selection. if (outlineStart >= start && outlineEnd <= end) { covered.add(outline); return; } // The outline covers the selection. if (outlineStart <= start && end <= outlineEnd) { if (outline.getChildren() != null) { for (FlutterOutline child : outline.getChildren()) { addOutlinesCoveredByRange(covered, start, end, child); } } } } private void setSelectedFile(VirtualFile newFile) { if (currentFile != null) { flutterAnalysisServer.removeOutlineListener(currentFile.getPath(), outlineListener); currentFile = null; } // Show the toolbar if the new file is a Dart file, or hide otherwise. if (windowPanel != null) { if (newFile != null && FlutterUtils.isDartFile(newFile)) { windowPanel.setToolbar(windowToolbar.getComponent()); } else if (windowPanel.isToolbarVisible()) { windowPanel.setToolbar(null); } } // If the tree is already created, clear it now, until the outline for the new file is received. if (tree != null) { final DefaultMutableTreeNode rootNode = getRootNode(); rootNode.removeAllChildren(); getTreeModel().reload(rootNode); } // Subscribe for the outline for the new file. if (newFile != null) { currentFile = newFile; flutterAnalysisServer.addOutlineListener(currentFile.getPath(), outlineListener); } } private void setSelectedEditor(FileEditor newEditor) { if (currentEditor != null) { currentEditor.getCaretModel().removeCaretListener(caretListener); } if (newEditor instanceof TextEditor) { currentEditor = ((TextEditor)newEditor).getEditor(); currentEditor.getCaretModel().addCaretListener(caretListener); } } private void applyEditorSelectionToTree(Caret caret) { final List<FlutterOutline> selectedOutlines = new ArrayList<>(); // Try to find outlines covered by the selection. addOutlinesCoveredByRange(selectedOutlines, caret.getSelectionStart(), caret.getSelectionEnd(), currentOutline); // If no covered outlines, try to find the outline under the caret. if (selectedOutlines.isEmpty()) { final FlutterOutline outline = findOutlineAtOffset(currentOutline, caret.getOffset()); if (outline != null) { selectedOutlines.add(outline); } } updateActionsForOutlines(selectedOutlines); applyOutlinesSelectionToTree(selectedOutlines); } private void applyOutlinesSelectionToTree(List<FlutterOutline> outlines) { final List<TreePath> selectedPaths = new ArrayList<>(); TreeNode[] lastNodePath = null; TreePath lastTreePath = null; for (FlutterOutline outline : outlines) { final DefaultMutableTreeNode selectedNode = outlineToNodeMap.get(outline); if (selectedNode != null) { lastNodePath = selectedNode.getPath(); lastTreePath = new TreePath(lastNodePath); selectedPaths.add(lastTreePath); } } if (lastNodePath != null) { // Ensure that all parent nodes are expected. tree.scrollPathToVisible(lastTreePath); // Ensure that the top-level declaration (class) is on the top of the tree. if (lastNodePath.length >= 2) { scrollTreeToNodeOnTop(lastNodePath[1]); } // Ensure that the selected node is still visible, even if the top-level declaration is long. tree.scrollPathToVisible(lastTreePath); } // Now actually select the node. tree.removeTreeSelectionListener(treeSelectionListener); tree.setSelectionPaths(selectedPaths.toArray(new TreePath[selectedPaths.size()])); tree.addTreeSelectionListener(treeSelectionListener); // JTree attempts to show as much of the node as possible, so scrolls horizonally. // But we actually need to see the whole hierarchy, so we scroll back to zero. scrollPane.getHorizontalScrollBar().setValue(0); } private void scrollTreeToNodeOnTop(TreeNode node) { if (node instanceof DefaultMutableTreeNode) { final DefaultMutableTreeNode defaultNode = (DefaultMutableTreeNode)node; final Rectangle bounds = tree.getPathBounds(new TreePath(defaultNode.getPath())); // Set the height to the visible tree height to force the node to top. if (bounds != null) { bounds.height = tree.getVisibleRect().height; tree.scrollRectToVisible(bounds); } } } private void sendAnalyticEvent(@NotNull String name) { FlutterInitializer.getAnalytics().sendEvent("preview", name); } private class QuickAssistAction extends AnAction { private final String id; QuickAssistAction(@NotNull String id, Icon icon, String assistMessage) { super(assistMessage, null, icon); this.id = id; messageToActionMap.put(assistMessage, this); } @Override public void actionPerformed(AnActionEvent e) { sendAnalyticEvent(id); final SourceChange change; synchronized (actionToChangeMap) { change = actionToChangeMap.get(this); actionToChangeMap.clear(); } if (change != null) { ApplicationManager.getApplication().runWriteAction(() -> { try { AssistUtils.applySourceChange(project, change, false); } catch (DartSourceEditException exception) { FlutterMessages.showError("Error applying change", exception.getMessage()); } }); } } @Override public void update(AnActionEvent e) { final boolean hasChange = actionToChangeMap.containsKey(this); e.getPresentation().setEnabled(hasChange); } } } class OutlineTree extends Tree { OutlineTree(DefaultMutableTreeNode model) { super(model); setRootVisible(false); setToggleClickCount(0); } void expandAll() { for (int row = 0; row < getRowCount(); row++) { expandRow(row); } } } class OutlineObject { private static final CustomIconMaker iconMaker = new CustomIconMaker(); final FlutterOutline outline; private Icon icon; OutlineObject(FlutterOutline outline) { this.outline = outline; } Icon getIcon() { if (outline.getKind().equals(FlutterOutlineKind.DART_ELEMENT)) { return null; } if (icon == null) { final String className = outline.getClassName(); final FlutterWidget widget = FlutterWidget.getCatalog().getWidget(className); if (widget != null) { icon = widget.getIcon(); } if (icon == null) { icon = iconMaker.fromWidgetName(className); } } return icon; } /** * Return the string that is suitable for speed search. It has every name part separted so that we search only inside individual name * parts, but not in their accidential concatenation. */ @NotNull String getSpeedSearchString() { final StringBuilder builder = new StringBuilder(); final Element dartElement = outline.getDartElement(); if (dartElement != null) { builder.append(dartElement.getName()); } else { builder.append(outline.getClassName()); } if (outline.getVariableName() != null) { builder.append('|'); builder.append(outline.getVariableName()); } final List<FlutterOutlineAttribute> attributes = outline.getAttributes(); if (attributes != null) { for (FlutterOutlineAttribute attribute : attributes) { builder.append(attribute.getName()); builder.append(':'); builder.append(attribute.getLabel()); } } return builder.toString(); } } class OutlineTreeCellRenderer extends ColoredTreeCellRenderer { private JTree tree; private boolean selected; public void customizeCellRenderer( @NotNull final JTree tree, final Object value, final boolean selected, final boolean expanded, final boolean leaf, final int row, final boolean hasFocus ) { final Object userObject = ((DefaultMutableTreeNode)value).getUserObject(); if (!(userObject instanceof OutlineObject)) { return; } final OutlineObject node = (OutlineObject)userObject; final FlutterOutline outline = node.outline; this.tree = tree; this.selected = selected; // Render a Dart element. final Element dartElement = outline.getDartElement(); if (dartElement != null) { final Icon icon = DartElementPresentationUtil.getIcon(dartElement); setIcon(icon); final boolean renderInBold = hasWidgetChild(outline) && ModelUtils.isBuildMethod(dartElement); DartElementPresentationUtil.renderElement(dartElement, this, renderInBold); return; } // Render the widget icon. final Icon icon = node.getIcon(); if (icon != null) { setIcon(icon); } // Render the widget class. appendSearch(outline.getClassName(), SimpleTextAttributes.REGULAR_ATTRIBUTES); // Render the variable. if (outline.getVariableName() != null) { append(" "); appendSearch(outline.getVariableName(), SimpleTextAttributes.GRAYED_ATTRIBUTES); } // Render a generic label. if (outline.getKind().equals(FlutterOutlineKind.GENERIC) && outline.getLabel() != null) { append(" "); final String label = outline.getLabel(); appendSearch(label, SimpleTextAttributes.GRAYED_ATTRIBUTES); } // Append all attributes. final List<FlutterOutlineAttribute> attributes = outline.getAttributes(); if (attributes != null) { if (attributes.size() == 1 && isAttributeElidable(attributes.get(0).getName())) { final FlutterOutlineAttribute attribute = attributes.get(0); append(" "); appendSearch(attribute.getLabel(), SimpleTextAttributes.GRAYED_ATTRIBUTES); } else { for (int i = 0; i < attributes.size(); i++) { final FlutterOutlineAttribute attribute = attributes.get(i); if (i > 0) { append(","); } append(" "); if (!StringUtil.equals("data", attribute.getName())) { appendSearch(attribute.getName(), SimpleTextAttributes.GRAYED_ATTRIBUTES); append(": ", SimpleTextAttributes.GRAYED_ATTRIBUTES); } appendSearch(attribute.getLabel(), SimpleTextAttributes.GRAYED_ATTRIBUTES); // TODO(scheglov): custom display for units, colors, iterables, and icons? } } } } private boolean hasWidgetChild(FlutterOutline outline) { if (outline.getChildren() == null) { return false; } for (FlutterOutline child : outline.getChildren()) { if (child.getDartElement() == null) { return true; } } return false; } private static boolean isAttributeElidable(String name) { return StringUtil.equals("text", name) || StringUtil.equals("icon", name); } void appendSearch(@NotNull String text, @NotNull SimpleTextAttributes attributes) { SpeedSearchUtil.appendFragmentsForSpeedSearch(tree, text, attributes, selected, this); } }
package org.voltdb.client; import java.io.EOFException; import java.io.IOException; import java.net.Inet4Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Enumeration; import java.util.HashMap; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.voltdb.ClientResponseImpl; import org.voltdb.messaging.FastDeserializer; import org.voltdb.messaging.FastSerializer; import org.voltdb.utils.DBBPool.BBContainer; /** * A utility class for opening a connection to a Volt server and authenticating as well * as sending invocations and receiving responses. It is safe to queue multiple requests * @author aweisberg * */ public class ConnectionUtil { private static class TF implements ThreadFactory { @Override public Thread newThread(Runnable r) { return new Thread(null, r, "Yet another thread", 65536); } } private static final TF m_tf = new TF(); public static class ExecutorPair { public final ExecutorService m_writeExecutor; public final ExecutorService m_readExecutor; public ExecutorPair() { m_writeExecutor = Executors.newSingleThreadExecutor(m_tf); m_readExecutor = Executors.newSingleThreadExecutor(m_tf); } private void shutdown() throws InterruptedException { m_readExecutor.shutdownNow(); m_writeExecutor.shutdownNow(); m_readExecutor.awaitTermination(1, TimeUnit.DAYS); m_writeExecutor.awaitTermination(1, TimeUnit.DAYS); } } private static final HashMap<SocketChannel, ExecutorPair> m_executors = new HashMap<SocketChannel, ExecutorPair>(); private static final AtomicLong m_handle = new AtomicLong(Long.MIN_VALUE); /** * Create a connection to a Volt server and authenticate the connection. * @param host * @param username * @param password * @param port * @throws IOException * @returns An array of objects. The first is an * authenticated socket channel, the second. is an array of 4 longs - * Integer hostId, Long connectionId, Long timestamp (part of instanceId), Int leaderAddress (part of instanceId). * The last object is the build string */ public static Object[] getAuthenticatedConnection( String host, String username, String password, int port) throws IOException { return getAuthenticatedConnection("database", host, username, password, port); } /** * Create a connection to a Volt server for export and authenticate the connection. * @param host * @param username * @param password * @param port * @throws IOException * @returns An array of objects. The first is an * authenticated socket channel, the second. is an array of 4 longs - * Integer hostId, Long connectionId, Long timestamp (part of instanceId), Int leaderAddress (part of instanceId). * The last object is the build string */ public static Object[] getAuthenticatedExportConnection( String host, String username, String password, int port) throws IOException { return getAuthenticatedConnection("export", host, username, password, port); } public static String getHostnameOrAddress() { try { final InetAddress addr = InetAddress.getLocalHost(); return addr.getHostName(); } catch (UnknownHostException e) { try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); if (interfaces == null) { return ""; } NetworkInterface intf = interfaces.nextElement(); Enumeration<InetAddress> addresses = intf.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (address instanceof Inet4Address) { return address.getHostAddress(); } } interfaces = NetworkInterface.getNetworkInterfaces(); while (addresses.hasMoreElements()) { return addresses.nextElement().getHostAddress(); } return ""; } catch (SocketException e1) { return ""; } } } public static InetAddress getLocalAddress() { try { final InetAddress addr = InetAddress.getLocalHost(); return addr; } catch (UnknownHostException e) { try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); if (interfaces == null) { return null; } NetworkInterface intf = interfaces.nextElement(); Enumeration<InetAddress> addresses = intf.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (address instanceof Inet4Address) { return address; } } interfaces = NetworkInterface.getNetworkInterfaces(); while (addresses.hasMoreElements()) { return addresses.nextElement(); } return null; } catch (SocketException e1) { return null; } } } private static Object[] getAuthenticatedConnection( String service, String host, String username, String password, int port) throws IOException { Object returnArray[] = new Object[3]; boolean success = false; InetSocketAddress addr = new InetSocketAddress(host, port); if (addr.isUnresolved()) { throw new java.net.UnknownHostException(host); } SocketChannel aChannel = SocketChannel.open(addr); returnArray[0] = aChannel; assert(aChannel.isConnected()); if (!aChannel.isConnected()) { // TODO Can open() be asynchronous if configureBlocking(true)? throw new IOException("Failed to open host " + host); } final long retvals[] = new long[4]; returnArray[1] = retvals; try { /* * Send login info */ aChannel.configureBlocking(true); aChannel.socket().setTcpNoDelay(true); MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.exit(-1); } byte passwordHash[] = md.digest(password.getBytes()); FastSerializer fs = new FastSerializer(); fs.writeInt(0); // placeholder for length fs.writeByte(0); // version fs.writeString(service); // data service (export|database) fs.writeString(username); fs.write(passwordHash); final ByteBuffer fsBuffer = fs.getBuffer(); final ByteBuffer b = ByteBuffer.allocate(fsBuffer.remaining()); b.put(fsBuffer); final int size = fsBuffer.limit() - 4; b.flip(); b.putInt(size); b.position(0); boolean successfulWrite = false; IOException writeException = null; try { for (int ii = 0; ii < 4 && b.hasRemaining(); ii++) { aChannel.write(b); } if (!b.hasRemaining()) { successfulWrite = true; } } catch (IOException e) { writeException = e; } ByteBuffer lengthBuffer = ByteBuffer.allocate(4); int read = aChannel.read(lengthBuffer); if (read == -1) { if (writeException != null) { throw writeException; } if (!successfulWrite) { throw new IOException("Unable to write authentication info to serer"); } throw new IOException("Authentication rejected"); } else { lengthBuffer.flip(); } ByteBuffer loginResponse = ByteBuffer.allocate(lengthBuffer.getInt());//Read version and length etc. read = aChannel.read(loginResponse); byte loginResponseCode = 0; if (read == -1) { if (writeException != null) { throw writeException; } if (!successfulWrite) { throw new IOException("Unable to write authentication info to serer"); } throw new IOException("Authentication rejected"); } else { loginResponse.flip(); loginResponse.position(1); loginResponseCode = loginResponse.get(); } if (loginResponseCode != 0) { aChannel.close(); switch (loginResponseCode) { case 1: throw new IOException("Server has too many connections"); case 2: throw new IOException("Connection timed out during authentication. " + "The VoltDB server may be overloaded."); default: throw new IOException("Authentication rejected"); } } retvals[0] = loginResponse.getInt(); retvals[1] = loginResponse.getLong(); retvals[2] = loginResponse.getLong(); retvals[3] = loginResponse.getInt(); int buildStringLength = loginResponse.getInt(); byte buildStringBytes[] = new byte[buildStringLength]; loginResponse.get(buildStringBytes); returnArray[2] = new String(buildStringBytes, "UTF-8"); aChannel.configureBlocking(false); aChannel.socket().setTcpNoDelay(false); aChannel.socket().setKeepAlive(true); success = true; } finally { if (!success) { aChannel.close(); } } return returnArray; } public static void closeConnection(SocketChannel connection) throws InterruptedException, IOException { synchronized (m_executors) { ExecutorPair p = m_executors.remove(connection); assert(p != null); p.shutdown(); } connection.close(); } private static ExecutorPair getExecutorPair(final SocketChannel channel) { synchronized (m_executors) { ExecutorPair p = m_executors.get(channel); if (p == null) { p = new ExecutorPair(); m_executors.put( channel, p); } return p; } } public static Future<Long> sendInvocation(final SocketChannel channel, final String procName,final Object ...parameters) { final ExecutorPair p = getExecutorPair(channel); return sendInvocation(p.m_writeExecutor, channel, procName, parameters); } public static Future<Long> sendInvocation(final ExecutorService executor, final SocketChannel channel, final String procName,final Object ...parameters) { return executor.submit(new Callable<Long>() { @Override public Long call() throws Exception { final long handle = m_handle.getAndIncrement(); final ProcedureInvocation invocation = new ProcedureInvocation(handle, procName, -1, parameters); final FastSerializer fs = new FastSerializer(); final BBContainer c = fs.writeObjectForMessaging(invocation); do { channel.write(c.b); if (c.b.hasRemaining()) { Thread.yield(); } } while(c.b.hasRemaining()); c.discard(); return handle; } }); } public static Future<ClientResponse> readResponse(final SocketChannel channel) { final ExecutorPair p = getExecutorPair(channel); return readResponse(p.m_readExecutor, channel); } public static Future<ClientResponse> readResponse(final ExecutorService executor, final SocketChannel channel) { return executor.submit(new Callable<ClientResponse>() { @Override public ClientResponse call() throws Exception { ByteBuffer lengthBuffer = ByteBuffer.allocate(4); do { final int read = channel.read(lengthBuffer); if (read == -1) { throw new EOFException(); } if (lengthBuffer.hasRemaining()) { Thread.yield(); } } while (lengthBuffer.hasRemaining()); lengthBuffer.flip(); ByteBuffer message = ByteBuffer.allocate(lengthBuffer.getInt()); do { final int read = channel.read(message); if (read == -1) { throw new EOFException(); } if (lengthBuffer.hasRemaining()) { Thread.yield(); } } while (message.hasRemaining()); message.flip(); FastDeserializer fds = new FastDeserializer(message); ClientResponseImpl response = fds.readObject(ClientResponseImpl.class); return response; } }); } }
package net.sf.jabref; import java.beans.*; import java.io.*; import java.util.*; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import net.sf.jabref.export.*; import net.sf.jabref.undo.*; public class EntryEditor extends JPanel implements VetoableChangeListener { /* * GUI component that allows editing of the fields of a BibtexEntry. * EntryTypeForm also registers itself as a VetoableChangeListener, * receiving events whenever a field of the entry changes, enabling the * text fields to update themselves if the change is made from somewhere * else. */ // A reference to the entry this object works on. BibtexEntry entry; CloseAction closeAction; // The action concerned with closing the window. DeleteAction deleteAction = new DeleteAction(); // The action that deletes the current entry, and closes the editor. CopyKeyAction copyKeyAction; // The action concerned with copying the BibTeX key to the clipboard. AbstractAction nextEntryAction = new NextEntryAction(), prevEntryAction = new PrevEntryAction(); // Actions for switching to next/previous entry. StoreFieldAction storeFieldAction; // The action concerned with storing a field value. SwitchLeftAction switchLeftAction = new SwitchLeftAction(); SwitchRightAction switchRightAction = new SwitchRightAction(); // The actions concerned with switching the panels. GenerateKeyAction generateKeyAction ; // The action which generates a bibtexkey for this entry. SaveDatabaseAction saveDatabaseAction = new SaveDatabaseAction(); JPanel mainPanel = new JPanel(), // The area below the toolbar. srcPanel = new JPanel(); FieldPanel reqPanel = new FieldPanel(), optPanel = new FieldPanel(), genPanel = new FieldPanel(); JTextField bibtexKey; FieldTextField tf; JTextArea source; JTabbedPane tabbed = new JTabbedPane();//JTabbedPane.RIGHT); GridBagLayout gbl = new GridBagLayout(); GridBagConstraints con = new GridBagConstraints(); JLabel lab; JabRefFrame frame; BasePanel panel; EntryEditor ths = this; boolean updateSource = true; // This can be set to false to stop the source // text area from gettin updated. This is used in cases where the source // couldn't be parsed, and the user is given the option to edit it. boolean lastSourceAccepted = true; // This indicates whether the last attempt // at parsing the source was successful. It is used to determine whether the // dialog should close; it should stay open if the user received an error // message about the source, whatever he or she chose to do about it. String lastSourceStringAccepted = null; // This is used to prevent double // updates after editing source. double optW = 0, reqW = 1, genW = 0; // Variables for total weight of fields. // These values can be used to calculate the preferred height for the form. // reqW starts at 1 because it needs room for the bibtex key field. private int sourceIndex = -1; // The index the source panel has in tabbed. private final int REQ=0, OPT=1, GEN=2, FIELD_WIDTH=40, FIELD_HEIGHT=2; private final String KEY_PROPERTY = "bibtexkey"; JabRefPreferences prefs; HelpAction helpAction; public EntryEditor(JabRefFrame frame_, BasePanel panel_, BibtexEntry entry_, JabRefPreferences prefs_) { //super(frame_); frame = frame_; panel = panel_; entry = entry_; prefs = prefs_; setBackground(GUIGlobals.lightGray);//Color.white); entry.addPropertyChangeListener(this); //setTitle(entry.getType().getName()); //setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); helpAction = new HelpAction (frame.helpDiag, GUIGlobals.entryEditorHelp, "Help"); closeAction = new CloseAction(); copyKeyAction = new CopyKeyAction(); // generateKeyAction = new GenerateKeyAction(baseFrame,entry); generateKeyAction = new GenerateKeyAction(frame); storeFieldAction = new StoreFieldAction(); BorderLayout bl = new BorderLayout(); //bl.setVgap(5); setLayout(bl); setupToolBar(); setupFieldPanels(reqPanel, optPanel, genPanel); setupSourcePanel(); tabbed.addTab(Globals.lang("Required fields"), new ImageIcon(GUIGlobals.showReqIconFile), reqPanel.getPane(), Globals.lang("Show required fields")); if ((entry.getOptionalFields() != null) && (entry.getOptionalFields().length >= 1)) tabbed.addTab(Globals.lang("Optional fields"), new ImageIcon(GUIGlobals.showOptIconFile), optPanel.getPane(), Globals.lang("Show optional fields")); if ((entry.getGeneralFields() != null) && (entry.getGeneralFields().length >= 1)) tabbed.addTab(Globals.lang("General fields"), new ImageIcon(GUIGlobals.showGenIconFile), genPanel.getPane(), Globals.lang("Show general fields")); tabbed.addTab(Globals.lang("Bibtex source"), new ImageIcon(GUIGlobals.sourceIconFile), srcPanel, Globals.lang("Show/edit bibtex source")); sourceIndex = tabbed.getTabCount()-1; // Set the sourceIndex variable. tabbed.addChangeListener(new TabListener()); add(tabbed, BorderLayout.CENTER); //Util.pr("opt: "+optW+" req:"+reqW); int prefHeight = (int)(Math.max(genW, Math.max(optW, reqW))*GUIGlobals.FORM_HEIGHT[prefs.getInt("entryTypeFormHeightFactor")]); setSize(GUIGlobals.FORM_WIDTH[prefs.getInt("entryTypeFormWidth")], prefHeight); if (prefs.getBoolean("defaultShowSource")) { tabbed.setSelectedIndex(sourceIndex); } } private void setupToolBar() { JToolBar tlb = new JToolBar(JToolBar.VERTICAL); tlb.setMargin(new Insets(2,2,2,2)); // The toolbar carries all the key bindings that are valid for the whole // window. tlb.setBackground(GUIGlobals.lightGray);//Color.white); ActionMap am = tlb.getActionMap(); InputMap im = tlb.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); im.put(GUIGlobals.exitDialog, "close"); am.put("close", closeAction); im.put(prefs.getKey("Entry editor: store field"), "store"); am.put("store", storeFieldAction); im.put(GUIGlobals.generateKeyStroke, "generateKey"); am.put("generateKey", generateKeyAction); im.put(prefs.getKey("Entry editor: previous panel"), "left"); am.put("left", switchLeftAction); im.put(prefs.getKey("Entry editor: next panel"), "right"); am.put("right", switchRightAction); im.put(prefs.getKey("Entry editor: previous entry"), "prev"); am.put("prev", prevEntryAction); im.put(prefs.getKey("Entry editor: next entry"), "next"); am.put("next", nextEntryAction); im.put(GUIGlobals.undoStroke, "undo"); am.put("undo", undoAction); im.put(GUIGlobals.redoStroke, "redo"); am.put("redo", redoAction); im.put(GUIGlobals.helpKeyStroke, "help"); am.put("help", helpAction); tlb.setFloatable(false); tlb.add(closeAction); //tlb.addSeparator(); //tlb.add(copyKeyAction); tlb.addSeparator(); tlb.add(generateKeyAction); tlb.addSeparator(); //tlb.add(undoAction); //tlb.add(redoAction); tlb.add(deleteAction); tlb.add(prevEntryAction); tlb.add(nextEntryAction); tlb.addSeparator(); tlb.add(helpAction); add(tlb, BorderLayout.WEST); } private void setupFieldPanels(FieldPanel req, FieldPanel opt, FieldPanel gen) { // First we ask the BibtexEntry which fields are optional and // required. String[] reqFields = entry.getRequiredFields(), optFields = entry.getOptionalFields(), // genFields = new String[] {"crossref", "url", "abstract", "comment"}; // May change... genFields = prefs.getStringArray("generalFields");//entry.getGeneralFields() ; if (reqFields == null) reqFields = new String[0]; if (optFields == null) optFields = new String[0]; if (genFields == null) genFields = new String[0]; int iter, rmax, omax, gmax; rmax = reqFields.length; omax = optFields.length; gmax = genFields.length; iter = Math.max(rmax, Math.max(omax, gmax)); FieldTextArea ta1 = null, ta2 = null, ta3 = null, firstR = null, firstO = null; JComponent ex1 = null, ex2 = null, ex3 = null; String stringContent; Object content; req.setLayout(gbl); opt.setLayout(gbl); gen.setLayout(gbl); con.insets = new Insets(5,5,0,0); con.anchor = GridBagConstraints.WEST; con.fill = GridBagConstraints.BOTH; FieldTextArea firstReq = null, firstOpt = null, firstGen = null; for (int i=0; i<iter; i++) { // Constraints for the labels. con.gridwidth = 1; con.weightx = 0; con.weighty = 0; //con.fill = GridBagConstraints.BOTH; if (i<rmax) { if ((content = entry.getField(reqFields[i])) != null) { stringContent = content.toString(); } else stringContent = null; ta1 = new FieldTextArea(reqFields[i], stringContent); ex1 = getExtra(reqFields[i], ta1); /*if (i == 0) firstReq = ta1; if ((i == rmax-1) && (firstReq != null)) ta1.setNextFocusableComponent(firstReq);*/ setupJTextComponent(ta1); if (i==0) { firstR = ta1; req.setActive(ta1); } } if (i<omax) { if ((content = entry.getField(optFields[i])) != null) { stringContent = content.toString(); } else stringContent = null; ta2 = new FieldTextArea(optFields[i], stringContent); ex2 = getExtra(optFields[i], ta2); /*if (i == 0) firstOpt = ta1; if (i == omax-1) ta1.setNextFocusableComponent(firstOpt);*/ setupJTextComponent(ta2); if (i==0) { firstO = ta2; opt.setActive(ta2); } } if (i<gmax) { if ((content = entry.getField(genFields[i])) != null) { stringContent = content.toString(); } else stringContent = null; ta3 = new FieldTextArea(genFields[i], stringContent); ex3 = getExtra(genFields[i], ta3); /*if (i == 0) firstGen = ta1; if (i == gmax-1) ta1.setNextFocusableComponent(firstGen);*/ setupJTextComponent(ta3); if (i==0) { firstO = ta3; gen.setActive(ta3); } } if (i<rmax) { gbl.setConstraints(ta1.getLabel(),con); req.add(ta1.getLabel()); } if (i<omax) { gbl.setConstraints(ta2.getLabel(),con); opt.add(ta2.getLabel()); } if (i<gmax) { gbl.setConstraints(ta3.getLabel(),con); gen.add(ta3.getLabel()); } // Constraints for the text fields. con.gridwidth = GridBagConstraints.REMAINDER; con.weightx = 1; //con.fill = GridBagConstraints.BOTH; if (i<rmax) { if (ex1 != null) con.gridwidth = 1; else con.gridwidth = GridBagConstraints.REMAINDER; con.weighty = GUIGlobals.getFieldWeight(reqFields[i]); reqW += con.weighty; //Util.pr(reqFields[i]+" "+con.weighty+""); gbl.setConstraints(ta1.getPane(),con); req.add(ta1.getPane()); if (ex1 != null) { con.gridwidth = GridBagConstraints.REMAINDER; con.weightx = 0; gbl.setConstraints(ex1, con); req.add(ex1); } } if (i<omax) { if (ex2 != null) con.gridwidth = 1; else con.gridwidth = GridBagConstraints.REMAINDER; con.weighty = GUIGlobals.getFieldWeight(optFields[i]); optW += con.weighty; gbl.setConstraints(ta2.getPane(),con); opt.add(ta2.getPane()); if (ex2 != null) { con.gridwidth = GridBagConstraints.REMAINDER; con.weightx = 0; gbl.setConstraints(ex2, con); opt.add(ex2); } } if (i<gmax) { if (ex3 != null) con.gridwidth = 1; else con.gridwidth = GridBagConstraints.REMAINDER; con.weighty = GUIGlobals.getFieldWeight(genFields[i]); genW += con.weighty; gbl.setConstraints(ta3.getPane(),con); gen.add(ta3.getPane()); if (ex3 != null) { con.gridwidth = GridBagConstraints.REMAINDER; con.weightx = 0; //con.weighty = 1; con.fill = GridBagConstraints.HORIZONTAL; con.anchor = GridBagConstraints.NORTH; gbl.setConstraints(ex3, con); gen.add(ex3); con.fill = GridBagConstraints.BOTH; con.anchor = GridBagConstraints.CENTER; } } } // Add the edit field for Bibtex-key. con.insets.top += 25; con.insets.bottom = 10; con.gridwidth = 1; con.weighty = 0; con.weightx = 0; con.anchor = GridBagConstraints.SOUTHWEST; con.fill = GridBagConstraints.NONE; tf = new FieldTextField(KEY_PROPERTY, (String)entry.getField(KEY_PROPERTY)); gbl.setConstraints(tf.getLabel(),con); req.add(tf.getLabel()); con.gridwidth = GridBagConstraints.REMAINDER; // con.anchor = GridBagConstraints.WEST; con.weightx = 1; con.fill = GridBagConstraints.HORIZONTAL; setupJTextComponent(tf); gbl.setConstraints(tf,con); req.add(tf); } /** * getExtra checks the field name against GUIGlobals.FIELD_EXTRAS. If the name * has an entry, the proper component to be shown is created and returned. * Otherwise, null is returned. * In addition, e.g. listeners can be added to the field editor, even if no * component is returned. * * @param string Field name * @return Component to show, or null if none. */ private JComponent getExtra(String string, FieldEditor editor) { final FieldEditor ed = editor; Object o = GUIGlobals.FIELD_EXTRAS.get(string); final String fieldName = editor.getFieldName(); if (o == null) return null; String s = (String)o; if (s.equals("external")) { // Add external viewer listener for "pdf" and "url" fields. ((JComponent)editor).addMouseListener(new ExternalViewerListener()); return null; } else if (s.equals("browse")) { JButton but = new JButton(Globals.lang("Browse")); ((JComponent)editor).addMouseListener(new ExternalViewerListener()); but.setBackground(GUIGlobals.lightGray); but.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JabRefFileChooser chooser = new JabRefFileChooser (new File(ed.getText())); if (ed.getText().equals("")) { chooser.setCurrentDirectory(new File(prefs.get(fieldName + Globals.FILETYPE_PREFS_EXT, ""))); } //chooser.addChoosableFileFilter(new OpenFileFilter()); //nb nov2 int returnVal = chooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File newFile = chooser.getSelectedFile(); ed.setText(newFile.getPath()); prefs.put(fieldName+Globals.FILETYPE_PREFS_EXT, newFile.getPath()); storeFieldAction.actionPerformed(new ActionEvent(ed, 0, "")); } } }); return but; } else return null; } private void setupSourcePanel() { source = new JTextArea(); con = new GridBagConstraints(); con.insets = new Insets(10,10,10,10); con.fill = GridBagConstraints.BOTH; con.gridwidth = GridBagConstraints.REMAINDER; con.gridheight = GridBagConstraints.REMAINDER; con.weightx = 1; con.weighty = 1; srcPanel.setLayout(gbl); source.setEditable(true);//prefs.getBoolean("enableSourceEditing")); source.setLineWrap(true); source.setTabSize(GUIGlobals.INDENT); setupJTextComponent(source); updateSource(); JScrollPane sp = new JScrollPane(source, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); gbl.setConstraints(sp, con); srcPanel.add(sp); } private void updateSource() { if (updateSource) { StringWriter sw = new StringWriter(200); try { entry.write(sw, new net.sf.jabref.export.LatexFieldFormatter()); String srcString = sw.getBuffer().toString(); source.setText(srcString); } catch (IOException ex) { source.setText("Error: "+ex.getMessage()+"\n\n" +"Correct the entry, and " +"reopen editor to display/edit source."); source.setEditable(false); } } } private void setupJTextComponent(JTextComponent ta) { // Activate autocompletion if it should be used for this field. /* if ((ta instanceof FieldTextArea) && (prefs.getBoolean("autoComplete"))) { FieldTextArea fta = (FieldTextArea)ta; Completer comp = baseFrame.getAutoCompleter(fta.getFieldName()); if (comp != null) fta.setAutoComplete(comp); } */ // Set up key bindings and focus listener for the FieldEditor. InputMap im = ta.getInputMap(JComponent.WHEN_FOCUSED); ActionMap am = ta.getActionMap(); //im.put(KeyStroke.getKeyStroke(GUIGlobals.closeKey), "close"); //am.put("close", closeAction); im.put(prefs.getKey("Entry editor: store field"), "store"); am.put("store", storeFieldAction); im.put(GUIGlobals.switchPanelLeft, "left"); am.put("left", switchLeftAction); im.put(GUIGlobals.switchPanelRight, "right"); am.put("right", switchRightAction); im.put(GUIGlobals.helpKeyStroke, "help"); am.put("help", helpAction); im.put(prefs.getKey("Save"), "save"); am.put("save", saveDatabaseAction); try{ int i = 0 ; HashSet keys = new HashSet(ta.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS)) ; keys.add(AWTKeyStroke.getAWTKeyStroke("pressed TAB")) ; ta.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, keys) ; keys = new HashSet(ta.getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS)) ; keys.add(KeyStroke.getKeyStroke("shift pressed TAB")) ; ta.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, keys) ; }catch(Throwable t){ System.err.println(t) ; } ta.addFocusListener(new FieldListener()); } public void requestFocus() { if (tabbed.getSelectedComponent() instanceof FieldPanel) ((FieldPanel)tabbed.getSelectedComponent()).activate(); else source.requestFocus(); } class FieldListener extends FocusAdapter { /* * Focus listener that fires the storeFieldAction when a FieldTextArea * loses focus. */ public void focusGained(FocusEvent e) { //Util.pr("Gained focus "+e.getSource().toString().substring(0,30)); if (e.getSource() instanceof FieldEditor) { FieldEditor ta = (FieldEditor)e.getSource(); Component parent = ta.getParent(); while (!(parent instanceof FieldPanel)) { parent = parent.getParent(); } ((FieldPanel)parent).setActive(ta); } else { // The source panel must have been chosen. Update it. if (panel.baseChanged) updateSource(); } } public void focusLost(FocusEvent e) { //Util.pr("Lost focus "+e.getSource().toString().substring(0,30)); if (!e.isTemporary()) { storeFieldAction.actionPerformed (new ActionEvent(e.getSource(), 0, "")); } } } class FieldPanel extends JPanel { /* * This extension to JPanel keeps a reference to its active * field, on behalf of which it requests the focus when * it is told to. */ public FieldPanel() { //setBackground(Color.white); } FieldEditor activeField = null; JScrollPane sp; public JComponent getPane() { return this; // Component to add. Return the scrollpane, if there is one. } public void setActive(FieldEditor c) { activeField = c; } public Vector getFields(){ Vector textFields = new Vector() ; Component[] components = this.getComponents() ; try{ for(int i = 0 ; i < components.length ; i++){ if(components[i] instanceof FieldEditor){ textFields.add(components[i]) ; } //else if ((components[i] instanceof JScrollPane)) { // Util.pr(((JScrollPane)components[i]).getViewport().getComponent(0).toString().substring(0,50)); else if (components[i] instanceof JScrollPane) { textFields.add(((JScrollPane)components[i]).getViewport() .getComponent(0)); } } return textFields ; }catch(ClassCastException cce){ System.err.println("caught in getFields: "+cce) ; } return null ; } public void activate() { if (activeField != null) activeField.requestFocus(); else tf.requestFocus(); } } class TabListener implements ChangeListener { public void stateChanged(ChangeEvent e) { if (((JTabbedPane)e.getSource()).getSelectedIndex() != sourceIndex) { FieldPanel fp = (FieldPanel)(((JTabbedPane)e.getSource()).getSelectedComponent()); fp.activate(); } else { source.requestFocus(); } } } class DeleteAction extends AbstractAction { public DeleteAction() { super(Globals.lang("Delete"), new ImageIcon(GUIGlobals.removeIconFile)); putValue(SHORT_DESCRIPTION, Globals.lang("Delete")+" "+Globals.lang("entry")); } public void actionPerformed(ActionEvent e) { panel.hideEntryEditor(); panel.database.removeEntry(entry.getId()); panel.markBaseChanged(); panel.refreshTable(); panel.undoManager.addEdit(new UndoableRemoveEntry(panel.database, entry, panel)); panel.output(Globals.lang("Deleted")+" "+Globals.lang("entry")); } } class CloseAction extends AbstractAction { public CloseAction() { super(Globals.lang("Close window"), new ImageIcon(GUIGlobals.closeIconFile)); putValue(SHORT_DESCRIPTION, Globals.lang("Close window")); } public void actionPerformed(ActionEvent e) { if (tabbed.getSelectedComponent() == srcPanel) { storeFieldAction.actionPerformed(new ActionEvent(source, 0, "")); if (lastSourceAccepted) { panel.entryTypeFormClosing(entry.getId()); panel.hideEntryEditor(); } } else { panel.entryTypeFormClosing(entry.getId()); panel.hideEntryEditor(); } } } class CopyKeyAction extends AbstractAction { public CopyKeyAction() { super("Copy BibTeX key to clipboard", new ImageIcon(GUIGlobals.copyKeyIconFile)); putValue(SHORT_DESCRIPTION, "Copy BibTeX key to clipboard (Ctrl-K)"); //putValue(MNEMONIC_KEY, GUIGlobals.copyKeyCode); } public void actionPerformed(ActionEvent e) { String s = (String)(entry.getField(KEY_PROPERTY)); StringSelection ss = new StringSelection(s); if (s != null) { Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss,ss); } } } class StoreFieldAction extends AbstractAction { public StoreFieldAction() { super("Store field value"); putValue(SHORT_DESCRIPTION, "Store field value"); } public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof FieldTextArea) { String toSet = null, fieldName = null; FieldEditor fe = (FieldEditor)e.getSource(); boolean set; if (fe.getText().length() > 0) toSet = fe.getText(); // We check if the field has changed, since we don't want to mark the // base as changed unless we have a real change. if (toSet == null) { if (entry.getField(fe.getFieldName()) == null) set = false; else set = true; } else { if ((entry.getField(fe.getFieldName()) != null) && toSet.equals(entry.getField(fe.getFieldName()).toString())) set = false; else set = true; } if (set) try { // The following statement attempts to write the // new contents into a StringWriter, and this will // cause an IOException if the field is not // properly formatted. If that happens, the field // is not stored and the textarea turns red. if (toSet != null) (new LatexFieldFormatter()).format (toSet, GUIGlobals.isStandardField(fe.getFieldName())); Object oldValue = entry.getField(fe.getFieldName()); entry.setField(fe.getFieldName(), toSet); if ((toSet != null) && (toSet.length() > 0)) { fe.setLabelColor(GUIGlobals.validFieldColor); fe.setBackground(GUIGlobals.validFieldBackground); } else { fe.setLabelColor(GUIGlobals.nullFieldColor); fe.setBackground(GUIGlobals.validFieldBackground); } // Add an UndoableFieldChange to the baseframe's undoManager. panel.undoManager.addEdit (new UndoableFieldChange(entry, fe.getFieldName(), oldValue, toSet)); updateSource(); panel.refreshTable(); panel.markBaseChanged(); } catch (IllegalArgumentException ex) { frame.output("Invalid field format: "+ex.getMessage()); fe.setLabelColor(GUIGlobals.invalidFieldColor); fe.setBackground(GUIGlobals.invalidFieldBackground); } /*catch (java.io.IOException ex2) { fe.setLabelColor(GUIGlobals.invalidFieldColor); fe.setBackground(GUIGlobals.invalidFieldBackground); }*/ else { // set == false // We set the field and label color. fe.setBackground(GUIGlobals.validFieldBackground); fe.setLabelColor((toSet == null) ? GUIGlobals.nullFieldColor : GUIGlobals.validFieldColor); } } else if (e.getSource() instanceof FieldTextField) { // Storage from bibtex key field. FieldTextField fe = (FieldTextField)e.getSource(); String oldValue = entry.getCiteKey(), newValue = fe.getText(); if (((oldValue == null) && (newValue == null)) || ((oldValue != null) && (newValue != null) && oldValue.equals(newValue))) return; // No change. boolean isDuplicate = panel.database.setCiteKeyForEntry (entry.getId(), newValue); if (isDuplicate) panel.output(Globals.lang("Warning: duplicate bibtex key.")); else panel.output(Globals.lang("Bibtex key is unique.")); // Add an UndoableKeyChange to the baseframe's undoManager. panel.undoManager.addEdit (new UndoableKeyChange(panel.database, entry.getId(), oldValue, newValue)); if ((newValue != null) && (newValue.length() > 0)) { fe.setLabelColor(GUIGlobals.validFieldColor); fe.setBackground(GUIGlobals.validFieldBackground); } else { fe.setLabelColor(GUIGlobals.nullFieldColor); fe.setBackground(GUIGlobals.validFieldBackground); } panel.refreshTable(); panel.markBaseChanged(); } else if ((source.isEditable()) && (source.getText() != lastSourceStringAccepted)) { // Store edited bibtex code. BibtexParser bp = new BibtexParser (new java.io.StringReader(source.getText())); try { BibtexDatabase db = bp.parse().getDatabase(); if (db.getEntryCount() > 1) throw new Exception("More than one entry found."); if (db.getEntryCount() < 1) throw new Exception("No entries found."); NamedCompound compound = new NamedCompound("source edit"); BibtexEntry nu = db.getEntryById ((String)db.getKeySet().iterator().next()); String id = entry.getId(), oldKey = entry.getCiteKey(), newKey = nu.getCiteKey(); boolean anyChanged = false, duplicateWarning = false; if (panel.database.setCiteKeyForEntry(id, newKey)) duplicateWarning = true; // First, remove fields that the user have removed. Object[] fields = entry.getAllFields(); for (int i=0; i<fields.length; i++) if (GUIGlobals.isWriteableField(fields[i].toString())) if (nu.getField(fields[i].toString()) == null) { compound.addEdit(new UndoableFieldChange (entry, fields[i].toString(), entry.getField(fields[i].toString()), (Object)null)); entry.setField(fields[i].toString(), null); anyChanged = true; } // Then set all fields that have been set by the user. fields = nu.getAllFields(); for (int i=0; i<fields.length; i++) if (entry.getField(fields[i].toString()) != nu.getField(fields[i].toString())) { compound.addEdit (new UndoableFieldChange (entry, fields[i].toString(), entry.getField(fields[i].toString()), nu.getField(fields[i].toString()))); entry.setField(fields[i].toString(), nu.getField(fields[i].toString())); anyChanged = true; } compound.end(); if (!anyChanged) return; panel.undoManager.addEdit(compound); /*if (((oldKey == null) && (newKey != null)) || ((oldKey != null) && (newKey == null)) || ((oldKey != null) && (newKey != null) && !oldKey.equals(newKey))) { } */ if (duplicateWarning) panel.output(Globals.lang("Warning: duplicate bibtex key.")); else panel.output(Globals.lang("Stored entry.")); lastSourceStringAccepted = source.getText(); updateAllFields(); lastSourceAccepted = true; updateSource = true; panel.refreshTable(); panel.markBaseChanged(); } catch (Throwable ex) { // The source couldn't be parsed, so the user is given an // error message, and the choice to keep or revert the contents // of the source text field. updateSource = false; lastSourceAccepted = false; tabbed.setSelectedComponent(srcPanel); Object[] options = { "Edit","Revert to original source" }; int answer = JOptionPane.showOptionDialog (frame, "Error: "+ex.getMessage(), "Problem with parsing entry", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE,null, options,options[0]); if (answer == 0) { //updateSource = true; } else { updateSource = true; updateSource(); } } } } } class SwitchLeftAction extends AbstractAction { public SwitchLeftAction() { super("Switch to the panel to the left"); } public void actionPerformed(ActionEvent e) { int i = tabbed.getSelectedIndex(); tabbed.setSelectedIndex((i>0 ? i-1 : tabbed.getTabCount()-1)); if (tabbed.getSelectedComponent() instanceof FieldPanel) ((FieldPanel)tabbed.getSelectedComponent()).activate(); // Set focus to the last used textfield. } } class SwitchRightAction extends AbstractAction { public SwitchRightAction() { super("Switch to the panel to the right"); } public void actionPerformed(ActionEvent e) { int i = tabbed.getSelectedIndex(); tabbed.setSelectedIndex(i<tabbed.getTabCount()-1 ? i+1 : 0); if (tabbed.getSelectedComponent() instanceof FieldPanel) ((FieldPanel)tabbed.getSelectedComponent()).activate(); // Set focus to the last used textfield. } } /* class ShowReqAction extends AbstractAction { public ShowReqAction() { super("Show required", new ImageIcon(GUIGlobals.showReqIconFile)); putValue(SHORT_DESCRIPTION, "Show required fields"); putValue(MNEMONIC_KEY, GUIGlobals.showReqKeyCode); } public void actionPerformed(ActionEvent e) { //System.out.println("Show required fields"); tabbed.setSelectedIndex(REQ); reqPanel.activate(); // Set focus to the last used textfield. } } class ShowOptAction extends AbstractAction { public ShowOptAction() { super("Show optional", new ImageIcon(GUIGlobals.showOptIconFile)); putValue(SHORT_DESCRIPTION, "Show optional fields"); putValue(MNEMONIC_KEY, GUIGlobals.showOptKeyCode); } public void actionPerformed(ActionEvent e) { tabbed.setSelectedIndex(OPT); optPanel.activate(); // Set focus to the last used textfield. } } class ShowGenAction extends AbstractAction { public ShowGenAction() { super("Show general", new ImageIcon(GUIGlobals.showGenIconFile)); putValue(SHORT_DESCRIPTION, "Show general fields"); putValue(MNEMONIC_KEY, GUIGlobals.showGenKeyCode); } public void actionPerformed(ActionEvent e) { tabbed.setSelectedIndex(GEN); genPanel.activate(); // Set focus to the last used textfield. } } */ class NextEntryAction extends AbstractAction { public NextEntryAction() { super(Globals.lang("Next entry"), new ImageIcon(GUIGlobals.downIconFile)); putValue(SHORT_DESCRIPTION, Globals.lang("Next entry")); } public void actionPerformed(ActionEvent e) { int thisRow = panel.tableModel .getNumberFromName(entry.getId()); String id = null; int newRow = -1; if (thisRow+1 < panel.database.getEntryCount()) newRow = thisRow+1; else if (thisRow > 0) newRow = 0; else return; // newRow is still -1, so we can assume the database // has only one entry. id = panel.tableModel.getNameFromNumber(newRow); switchTo(id); final int nr = newRow; (new Thread() { public void run() { scrollTo(nr); } }).start(); } } class PrevEntryAction extends AbstractAction { public PrevEntryAction() { super(Globals.lang("Previous entry"), new ImageIcon(GUIGlobals.upIconFile)); putValue(SHORT_DESCRIPTION, Globals.lang("Previous entry")); } public void actionPerformed(ActionEvent e) { int thisRow = panel.tableModel .getNumberFromName(entry.getId()); String id = null; int newRow = -1; if (thisRow-1 >= 0) newRow = thisRow-1; else if (thisRow != panel.database.getEntryCount()-1) newRow = panel.database.getEntryCount()-1; else return; // newRow is still -1, so we can assume the database // has only one entry. id = panel.tableModel .getNameFromNumber(newRow); switchTo(id); final int nr = newRow; (new Thread() { public void run() { scrollTo(nr); } }).start(); } }; /** * Centers the given row, and highlights it. * * @param row an <code>int</code> value */ private void scrollTo(int row) { panel.entryTable.scrollToCenter(row, 0); panel.entryTable.setRowSelectionInterval(row, row); panel.entryTable.setColumnSelectionInterval (0, panel.entryTable.getColumnCount()-1); } /** * Switches the entry for this editor to the one with the given * id. If the target entry is of the same type as the current, * field values are simply updated. Otherwise, a new editor * created to replace this one. * * @param id a <code>String</code> value */ private void switchTo(String id) { BibtexEntry be = panel.database.getEntryById(id); // If the entry we are switching to is of the same type as // this one, we can make the switch more elegant by keeping this // same dialog, and updating it. if (entry.getType() == be.getType()) { switchTo(be); } else { panel.showEntry(be); } } /** * Returns the index of the active (visible) panel. * * @return an <code>int</code> value */ public int getVisiblePanel() { return tabbed.getSelectedIndex(); } /** * Sets the panel with the given index visible. * * @param i an <code>int</code> value */ public void setVisiblePanel(int i) { if (i < tabbed.getTabCount()) tabbed.setSelectedIndex(i); else { while (i >= tabbed.getTabCount()) i tabbed.setSelectedIndex(i); } } /** * Updates this editor to show the given entry, regardless of * type correspondence. * * @param be a <code>BibtexEntry</code> value */ public void switchTo(BibtexEntry be) { entry = be; updateAllFields(); updateSource(); if (tabbed.getSelectedComponent() instanceof FieldPanel) ((FieldPanel)tabbed.getSelectedComponent()).activate(); else ((JComponent)tabbed.getSelectedComponent()).requestFocus(); } class GenerateKeyAction extends AbstractAction { JabRefFrame parent ; BibtexEntry selectedEntry ; public GenerateKeyAction(JabRefFrame parentFrame) { super("Generate Bibtexkey", new ImageIcon(GUIGlobals.genKeyIconFile)); parent = parentFrame ; // selectedEntry = newEntry ; putValue(SHORT_DESCRIPTION, "Generate Bibtexkey (Ctrl-G)"); // putValue(MNEMONIC_KEY, GUIGlobals.showGenKeyCode); } public void actionPerformed(ActionEvent e) { // 1. get Bitexentry for selected index (already have) // 2. run the LabelMaker by it try { // this updates the table automatically, on close, but not within the tab Object oldValue = entry.getField(GUIGlobals.KEY_FIELD); entry = frame.labelMaker.applyRule(entry, panel.database) ; // Store undo information: panel.undoManager.addEdit(new UndoableFieldChange (entry, GUIGlobals.KEY_FIELD, oldValue, entry.getField(GUIGlobals.KEY_FIELD))); // here we update the field String bibtexKeyData = (String) entry.getField (Globals.KEY_FIELD) ; // set the field named for "bibtexkey" setField(Globals.KEY_FIELD, bibtexKeyData) ; panel.markBaseChanged(); panel.refreshTable(); } catch (Throwable t){ System.err.println("error setting key: " +t) ; } } } UndoAction undoAction = new UndoAction(); class UndoAction extends AbstractAction { public UndoAction() { super("Undo", new ImageIcon(GUIGlobals.undoIconFile)); putValue(SHORT_DESCRIPTION, "Undo"); } public void actionPerformed(ActionEvent e) { panel.runCommand("undo"); } } RedoAction redoAction = new RedoAction(); class RedoAction extends AbstractAction { public RedoAction() { super("Undo", new ImageIcon(GUIGlobals.redoIconFile)); putValue(SHORT_DESCRIPTION, "Redo"); } public void actionPerformed(ActionEvent e) { panel.runCommand("redo"); } } class SaveDatabaseAction extends AbstractAction { public SaveDatabaseAction() { super("Save database"); } public void actionPerformed(ActionEvent e) { Object comp = tabbed.getSelectedComponent(); if (comp instanceof FieldPanel) { // Normal panel. FieldPanel fp = (FieldPanel)comp; storeFieldAction.actionPerformed(new ActionEvent(fp.activeField, 0,"")); } else { // Source panel. storeFieldAction.actionPerformed(new ActionEvent(comp, 0,"")); } panel.runCommand("save"); } } public boolean setField(String fieldName, String newFieldData){ // iterate through all tabs and fields within those tabs until we get // the appropriate field name. // Thanks to reflection, this shouldn't be too bad // search each panel individually try{ if (setFieldInPanel(reqPanel, fieldName, newFieldData)) return true; if (setFieldInPanel(optPanel, fieldName, newFieldData)) return true; if (setFieldInPanel(genPanel, fieldName, newFieldData)) return true; }catch(ClassCastException cce){ System.err.println("caught in setField: "+cce) ; return false ; } return false ; } private boolean setFieldInPanel(FieldPanel pan, String fieldName, String newFieldData) throws ClassCastException { Vector fields = pan.getFields() ; for(int i = 0 ; i < fields.size() ; i++){ if(((FieldEditor) fields.elementAt(i)).getFieldName().equals(fieldName)){ FieldEditor ed = ((FieldEditor) fields.elementAt(i)); ed.setText(newFieldData) ; ed.setLabelColor(((newFieldData == null) || newFieldData.equals("")) ? GUIGlobals.nullFieldColor : GUIGlobals.validFieldColor); return true ; } } return false; // Nothing found. } private void updateAllFields() { FieldPanel[] panels = new FieldPanel[] {reqPanel, optPanel, genPanel}; for (int i=0; i<panels.length; i++) { Vector fields = panels[i].getFields(); for (int j=0; j<fields.size(); j++) { FieldEditor ed = (FieldEditor)fields.elementAt(j); Object content = entry.getField(ed.getFieldName()); ed.setText(content == null ? "" : content.toString()); ed.setLabelColor(content == null ? GUIGlobals.nullFieldColor : GUIGlobals.validFieldColor); //if (ed.getFieldName().equals("year")) // Util.pr(content.toString()); } } } // Update the JTextArea when a field has changed. public void vetoableChange(PropertyChangeEvent e) { setField(e.getPropertyName(), (String)(e.getNewValue())); //Util.pr(e.getPropertyName()); } class ExternalViewerListener extends MouseAdapter { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { JTextComponent tf = (JTextComponent)evt.getSource(); if (tf.getText().equals("")) return; tf.selectAll(); String link = tf.getText(); // get selected ? String getSelectedText() // check html first since browser can invoke viewers if(link.substring(0,7).equals("http://")){ // hml try { System.err.println("Message: Opening url (" + link + ") with the HTML viewer (" + prefs.get("htmlviewer") +")"); Process child = Runtime.getRuntime() .exec(prefs.get("htmlviewer") + " " + link.replaceAll(" ","\\ ")); } catch (IOException e) { System.err.println("Warning: Unable to open url " + link + " with the HTML viewer (" + prefs.get("htmlviewer") +")"); } } else if(link.endsWith(".ps")){ try { System.err.println("Message: Opening file " + link + " with the ps viewer (" + prefs.get("psviewer") +")"); Process child = Runtime.getRuntime().exec(prefs.get("psviewer") + " " + link); } catch (IOException e) { System.err.println("Warning: Unable to open file (" + link + ") with the postscipt viewer (" + prefs.get("psviewer") +")"); } }else if(link.endsWith(".pdf")){ try { System.err.println("Message: Opening file (" + link + ") with the pdf viewer (" + prefs.get("pdfviewer") +")"); Process child = Runtime.getRuntime().exec(prefs.get("pdfviewer") + " " + link); } catch (IOException e) { System.err.println("Warning: Unable to open file " + link + " with the pdf viewer (" + prefs.get("pdfviewer") +")"); } } else{ System.err.println("Message: currently only pdf, ps and HTML files can be opened by double clicking"); //ignore } } } } }
package net.xisberto.work_schedule; import net.xisberto.work_schedule.Settings.Period; import android.content.Context; import android.database.DataSetObserver; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.ListAdapter; import android.widget.TextView; public class PeriodListAdapter implements ListAdapter { Context context; private SparseArray<Period> list; public PeriodListAdapter(Context context, SparseArray<Period> periods) { this.context = context; list = periods; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.valueAt(position); } @Override public long getItemId(int position) { return (Integer) list.keyAt(position); } @Override public int getItemViewType(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.period_list_item, null); } final Period period = (Period) getItem(position); final Settings settings = new Settings(context); final String period_pref_key = context.getString(period.pref_id); ((TextView) view.findViewById(R.id.period_label)).setText(context .getString(period.label_id)); ((TextView) view.findViewById(R.id.period_time)).setText(settings .formatCalendar(settings.getCalendar(period_pref_key))); CheckBox check_alarm = (CheckBox) view.findViewById(R.id.check_alarm); check_alarm.setChecked(settings.isAlarmSet(period.pref_id)); check_alarm.setOnClickListener(new OnClickListener() { @Override public void onClick(View check_box) { settings.setAlarm(period, settings.getCalendar(period_pref_key), ((CheckBox) check_box).isChecked()); } }); return view; } @Override public int getViewTypeCount() { return 1; } @Override public boolean hasStableIds() { return true; } @Override public boolean isEmpty() { return getCount() == 0; } @Override public void registerDataSetObserver(DataSetObserver arg0) { // TODO Auto-generated method stub } @Override public void unregisterDataSetObserver(DataSetObserver arg0) { // TODO Auto-generated method stub } @Override public boolean areAllItemsEnabled() { return true; } @Override public boolean isEnabled(int position) { return true; } }
package net.sf.samtools; import net.sf.samtools.util.StringUtil; import java.util.*; public class SAMRecord implements Cloneable { /** * Alignment score for a good alignment, but where computing a Phred-score is not feasible. */ public static final int UNKNOWN_MAPPING_QUALITY = 255; /** * Alignment score for an unaligned read. */ public static final int NO_MAPPING_QUALITY = 0; /** * If a read has this reference name, it is unaligned, but not all unaligned reads have * this reference name (see above). */ public static final String NO_ALIGNMENT_REFERENCE_NAME = "*"; /** * If a read has this reference index, it is unaligned, but not all unaligned reads have * this reference index (see above). */ public static final int NO_ALIGNMENT_REFERENCE_INDEX = -1; /** * Cigar string for an unaligned read. */ public static final String NO_ALIGNMENT_CIGAR = "*"; /** * If a read has reference name "*", it will have this value for position. */ public static final int NO_ALIGNMENT_START = 0; /** * This should rarely be used, since a read with no sequence doesn't make much sense. */ public static final byte[] NULL_SEQUENCE = new byte[0]; public static final String NULL_SEQUENCE_STRING = "*"; /** * This should rarely be used, since all reads should have quality scores. */ public static final byte[] NULL_QUALS = new byte[0]; public static final String NULL_QUALS_STRING = "*"; /** * abs(insertSize) must be <= this */ public static final int MAX_INSERT_SIZE = 1<<29; /** * It is not necessary in general to use the flag constants, because there are getters * & setters that handles these symbolically. */ private static final int READ_PAIRED_FLAG = 0x1; private static final int PROPER_PAIR_FLAG = 0x2; private static final int READ_UNMAPPED_FLAG = 0x4; private static final int MATE_UNMAPPED_FLAG = 0x8; private static final int READ_STRAND_FLAG = 0x10; private static final int MATE_STRAND_FLAG = 0x20; private static final int FIRST_OF_PAIR_FLAG = 0x40; private static final int SECOND_OF_PAIR_FLAG = 0x80; private static final int NOT_PRIMARY_ALIGNMENT_FLAG = 0x100; private static final int READ_FAILS_VENDOR_QUALITY_CHECK_FLAG = 0x200; private static final int DUPLICATE_READ_FLAG = 0x400; private String mReadName = null; private byte[] mReadBases = NULL_SEQUENCE; private byte[] mBaseQualities = NULL_QUALS; private String mReferenceName = NO_ALIGNMENT_REFERENCE_NAME; private int mAlignmentStart = NO_ALIGNMENT_START; private transient int mAlignmentEnd = NO_ALIGNMENT_START; private int mMappingQuality = NO_MAPPING_QUALITY; private String mCigarString = NO_ALIGNMENT_CIGAR; private Cigar mCigar = null; private List<AlignmentBlock> mAlignmentBlocks = null; private int mFlags = 0; private String mMateReferenceName = NO_ALIGNMENT_REFERENCE_NAME; private int mMateAlignmentStart = 0; private int mInferredInsertSize = 0; private List<SAMBinaryTagAndValue> mAttributes = null; private Integer mReferenceIndex = null; private Integer mMateReferenceIndex = null; private Integer mIndexingBin = null; /** * Some attributes (e.g. CIGAR) are not decoded immediately. Use this to decide how to validate when decoded. */ private SAMFileReader.ValidationStringency mValidationStringency = SAMFileReader.ValidationStringency.SILENT; private SAMFileHeader mHeader = null; public SAMRecord(final SAMFileHeader header) { mHeader = header; } public String getReadName() { return mReadName; } /** * This method is preferred over getReadName().length(), because for BAMRecord * it may be faster. * @return length not including a null terminator. */ public int getReadNameLength() { return mReadName.length(); } public void setReadName(final String value) { mReadName = value; } /** * @return read sequence as a string of ACGTN=. */ public String getReadString() { final byte[] readBases = getReadBases(); if (readBases.length == 0) { return NULL_SEQUENCE_STRING; } return StringUtil.bytesToString(readBases); } public void setReadString(final String value) { if (NULL_SEQUENCE_STRING.equals(value)) { mReadBases = NULL_SEQUENCE; } else { final byte[] bases = StringUtil.stringToBytes(value); SAMUtils.normalizeBases(bases); mReadBases = bases; } } /** * Do not modify the value returned by this method. If you want to change the bases, create a new * byte[] and call setReadBases() or call setReadString(). * @return read sequence as ASCII bytes ACGTN=. */ public byte[] getReadBases() { return mReadBases; } public void setReadBases(final byte[] value) { mReadBases = value; } /** * This method is preferred over getReadBases().length, because for BAMRecord it may be faster. * @return number of bases in the read. */ public int getReadLength() { return getReadBases().length; } /** * @return Base qualities, encoded as a FASTQ string. */ public String getBaseQualityString() { if (Arrays.equals(NULL_QUALS, getBaseQualities())) { return NULL_QUALS_STRING; } return SAMUtils.phredToFastq(getBaseQualities()); } public void setBaseQualityString(final String value) { if (NULL_QUALS_STRING.equals(value)) { setBaseQualities(NULL_QUALS); } else { setBaseQualities(SAMUtils.fastqToPhred(value)); } } /** * Do not modify the value returned by this method. If you want to change the qualities, create a new * byte[] and call setBaseQualities() or call setBaseQualityString(). * @return Base qualities, as binary phred scores (not ASCII). */ public byte[] getBaseQualities() { return mBaseQualities; } public void setBaseQualities(final byte[] value) { mBaseQualities = value; } private static boolean hasReferenceName(final Integer referenceIndex, final String referenceName) { return (referenceIndex != null && referenceIndex != NO_ALIGNMENT_REFERENCE_INDEX) || !NO_ALIGNMENT_REFERENCE_NAME.equals(referenceName); } /** * @return true if this SAMRecord has a reference, either as a String or index (or both). */ private boolean hasReferenceName() { return hasReferenceName(mReferenceIndex, mReferenceName); } /** * @return true if this SAMRecord has a mate reference, either as a String or index (or both). */ private boolean hasMateReferenceName() { return hasReferenceName(mMateReferenceIndex, mMateReferenceName); } /** * @return Reference name, or null if record has no reference. */ public String getReferenceName() { return mReferenceName; } public void setReferenceName(final String value) { mReferenceName = value; mReferenceIndex = null; } /** * @return index of the reference sequence for this read in the sequence dictionary, or -1 * if read has no reference sequence set, or if a String reference name is not found in the sequence index.. */ public Integer getReferenceIndex() { if (mReferenceIndex == null) { if (mReferenceName == null) { mReferenceIndex = NO_ALIGNMENT_REFERENCE_INDEX; } else if (NO_ALIGNMENT_REFERENCE_NAME.equals(mReferenceName)) { mReferenceIndex = NO_ALIGNMENT_REFERENCE_INDEX; } else { mReferenceIndex = mHeader.getSequenceIndex(mReferenceName); } } return mReferenceIndex; } /** * @param referenceIndex Must either equal -1 (indicating no reference), or exist in the sequence dictionary * in the header associated with this record. */ public void setReferenceIndex(final int referenceIndex) { mReferenceIndex = referenceIndex; if (mReferenceIndex == NO_ALIGNMENT_REFERENCE_INDEX) { mReferenceName = NO_ALIGNMENT_REFERENCE_NAME; } else { mReferenceName = mHeader.getSequence(referenceIndex).getSequenceName(); } } /** * @return Mate reference name, or null if one is not assigned. */ public String getMateReferenceName() { return mMateReferenceName; } public void setMateReferenceName(final String mateReferenceName) { this.mMateReferenceName = mateReferenceName; mMateReferenceIndex = null; } /** * @return index of the reference sequence for this read's mate in the sequence dictionary, or -1 * if mate has no reference sequence set. */ public Integer getMateReferenceIndex() { if (mMateReferenceIndex == null) { if (mMateReferenceName == null) { mMateReferenceIndex = NO_ALIGNMENT_REFERENCE_INDEX; } else if (NO_ALIGNMENT_REFERENCE_NAME.equals(mMateReferenceName)){ mMateReferenceIndex = NO_ALIGNMENT_REFERENCE_INDEX; } else { mMateReferenceIndex = mHeader.getSequenceIndex(mMateReferenceName); } } return mMateReferenceIndex; } /** * @param referenceIndex Must either equal -1 (indicating no reference), or exist in the sequence dictionary * in the header associated with this record. */ public void setMateReferenceIndex(final int referenceIndex) { mMateReferenceIndex = referenceIndex; if (mMateReferenceIndex == NO_ALIGNMENT_REFERENCE_INDEX) { mMateReferenceName = NO_ALIGNMENT_REFERENCE_NAME; } else { mMateReferenceName = mHeader.getSequence(referenceIndex).getSequenceName(); } } /** * @return 1-based inclusive leftmost position of the clippped sequence, or 0 if there is no position. */ public int getAlignmentStart() { return mAlignmentStart; } /** * @param value 1-based inclusive leftmost position of the clippped sequence, or 0 if there is no position. */ public void setAlignmentStart(final int value) { mAlignmentStart = value; // Clear cached alignment end mAlignmentEnd = NO_ALIGNMENT_START; // Change to alignmentStart could change indexing bin setIndexingBin(null); } /** * @return 1-based inclusive rightmost position of the clippped sequence, or -1 read if unmapped. */ public int getAlignmentEnd() { if (getReadUnmappedFlag()) { return NO_ALIGNMENT_START; } else if (this.mAlignmentEnd == NO_ALIGNMENT_START) { this.mAlignmentEnd = mAlignmentStart + getCigar().getReferenceLength() - 1; } return this.mAlignmentEnd; } /** * @return the alignment start (1-based, inclusive) adjusted for clipped bases. For example if the read * has an alignment start of 100 but the first 4 bases were clipped (hard or soft clipped) * then this method will return 96. * * Invalid to call on an unmapped read. */ public int getUnclippedStart() { int pos = getAlignmentStart(); for (final CigarElement cig : getCigar().getCigarElements()) { final CigarOperator op = cig.getOperator(); if (op == CigarOperator.SOFT_CLIP || op == CigarOperator.HARD_CLIP) { pos -= cig.getLength(); } else { break; } } return pos; } /** * @return the alignment end (1-based, inclusive) adjusted for clipped bases. For example if the read * has an alignment end of 100 but the last 7 bases were clipped (hard or soft clipped) * then this method will return 107. * * Invalid to call on an unmapped read. */ public int getUnclippedEnd() { int pos = getAlignmentEnd(); final List<CigarElement> cigs = getCigar().getCigarElements(); for (int i=cigs.size() - 1; i>=0; --i) { final CigarElement cig = cigs.get(i); final CigarOperator op = cig.getOperator(); if (op == CigarOperator.SOFT_CLIP || op == CigarOperator.HARD_CLIP) { pos += cig.getLength(); } else { break; } } return pos; } /** * Unsupported. This property is derived from alignment start and CIGAR. */ public void setAlignmentEnd(final int value) { throw new UnsupportedOperationException("Not supported: setAlignmentEnd"); } /** * @return 1-based inclusive leftmost position of the clippped mate sequence, or 0 if there is no position. */ public int getMateAlignmentStart() { return mMateAlignmentStart; } public void setMateAlignmentStart(final int mateAlignmentStart) { this.mMateAlignmentStart = mateAlignmentStart; } /** * @return insert size (difference btw 5' end of read & 5' end of mate), if possible, else 0. * Negative if mate maps to lower position than read. */ public int getInferredInsertSize() { return mInferredInsertSize; } public void setInferredInsertSize(final int inferredInsertSize) { this.mInferredInsertSize = inferredInsertSize; } /** * @return phred scaled mapping quality. 255 implies valid mapping but quality is hard to compute. */ public int getMappingQuality() { return mMappingQuality; } public void setMappingQuality(final int value) { mMappingQuality = value; } public String getCigarString() { if (mCigarString == null && getCigar() != null) { mCigarString = TextCigarCodec.getSingleton().encode(getCigar()); } return mCigarString; } public void setCigarString(final String value) { mCigarString = value; mCigar = null; mAlignmentBlocks = null; // Clear cached alignment end mAlignmentEnd = NO_ALIGNMENT_START; // Change to cigar could change alignmentEnd, and thus indexing bin setIndexingBin(null); } /** * Do not modify the value returned by this method. If you want to change the Cigar, create a new * Cigar and call setCigar() or call setCigarString() * @return Cigar object for the read, or null if there is none. */ public Cigar getCigar() { if (mCigar == null && mCigarString != null) { mCigar = TextCigarCodec.getSingleton().decode(mCigarString); if (getValidationStringency() != SAMFileReader.ValidationStringency.SILENT && !this.getReadUnmappedFlag()) { // Don't know line number, and don't want to force read name to be decoded. SAMUtils.processValidationErrors(mCigar.isValid(mReadName, -1L), -1L, getValidationStringency()); } } return mCigar; } /** * This method is preferred over getCigar().getNumElements(), because for BAMRecord it may be faster. * @return number of cigar elements (number + operator) in the cigar string. */ public int getCigarLength() { return getCigar().numCigarElements(); } public void setCigar(final Cigar cigar) { initializeCigar(cigar); // Change to cigar could change alignmentEnd, and thus indexing bin setIndexingBin(null); } /** * For setting the Cigar string when BAMRecord has decoded it. Use this rather than setCigar() * so that indexing bin doesn't get clobbered. */ protected void initializeCigar(final Cigar cigar) { this.mCigar = cigar; mCigarString = null; mAlignmentBlocks = null; // Clear cached alignment end mAlignmentEnd = NO_ALIGNMENT_START; } /** * It is preferrable to use the get*Flag() methods that handle the flag word symbolically. */ public int getFlags() { return mFlags; } public void setFlags(final int value) { mFlags = value; // Could imply change to readUnmapped flag, which could change indexing bin setIndexingBin(null); } /** * the read is paired in sequencing, no matter whether it is mapped in a pair. */ public boolean getReadPairedFlag() { return (mFlags & READ_PAIRED_FLAG) != 0; } private void requireReadPaired() { if (!getReadPairedFlag()) { throw new IllegalStateException("Inappropriate call if not paired read"); } } /** * the read is mapped in a proper pair (depends on the protocol, normally inferred during alignment). */ public boolean getProperPairFlag() { requireReadPaired(); return getProperPairFlagUnchecked(); } private boolean getProperPairFlagUnchecked() { return (mFlags & PROPER_PAIR_FLAG) != 0; } /** * the query sequence itself is unmapped. */ public boolean getReadUnmappedFlag() { return (mFlags & READ_UNMAPPED_FLAG) != 0; } /** * the mate is unmapped. */ public boolean getMateUnmappedFlag() { requireReadPaired(); return getMateUnmappedFlagUnchecked(); } private boolean getMateUnmappedFlagUnchecked() { return (mFlags & MATE_UNMAPPED_FLAG) != 0; } /** * strand of the query (false for forward; true for reverse strand). */ public boolean getReadNegativeStrandFlag() { return (mFlags & READ_STRAND_FLAG) != 0; } /** * strand of the mate (false for forward; true for reverse strand). */ public boolean getMateNegativeStrandFlag() { requireReadPaired(); return getMateNegativeStrandFlagUnchecked(); } private boolean getMateNegativeStrandFlagUnchecked() { return (mFlags & MATE_STRAND_FLAG) != 0; } /** * the read is the first read in a pair. */ public boolean getFirstOfPairFlag() { requireReadPaired(); return getFirstOfPairFlagUnchecked(); } private boolean getFirstOfPairFlagUnchecked() { return (mFlags & FIRST_OF_PAIR_FLAG) != 0; } /** * the read is the second read in a pair. */ public boolean getSecondOfPairFlag() { requireReadPaired(); return getSecondOfPairFlagUnchecked(); } private boolean getSecondOfPairFlagUnchecked() { return (mFlags & SECOND_OF_PAIR_FLAG) != 0; } /** * the alignment is not primary (a read having split hits may have multiple primary alignment records). */ public boolean getNotPrimaryAlignmentFlag() { return (mFlags & NOT_PRIMARY_ALIGNMENT_FLAG) != 0; } /** * the read fails platform/vendor quality checks. */ public boolean getReadFailsVendorQualityCheckFlag() { return (mFlags & READ_FAILS_VENDOR_QUALITY_CHECK_FLAG) != 0; } /** * the read is either a PCR duplicate or an optical duplicate. */ public boolean getDuplicateReadFlag() { return (mFlags & DUPLICATE_READ_FLAG) != 0; } /** * the read is paired in sequencing, no matter whether it is mapped in a pair. */ public void setReadPairedFlag(final boolean flag) { setFlag(flag, READ_PAIRED_FLAG); } /** * the read is mapped in a proper pair (depends on the protocol, normally inferred during alignment). */ public void setProperPairFlag(final boolean flag) { setFlag(flag, PROPER_PAIR_FLAG); } /** * the query sequence itself is unmapped. */ public void setReadUmappedFlag(final boolean flag) { setFlag(flag, READ_UNMAPPED_FLAG); // Change to readUnmapped could change indexing bin setIndexingBin(null); } /** * the mate is unmapped. */ public void setMateUnmappedFlag(final boolean flag) { setFlag(flag, MATE_UNMAPPED_FLAG); } /** * strand of the query (false for forward; true for reverse strand). */ public void setReadNegativeStrandFlag(final boolean flag) { setFlag(flag, READ_STRAND_FLAG); } /** * strand of the mate (false for forward; true for reverse strand). */ public void setMateNegativeStrandFlag(final boolean flag) { setFlag(flag, MATE_STRAND_FLAG); } /** * the read is the first read in a pair. */ public void setFirstOfPairFlag(final boolean flag) { setFlag(flag, FIRST_OF_PAIR_FLAG); } /** * the read is the second read in a pair. */ public void setSecondOfPairFlag(final boolean flag) { setFlag(flag, SECOND_OF_PAIR_FLAG); } /** * the alignment is not primary (a read having split hits may have multiple primary alignment records). */ public void setNotPrimaryAlignmentFlag(final boolean flag) { setFlag(flag, NOT_PRIMARY_ALIGNMENT_FLAG); } /** * the read fails platform/vendor quality checks. */ public void setReadFailsVendorQualityCheckFlag(final boolean flag) { setFlag(flag, READ_FAILS_VENDOR_QUALITY_CHECK_FLAG); } /** * the read is either a PCR duplicate or an optical duplicate. */ public void setDuplicateReadFlag(final boolean flag) { setFlag(flag, DUPLICATE_READ_FLAG); } private void setFlag(final boolean flag, final int bit) { if (flag) { mFlags |= bit; } else { mFlags &= ~bit; } } public SAMFileReader.ValidationStringency getValidationStringency() { return mValidationStringency; } /** * Control validation of lazily-decoded elements. */ public void setValidationStringency(final SAMFileReader.ValidationStringency validationStringency) { this.mValidationStringency = validationStringency; } /** * Get the value for a SAM tag. * WARNING: Some value types (e.g. byte[]) are mutable. It is dangerous to change one of these values in * place, because some SAMRecord implementations keep track of when attributes have been changed. If you * want to change an attribute value, call setAttribute() to replace the value. * * @param tag Two-character tag name. * @return Appropriately typed tag value, or null if the requested tag is not present. */ public final Object getAttribute(final String tag) { return getAttribute(SAMTagUtil.getSingleton().makeBinaryTag(tag)); } protected Object getAttribute(final short tag) { if (mAttributes == null) { return null; } for (final SAMBinaryTagAndValue tagAndValue : mAttributes) { if (tagAndValue.tag == tag) { return tagAndValue.value; } } return null; } final public void setAttribute(final String tag, final Object value) { setAttribute(SAMTagUtil.getSingleton().makeBinaryTag(tag), value); } protected void setAttribute(final short tag, final Object value) { if (mAttributes == null) { mAttributes = new ArrayList<SAMBinaryTagAndValue>(); } int i; for (i = 0; i < mAttributes.size(); ++i) { if (mAttributes.get(i).tag == tag) { break; } } if (i < mAttributes.size()) { if (value != null) { mAttributes.set(i, new SAMBinaryTagAndValue(tag, value)); } else { mAttributes.remove(i); } } else if (value != null) { mAttributes.add(new SAMBinaryTagAndValue(tag, value)); } } /** * Replace any existing attributes with the given list. Does not copy the list * but installs it directly. */ protected void setAttributes(final List<SAMBinaryTagAndValue> attributes) { mAttributes = attributes; } /** * @return List of all tags on this record. Returns null if there are no tags. */ protected List<SAMBinaryTagAndValue> getBinaryAttributes() { if (mAttributes == null || mAttributes.isEmpty()) { return null; } return Collections.unmodifiableList(mAttributes); } /** * Tag name and value of an attribute, for getAttributes() method. */ public static class SAMTagAndValue { public final String tag; public final Object value; public SAMTagAndValue(final String tag, final Object value) { this.tag = tag; this.value = value; } } /** * @return list of {tag, value} tuples */ public final List<SAMTagAndValue> getAttributes() { final List<SAMBinaryTagAndValue> binaryAttributes = getBinaryAttributes(); final List<SAMTagAndValue> ret = new ArrayList<SAMTagAndValue>(binaryAttributes.size()); for (final SAMBinaryTagAndValue tagAndValue : binaryAttributes) { ret.add(new SAMTagAndValue(SAMTagUtil.getSingleton().makeStringTag(tagAndValue.tag), tagAndValue.value)); } return ret; } Integer getIndexingBin() { return mIndexingBin; } void setIndexingBin(final Integer mIndexingBin) { this.mIndexingBin = mIndexingBin; } /** * Does not change state of this. * @return indexing bin based on alignment start & end. */ int computeIndexingBin() { // reg2bin has zero-based, half-open API final int alignmentStart = getAlignmentStart()-1; int alignmentEnd = getAlignmentEnd(); if (alignmentEnd <= 0) { // If alignment end cannot be determined (e.g. because this read is not really aligned), // then treat this as a one base alignment for indexing purposes. alignmentEnd = alignmentStart + 1; } return SAMUtils.reg2bin(alignmentStart, alignmentEnd); } public SAMFileHeader getHeader() { return mHeader; } /** * Setting header into SAMRecord facilitates conversion btw reference sequence names and indices * @param header contains sequence dictionary for this SAMRecord */ public void setHeader(final SAMFileHeader header) { this.mHeader = header; } /** * If this record has a valid binary representation of the variable-length portion of a binary record stored, * return that byte array, otherwise return null. This will never be true for SAMRecords. It will be true * for BAMRecords that have not been eagerDecoded(), and for which none of the data in the variable-length * portion has been changed. */ public byte[] getVariableBinaryRepresentation() { return null; } /** * Depending on the concrete implementation, the binary file size of attributes may be known without * computing them all. * @return binary file size of attribute, if known, else -1 */ public int getAttributesBinarySize() { return -1; } public String format() { final StringBuilder buffer = new StringBuilder(); addField(buffer, getReadName(), null, null); addField(buffer, getFlags(), null, null); addField(buffer, getReferenceName(), null, "*"); addField(buffer, getAlignmentStart(), 0, "*"); addField(buffer, getMappingQuality(), 0, "0"); addField(buffer, getCigarString(), null, "*"); addField(buffer, getMateReferenceName(), null, "*"); addField(buffer, getMateAlignmentStart(), 0, "*"); addField(buffer, getInferredInsertSize(), 0, "*"); addField(buffer, getReadString(), null, "*"); addField(buffer, getBaseQualityString(), null, "*"); if (mAttributes != null) { for (final SAMBinaryTagAndValue entry : getBinaryAttributes()) { addField(buffer, formatTagValue(entry.tag, entry.value)); } } return buffer.toString(); } private void addField(final StringBuilder buffer, final Object value, final Object defaultValue, final String defaultString) { if (safeEquals(value, defaultValue)) { addField(buffer, defaultString); } else if (value == null) { addField(buffer, ""); } else { addField(buffer, value.toString()); } } private void addField(final StringBuilder buffer, final String field) { if (buffer.length() > 0) { buffer.append('\t'); } buffer.append(field); } private String formatTagValue(final short tag, final Object value) { final String tagString = SAMTagUtil.getSingleton().makeStringTag(tag); if (value == null || value instanceof String) { return tagString + ":Z:" + value; } else if (value instanceof Integer) { return tagString + ":i:" + value; } else if (value instanceof Character) { return tagString + ":A:" + value; } else if (value instanceof Float) { return tagString + ":f:" + value; } else if (value instanceof byte[]) { return tagString + ":H:" + SAMUtils.bytesToHexString((byte[]) value); } else { throw new RuntimeException("Unexpected value type for tag " + tagString + ": " + value); } } private boolean safeEquals(final Object o1, final Object o2) { if (o1 == o2) { return true; } else if (o1 == null || o2 == null) { return false; } else { return o1.equals(o2); } } /** * Force all lazily-initialized data members to be initialized. If a subclass overrides this method, * typically it should also call super method. */ protected void eagerDecode() { getCigar(); getCigarString(); } /** * Returns blocks of the read sequence that have been aligned directly to the * reference sequence. Note that clipped portions of the read and inserted and * deleted bases (vs. the reference) are not represented in the alignment blocks. */ public List<AlignmentBlock> getAlignmentBlocks() { if (this.mAlignmentBlocks != null) return this.mAlignmentBlocks; final Cigar cigar = getCigar(); if (cigar == null) return Collections.emptyList(); final List<AlignmentBlock> alignmentBlocks = new ArrayList<AlignmentBlock>(); int readBase = 1; int refBase = getAlignmentStart(); for (final CigarElement e : cigar.getCigarElements()) { switch (e.getOperator()) { case H : break; // ignore hard clips case P : break; // ignore pads case S : readBase += e.getLength(); break; // soft clip read bases case N : refBase += e.getLength(); break; // reference skip case D : refBase += e.getLength(); break; case I : readBase += e.getLength(); break; case M : final int length = e.getLength(); alignmentBlocks.add(new AlignmentBlock(readBase, refBase, length)); readBase += length; refBase += length; break; default : throw new IllegalStateException("Case statement didn't deal with cigar op: " + e.getOperator()); } } this.mAlignmentBlocks = Collections.unmodifiableList(alignmentBlocks); return this.mAlignmentBlocks; } @Override public boolean equals(final Object o) { if (this == o) return true; if (!(o instanceof SAMRecord)) return false; final SAMRecord samRecord = (SAMRecord) o; eagerDecode(); samRecord.eagerDecode(); if (mAlignmentStart != samRecord.mAlignmentStart) return false; if (mFlags != samRecord.mFlags) return false; if (mInferredInsertSize != samRecord.mInferredInsertSize) return false; if (mMappingQuality != samRecord.mMappingQuality) return false; if (mMateAlignmentStart != samRecord.mMateAlignmentStart) return false; if (mAttributes != null ? !mAttributes.equals(samRecord.mAttributes) : samRecord.mAttributes != null) return false; if (!Arrays.equals(mBaseQualities, samRecord.mBaseQualities)) return false; if (mCigar != null ? !mCigar.equals(samRecord.mCigar) : samRecord.mCigar != null) return false; if (mIndexingBin != null ? !mIndexingBin.equals(samRecord.mIndexingBin) : samRecord.mIndexingBin != null) return false; if (mMateReferenceIndex != null ? !mMateReferenceIndex.equals(samRecord.mMateReferenceIndex) : samRecord.mMateReferenceIndex != null) return false; if (mMateReferenceName != null ? !mMateReferenceName.equals(samRecord.mMateReferenceName) : samRecord.mMateReferenceName != null) return false; if (!Arrays.equals(mReadBases, samRecord.mReadBases)) return false; if (mReadName != null ? !mReadName.equals(samRecord.mReadName) : samRecord.mReadName != null) return false; if (mReferenceIndex != null ? !mReferenceIndex.equals(samRecord.mReferenceIndex) : samRecord.mReferenceIndex != null) return false; if (mReferenceName != null ? !mReferenceName.equals(samRecord.mReferenceName) : samRecord.mReferenceName != null) return false; return true; } @Override public int hashCode() { eagerDecode(); int result = mReadName != null ? mReadName.hashCode() : 0; result = 31 * result + (mReadBases != null ? Arrays.hashCode(mReadBases) : 0); result = 31 * result + (mBaseQualities != null ? Arrays.hashCode(mBaseQualities) : 0); result = 31 * result + (mReferenceName != null ? mReferenceName.hashCode() : 0); result = 31 * result + mAlignmentStart; result = 31 * result + mMappingQuality; result = 31 * result + (mCigarString != null ? mCigarString.hashCode() : 0); result = 31 * result + mFlags; result = 31 * result + (mMateReferenceName != null ? mMateReferenceName.hashCode() : 0); result = 31 * result + mMateAlignmentStart; result = 31 * result + mInferredInsertSize; result = 31 * result + (mAttributes != null ? mAttributes.hashCode() : 0); result = 31 * result + (mReferenceIndex != null ? mReferenceIndex.hashCode() : 0); result = 31 * result + (mMateReferenceIndex != null ? mMateReferenceIndex.hashCode() : 0); result = 31 * result + (mIndexingBin != null ? mIndexingBin.hashCode() : 0); return result; } /** * Perform various validations of SAMRecord. * @return null if valid. If invalid, returns a list of error messages. */ public List<SAMValidationError> isValid() { // ret is only instantiate if there are errors to report, in order to reduce GC in the typical case // in which everything is valid. It's ugly, but more efficient. ArrayList<SAMValidationError> ret = null; if (!getReadPairedFlag()) { if (getProperPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_PROPER_PAIR, "Proper pair flag should not be set for unpaired read.", getReadName())); } if (getMateUnmappedFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_MATE_UNMAPPED, "Mate unmapped flag should not be set for unpaired read.", getReadName())); } if (getMateNegativeStrandFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_MATE_NEG_STRAND, "Mate negative strand flag should not be set for unpaired read.", getReadName())); } if (getFirstOfPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_FIRST_OF_PAIR, "First of pair flag should not be set for unpaired read.", getReadName())); } if (getSecondOfPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_SECOND_OF_PAIR, "First of pair flag should not be set for unpaired read.", getReadName())); } if (getMateReferenceIndex() != NO_ALIGNMENT_REFERENCE_INDEX) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_MATE_REF_INDEX, "MRNM should not be set for unpaired read.", getReadName())); } } else { final List<SAMValidationError> errors = isValidReferenceIndexAndPosition(mMateReferenceIndex, mMateReferenceName, getMateAlignmentStart(), true); if (errors != null) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.addAll(errors); } if (!hasMateReferenceName() && !getMateUnmappedFlag()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_MATE_UNMAPPED, "Mapped mate should have mate reference name", getReadName())); } /* TODO: PIC-97 This validation should be enabled, but probably at this point there are too many BAM files that have the proper pair flag set when read or mate is unmapped. if (getMateUnmappedFlag() && getProperPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_PROPER_PAIR, "Proper pair flag should not be set for unpaired read.", getReadName())); } */ } if (getInferredInsertSize() > MAX_INSERT_SIZE || getInferredInsertSize() < -MAX_INSERT_SIZE) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_INSERT_SIZE, "Insert size out of range", getReadName())); } if (getReadUnmappedFlag()) { if (getReadNegativeStrandFlag()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_READ_NEG_STRAND, "Read negative strand flag should not be set for unmapped read.", getReadName())); } if (getNotPrimaryAlignmentFlag()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_NOT_PRIM_ALIGNMENT, "Not primary alignment flag should not be set for unmapped read.", getReadName())); } if (getMappingQuality() != 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_MAPPING_QUALITY, "MAPQ must should be 0 for unmapped read.", getReadName())); } if (getCigarLength() != 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_CIGAR, "CIGAR should have zero elements for unmapped read.", getReadName())); } /* TODO: PIC-97 This validation should be enabled, but probably at this point there are too many BAM files that have the proper pair flag set when read or mate is unmapped. if (getProperPairFlagUnchecked()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_PROPER_PAIR, "Proper pair flag should not be set for unmapped read.", getReadName())); } */ } else { if (getMappingQuality() >= 256) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_MAPPING_QUALITY, "MAPQ should be < 256.", getReadName())); } if (getCigarLength() == 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_CIGAR, "CIGAR should have > zero elements for mapped read.", getReadName())); } if (getHeader().getSequenceDictionary().size() == 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.MISSING_SEQUENCE_DICTIONARY, "Empty sequence dictionary.", getReadName())); } if (!hasReferenceName()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_FLAG_READ_UNMAPPED, "Mapped read should have valid reference name", getReadName())); } /* Oops! We know this is broken in older BAM files, so this having this validation will cause all sorts of problems! if (getIndexingBin() != null && getIndexingBin() != computeIndexingBin()) { ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_INDEXING_BIN, "Indexing bin (" + getIndexingBin() + ") does not agree with computed value (" + computeIndexingBin() + ")", getReadName())); } */ } // Validate the RG ID is found in header final String rgId = (String)getAttribute(SAMTagUtil.getSingleton().RG); if (rgId != null && getHeader().getReadGroup(rgId) == null) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.READ_GROUP_NOT_FOUND, "RG ID on SAMRecord not found in header: " + rgId, getReadName())); } final List<SAMValidationError> errors = isValidReferenceIndexAndPosition(mReferenceIndex, mReferenceName, getAlignmentStart(), false); if (errors != null) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.addAll(errors); } if (ret == null || ret.size() == 0) { return null; } return ret; } private List<SAMValidationError> isValidReferenceIndexAndPosition(final Integer referenceIndex, final String referenceName, final int alignmentStart, final boolean isMate) { final boolean hasReference = hasReferenceName(referenceIndex, referenceName); // ret is only instantiate if there are errors to report, in order to reduce GC in the typical case // in which everything is valid. It's ugly, but more efficient. ArrayList<SAMValidationError> ret = null; if (!hasReference) { if (alignmentStart != 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_ALIGNMENT_START, buildMessage("Alignment start should be 0 because reference name = *.", isMate), getReadName())); } } else { if (alignmentStart == 0) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_ALIGNMENT_START, buildMessage("Alignment start should != 0 because reference name != *.", isMate), getReadName())); } if (getHeader().getSequenceDictionary().size() > 0) { final SAMSequenceRecord sequence = (referenceIndex != null? getHeader().getSequence(referenceIndex): getHeader().getSequence(referenceName)); if (sequence == null) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_REFERENCE_INDEX, buildMessage("Reference sequence not found in sequence dictionary.", isMate), getReadName())); } else { if (alignmentStart > sequence.getSequenceLength()) { if (ret == null) ret = new ArrayList<SAMValidationError>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_ALIGNMENT_START, buildMessage("Alignment start (" + alignmentStart + ") must be <= reference sequence length (" + sequence.getSequenceLength() + ") on reference " + sequence.getSequenceName(), isMate), getReadName())); } } } } return ret; } private String buildMessage(final String baseMessage, final boolean isMate) { return isMate ? "Mate " + baseMessage : baseMessage; } /** * Note that this does a shallow copy of everything, except for the attribute list, for which a copy of the list * is made, but the attributes themselves are copied by reference. This should be safe because callers should * never modify a mutable value returned by any of the get() methods anyway. */ @Override public Object clone() throws CloneNotSupportedException { final SAMRecord newRecord = (SAMRecord)super.clone(); if (mAttributes != null) { newRecord.mAttributes = (ArrayList)((ArrayList)mAttributes).clone(); } return newRecord; } }
package org.anddev.andengine.entity.primitives; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.entity.DynamicEntity; import org.anddev.andengine.opengl.GLHelper; import org.anddev.andengine.opengl.vertex.VertexBuffer; /** * @author Nicolas Gramlich * @since 11:51:27 - 13.03.2010 */ public abstract class Shape extends DynamicEntity { // Constants // Fields protected final VertexBuffer mVertexBuffer; private float mRed = 1; private float mGreen = 1; private float mBlue = 1; private float mAlpha = 1f; // Constructors public Shape(final float pX, final float pY, final float pWidth, final float pHeight, final VertexBuffer pVertexBuffer) { super(pX, pY, pWidth, pHeight); this.mVertexBuffer = pVertexBuffer; this.updateVertexBuffer(); } // Getter & Setter public float getRed() { return this.mRed; } public float getGreen() { return this.mGreen; } public float getBlue() { return this.mBlue; } public float getAlpha() { return this.mAlpha; } public VertexBuffer getVertexBuffer() { return this.mVertexBuffer; } public void setAlpha(final float pAlpha) { this.mAlpha = pAlpha; } public void setColor(final float pRed, final float pGreen, final float pBlue) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; } public void setColor(final float pRed, final float pGreen, final float pBlue, final float pAlpha) { this.mRed = pRed; this.mGreen = pGreen; this.mBlue = pBlue; this.mAlpha = pAlpha; } // Methods for/from SuperClass/Interfaces @Override protected void onPositionChanged() { this.updateVertexBuffer(); } protected abstract void updateVertexBuffer(); @Override protected void onManagedDraw(final GL10 pGL) { this.onInitDraw(pGL); pGL.glPushMatrix(); GLHelper.vertexPointer(pGL, this.getVertexBuffer().getByteBuffer(), GL10.GL_FLOAT); this.onPreTransformations(pGL); this.onApplyTransformations(pGL); this.onPostTransformations(pGL); pGL.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4); pGL.glPopMatrix(); } // Methods @Override public void reset() { super.reset(); this.mRed = 1.0f; this.mGreen = 1.0f; this.mBlue = 1.0f; this.mAlpha = 1.0f; } protected void onInitDraw(final GL10 pGL) { GLHelper.color4f(pGL, this.mRed, this.mGreen, this.mBlue, this.mAlpha); GLHelper.enableVertexArray(pGL); } protected void onPreTransformations(final GL10 pGL) { } protected void onApplyTransformations(final GL10 pGL) { /* Translate */ this.applyTranslation(pGL); /* Rotate */ this.applyRotation(pGL); /* Scale */ this.applyScale(pGL); } protected void applyTranslation(final GL10 pGL) { pGL.glTranslatef(this.getX(), this.getY(), 0); } protected void applyRotation(final GL10 pGL) { // TODO Offset needs to be taken into account. final float rotationAngleClockwise = this.getRotationAngleClockwise(); if(rotationAngleClockwise != 0) { final float halfWidth = this.getWidth() / 2; final float halfHeight = this.getHeight() / 2; pGL.glTranslatef(halfWidth, halfHeight, 0); pGL.glRotatef(rotationAngleClockwise, 0, 0, 1); pGL.glTranslatef(-halfWidth, -halfHeight, 0); } } protected void applyScale(final GL10 pGL) { final float scale = this.getScale(); if(scale != 1) { pGL.glScalef(scale, scale, 1); } } protected void onPostTransformations(final GL10 pGL) { } // Inner and Anonymous Classes }
package com.intellij.ui; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.application.ex.ProgressSlide; import com.intellij.openapi.util.NotNullLazyValue; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.SystemInfoRt; import com.intellij.util.ImageLoader; import com.intellij.util.ui.JBInsets; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.JBUIScale; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.net.URL; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; /** * To customize your IDE splash go to YourIdeNameApplicationInfo.xml and edit 'logo' tag. For more information see documentation for * the tag attributes in ApplicationInfo.xsd file. */ public final class Splash extends Window { private static final float JBUI_INIT_SCALE = JBUI.scale(1f); private final ApplicationInfoEx myInfo; private final int myWidth; private final int myHeight; private final int myProgressHeight; private final int myProgressY; private double myProgress; private int myProgressLastPosition = 0; private final Icon myProgressTail; private final List<ProgressSlideAndImage> myProgressSlideImages = new ArrayList<>(); private final Image myImage; private final NotNullLazyValue<Font> myFont = createFont(); public Splash(@NotNull ApplicationInfoEx info) { super(null); myInfo = info; myProgressHeight = uiScale(info.getProgressHeight()); myProgressY = uiScale(info.getProgressY()); myProgressTail = info.getProgressTailIcon(); setFocusableWindowState(false); myImage = loadImage(info.getSplashImageUrl()); myWidth = myImage.getWidth(null); myHeight = myImage.getHeight(null); Dimension size = new Dimension(myWidth, myHeight); if (Boolean.getBoolean("suppress.focus.stealing") && Boolean.getBoolean("suppress.focus.stealing.auto.request.focus")) { setAutoRequestFocus(false); } setSize(size); setLocationInTheCenterOfScreen(); initImages(); setVisible(true); paint(getGraphics()); toFront(); } @Override public void dispose() { super.dispose(); } @NotNull private static Image loadImage(@NotNull String url) { URL imageUrl = Splash.class.getResource(url); if (imageUrl == null) { throw new IllegalStateException("Cannot find image: " + url); } return Objects.requireNonNull(ImageLoader.loadFromUrl(imageUrl, Splash.class, true, false, false, null, JBUIScale.ScaleContext.create())); } @NotNull public static NotNullLazyValue<Font> createFont() { return NotNullLazyValue.createValue(() -> { Font font; if (SystemInfo.isMacOSElCapitan) { font = createFont(".SF NS Text"); } else { //noinspection SpellCheckingInspection font = SystemInfo.isMacOSYosemite ? createFont("HelveticaNeue-Regular") : null; } if (font == null || UIUtil.isDialogFont(font)) { font = createFont(UIUtil.ARIAL_FONT_NAME); } return font; }); } @Override public void paint(Graphics g) { UIUtil.drawImage(g, myImage, 0, 0, null); paintProgress(g); } private void initImages() { List<ProgressSlide> progressSlides = myInfo.getProgressSlides(); if (progressSlides.isEmpty()) { return; } for (ProgressSlide progressSlide : progressSlides) { myProgressSlideImages.add(new ProgressSlideAndImage(progressSlide, loadImage(progressSlide.getUrl()))); } myProgressSlideImages.sort(Comparator.comparing(t -> t.slide.getProgressRation())); } private void setLocationInTheCenterOfScreen() { Rectangle bounds = getGraphicsConfiguration().getBounds(); if (SystemInfoRt.isWindows) { JBInsets.removeFrom(bounds, ScreenUtil.getScreenInsets(getGraphicsConfiguration())); } setLocation(UIUtil.getCenterPoint(bounds, getSize())); } public void showProgress(double progress) { if (myInfo.getProgressColor() == null) { return; } if (((progress - myProgress) > 0.01) || (progress > 0.99)) { myProgress = progress; paintProgress(getGraphics()); } } private void paintProgress(@NotNull Graphics g) { boolean hasSlides = !myProgressSlideImages.isEmpty(); if (hasSlides) { paintSlides(g); } Color color = myInfo.getProgressColor(); if (color == null) { return; } final int progressWidth = (int)(myWidth * myProgress); int currentWidth = progressWidth - myProgressLastPosition; if (currentWidth == 0) { return; } g.setColor(color); int y = hasSlides ? myHeight - myProgressHeight : myProgressY; g.fillRect(myProgressLastPosition, y, currentWidth, myProgressHeight); if (myProgressTail != null) { float onePixel = JBUI_INIT_SCALE; myProgressTail.paintIcon(this, g, (int)(currentWidth - (myProgressTail.getIconWidth() / onePixel / 2f * onePixel)), (int)(myProgressY - (myProgressTail.getIconHeight() - myProgressHeight) / onePixel / 2f * onePixel)); //I'll buy you a beer if you understand this line without playing with it } myProgressLastPosition = progressWidth; } private void paintSlides(@NotNull Graphics g) { for (ProgressSlideAndImage progressSlide : myProgressSlideImages) { if (progressSlide.slide.getProgressRation() <= myProgress) { UIUtil.drawImage(g, progressSlide.image, 0, 0, null); } } } public void paintLicenseeInfo() { showLicenseeInfo(getGraphics(), 0, 0, myHeight, myInfo, myFont); } public static boolean showLicenseeInfo(@NotNull Graphics g, int x, int y, final int height, @NotNull ApplicationInfoEx info, @NotNull NotNullLazyValue<? extends Font> font) { if (!info.showLicenseeInfo()) { return false; } LicensingFacade provider = LicensingFacade.getInstance(); if (provider == null) { return true; } String licensedToMessage = provider.getLicensedToMessage(); List<String> licenseRestrictionsMessages = provider.getLicenseRestrictionsMessages(); if (licensedToMessage == null && licenseRestrictionsMessages.isEmpty()) { return true; } UIUtil.applyRenderingHints(g); g.setFont(font.getValue()); g.setColor(info.getSplashTextColor()); int offsetX = Math.max(uiScale(15), uiScale(info.getLicenseOffsetX())); int offsetYUnscaled = info.getLicenseOffsetY(); if (licensedToMessage != null) { g.drawString(licensedToMessage, x + offsetX, y + height - uiScale(offsetYUnscaled)); } if (!licenseRestrictionsMessages.isEmpty()) { g.drawString(licenseRestrictionsMessages.get(0), x + offsetX, y + height - uiScale(offsetYUnscaled - 16)); } return true; } @NotNull private static Font createFont(String name) { return new Font(name, Font.PLAIN, uiScale(12)); } private static int uiScale(int i) { return (int)(i * JBUI_INIT_SCALE); } } final class ProgressSlideAndImage { public final ProgressSlide slide; public final Image image; ProgressSlideAndImage(@NotNull ProgressSlide slide, @NotNull Image image) { this.slide = slide; this.image = image; } }
package gov.nih.nci.camod.webapp.util; import gov.nih.nci.camod.Constants; import javax.servlet.http.HttpServletRequest; public class SidebarUtil extends gov.nih.nci.camod.webapp.action.BaseAction { public String findSubMenu( HttpServletRequest request, String jspName ) { System.out.println("<sidebar.jsp> String jspName=" + jspName ); if( jspName.equals("searchSimple.jsp") || jspName.equals("searchHelp.jsp") || jspName.equals("searchAdvanced.jsp") || jspName.equals("searchDrugScreening.jsp") || jspName.equals("searchTableOfContents.jsp") || jspName.equals("searchResultsDrugScreen.jsp") || jspName.equals("searchResults.jsp")|| jspName.equals("expDesignStage0.jsp")|| jspName.equals("expDesignStage1.jsp")|| jspName.equals("expDesignStage2.jsp")|| jspName.equals("yeastStrainsStage01.jsp")|| jspName.equals("yeastStrainsStage2.jsp")) { return "subSearchMenu.jsp"; } else if ( jspName.equals("viewModelCharacteristics.jsp") || jspName.equals("viewTransplantXenograft.jsp") || jspName.equals("viewGeneticDescription.jsp") || jspName.equals("viewInvivoDetails.jsp") || jspName.equals("viewPublications.jsp") || jspName.equals("viewCarcinogenicInterventions.jsp") || jspName.equals("viewHistopathology.jsp") || jspName.equals("viewTherapeuticApproaches.jsp") || jspName.equals("viewTransientInterference.jsp") || jspName.equals("viewCellLines.jsp") || jspName.equals("viewImages.jsp") || jspName.equals("viewMicroarrays.jsp") ){ String theSubMenu = "subViewModelMenu.jsp"; // For special cases when we don't have an animal model if (request.getSession().getAttribute(Constants.ANIMALMODEL) == null) { theSubMenu = "subSearchMenu.jsp"; } return theSubMenu; } else if ( jspName.equals("adminRoles.jsp") || jspName.equals("helpAdmin.jsp") || jspName.equals("adminModelsAssignment.jsp") || jspName.equals("adminCommentsAssignment.jsp") || jspName.equals("adminRolesAssignment.jsp") || jspName.equals("adminEditUserRoles.jsp") || jspName.equals("adminEditUser.jsp") || jspName.equals("adminEditModels.jsp") || jspName.equals("adminUserManagement.jsp") || jspName.equals("helpDesk.jsp") ) { return "subAdminMenu.jsp"; } else if ( jspName.equals("submitOverview.jsp") || jspName.equals("submitAssocExpression.jsp") || jspName.equals("submitAssocMetastasis.jsp") || jspName.equals("submitSpontaneousMutation.jsp") || jspName.equals("submitClinicalMarkers.jsp") || jspName.equals("submitGeneDelivery.jsp") || jspName.equals("submitModelCharacteristics.jsp") || jspName.equals("submitEngineeredTransgene.jsp") || jspName.equals("submitGenomicSegment.jsp") || jspName.equals("submitTargetedModification.jsp") || jspName.equals("submitInducedMutation.jsp") || jspName.equals("submitChemicalDrug.jsp") || jspName.equals("submitEnvironmentalFactors.jsp") || jspName.equals("submitNutritionalFactors.jsp") || jspName.equals("submitGrowthFactors.jsp") || jspName.equals("submitHormone.jsp") || jspName.equals("submitRadiation.jsp") || jspName.equals("submitViralTreatment.jsp")|| jspName.equals("submitTransplantXenograft.jsp") || jspName.equals("submitSurgeryOther.jsp") || jspName.equals("submitPublications.jsp") || jspName.equals("submitHistopathology.jsp")|| jspName.equals("submitCellLines.jsp") || jspName.equals("submitTherapy.jsp") || jspName.equals("submitImages.jsp") || jspName.equals("submitMicroarrayData.jsp") || jspName.equals("submitJacksonLab.jsp") || jspName.equals("submitMMHCCRepo.jsp") || jspName.equals("submitInvestigator.jsp") || jspName.equals("submitMorpholino.jsp") || jspName.equals("submitIMSR.jsp") ) { return "subSubmitMenu.jsp"; } else if ( jspName.equals("submitModels.jsp") || jspName.equals("submitNewModel.jsp") ) { return "subEmptyMenu.jsp"; } else { return "subEmptyMenu.jsp"; } } }
package org.biojavax.bio.phylo; public class MultipleHitCorrection { public static double JukesCantor(String taxa1, String taxa2){ taxa1 = taxa1.replace(" ", ""); taxa2 = taxa2.replace(" ", ""); int length = taxa1.length(); if(length == taxa2.length()){ //only if sequence lengths are the same, run the JC method double counter = 0.0; //for every single base pairs for( int i = 0 ; i < length; i++){ //compare and increase the counter when it is not identical if(taxa1.charAt(i) != taxa2.charAt(i)) counter++; } //calculate proportion of mismatch in the sequence //and, it will be used as the probability of those two taxa which will have diff. base pair at any given site double p = counter/ (double) length; //calculate evolutionary distance between them (by the formula) and return it return (-0.75 * Math.log(1.0-(4.0/3.0)*p)); }else{ System.out.println("Error: Sequence Length dose not match!\n"); return 0.0; } } public static double KimuraTwoParameter(String taxa1, String taxa2){ taxa1 = taxa1.replace(" ",""); taxa2 = taxa2.replace(" ",""); int length = taxa1.length(); if(length == taxa2.length()){ double counter1 = 0.0; double counter2 = 0.0; for( int i = 0; i < length; i++){ //if two taxa have diff. base-pair at a site if(taxa1.charAt(i) != taxa2.charAt(i)){ if((taxa1.charAt(i) == 'A' && taxa2.charAt(i) == 'G') || (taxa1.charAt(i) == 'G' && taxa2.charAt(i) == 'A')){ //see if it is a transition between A and G, and if so increase counter1 counter1++; }else if((taxa1.charAt(i) == 'T' && taxa2.charAt(i) == 'C') || (taxa1.charAt(i) == 'C' && taxa2.charAt(i) == 'T')){ //see if it is a transition between C and T, and if so increase counter1 counter1++; }else{ //if it is not transition, then increase counter2 for the transversion counter2++; } } } //calculate p and q, based on counter 1 & counter 2 double p = counter1 / (double) length; double q = counter2 / (double) length; //calculate the distance (by formula) and return it. return ( (0.5)*Math.log(1.0/(1.0 - 2.0*p - q)) + (0.25)*Math.log(1.0/(1.0 - 2.0*q))); }else{ System.out.println("Error: Sequence Length dose not match!\n"); return 0.0; } } }
package org.bouncycastle.crypto.tls; import java.io.IOException; import java.util.Hashtable; import java.util.Vector; import org.bouncycastle.asn1.x509.X509CertificateStructure; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.CryptoException; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.engines.AESFastEngine; import org.bouncycastle.crypto.engines.DESedeEngine; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DSAPrivateKeyParameters; import org.bouncycastle.crypto.params.RSAKeyParameters; class DefaultTlsClient implements TlsClient { private CertificateVerifyer verifyer; private TlsProtocolHandler handler; // (Optional) details for client-side authentication private Certificate clientCert = new Certificate(new X509CertificateStructure[0]); private AsymmetricKeyParameter clientPrivateKey = null; private TlsSigner clientSigner = null; private int selectedCipherSuite; DefaultTlsClient(CertificateVerifyer verifyer) { this.verifyer = verifyer; } void enableClientAuthentication(Certificate clientCertificate, AsymmetricKeyParameter clientPrivateKey) { if (clientCertificate == null) { throw new IllegalArgumentException("'clientCertificate' cannot be null"); } if (clientCertificate.certs.length == 0) { throw new IllegalArgumentException("'clientCertificate' cannot be empty"); } if (clientPrivateKey == null) { throw new IllegalArgumentException("'clientPrivateKey' cannot be null"); } if (!clientPrivateKey.isPrivate()) { throw new IllegalArgumentException("'clientPrivateKey' must be private"); } if (clientPrivateKey instanceof RSAKeyParameters) { clientSigner = new TlsRSASigner(); } else if (clientPrivateKey instanceof DSAPrivateKeyParameters) { clientSigner = new TlsDSSSigner(); } else { throw new IllegalArgumentException("'clientPrivateKey' type not supported: " + clientPrivateKey.getClass().getName()); } this.clientCert = clientCertificate; this.clientPrivateKey = clientPrivateKey; } public void init(TlsProtocolHandler handler) { this.handler = handler; } public int[] getCipherSuites() { return new int[] { CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA, CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA, CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA, CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA, CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA, // CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA, // CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA, // CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA, // CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA, // CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA, // CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA, // CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA, // CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA, // CipherSuite.TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA, // CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA, // CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA, // CipherSuite.TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA, // CipherSuite.TLS_SRP_SHA_WITH_AES_256_CBC_SHA, // CipherSuite.TLS_SRP_SHA_WITH_AES_128_CBC_SHA, // CipherSuite.TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA, }; } public Hashtable generateClientExtensions() { // TODO[SRP] // Hashtable clientExtensions = new Hashtable(); // ByteArrayOutputStream srpData = new ByteArrayOutputStream(); // TlsUtils.writeOpaque8(SRP_identity, srpData); // clientExtensions.put(Integer.valueOf(ExtensionType.srp), srpData.toByteArray()); // return clientExtensions; return null; } public short[] getCompressionMethods() { return new short[] { CompressionMethod.NULL }; } public void notifySessionID(byte[] sessionID) { // Currently ignored } public void notifySelectedCipherSuite(int selectedCipherSuite) { this.selectedCipherSuite = selectedCipherSuite; } public void notifySelectedCompressionMethod(short selectedCompressionMethod) { // TODO Store and use } public void notifySecureRenegotiation(boolean secureRenegotiation) throws IOException { if (!secureRenegotiation) { /* * RFC 5746 3.4. If the extension is not present, the server does not support * secure renegotiation; set secure_renegotiation flag to FALSE. In this case, * some clients may want to terminate the handshake instead of continuing; see * Section 4.1 for discussion. */ // handler.failWithError(AlertLevel.fatal, // TlsProtocolHandler.AP_handshake_failure); } } public void processServerExtensions(Hashtable serverExtensions) { // TODO Validate/process serverExtensions (via client?) // TODO[SRP] } public TlsKeyExchange createKeyExchange() throws IOException { switch (selectedCipherSuite) { case CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA: return createRSAKeyExchange(); case CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA: return createDHKeyExchange(TlsKeyExchange.KE_DH_DSS); case CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA: return createDHKeyExchange(TlsKeyExchange.KE_DH_RSA); case CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA: return createDHKeyExchange(TlsKeyExchange.KE_DHE_DSS); case CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA: return createDHKeyExchange(TlsKeyExchange.KE_DHE_RSA); case CipherSuite.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: return createECDHKeyExchange(TlsKeyExchange.KE_ECDH_ECDSA); case CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: return createECDHEKeyExchange(TlsKeyExchange.KE_ECDHE_ECDSA); case CipherSuite.TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: return createECDHKeyExchange(TlsKeyExchange.KE_ECDH_RSA); case CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: return createECDHEKeyExchange(TlsKeyExchange.KE_ECDHE_RSA); case CipherSuite.TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_anon_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_anon_WITH_AES_256_CBC_SHA: return createECDHKeyExchange(TlsKeyExchange.KE_ECDH_anon); case CipherSuite.TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_AES_256_CBC_SHA: return createSRPExchange(TlsKeyExchange.KE_SRP); case CipherSuite.TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA: return createSRPExchange(TlsKeyExchange.KE_SRP_RSA); case CipherSuite.TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA: return createSRPExchange(TlsKeyExchange.KE_SRP_DSS); default: /* * Note: internal error here; the TlsProtocolHandler verifies that the * server-selected cipher suite was in the list of client-offered cipher * suites, so if we now can't produce an implementation, we shouldn't have * offered it! */ handler.failWithError(AlertLevel.fatal, AlertDescription.internal_error); return null; // Unreachable! } } public void processServerCertificateRequest(short[] certificateTypes, Vector certificateAuthorities) { // TODO There shouldn't be a certificate request for SRP // TODO Use provided info to choose a certificate in getCertificate() } public byte[] generateCertificateSignature(byte[] md5andsha1) throws IOException { if (clientSigner == null) { return null; } try { return clientSigner.calculateRawSignature(clientPrivateKey, md5andsha1); } catch (CryptoException e) { handler.failWithError(AlertLevel.fatal, AlertDescription.internal_error); return null; } } public Certificate getCertificate() { return clientCert; } public TlsCipher createCipher(SecurityParameters securityParameters) throws IOException { switch (selectedCipherSuite) { case CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA: return createDESedeCipher(24, securityParameters); case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_ECDH_anon_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA: return createAESCipher(16, securityParameters); case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_ECDH_anon_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_SRP_SHA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA: case CipherSuite.TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA: return createAESCipher(32, securityParameters); default: /* * Note: internal error here; the TlsProtocolHandler verifies that the * server-selected cipher suite was in the list of client-offered cipher * suites, so if we now can't produce an implementation, we shouldn't have * offered it! */ handler.failWithError(AlertLevel.fatal, AlertDescription.internal_error); return null; // Unreachable! } } private TlsKeyExchange createDHKeyExchange(short keyExchange) { return new TlsDHKeyExchange(handler, verifyer, keyExchange); } private TlsKeyExchange createECDHKeyExchange(short keyExchange) { return new TlsECDHKeyExchange(handler, verifyer, keyExchange, clientCert, clientPrivateKey); } private TlsKeyExchange createECDHEKeyExchange(short keyExchange) { return new TlsECDHEKeyExchange(handler, verifyer, keyExchange, clientCert, clientPrivateKey); } private TlsKeyExchange createRSAKeyExchange() { return new TlsRSAKeyExchange(handler, verifyer); } private TlsKeyExchange createSRPExchange(short keyExchange) { return new TlsSRPKeyExchange(handler, verifyer, keyExchange); } private TlsCipher createAESCipher(int cipherKeySize, SecurityParameters securityParameters) { return new TlsBlockCipher(handler, createAESBlockCipher(), createAESBlockCipher(), new SHA1Digest(), new SHA1Digest(), cipherKeySize, securityParameters); } private TlsCipher createDESedeCipher(int cipherKeySize, SecurityParameters securityParameters) { return new TlsBlockCipher(handler, createDESedeBlockCipher(), createDESedeBlockCipher(), new SHA1Digest(), new SHA1Digest(), cipherKeySize, securityParameters); } private static BlockCipher createAESBlockCipher() { return new CBCBlockCipher(new AESFastEngine()); } private static BlockCipher createDESedeBlockCipher() { return new CBCBlockCipher(new DESedeEngine()); } }
package org.codefx.lab.optional; import java.io.Serializable; import java.util.Objects; import java.util.Optional; public final class SerializableOptional<T extends Serializable> implements Serializable { private static final long serialVersionUID = -652697447004597911L; private final T value; private SerializableOptional() { value = null; } private SerializableOptional(T value) { Objects.requireNonNull(value, "The argument 'value' must not be null."); this.value = value; } public static <T extends Serializable> SerializableOptional<T> fromOptional(Optional<T> optional) { if (optional.isPresent()) return new SerializableOptional<T>(optional.get()); else return new SerializableOptional<>(); } public Optional<T> toOptional() { return Optional.ofNullable(value); } }
package org.unix4j.util; import java.util.ArrayList; import java.util.List; /** * Range offers ways of specifying a range of numbers. * <b>USAGE:</b><br/> * There are no public constructors in this object. The user should use one of the static factory * methods to create a Range.<br/> * e.g. The following will create a range of numbers from 1 to 5<br/> * <pre>Range.between(1,5);</pre> * <br/> * Chaining can be used to specify multiple range "elements"<br/> * e.g. The following will create a range of numbers from 1 to 5, and all numbers above 10<br/> * <pre>Range.between(1,5).andToEndFrom(10);</pre> */ public class Range{ final CompositeRange compositeRange = new CompositeRange(); private Range(){} private Range(final AbstractRange range){ compositeRange.add(range); } /** * @param index * @return whether the given index is within this range */ public boolean isWithinRange(final int index) { return compositeRange.isWithinRange(index); } /** * @param indexes a list of indexes to include in the range * @return a range object consisting of this range, and all * previous range elements in the chain so far. */ public Range andOf(final int... indexes) { compositeRange.add(Range.of(indexes)); return this; } /** * Adds a range element to include all indexes from 1 to and inclusive of the * given index. * @param to * @return A range object consisting of this range, and all * previous range elements in the chain so far. */ public Range andFromStartTo(final int to) { compositeRange.add(Range.fromStartTo(to)); return this; } /** * Adds a range element to include all indexes from (and including) the given index * to any greater index. * @param from * @return A range object consisting of this range, and all * previous range elements in the chain so far. */ public Range andToEndFrom(final int from) { compositeRange.add(Range.toEndFrom(from)); return this; } /** * Adds a range element to include all indexes between (and including) the given * indexes. * @param from * @param to * @return A range object consisting of this range, and all * previous range elements in the chain so far. */ public Range andBetween(final int from, final int to) { compositeRange.add(Range.between(from, to)); return this; } @Override public String toString() { return compositeRange.toString(); } /** * @param indexes a list of indexes to include in the range * @return A new range object consisting of this range. */ public static Range of(int ... indexes){ final Range range = new Range(); for(int i: indexes){ range.compositeRange.add(Range.includingSingleIndexOf(i)); } return range; } /** * Creates a range element to include all indexes from 1 to (and inclusive of) the * given index. * @param to * @return A range object consisting of this range, and all * previous range elements in the chain so far. */ public static Range fromStartTo(final int to){ Assert.assertArgGreaterThan("index must be greater than zero", to, 0); return new Range(new AbstractRange(){ @Override public String toString(){ return "-" + to; } @Override public boolean isWithinRange(int index){return index <= to;} }); } /** * Creates a range element to include all elements from (and including) the given * index to any greater index. * @param from * @return A range object consisting of this range. */ public static Range toEndFrom(final int from){ Assert.assertArgGreaterThan("index must be greater than zero", from, 0); return new Range(new AbstractRange(){ private final int index = from; @Override public String toString(){ return index + "-";} @Override public boolean isWithinRange(int index){return index >= from;} }); } /** * Creates a range element to include all elements between (and including) the given * indexes. * @param from * @param to * @return A new range object consisting of this range. */ public static Range between(final int from, final int to){ Assert.assertArgGreaterThan("index must be greater than zero", from, 0); return new Range(new AbstractRange(){ @Override public String toString(){ return from + "-" + to;} @Override public boolean isWithinRange(int index){return from <= index && index <= to;} }); } private static AbstractRange includingSingleIndexOf(final int singleIndex){ Assert.assertArgGreaterThan("index must be greater than zero", singleIndex, 0); return new AbstractRange(){ @Override public String toString(){ return "" + singleIndex;} @Override public boolean isWithinRange(int index){return index == singleIndex;} }; } } abstract class AbstractRange { public abstract boolean isWithinRange(int index); } class CompositeRange extends AbstractRange { private List<AbstractRange> rangeElements = new ArrayList<AbstractRange>(); public void add(final AbstractRange range){ rangeElements.add(range); } public void add(final Range range){ rangeElements.addAll(range.compositeRange.rangeElements); } public AbstractRange first() { return rangeElements.get(0); } public AbstractRange last() { return rangeElements.get(rangeElements.size() - 1); } @Override public boolean isWithinRange(int index){ for(final AbstractRange range: rangeElements){ if(range.isWithinRange(index)){ return true; } } return false; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); for (AbstractRange range : rangeElements) { if (sb.length() > 0) sb.append(","); sb.append(range); } return sb.toString(); } }
package org.dbflute.erflute.editor; import java.util.ArrayList; import java.util.Arrays; import java.util.EventObject; import java.util.HashMap; import java.util.List; import java.util.Map; import org.dbflute.erflute.Activator; import org.dbflute.erflute.core.DesignResources; import org.dbflute.erflute.editor.controller.editpart.element.AbstractModelEditPart; import org.dbflute.erflute.editor.controller.editpart.element.ERDiagramEditPart; import org.dbflute.erflute.editor.controller.editpart.element.ERDiagramEditPartFactory; import org.dbflute.erflute.editor.controller.editpart.element.PagableFreeformRootEditPart; import org.dbflute.erflute.editor.controller.editpart.element.node.DiagramWalkerEditPart; import org.dbflute.erflute.editor.extension.ExtensionLoader; import org.dbflute.erflute.editor.model.ERDiagram; import org.dbflute.erflute.editor.model.diagram_contents.element.node.DiagramWalker; import org.dbflute.erflute.editor.view.ERDiagramGotoMarker; import org.dbflute.erflute.editor.view.ERDiagramPopupMenuManager; import org.dbflute.erflute.editor.view.action.category.ChangeFreeLayoutAction; import org.dbflute.erflute.editor.view.action.category.ChangeShowReferredTablesAction; import org.dbflute.erflute.editor.view.action.dbexport.ExportToDBAction; import org.dbflute.erflute.editor.view.action.dbexport.ExportToDDLAction; import org.dbflute.erflute.editor.view.action.dbexport.ExportToImageAction; import org.dbflute.erflute.editor.view.action.dbimport.ImportFromDBAction; import org.dbflute.erflute.editor.view.action.dbimport.ImportFromFileAction; import org.dbflute.erflute.editor.view.action.edit.ChangeBackgroundColorAction; import org.dbflute.erflute.editor.view.action.edit.CopyAction; import org.dbflute.erflute.editor.view.action.edit.DeleteWithoutUpdateAction; import org.dbflute.erflute.editor.view.action.edit.PasteAction; import org.dbflute.erflute.editor.view.action.edit.SelectAllContentsAction; import org.dbflute.erflute.editor.view.action.ermodel.ERDiagramQuickOutlineAction; import org.dbflute.erflute.editor.view.action.ermodel.VirtualDiagramAddAction; import org.dbflute.erflute.editor.view.action.group.ColumnGroupManageAction; import org.dbflute.erflute.editor.view.action.line.DefaultLineAction; import org.dbflute.erflute.editor.view.action.line.ERDiagramAlignmentAction; import org.dbflute.erflute.editor.view.action.line.ERDiagramMatchHeightAction; import org.dbflute.erflute.editor.view.action.line.ERDiagramMatchWidthAction; import org.dbflute.erflute.editor.view.action.line.HorizontalLineAction; import org.dbflute.erflute.editor.view.action.line.ResizeModelAction; import org.dbflute.erflute.editor.view.action.line.RightAngleLineAction; import org.dbflute.erflute.editor.view.action.line.VerticalLineAction; import org.dbflute.erflute.editor.view.action.option.OptionSettingAction; import org.dbflute.erflute.editor.view.action.option.notation.ChangeCapitalAction; import org.dbflute.erflute.editor.view.action.option.notation.ChangeNotationExpandGroupAction; import org.dbflute.erflute.editor.view.action.option.notation.ChangeStampAction; import org.dbflute.erflute.editor.view.action.option.notation.LockEditAction; import org.dbflute.erflute.editor.view.action.option.notation.ToggleMainColumnAction; import org.dbflute.erflute.editor.view.action.option.notation.design.ChangeDesignToFrameAction; import org.dbflute.erflute.editor.view.action.option.notation.design.ChangeDesignToFunnyAction; import org.dbflute.erflute.editor.view.action.option.notation.design.ChangeDesignToSimpleAction; import org.dbflute.erflute.editor.view.action.option.notation.level.ChangeNotationLevelToColumnAction; import org.dbflute.erflute.editor.view.action.option.notation.level.ChangeNotationLevelToDetailAction; import org.dbflute.erflute.editor.view.action.option.notation.level.ChangeNotationLevelToExcludeTypeAction; import org.dbflute.erflute.editor.view.action.option.notation.level.ChangeNotationLevelToNameAndKeyAction; import org.dbflute.erflute.editor.view.action.option.notation.level.ChangeNotationLevelToOnlyKeyAction; import org.dbflute.erflute.editor.view.action.option.notation.level.ChangeNotationLevelToOnlyTitleAction; import org.dbflute.erflute.editor.view.action.option.notation.system.ChangeToIDEF1XNotationAction; import org.dbflute.erflute.editor.view.action.option.notation.system.ChangeToIENotationAction; import org.dbflute.erflute.editor.view.action.option.notation.type.ChangeViewToBothAction; import org.dbflute.erflute.editor.view.action.option.notation.type.ChangeViewToLogicalAction; import org.dbflute.erflute.editor.view.action.option.notation.type.ChangeViewToPhysicalAction; import org.dbflute.erflute.editor.view.action.printer.PageSettingAction; import org.dbflute.erflute.editor.view.action.printer.PrintImageAction; import org.dbflute.erflute.editor.view.action.search.SearchAction; import org.dbflute.erflute.editor.view.action.zoom.ZoomAdjustAction; import org.dbflute.erflute.editor.view.contributor.ERDiagramActionBarContributor; import org.dbflute.erflute.editor.view.drag_drop.ERDiagramTransferDragSourceListener; import org.dbflute.erflute.editor.view.drag_drop.ERDiagramTransferDropTargetListener; import org.dbflute.erflute.editor.view.outline.ERDiagramOutlinePage; import org.dbflute.erflute.editor.view.outline.ERDiagramOutlinePopupMenuManager; import org.dbflute.erflute.editor.view.property_source.ERDiagramPropertySourceProvider; import org.dbflute.erflute.editor.view.tool.ERDiagramPaletteRoot; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.draw2d.FigureCanvas; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.PositionConstants; import org.eclipse.draw2d.geometry.Point; import org.eclipse.gef.DefaultEditDomain; import org.eclipse.gef.EditPart; import org.eclipse.gef.GraphicalViewer; import org.eclipse.gef.LayerConstants; import org.eclipse.gef.MouseWheelHandler; import org.eclipse.gef.MouseWheelZoomHandler; import org.eclipse.gef.SnapToGeometry; import org.eclipse.gef.SnapToGrid; import org.eclipse.gef.dnd.AbstractTransferDragSourceListener; import org.eclipse.gef.dnd.AbstractTransferDropTargetListener; import org.eclipse.gef.dnd.TemplateTransfer; import org.eclipse.gef.editparts.ScalableFreeformRootEditPart; import org.eclipse.gef.editparts.ZoomManager; import org.eclipse.gef.palette.PaletteRoot; import org.eclipse.gef.ui.actions.ActionRegistry; import org.eclipse.gef.ui.actions.DirectEditAction; import org.eclipse.gef.ui.actions.SelectionAction; import org.eclipse.gef.ui.actions.ToggleGridAction; import org.eclipse.gef.ui.actions.ZoomComboContributionItem; import org.eclipse.gef.ui.actions.ZoomInAction; import org.eclipse.gef.ui.actions.ZoomOutAction; import org.eclipse.gef.ui.parts.GraphicalEditorWithPalette; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.commands.ActionHandler; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.SWT; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.ide.IGotoMarker; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.ui.views.properties.IPropertySheetPage; import org.eclipse.ui.views.properties.PropertySheetPage; public class MainDiagramEditor extends GraphicalEditorWithPalette { /* * TODO ymd * revealEditPart * (this)Quick Outline */ private static EditPart selectionEditPart; protected static void selectEditPart(EditPart editPart) { unselectEditPart(); selectionEditPart = editPart; selectionEditPart.setSelected(EditPart.SELECTED_PRIMARY); } protected static void unselectEditPart() { if (selectionEditPart != null) { selectionEditPart.setSelected(EditPart.SELECTED_NONE); selectionEditPart = null; } } // Definition public static final String ACTION_OUTLINE = "_outline"; // Attribute protected final ERDiagram diagram; protected final ERDiagramEditPartFactory editPartFactory; protected final ZoomComboContributionItem zoomComboContributionItem; protected ERDiagramOutlinePage outlinePage; protected final PropertySheetPage propertySheetPage; protected ERDiagramActionBarContributor actionBarContributor; protected IGotoMarker gotoMaker; protected MenuManager outlineMenuMgr; protected ExtensionLoader extensionLoader; protected boolean isDirty; protected final Map<IMarker, Object> markedObjectMap = new HashMap<>(); // Constructor public MainDiagramEditor(ERDiagram diagram, ERDiagramEditPartFactory editPartFactory, ZoomComboContributionItem zoomComboContributionItem, ERDiagramOutlinePage outlinePage) { Activator.debug(this, "constructor", "...Creating diagram editor: " + diagram); this.diagram = diagram; this.editPartFactory = editPartFactory; this.zoomComboContributionItem = zoomComboContributionItem; this.outlinePage = outlinePage; this.propertySheetPage = new PropertySheetPage(); this.propertySheetPage.setPropertySourceProvider(new ERDiagramPropertySourceProvider()); try { this.extensionLoader = new ExtensionLoader(this); } catch (final CoreException e) { Activator.showExceptionDialog(e); } setEditDomain(new DefaultEditDomain(this)); getSelectionSynchronizer().addViewer(outlinePage.getViewer()); } @Override public void dispose() { getSelectionSynchronizer().removeViewer(outlinePage.getViewer()); super.dispose(); } @Override public void doSave(IProgressMonitor monitor) { getCommandStack().markSaveLocation(); this.isDirty = false; } @Override public void commandStackChanged(EventObject eventObject) { firePropertyChange(IEditorPart.PROP_DIRTY); super.commandStackChanged(eventObject); } @Override protected void initializeGraphicalViewer() { final GraphicalViewer viewer = getGraphicalViewer(); viewer.setEditPartFactory(editPartFactory); initViewerAction(viewer); initDragAndDrop(viewer); viewer.setProperty(MouseWheelHandler.KeyGenerator.getKey(SWT.MOD1), MouseWheelZoomHandler.SINGLETON); viewer.setProperty(SnapToGrid.PROPERTY_GRID_ENABLED, true); viewer.setProperty(SnapToGrid.PROPERTY_GRID_VISIBLE, true); viewer.setProperty(SnapToGeometry.PROPERTY_SNAP_ENABLED, true); prepareERDiagramPopupMenu(viewer); this.outlineMenuMgr = new ERDiagramOutlinePopupMenuManager( diagram, getActionRegistry(), outlinePage.getOutlineActionRegistory(), outlinePage.getViewer()); outlinePage.setContextMenu(outlineMenuMgr); this.gotoMaker = new ERDiagramGotoMarker(this); } protected void prepareERDiagramPopupMenu(final GraphicalViewer viewer) { final MenuManager menuMgr = new ERDiagramPopupMenuManager(getActionRegistry(), diagram); extensionLoader.addERDiagramPopupMenu(menuMgr, getActionRegistry()); viewer.setContextMenu(menuMgr); } @Override protected PaletteRoot getPaletteRoot() { Activator.debug(this, "getPaletteRoot()", "...Creating palette root: " + diagram); return new ERDiagramPaletteRoot(diagram); } @Override public Object getAdapter(@SuppressWarnings("rawtypes") Class type) { if (type == ZoomManager.class) { return ((ScalableFreeformRootEditPart) getGraphicalViewer().getRootEditPart()).getZoomManager(); } if (type == IContentOutlinePage.class) { return outlinePage; } if (type == IGotoMarker.class) { return gotoMaker; } if (type == IPropertySheetPage.class) { return propertySheetPage; } return super.getAdapter(type); } public void changeCategory() { outlinePage.setCategory(getEditDomain(), getGraphicalViewer(), getActionRegistry()); } public void clearSelection() { if (!(getGraphicalViewer().getContents() instanceof ERDiagramEditPart)) { return; } final ERDiagramEditPart erDiagramEditPart = (ERDiagramEditPart) getGraphicalViewer().getContents(); if (erDiagramEditPart != null) { erDiagramEditPart.clearSelection(); } } @Override public void setFocus() { if (getGraphicalViewer().getContents() == null) { getGraphicalViewer().setContents(diagram); } super.setFocus(); } // TODO jflute ermaster: @Override @SuppressWarnings("unchecked") protected void createActions() { super.createActions(); final ActionRegistry registry = getActionRegistry(); final List<String> selectionActionList = getSelectionActions(); final List<IAction> actionList = new ArrayList<>(Arrays.asList(new IAction[] { new ChangeViewToLogicalAction(this), new ChangeViewToPhysicalAction(this), new ChangeViewToBothAction(this), new ChangeToIENotationAction(this), new ChangeToIDEF1XNotationAction(this), new ChangeNotationLevelToColumnAction(this), new ChangeNotationLevelToExcludeTypeAction(this), new ChangeNotationLevelToDetailAction(this), new ChangeNotationLevelToOnlyTitleAction(this), new ChangeNotationLevelToOnlyKeyAction(this), new ChangeNotationLevelToNameAndKeyAction(this), new ChangeNotationExpandGroupAction(this), new ChangeDesignToFunnyAction(this), new ChangeDesignToFrameAction(this), new ChangeDesignToSimpleAction(this), new ChangeCapitalAction(this), new ChangeStampAction(this), new ColumnGroupManageAction(this), /* #deleted new ChangeTrackingAction(this), */ new OptionSettingAction(this), /* #deleted new CategoryManageAction(this), */new ChangeFreeLayoutAction(this), new ChangeShowReferredTablesAction(this), /* #deleted new TranslationManageAction(this), */ /* #deleted new TestDataCreateAction(this), */new ImportFromDBAction(this), new ImportFromFileAction(this), new ExportToImageAction(this), /* #deleted new ExportToExcelAction(this), */ /* #deleted new ExportToHtmlAction(this), new ExportToJavaAction(this), */new ExportToDDLAction(this), /* #deleted new ExportToDictionaryAction(this), new ExportToTranslationDictionaryAction(this), */ /* #deleted new ExportToTestDataAction(this), */new PageSettingAction(this), /* #deleted new EditAllAttributesAction(this), */ new DirectEditAction((IWorkbenchPart) this), new ERDiagramAlignmentAction(this, PositionConstants.LEFT), new ERDiagramAlignmentAction(this, PositionConstants.CENTER), new ERDiagramAlignmentAction(this, PositionConstants.RIGHT), new ERDiagramAlignmentAction(this, PositionConstants.TOP), new ERDiagramAlignmentAction(this, PositionConstants.MIDDLE), new ERDiagramAlignmentAction(this, PositionConstants.BOTTOM), new ERDiagramMatchWidthAction(this), new ERDiagramMatchHeightAction(this), new HorizontalLineAction(this), new VerticalLineAction(this), new RightAngleLineAction(this), new DefaultLineAction(this), new CopyAction(this), new PasteAction(this), new SearchAction(this), new ResizeModelAction(this), new PrintImageAction(this), new DeleteWithoutUpdateAction(this), new SelectAllContentsAction(this), new VirtualDiagramAddAction(this), new ERDiagramQuickOutlineAction(this), })); Activator.debug(this, "createActions()", "...Preparing diagram actions: " + actionList.size()); actionList.addAll(extensionLoader.createExtendedActions()); for (final IAction action : actionList) { if (action instanceof SelectionAction) { final IAction originalAction = registry.getAction(action.getId()); if (originalAction != null) { selectionActionList.remove(originalAction); } selectionActionList.add(action.getId()); } registry.registerAction(action); } addKeyHandler(registry.getAction(SearchAction.ID)); addKeyHandler(registry.getAction(ERDiagramQuickOutlineAction.ID)); } @SuppressWarnings("unchecked") protected void initViewerAction(GraphicalViewer viewer) { final ScalableFreeformRootEditPart rootEditPart = new PagableFreeformRootEditPart(diagram); viewer.setRootEditPart(rootEditPart); final ZoomManager manager = rootEditPart.getZoomManager(); final double[] zoomLevels = new double[] { 0.1, 0.25, 0.5, 0.75, 0.8, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0, 10.0, 20.0 }; manager.setZoomLevels(zoomLevels); final List<String> zoomContributions = new ArrayList<>(); zoomContributions.add(ZoomManager.FIT_ALL); zoomContributions.add(ZoomManager.FIT_HEIGHT); zoomContributions.add(ZoomManager.FIT_WIDTH); manager.setZoomLevelContributions(zoomContributions); final ZoomInAction zoomInAction = new ZoomInAction(manager); final ZoomOutAction zoomOutAction = new ZoomOutAction(manager); final ZoomAdjustAction zoomAdjustAction = new ZoomAdjustAction(manager); getActionRegistry().registerAction(zoomInAction); getActionRegistry().registerAction(zoomOutAction); getActionRegistry().registerAction(zoomAdjustAction); addKeyHandler(zoomInAction); addKeyHandler(zoomOutAction); final IFigure gridLayer = rootEditPart.getLayer(LayerConstants.GRID_LAYER); gridLayer.setForegroundColor(DesignResources.GRID_COLOR); IAction action = new ToggleGridAction(viewer); getActionRegistry().registerAction(action); action = new ChangeBackgroundColorAction(this, diagram); getActionRegistry().registerAction(action); getSelectionActions().add(action.getId()); action = new ToggleMainColumnAction(this); getActionRegistry().registerAction(action); action = new LockEditAction(this); getActionRegistry().registerAction(action); action = new ExportToDBAction(this); getActionRegistry().registerAction(action); this.actionBarContributor = new ERDiagramActionBarContributor(zoomComboContributionItem); } protected void initDragAndDrop(GraphicalViewer viewer) { final AbstractTransferDragSourceListener dragSourceListener = new ERDiagramTransferDragSourceListener(viewer, TemplateTransfer.getInstance()); viewer.addDragSourceListener(dragSourceListener); final AbstractTransferDropTargetListener dropTargetListener = new ERDiagramTransferDropTargetListener(viewer, TemplateTransfer.getInstance()); viewer.addDropTargetListener(dropTargetListener); } private void addKeyHandler(IAction action) { final IHandlerService service = (IHandlerService) getSite().getService(IHandlerService.class); service.activateHandler(action.getActionDefinitionId(), new ActionHandler(action)); } @Override public void selectionChanged(IWorkbenchPart part, ISelection selection) { unselectEditPart(); final IEditorPart editorPart = getSite().getPage().getActiveEditor(); if (editorPart instanceof ERFluteMultiPageEditor) { final ERFluteMultiPageEditor multiPageEditorPart = (ERFluteMultiPageEditor) editorPart; if (equals(multiPageEditorPart.getActiveEditor())) { updateActions(getSelectionActions()); } } else { super.selectionChanged(part, selection); } } public Point getLocation() { final FigureCanvas canvas = (FigureCanvas) getGraphicalViewer().getControl(); return canvas.getViewport().getViewLocation(); } public void setLocation(int x, int y) { final FigureCanvas canvas = (FigureCanvas) getGraphicalViewer().getControl(); canvas.scrollTo(x, y); } public Object getMarkedObject(IMarker marker) { return markedObjectMap.get(marker); } public void setMarkedObject(IMarker marker, Object markedObject) { markedObjectMap.put(marker, markedObject); } public void clearMarkedObject() { markedObjectMap.clear(); } public String getProjectFilePath(String extention) { final IFile file = ((IFileEditorInput) getEditorInput()).getFile(); final String filePath = file.getLocation().toOSString(); return filePath.substring(0, filePath.lastIndexOf(".")) + extention; } public DefaultEditDomain getDefaultEditDomain() { return getEditDomain(); } public ActionRegistry getDefaultActionRegistry() { return getActionRegistry(); } // Reveal public void reveal(DiagramWalker walker) { final AbstractModelEditPart modelEditPart = (AbstractModelEditPart) getGraphicalViewer().getContents(); final List<?> editParts = modelEditPart.getChildren(); for (final Object editPart : editParts) { if (editPart instanceof DiagramWalkerEditPart) { final DiagramWalkerEditPart walkerEditPart = (DiagramWalkerEditPart) editPart; if (((DiagramWalker) walkerEditPart.getModel()).sameMaterial(walker)) { getGraphicalViewer().reveal(walkerEditPart); selectEditPart(walkerEditPart); return; } } } } // Accessor public ERDiagram getDiagram() { return diagram; } @Override public GraphicalViewer getGraphicalViewer() { return super.getGraphicalViewer(); } public ERDiagramEditPartFactory getEditPartFactory() { return editPartFactory; } public ERDiagramActionBarContributor getActionBarContributor() { return actionBarContributor; } @Override public boolean isDirty() { return isDirty || super.isDirty(); } public void setDirty(boolean isDirty) { this.isDirty = isDirty; } public void runERDiagramQuickOutlineAction() { getActionRegistry().getAction(ERDiagramQuickOutlineAction.ID).runWithEvent(null); } }
package org.xins.util.threads; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Set; /** * Monitor that acts like a doorman. It implements a variation of the * <em>Alternating Reader Writer</em> algorithm. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) * * @since XINS 0.66 */ public final class Doorman extends Object { // Class fields /** * The type for readers in the queue. */ private static final Queue.EntryType READ_QUEUE_ENTRY_TYPE = new Queue.EntryType(); /** * The type for writers in the queue. */ private static final Queue.EntryType WRITE_QUEUE_ENTRY_TYPE = new Queue.EntryType(); /** * The maximum time an entry can be in the queue. This is currently set to * 30 seconds. */ private static final long MAX_QUEUE_WAIT_TIME = 30000L; // Class functions // Constructors public Doorman(int queueSize) throws IllegalArgumentException { // Check preconditions if (queueSize < 0) { throw new IllegalArgumentException("queueSize (" + queueSize + ") < 0"); } // Initialize fields _currentActorLock = new Object(); _currentReaders = new HashSet(); _queue = new Queue(queueSize); } // Fields /** * Lock object for reading and writing the set of current readers and the * current writer. */ private final Object _currentActorLock; /** * The set of currently active readers. All elements in the set are * {@link Thread} instances. */ private final Set _currentReaders; /** * The currently active writer, if any. */ private Thread _currentWriter; /** * The queue that contains the waiting readers and/or writers. */ private final Queue _queue; // Methods /** * Enters the 'protected area' as a reader. If necessary, this method will * wait until the area can be entered. * * @throws QueueTimeOutException * if this thread was waiting in the queue for too long. */ public void enterAsReader() throws QueueTimeOutException { Thread reader = Thread.currentThread(); synchronized (_currentActorLock) { // Short-circuit if this thread is already entered if (_currentWriter == reader) { throw new IllegalStateException("Thread cannot enter as a reader if it is already an active writer."); } else if (_currentReaders.contains(reader)) { throw new IllegalStateException("Thread cannot enter as a reader if it is already an active reader."); } // If there is a current writer, then we need to wait in the queue boolean enterQueue = _currentWriter != null; synchronized (_queue) { // If there is no current writer, but there is already a queue, // then we also need to join it enterQueue = enterQueue ? true : !_queue.isEmpty(); // Join the queue if necessary if (enterQueue) { _queue.add(reader, READ_QUEUE_ENTRY_TYPE); } } // If we don't have to join the queue, join the set of current // readers and go ahead if (!enterQueue) { _currentReaders.add(reader); return; } } // Wait for read access try { Thread.sleep(MAX_QUEUE_WAIT_TIME); throw new QueueTimeOutException(); } catch (InterruptedException exception) { // fall through } } /** * Enters the 'protected area' as a writer. If necessary, this method will * wait until the area can be entered. * * @throws QueueTimeOutException * if this thread was waiting in the queue for too long. */ public void enterAsWriter() throws QueueTimeOutException { Thread writer = Thread.currentThread(); synchronized (_currentActorLock) { // Short-circuit if this thread is already entered if (_currentWriter == writer) { throw new IllegalStateException("Thread cannot enter as a writer if it is already an active writer."); } else if (_currentReaders.contains(writer)) { throw new IllegalStateException("Thread cannot enter as a writer if it is already an active reader."); } // If there is a current writer or one or more current readers, then // we need to wait in the queue boolean enterQueue = _currentWriter != null || !_currentReaders.isEmpty(); // Join the queue if necessary if (enterQueue) { synchronized (_queue) { _queue.add(writer, WRITE_QUEUE_ENTRY_TYPE); } } // If we don't have to join the queue, become the current writer and // return if (!enterQueue) { _currentWriter = writer; return; } } // Wait for write access try { Thread.sleep(MAX_QUEUE_WAIT_TIME); throw new QueueTimeOutException(); } catch (InterruptedException exception) { // fall through } } /** * Leaves the 'protected area' as a reader. */ public void leaveAsReader() { Thread reader = Thread.currentThread(); synchronized (_currentActorLock) { boolean readerRemoved = _currentReaders.remove(reader); if (!readerRemoved) { throw new IllegalStateException("Cannot leave protected area as reader, because it has not entered as a reader."); } if (_currentReaders.isEmpty()) { synchronized (_queue) { // Determine if the queue has a writer atop, a reader atop or is // empty Queue.EntryType type = _queue.getTypeOfFirst(); if (type == WRITE_QUEUE_ENTRY_TYPE) { // If a writer is waiting, activate it _currentWriter = _queue.pop(); _currentWriter.interrupt(); } else if (type == READ_QUEUE_ENTRY_TYPE) { // If a reader leaves, the queue cannot contain a reader at the // top, it must be either empty or have a writer at the top throw new IllegalStateException("Found writer at top of queue while a reader is leaving the protected area."); } } } } } /** * Leaves the 'protected area' as a writer. */ public void leaveAsWriter() { Thread writer = Thread.currentThread(); synchronized (_currentActorLock) { if (_currentWriter != writer) { throw new IllegalStateException("Cannot leave protected area as writer, because it has not entered as a writer."); } synchronized (_queue) { // Determine if the queue has a writer atop, a reader atop or is // empty Queue.EntryType type = _queue.getTypeOfFirst(); if (type == WRITE_QUEUE_ENTRY_TYPE) { // If a writer is waiting, activate it _currentWriter = _queue.pop(); _currentWriter.interrupt(); } else if (type == READ_QUEUE_ENTRY_TYPE) { // If there are multiple readers atop, activate all of them do { _queue.pop().interrupt(); } while (_queue.getTypeOfFirst() == READ_QUEUE_ENTRY_TYPE); } } } } // Inner class /** * Queue of waiting reader and writer threads. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) * * @since XINS 0.66 */ private static final class Queue extends Object { // Constructors public Queue(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("capacity (" + capacity + ") < 0"); } _entries = new LinkedList(); _entryTypes = new HashMap(capacity); } // Fields /** * The list of entries. */ private final LinkedList _entries; /** * The entry types, by entry. This map has the {@link Thread threads} as * keys and their {@link EntryType types} as values. */ private final Map _entryTypes; /** * Cached link to the first entry. This field is either * <code>null</code> or an instance of class {@link Thread}. */ private Thread _first; /** * Cached type of the first entry. This field is either * <code>null</code> (if {@link #_entries} is empty), or * <code>(EntryType) </code>{@link #_entries}<code>.</code>{@link List#get() get}<code>(0)</code> * (if {@link #_entries} is not empty). */ private EntryType _typeOfFirst; // Methods /** * Determines if this queue is empty. * * @return * <code>true</code> if this queue is empty, <code>false</code> if it * is not. */ public boolean isEmpty() { return (_first == null); } /** * Gets the type of the first waiting thread in this queue. If this * queue is empty, then <code>null</code> is returned. * * @return * <code>null</code> if this queue is empty; * {@link #READ_QUEUE_ENTRY_TYPE} is the first thread in this queue * is waiting for read access; * {@link #WRITE_QUEUE_ENTRY_TYPE} is the first thread in this queue * is waiting for write access; */ public EntryType getTypeOfFirst() { return _typeOfFirst; } public void add(Thread thread, EntryType type) throws IllegalStateException { // Check preconditions if (_entryTypes.containsKey(thread)) { throw new IllegalStateException("The specified thread is already in this queue."); } // If the queue is empty, then store the new waiter as the first if (_first == null) { _first = thread; _typeOfFirst = type; } // Store the waiter thread and its type _entryTypes.put(thread, type); _entries.addLast(thread); } public Thread pop() throws IllegalStateException { // Check preconditions if (_first == null) { throw new IllegalStateException("This queue is empty."); } Thread oldFirst = _first; // Remove the current first _entries.removeFirst(); _entryTypes.remove(oldFirst); // Get the new first, now that the other one is removed Object newFirst = _entries.getFirst(); _first = newFirst == null ? null : (Thread) _entries.getFirst(); _typeOfFirst = newFirst == null ? null : (EntryType) _entryTypes.get(_first); return oldFirst; } public void remove(Thread thread) throws IllegalStateException { if (thread == _first) { // Remove the current first _entries.removeFirst(); // Get the new first, now that the other one is removed Object newFirst = _entries.getFirst(); _first = newFirst == null ? null : (Thread) _entries.getFirst(); _typeOfFirst = newFirst == null ? null : (EntryType) _entryTypes.get(_first); } else { // Remove the thread from the list if (! _entries.remove(thread)) { throw new IllegalStateException("The specified thread is not in this queue."); } } _entryTypes.remove(thread); } // Inner classes /** * Type of an entry in a queue for a doorman. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) * * @since XINS 0.66 */ public static final class EntryType extends Object { // empty } } }
package com.pump.plaf; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JTextField; import javax.swing.plaf.basic.BasicTextFieldUI; import javax.swing.text.JTextComponent; import com.pump.blog.Blurb; import com.pump.icon.SearchIcon; /** * A <code>TextFieldUI</code> that features rounded horizontal endpoints. * <P> * Also if the <code>JTextField</code> has the client property "useSearchIcon" * defined, this may place a magnifying glass icon in the left edge of this UI * before the text. * */ @Blurb(imageName = "PromptSearch.png", title = "Text: Prompts and Search Fields", releaseDate = "December 2009", summary = "This article has 2 goals:\n" + "<br>1. Display a gray prompt over a <code>JTextField</code> if it doesn't have the focus.</br>\n" + "<br>2. Implement a <code>RoundTextFieldUI</code> (with an optional magnifying glass).</br>", article = "http://javagraphics.blogspot.com/2009/12/text-prompts-and-search-fields.html") public class RoundTextFieldUI extends BasicTextFieldUI { public final static ButtonShape ROUNDRECT_SHAPE = new ButtonShape(8, Short.MAX_VALUE); static Insets fieldInsets = new Insets(6, 6, 6, 6); JTextComponent editor; int focusPadding = 2; @Override public Dimension getMaximumSize(JComponent c) { // don't use the max height ever; it looks bizarre with a round rect // text field Dimension pref = super.getPreferredSize(c); Dimension max = super.getMaximumSize(c); return ROUNDRECT_SHAPE.getPreferredSize(null, max.width, pref.height, fieldInsets, null); } @Override public Dimension getMinimumSize(JComponent c) { Dimension d = super.getMinimumSize(c); return ROUNDRECT_SHAPE.getPreferredSize(null, d.width, d.height, fieldInsets, null); } @Override public Dimension getPreferredSize(JComponent c) { Dimension d = super.getPreferredSize(c); return ROUNDRECT_SHAPE.getPreferredSize(null, d.width, d.height, fieldInsets, null); } static Color[] gradientColors = new Color[] { new Color(0x666666), new Color(0x999999) }; static float[] gradientPositions = new float[] { 0, 1 }; private GeneralPath path = new GeneralPath(); private AffineTransform transform = new AffineTransform(); private int radius = 0; private static Icon searchIcon = new SearchIcon(12); protected void updateGeometry() { Rectangle editorRect = getVisibleEditorRect(); int iconExtra = includeSearchIcon() ? searchIcon.getIconWidth() : 0; ROUNDRECT_SHAPE.getShape(path, editorRect.width + 2 * radius + iconExtra, editorRect.height); transform.setToTranslation(focusPadding, focusPadding); path.transform(transform); } protected boolean includeSearchIcon() { Object obj = editor.getClientProperty("useSearchIcon"); if (obj != null) return obj.toString().equalsIgnoreCase("true"); // the apple-tech-note-2196 key: obj = editor.getClientProperty("JTextField.variant"); if ("search".equals(obj)) return true; return false; } @Override protected void paintSafely(Graphics g) { updateGeometry(); paintRealBackground(g); /** * I really wish we could just completely replace this method, but it * includes references to fields I don't have access to... */ super.paintSafely(g); } /** * Does nothing. This will be called in super.paintSafely() if the text * field is set to opaque. However we paint the real background in * <code>paintRealBackground()</code>, which includes the opaque background, * focus ring, and rounded border. */ @Override protected void paintBackground(Graphics g) { } protected void paintRealBackground(Graphics g0) { Graphics g = g0.create(); Insets i = getComponent().getInsets(); g.translate(i.left, i.top); if (editor.isOpaque()) { g.setColor(editor.getBackground()); g.fillRect(0, 0, editor.getWidth(), editor.getHeight()); } Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (editor.hasFocus()) { PlafPaintUtils.paintFocus(g2, path, focusPadding); } g2.setColor(editor.getBackground()); g2.fill(path); Shape oldClip = g2.getClip(); g2.clipRect(0, 0, editor.getWidth(), editor.getHeight() / 2); g2.translate(0, 1); g2.setPaint(new Color(0xBBBBBB)); g2.draw(path); g2.translate(0, -1); g2.setClip(oldClip); if (editor.hasFocus() == false) { g2.clipRect(0, editor.getHeight() / 2, editor.getWidth(), editor.getHeight() / 2); g2.translate(0, 1); g2.setPaint(new Color(0x66FFFFFF, true)); g2.draw(path); g2.translate(0, -1); g2.setClip(oldClip); } Rectangle editorRect = getVisibleEditorRect(); g2.setPaint(PlafPaintUtils.getVerticalGradient("roundTextField", editorRect.height, focusPadding, gradientPositions, gradientColors)); g2.draw(path); if (includeSearchIcon()) { searchIcon.paintIcon( editor, g0, editorRect.x - searchIcon.getIconWidth() - 4, editorRect.y + 1 + editorRect.height / 2 - searchIcon.getIconHeight() / 2); } } protected static FocusListener focusListener = new FocusListener() { public void focusGained(FocusEvent e) { ((Component) e.getSource()).repaint(); } public void focusLost(FocusEvent e) { ((Component) e.getSource()).repaint(); } }; protected static PropertyChangeListener iconListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("useSearchIcon") || evt.getPropertyName().equals("JTextField.variant")) { JTextField tf = (JTextField) evt.getSource(); tf.revalidate(); tf.repaint(); } } }; @Override protected Rectangle getVisibleEditorRect() { Rectangle r = super.getVisibleEditorRect(); if (r == null) return null; int left = r.x; int right = r.x + r.width; radius = (r.height - 2 * focusPadding) / 2; int dx = includeSearchIcon() ? searchIcon.getIconWidth() / 2 + 6 : 0; left += focusPadding + this.radius + dx; right -= focusPadding + this.radius; r.x = left; r.width = right - left; r.y += focusPadding; r.height -= 2 * focusPadding; return r; } @Override public void installUI(JComponent c) { editor = (JTextComponent) c; super.installUI(c); c.setBorder(null); c.setOpaque(false); c.addFocusListener(focusListener); editor.addPropertyChangeListener(iconListener); } @Override public void uninstallUI(JComponent c) { super.uninstallUI(c); c.removeFocusListener(focusListener); } }
package org.xins.server; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.TimeZone; import javax.servlet.ServletRequest; import org.xins.types.Type; import org.xins.types.TypeValueException; import org.xins.types.standard.Text; import org.xins.util.MandatoryArgumentChecker; import org.xins.util.collections.BasicPropertyReader; import org.xins.util.collections.InvalidPropertyValueException; import org.xins.util.collections.MissingRequiredPropertyException; import org.xins.util.collections.PropertyReader; import org.xins.util.collections.PropertyReaderUtils; import org.xins.util.collections.PropertiesPropertyReader; import org.xins.util.collections.expiry.ExpiryFolder; import org.xins.util.collections.expiry.ExpiryStrategy; import org.xins.util.io.FastStringWriter; import org.xins.util.manageable.BootstrapException; import org.xins.util.manageable.DeinitializationException; import org.xins.util.manageable.InitializationException; import org.xins.util.manageable.Manageable; import org.xins.util.text.DateConverter; import org.xins.util.text.FastStringBuffer; import org.xins.util.text.ParseException; import org.znerd.xmlenc.XMLOutputter; /** * Base class for API implementation classes. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) */ public abstract class API extends Manageable implements DefaultResultCodes { // Class fields /** * String returned by the function <code>_GetStatistics</code> when certain * information is not available. */ private static final String NOT_AVAILABLE = "N/A"; /** * Successful empty call result. */ private static final CallResult SUCCESSFUL_RESULT = new BasicCallResult(true, null, null, null); /** * The runtime (init) property that contains the ACL descriptor. */ private static final String ACL_PROPERTY = "org.xins.server.acl"; /** * The default access rule list. */ private static final String DEFAULT_ACCESS_RULE_LIST = "allow 0.0.0.0/0 *"; // Class functions // Constructors protected API(String name) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("name", name); if (name.length() < 1) { throw new IllegalArgumentException("name.length() (" + name.length() + " < 1"); } // Initialize fields _name = name; _startupTimestamp = System.currentTimeMillis(); _manageableObjects = new ArrayList(); _functionsByName = new HashMap(); _functionList = new ArrayList(); _resultCodesByName = new HashMap(); _resultCodeList = new ArrayList(); } // Fields /** * The name of this API. Cannot be <code>null</code> and cannot be an empty * string. */ private final String _name; /** * Flag that indicates if this API is session-based. */ private boolean _sessionBased; /** * List of registered manageable objects. See {@link #add(Manageable)}. * * <p />This field is initialized to a non-<code>null</code> value by the * constructor. */ private final List _manageableObjects; /** * Expiry strategy for <code>_sessionsByID</code>. * * <p />For session-based APIs, this field is initialized to a * non-<code>null</code> value by the initialization method * {@link #init(PropertyReader)}. */ private ExpiryStrategy _sessionExpiryStrategy; /** * Collection that maps session identifiers to <code>Session</code> * instances. Contains all sessions associated with this API. * * <p />For session-based APIs, this field is initialized to a * non-<code>null</code> value by the initialization method * {@link #init(PropertyReader)}. */ private ExpiryFolder _sessionsByID; /** * Map that maps function names to <code>Function</code> instances. * Contains all functions associated with this API. * * <p />This field is initialized to a non-<code>null</code> value by the * constructor. */ private final Map _functionsByName; /** * List of all functions. This field cannot be <code>null</code>. */ private final List _functionList; /** * Map that maps result code names to <code>ResultCode</code> instances. * Contains all result codes associated with this API. * * <p />This field is initialized to a non-<code>null</code> value by the * constructor. */ private final Map _resultCodesByName; /** * List of all result codes. This field cannot be <code>null</code>. */ private final List _resultCodeList; /** * The build-time settings. This field is initialized exactly once by * {@link #bootstrap(PropertyReader)}. It can be <code>null</code> before * that. */ private PropertyReader _buildSettings; /** * The runtime-time settings. This field is initialized by * {@link #init(PropertyReader)}. It can be <code>null</code> before that. */ private PropertyReader _runtimeSettings; /** * The type that applies for session identifiers. For session-based APIs * this will be set in {@link #init(PropertyReader)}. */ private SessionIDType _sessionIDType; /** * The session ID generator. For session-based APIs this will be set in * {@link #init(PropertyReader)}. */ private SessionIDType.Generator _sessionIDGenerator; /** * Flag that indicates if the shutdown sequence has been initiated. */ private boolean _shutDown; // TODO: Use a state for this /** * Timestamp indicating when this API instance was created. */ private final long _startupTimestamp; /** * Host name for the machine that was used for this build. */ private String _buildHost; /** * Time stamp that indicates when this build was done. */ private String _buildTime; /** * XINS version used to build the web application package. */ private String _buildVersion; /** * The time zone used when generating dates for output. */ private TimeZone _timeZone; /** * The access rule list. */ private AccessRuleList _accessRuleList; // Methods /** * Gets the name of this API. * * @return * the name of this API, never <code>null</code> and never an empty * string. */ public final String getName() { return _name; } /** * Gets the timestamp that indicates when this <code>API</code> instance * was created. * * @return * the time this instance was constructed, as a number of milliseconds * since midnight January 1, 1970. */ public final long getStartupTimestamp() { return _startupTimestamp; } /** * Returns the applicable time zone. * * @return * the time zone, not <code>null</code>. * * @since XINS 0.95 */ public final TimeZone getTimeZone() { return _timeZone; } public final int getCurrentSessions() throws IllegalStateException { // Check preconditions if (! _sessionBased) { throw new IllegalStateException("This API is not session-based."); } return _sessionsByID.size(); } /** * Checks if response validation is enabled. * * @return * <code>true</code> if response validation is enabled, * <code>false</code> otherwise. * * @since XINS 0.98 * * @deprecated * Deprecated since XINS 0.157, with no replacement. This method always * returns <code>false</code>. */ public final boolean isResponseValidationEnabled() { return false; } /** * Bootstraps this API (wrapper method). This method calls * {@link #bootstrapImpl2(PropertyReader)}. * * @param buildSettings * the build-time configuration properties, not <code>null</code>. * * @throws MissingRequiredPropertyException * if a required property is not given. * * @throws InvalidPropertyValueException * if a property has an invalid value. * * @throws BootstrapException * if the bootstrap fails. */ protected final void bootstrapImpl(PropertyReader buildSettings) throws MissingRequiredPropertyException, InvalidPropertyValueException, BootstrapException { // Log the time zone // TODO: Why log the time zone? _timeZone = TimeZone.getDefault(); String tzShortName = _timeZone.getDisplayName(false, TimeZone.SHORT); String tzLongName = _timeZone.getDisplayName(false, TimeZone.LONG); Log.log_4004(tzShortName, tzLongName); // Store the build-time settings _buildSettings = buildSettings; // Check if this API is session-based _sessionBased = PropertyReaderUtils.getBooleanProperty(buildSettings, "org.xins.api.sessionBased", false); if (_sessionBased) { Log.log_2013(); } else { Log.log_2014(); } // XXX: Allow configuration of session ID type ? // Initialize session-based API if (_sessionBased) { Log.log_2015(); // Initialize session ID type _sessionIDType = new BasicSessionIDType(this); _sessionIDGenerator = _sessionIDType.getGenerator(); // Determine session time-out duration and precision (in seconds) int timeOut = PropertyReaderUtils.getIntProperty(buildSettings, "org.xins.api.sessionTimeOut"); int precision = PropertyReaderUtils.getIntProperty(buildSettings, "org.xins.api.sessionTimeOutPrecision"); Log.log_2017(String.valueOf(timeOut), String.valueOf(precision)); // Create expiry strategy and folder final long MINUTE_IN_MS = 60000L; _sessionExpiryStrategy = new ExpiryStrategy(timeOut * MINUTE_IN_MS, precision * MINUTE_IN_MS); _sessionsByID = new ExpiryFolder("sessionsByID", // name of folder (for logging) _sessionExpiryStrategy, // expiry strategy false, // strict thread sync checking? (TODO) 5000L); // max queue wait time in ms (TODO) Log.log_2016(); } // Get build-time properties _buildHost = _buildSettings.get("org.xins.api.build.host"); _buildTime = _buildSettings.get("org.xins.api.build.time"); _buildVersion = _buildSettings.get("org.xins.api.build.version"); Log.log_2018(_buildHost, _buildTime, _buildVersion); // Let the subclass perform initialization bootstrapImpl2(buildSettings); // Bootstrap all instances int count = _manageableObjects.size(); for (int i = 0; i < count; i++) { Manageable m = (Manageable) _manageableObjects.get(i); String className = m.getClass().getName(); Log.log_2019(className, _name); try { m.bootstrap(_buildSettings); Log.log_2020(_name, className); } catch (MissingRequiredPropertyException exception) { Log.log_2021(_name, className, exception.getPropertyName()); throw exception; } catch (InvalidPropertyValueException exception) { Log.log_2022(_name, className, exception.getPropertyName(), exception.getPropertyValue()); throw exception; } catch (BootstrapException exception) { Log.log_2023(_name, className, exception.getMessage()); throw exception; } catch (Throwable exception) { Log.log_2024(_name, className, exception.getClass().getName(), exception.getMessage()); throw new BootstrapException(exception); } } // Bootstrap all functions count = _functionList.size(); for (int i = 0; i < count; i++) { Function f = (Function) _functionList.get(i); String functionName = f.getName(); Log.log_2027(_name, functionName); try { f.bootstrap(_buildSettings); Log.log_2028(_name, functionName); } catch (MissingRequiredPropertyException exception) { Log.log_2029(_name, functionName, exception.getPropertyName()); throw exception; } catch (InvalidPropertyValueException exception) { Log.log_2030(_name, functionName, exception.getPropertyName(), exception.getPropertyValue()); throw exception; } catch (BootstrapException exception) { Log.log_2031(_name, functionName, exception.getMessage()); throw exception; } catch (Throwable exception) { Log.log_2032(_name, functionName, exception.getClass().getName(), exception.getMessage()); throw new BootstrapException(exception); } } } /** * Bootstraps this API (implementation method). * * <p />The implementation of this method in class {@link API} is empty. * Custom subclasses can perform any necessary bootstrapping in this * class. * * <p />Note that bootstrapping and initialization are different. Bootstrap * includes only the one-time configuration of the API based on the * build-time settings, while the initialization * * <p />The {@link #add(Manageable)} may be called from this method, * and from this method <em>only</em>. * * @param buildSettings * the build-time properties, guaranteed not to be <code>null</code>. * * @throws MissingRequiredPropertyException * if a required property is not given. * * @throws InvalidPropertyValueException * if a property has an invalid value. * * @throws BootstrapException * if the bootstrap fails. */ protected void bootstrapImpl2(PropertyReader buildSettings) throws MissingRequiredPropertyException, InvalidPropertyValueException, BootstrapException { // empty } /** * Initializes this API. * * @param runtimeSettings * the runtime configuration settings, cannot be <code>null</code>. * * @throws MissingRequiredPropertyException * if a required property is missing. * * @throws InvalidPropertyValueException * if a property has an invalid value. * * @throws InitializationException * if the initialization failed for some other reason. */ protected final void initImpl(PropertyReader runtimeSettings) throws MissingRequiredPropertyException, InvalidPropertyValueException, InitializationException { // TODO: Check state // TODO: Perform rollback if initialization fails at some point Log.log_4005(_name); // Store runtime settings _runtimeSettings = runtimeSettings; // Initialize ACL subsystem String acl = runtimeSettings.get(ACL_PROPERTY); if (acl == null || acl.trim().length() < 1) { try { Log.log_4031(ACL_PROPERTY); Log.log_4032(DEFAULT_ACCESS_RULE_LIST); _accessRuleList = AccessRuleList.parseAccessRuleList(DEFAULT_ACCESS_RULE_LIST); } catch (ParseException exception) { Log.log_4033(DEFAULT_ACCESS_RULE_LIST, exception.getMessage()); throw new InitializationException(exception); } } else { try { _accessRuleList = AccessRuleList.parseAccessRuleList(acl); int ruleCount = _accessRuleList.getRuleCount(); Log.log_4034(String.valueOf(ruleCount)); } catch (ParseException exception) { Log.log_4035(ACL_PROPERTY, acl, exception.getMessage()); throw new InvalidPropertyValueException(ACL_PROPERTY, acl, exception.getMessage()); } } // Initialize all instances int count = _manageableObjects.size(); for (int i = 0; i < count; i++) { Manageable m = (Manageable) _manageableObjects.get(i); String className = m.getClass().getName(); Log.log_4019(_name, className); try { m.init(runtimeSettings); Log.log_4020(_name, className); } catch (MissingRequiredPropertyException exception) { Log.log_4021(_name, className, exception.getPropertyName()); throw exception; } catch (InvalidPropertyValueException exception) { Log.log_4022(_name, className, exception.getPropertyName(), exception.getPropertyValue()); throw exception; } catch (InitializationException exception) { Log.log_4023(_name, className, exception.getMessage()); throw exception; } catch (Throwable exception) { Log.log_4024(_name, className, exception.getClass().getName(), exception.getMessage()); throw new InitializationException(exception); } } // Initialize all functions count = _functionList.size(); for (int i = 0; i < count; i++) { Function f = (Function) _functionList.get(i); String functionName = f.getName(); Log.log_4025(_name, functionName); try { f.init(runtimeSettings); Log.log_4026(_name, functionName); } catch (MissingRequiredPropertyException exception) { Log.log_4027(_name, functionName, exception.getPropertyName()); throw exception; } catch (InvalidPropertyValueException exception) { Log.log_4028(_name, functionName, exception.getPropertyName(), exception.getPropertyValue()); throw exception; } catch (InitializationException exception) { Log.log_4029(_name, functionName, exception.getMessage()); throw exception; } catch (Throwable exception) { Log.log_4030(_name, functionName, exception.getClass().getName(), exception.getMessage()); throw new InitializationException(exception); } } // TODO: Call initImpl2(PropertyReader) ? Log.log_4006(_name); } protected final void add(Manageable m) throws IllegalStateException, IllegalArgumentException { // Check state Manageable.State state = getState(); if (getState() != BOOTSTRAPPING) { // TODO: Log throw new IllegalStateException("State is " + state + " instead of " + BOOTSTRAPPING + '.'); } // Check preconditions MandatoryArgumentChecker.check("m", m); String className = m.getClass().getName(); Log.log_2025(_name, className); // Store the manageable object in the list _manageableObjects.add(m); Log.log_2026(_name, className); } /** * Performs shutdown of this XINS API. This method will never throw any * exception. */ protected final void deinitImpl() { _shutDown = true; // Stop expiry strategy _sessionExpiryStrategy.stop(); // Destroy all sessions Log.log_6003(String.valueOf(_sessionsByID.size())); _sessionsByID = null; // Deinitialize instances int count = _manageableObjects.size(); for (int i = 0; i < count; i++) { Manageable m = (Manageable) _manageableObjects.get(i); String className = m.getClass().getName(); Log.log_6004(_name, className); try { m.deinit(); Log.log_6005(_name, className); } catch (DeinitializationException exception) { Log.log_6006(_name, className, exception.getMessage()); } catch (Throwable exception) { Log.log_6007(_name, className, exception.getClass().getName(), exception.getMessage()); } } // Deinitialize functions count = _functionList.size(); for (int i = 0; i < count; i++) { Function f = (Function) _functionList.get(i); String functionName = f.getName(); Log.log_6008(_name, functionName); try { f.deinit(); Log.log_6009(_name, functionName); } catch (DeinitializationException exception) { Log.log_6010(_name, functionName, exception.getMessage()); } catch (Throwable exception) { Log.log_6011(_name, functionName, exception.getClass().getName(), exception.getMessage()); } } } /** * Returns the name of the default function, if any. * * @return * the name of the default function, or <code>null</code> if there is * none. * * @deprecated * This method is deprecated since XINS 0.157, with no replacement. This * method will always return <code>null</code>. */ public String getDefaultFunctionName() { return null; } public boolean isSessionBased() throws IllegalStateException { assertUsable(); return _sessionBased; } public final SessionIDType getSessionIDType() throws IllegalStateException { // Check preconditions assertUsable(); if (! _sessionBased) { throw new IllegalStateException("This API is not session-based."); } return _sessionIDType; } final Session createSession() throws IllegalStateException { // Check preconditions assertUsable(); if (! _sessionBased) { throw new IllegalStateException("This API is not session-based."); } // Generate a session ID that does not yet exist Object sessionID; do { sessionID = _sessionIDGenerator.generateSessionID(); } while (_sessionsByID.get(sessionID) != null); // Construct a Session object... Session session = new Session(this, sessionID); // ...store it... _sessionsByID.put(sessionID, session); // ...and then return it return session; } final Session getSession(Object id) throws IllegalStateException { // Check preconditions assertUsable(); if (! _sessionBased) { throw new IllegalStateException("This API is not session-based."); } return (Session) _sessionsByID.get(id); } final Session getSessionByString(String idString) throws IllegalStateException, TypeValueException { // Check preconditions assertUsable(); if (! _sessionBased) { throw new IllegalStateException("This API is not session-based."); } return getSession(_sessionIDType.fromString(idString)); } /** * Callback method invoked when a function is constructed. * * @param function * the function that is added, not <code>null</code>. * * @throws NullPointerException * if <code>function == null</code>. */ final void functionAdded(Function function) throws NullPointerException { // TODO: Check the state here? _functionsByName.put(function.getName(), function); _functionList.add(function); } /** * Callback method invoked when a result code is constructed. * * @param resultCode * the result code that is added, not <code>null</code>. * * @throws NullPointerException * if <code>resultCode == null</code>. */ final void resultCodeAdded(ResultCode resultCode) throws NullPointerException { _resultCodesByName.put(resultCode.getName(), resultCode); _resultCodeList.add(resultCode); } /** * Returns the function with the specified name. * * @param name * the name of the function, will not be checked if it is * <code>null</code>. * * @return * the function with the specified name, or <code>null</code> if there * is no match. */ final Function getFunction(String name) { return (Function) _functionsByName.get(name); } /** * Forwards a call to a function. The call will actually be handled by * {@link Function#handleCall(long,ServletRequest)}. * * @param start * the start time of the request, in milliseconds since midnight January * 1, 1970. * * @param request * the original servlet request, not <code>null</code>. * * @return * the result of the call, never <code>null</code>. * * @throws NullPointerException * if <code>request == null</code>. * * @throws NoSuchFunctionException * if there is no matching function for the specified request. * * @throws AccessDeniedException * if access is denied for the specified combination of IP address and * function name. */ final CallResult handleCall(long start, ServletRequest request) throws NullPointerException, NoSuchFunctionException, AccessDeniedException { // Determine the function name String functionName = request.getParameter("_function"); if (functionName == null || functionName.length() == 0) { functionName = request.getParameter("function"); } if (functionName == null || functionName.length() == 0) { functionName = getDefaultFunctionName(); } // The function name is required if (functionName == null || functionName.length() == 0) { throw new NoSuchFunctionException(null); } // Check the access rule list String ip = request.getRemoteAddr(); boolean allow; try { allow = _accessRuleList.allow(ip, functionName); } catch (ParseException exception) { throw new Error("Malformed IP address: " + ip + '.'); } if (allow == false) { throw new AccessDeniedException(ip, functionName); } // Detect special functions if (functionName.charAt(0) == '_') { if ("_NoOp".equals(functionName)) { return SUCCESSFUL_RESULT; } else if ("_PerformGC".equals(functionName)) { return doPerformGC(); } else if ("_GetFunctionList".equals(functionName)) { return doGetFunctionList(); } else if ("_GetStatistics".equals(functionName)) { return doGetStatistics(); } else if ("_GetVersion".equals(functionName)) { return doGetVersion(); } else if ("_GetSettings".equals(functionName)) { return doGetSettings(); } else if ("_DisableFunction".equals(functionName)) { return doDisableFunction(request); } else if ("_EnableFunction".equals(functionName)) { return doEnableFunction(request); } else { throw new NoSuchFunctionException(functionName); } } // Short-circuit if we are shutting down if (_shutDown) { // TODO: Add message return new BasicCallResult(false, "InternalError", null, null); } // Get the function object Function function = getFunction(functionName); if (function == null) { throw new NoSuchFunctionException(functionName); } // Forward the call to the function return function.handleCall(start, request); } /** * Performs garbage collection. * * @return * the call result, never <code>null</code>. */ private final CallResult doPerformGC() { System.gc(); return SUCCESSFUL_RESULT; } /** * Returns a list of all functions in this API. Per function the name and * the version are returned. * * @return * the call result, never <code>null</code>. */ private final CallResult doGetFunctionList() { // Initialize a builder CallResultBuilder builder = new CallResultBuilder(); int count = _functionList.size(); for (int i = 0; i < count; i++) { Function function = (Function) _functionList.get(i); builder.startTag("function"); builder.attribute("name", function.getName()); builder.attribute("version", function.getVersion()); builder.attribute("enabled", function.isEnabled() ? "true" : "false"); builder.endTag(); } return builder; } /** * Returns the call statistics for all functions in this API. * * @return * the call result, never <code>null</code>. */ private final CallResult doGetStatistics() { // Initialize a builder CallResultBuilder builder = new CallResultBuilder(); builder.param("startup", DateConverter.toDateString(_timeZone, _startupTimestamp)); builder.param("now", DateConverter.toDateString(_timeZone, System.currentTimeMillis())); // Currently available processors Runtime rt = Runtime.getRuntime(); try { builder.param("availableProcessors", String.valueOf(rt.availableProcessors())); } catch (NoSuchMethodError error) { // ignore: Runtime.availableProcessors() is not available in Java 1.3 } // Heap memory statistics builder.startTag("heap"); long free = rt.freeMemory(); long total = rt.totalMemory(); builder.attribute("used", String.valueOf(total - free)); builder.attribute("free", String.valueOf(free)); builder.attribute("total", String.valueOf(total)); try { builder.attribute("max", String.valueOf(rt.maxMemory())); } catch (NoSuchMethodError error) { // ignore: Runtime.maxMemory() is not available in Java 1.3 } builder.endTag(); // heap // Function-specific statistics int count = _functionList.size(); for (int i = 0; i < count; i++) { Function function = (Function) _functionList.get(i); Function.Statistics stats = function.getStatistics(); long successfulCalls = stats.getSuccessfulCalls(); long unsuccessfulCalls = stats.getUnsuccessfulCalls(); long successfulDuration = stats.getSuccessfulDuration(); long unsuccessfulDuration = stats.getUnsuccessfulDuration(); String successfulAverage; String successfulMin; String successfulMinStart; String successfulMax; String successfulMaxStart; String lastSuccessfulStart; String lastSuccessfulDuration; if (successfulCalls == 0) { successfulAverage = NOT_AVAILABLE; successfulMin = NOT_AVAILABLE; successfulMinStart = NOT_AVAILABLE; successfulMax = NOT_AVAILABLE; successfulMaxStart = NOT_AVAILABLE; lastSuccessfulStart = NOT_AVAILABLE; lastSuccessfulDuration = NOT_AVAILABLE; } else if (successfulDuration == 0) { successfulAverage = "0"; successfulMin = String.valueOf(stats.getSuccessfulMin()); successfulMinStart = DateConverter.toDateString(_timeZone, stats.getSuccessfulMinStart()); successfulMax = String.valueOf(stats.getSuccessfulMax()); successfulMaxStart = DateConverter.toDateString(_timeZone, stats.getSuccessfulMaxStart()); lastSuccessfulStart = DateConverter.toDateString(_timeZone, stats.getLastSuccessfulStart()); lastSuccessfulDuration = String.valueOf(stats.getLastSuccessfulDuration()); } else { successfulAverage = String.valueOf(successfulDuration / successfulCalls); successfulMin = String.valueOf(stats.getSuccessfulMin()); successfulMinStart = DateConverter.toDateString(_timeZone, stats.getSuccessfulMinStart()); successfulMax = String.valueOf(stats.getSuccessfulMax()); successfulMaxStart = DateConverter.toDateString(_timeZone, stats.getSuccessfulMaxStart()); lastSuccessfulStart = DateConverter.toDateString(_timeZone, stats.getLastSuccessfulStart()); lastSuccessfulDuration = String.valueOf(stats.getLastSuccessfulDuration()); } String unsuccessfulAverage; String unsuccessfulMin; String unsuccessfulMinStart; String unsuccessfulMax; String unsuccessfulMaxStart; String lastUnsuccessfulStart; String lastUnsuccessfulDuration; if (unsuccessfulCalls == 0) { unsuccessfulAverage = NOT_AVAILABLE; unsuccessfulMin = NOT_AVAILABLE; unsuccessfulMinStart = NOT_AVAILABLE; unsuccessfulMax = NOT_AVAILABLE; unsuccessfulMaxStart = NOT_AVAILABLE; lastUnsuccessfulStart = NOT_AVAILABLE; lastUnsuccessfulDuration = NOT_AVAILABLE; } else if (unsuccessfulDuration == 0) { unsuccessfulAverage = "0"; unsuccessfulMin = String.valueOf(stats.getUnsuccessfulMin()); unsuccessfulMinStart = DateConverter.toDateString(_timeZone, stats.getUnsuccessfulMinStart()); unsuccessfulMax = String.valueOf(stats.getUnsuccessfulMax()); unsuccessfulMaxStart = DateConverter.toDateString(_timeZone, stats.getUnsuccessfulMaxStart()); lastUnsuccessfulStart = DateConverter.toDateString(_timeZone, stats.getLastUnsuccessfulStart()); lastUnsuccessfulDuration = String.valueOf(stats.getLastUnsuccessfulDuration()); } else { unsuccessfulAverage = String.valueOf(unsuccessfulDuration / unsuccessfulCalls); unsuccessfulMin = String.valueOf(stats.getUnsuccessfulMin()); unsuccessfulMinStart = DateConverter.toDateString(_timeZone, stats.getUnsuccessfulMinStart()); unsuccessfulMax = String.valueOf(stats.getUnsuccessfulMax()); unsuccessfulMaxStart = DateConverter.toDateString(_timeZone, stats.getUnsuccessfulMaxStart()); lastUnsuccessfulStart = DateConverter.toDateString(_timeZone, stats.getLastUnsuccessfulStart()); lastUnsuccessfulDuration = String.valueOf(stats.getLastUnsuccessfulDuration()); } builder.startTag("function"); builder.attribute("name", function.getName()); // Successful builder.startTag("successful"); builder.attribute("count", String.valueOf(successfulCalls)); builder.attribute("average", successfulAverage); builder.startTag("min"); builder.attribute("start", successfulMinStart); builder.attribute("duration", successfulMin); builder.endTag(); // min builder.startTag("max"); builder.attribute("start", successfulMaxStart); builder.attribute("duration", successfulMax); builder.endTag(); // max builder.startTag("last"); builder.attribute("start", lastSuccessfulStart); builder.attribute("duration", lastSuccessfulDuration); builder.endTag(); // last builder.endTag(); // successful // Unsuccessful builder.startTag("unsuccessful"); builder.attribute("count", String.valueOf(unsuccessfulCalls)); builder.attribute("average", unsuccessfulAverage); builder.startTag("min"); builder.attribute("start", unsuccessfulMinStart); builder.attribute("duration", unsuccessfulMin); builder.endTag(); // min builder.startTag("max"); builder.attribute("start", unsuccessfulMaxStart); builder.attribute("duration", unsuccessfulMax); builder.endTag(); // max builder.startTag("last"); builder.attribute("start", lastUnsuccessfulStart); builder.attribute("duration", lastUnsuccessfulDuration); builder.endTag(); // last builder.endTag(); // unsuccessful builder.endTag(); // function } return builder; } /** * Returns the XINS version. * * @return * the call result, never <code>null</code>. */ private final CallResult doGetVersion() { CallResultBuilder builder = new CallResultBuilder(); builder.param("java.version", System.getProperty("java.version")); builder.param("xmlenc.version", org.znerd.xmlenc.Library.getVersion()); builder.param("xins.version", Library.getVersion()); return builder; } /** * Returns the settings. * * @return * the call result, never <code>null</code>. */ private final CallResult doGetSettings() { CallResultBuilder builder = new CallResultBuilder(); // Build settings Iterator names = _buildSettings.getNames(); builder.startTag("build"); while (names.hasNext()) { String key = (String) names.next(); String value = _buildSettings.get(key); builder.startTag("property"); builder.attribute("name", key); builder.pcdata(value); builder.endTag(); } builder.endTag(); // Runtime settings names = _runtimeSettings.getNames(); builder.startTag("runtime"); while (names.hasNext()) { String key = (String) names.next(); String value = _runtimeSettings.get(key); builder.startTag("property"); builder.attribute("name", key); builder.pcdata(value); builder.endTag(); } builder.endTag(); // System properties Enumeration e = System.getProperties().propertyNames(); builder.startTag("system"); while (e.hasMoreElements()) { String key = (String) e.nextElement(); String value = System.getProperty(key); if (key != null && value != null && key.length() > 0 && value.length() > 0) { builder.startTag("property"); builder.attribute("name", key); builder.pcdata(value); builder.endTag(); } } builder.endTag(); return builder; } /** * Enables a function. * * @param request * the servlet request, cannot be <code>null</code>. * * @return * the call result, never <code>null</code>. * * @throws NullPointerException * if <code>request == null</code>. */ private final CallResult doEnableFunction(ServletRequest request) throws NullPointerException { // Get the name of the function to enable String functionName = request.getParameter("functionName"); if (functionName == null || functionName.length() < 1) { return new BasicCallResult(false, "MissingParameters", null, null); } // Get the Function object Function function = getFunction(functionName); if (function == null) { return new BasicCallResult(false, "InvalidParameters", null, null); } // Enable or disable the function function.setEnabled(true); return SUCCESSFUL_RESULT; } /** * Disables a function. * * @param request * the servlet request, cannot be <code>null</code>. * * @return * the call result, never <code>null</code>. * * @throws NullPointerException * if <code>request == null</code>. */ private final CallResult doDisableFunction(ServletRequest request) throws NullPointerException { // Get the name of the function to disable String functionName = request.getParameter("functionName"); if (functionName == null || functionName.length() < 1) { return new BasicCallResult(false, "MissingParameters", null, null); } // Get the Function object Function function = getFunction(functionName); if (function == null) { return new BasicCallResult(false, "InvalidParameters", null, null); } // Enable or disable the function function.setEnabled(false); return SUCCESSFUL_RESULT; } }
package afc.ant.modular; import java.io.File; import java.net.URL; import java.text.MessageFormat; import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Location; import org.apache.tools.ant.ProjectComponent; import org.apache.tools.ant.Task; import org.apache.tools.ant.taskdefs.CallTarget; import org.apache.tools.ant.taskdefs.Property; import org.apache.tools.ant.taskdefs.Ant.Reference; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.PropertySet; public class CallTargetForModules extends Task { private ArrayList<ModuleElement> moduleElements = new ArrayList<ModuleElement>(); private ModuleLoader moduleLoader; // If defined then the correspondent Module object is set to this property for each module being processed. private String moduleProperty; private String target; private final ArrayList<ParamElement> params = new ArrayList<ParamElement>(); private final ArrayList<Reference> references = new ArrayList<Reference>(); private final PropertySet propertySet = new PropertySet(); // Default values match antcall's defaults. private boolean inheritAll = true; private boolean inheritRefs = false; // The number of threads used to build modules. private int threadCount = 1; @Override public void execute() throws BuildException { if (target == null) { throw new BuildException("The attribute 'target' is undefined."); } if (moduleLoader == null) { throw new BuildException("No module loader is defined."); } final int moduleCount = moduleElements.size(); if (moduleCount == 0) { throw new BuildException("At least one <module> element is required."); } for (int i = 0; i < moduleCount; ++i) { final ModuleElement moduleParam = moduleElements.get(i); if (moduleParam.path == null) { throw new BuildException("There is a <module> element with the attribute 'path' undefined."); } } final ModuleRegistry registry = new ModuleRegistry(moduleLoader); try { final ArrayList<Module> modules = new ArrayList<Module>(moduleCount); // These targets will be invoked for these modules despite of the default target name. final IdentityHashMap<Module, String> overriddenTargets = new IdentityHashMap<Module, String>(modules.size()); for (int i = 0, n = moduleCount; i < n; ++i) { final ModuleElement moduleParam = moduleElements.get(i); final Module module = registry.resolveModule(moduleParam.path); modules.add(module); /* Resolving the name of the target to be invoked for this module. If the choice * if ambiguous (i.e. there are multiple <module> elements that define the same * module whose target name configured is different) then a BuildException * is thrown to terminate the build. */ String moduleTarget = moduleParam.target == null ? target : moduleParam.target; final String oldTarget = overriddenTargets.put(module, moduleTarget); if (oldTarget != null && !oldTarget.equals(moduleTarget)) { throw new BuildException(MessageFormat.format( "Ambiguous choice of the target to be invoked for the module ''{0}''. " + "At least the targets ''{1}'' and ''{2}'' are configured.", module.getPath(), oldTarget, moduleTarget)); } } if (threadCount == 1) { processModulesSerial(modules, overriddenTargets); } else { processModulesParallel(modules, overriddenTargets); } } catch (ModuleNotLoadedException ex) { throw new BuildException(ex.getMessage(), ex); } catch (CyclicDependenciesDetectedException ex) { throw new BuildException(ex.getMessage(), ex); } } private void callTarget(final Module module, final String target) { final CallTarget antcall = (CallTarget) getProject().createTask("antcall"); antcall.init(); if (moduleProperty != null) { final Property moduleParam = antcall.createParam(); moduleParam.setName(moduleProperty); moduleParam.setValue(module); } for (int i = 0, n = params.size(); i < n; ++i) { final ParamElement param = params.get(i); param.populate(antcall.createParam()); } for (int i = 0, n = references.size(); i < n; ++i) { antcall.addReference(references.get(i)); } antcall.addPropertyset(propertySet); antcall.setInheritAll(inheritAll); antcall.setInheritRefs(inheritRefs); antcall.setTarget(target); try { antcall.perform(); } catch (RuntimeException ex) { throw buildExceptionForModule(ex, module); } } private BuildException buildExceptionForModule(final Throwable cause, final Module module) { final BuildException ex = new BuildException(MessageFormat.format( "Module ''{0}'': {1}", module.getPath(), cause.getMessage()), cause); // Gathering all information available from the original build exception. if (cause instanceof BuildException) { /* The thread that generated this exception is either the current thread or a dead thread so synchronisation is not needed to read location. */ final Location location = ((BuildException) cause).getLocation(); ex.setLocation(location == null ? Location.UNKNOWN_LOCATION : location); ex.setStackTrace(cause.getStackTrace()); } return ex; } private void processModulesSerial(final ArrayList<Module> modules, final IdentityHashMap<Module, String> overriddenTargets) throws CyclicDependenciesDetectedException { final SerialDependencyResolver dependencyResolver = new SerialDependencyResolver(); dependencyResolver.init(modules); Module module; while ((module = dependencyResolver.getFreeModule()) != null) { String target = overriddenTargets.get(module); if (target == null) { target = this.target; } callTarget(module, target); dependencyResolver.moduleProcessed(module); } } private void processModulesParallel(final ArrayList<Module> modules, final IdentityHashMap<Module, String> overriddenTargets) throws CyclicDependenciesDetectedException { final ParallelDependencyResolver dependencyResolver = new ParallelDependencyResolver(); dependencyResolver.init(modules); final AtomicBoolean buildFailed = new AtomicBoolean(false); final AtomicReference<Throwable> buildFailureException = new AtomicReference<Throwable>(); /* A stateless worker to process modules using ParallelDependencyResolver. * This instance can be used by multiple threads simultaneously. * * It does not throw an exception outside run() and preserves the * interrupted status of the thread it is executed in. */ final Runnable parallelBuildWorker = new Runnable() { public void run() { try { do { final Module module = dependencyResolver.getFreeModule(); if (module == null) { /* Either all modules are processed or the build has failed and * the resolver was aborted. Finishing execution. */ return; } String target = overriddenTargets.get(module); if (target == null) { target = CallTargetForModules.this.target; } /* Do not call dependencyResolver#moduleProcessed in case of exception! * This could make the modules that depend upon this module * (whose processing has failed!) free for acquisition, despite of * their dependee module did not succeed. * * Instead, dependencyResolver#abort() is called. */ callTarget(module, target); // Reporting this module as processed if no error is encountered. dependencyResolver.moduleProcessed(module); } while (!Thread.currentThread().isInterrupted()); } catch (Throwable ex) { buildFailed.set(true); buildFailureException.set(ex); /* Ensure that other threads will stop module processing right after their current module is processed. */ dependencyResolver.abort(); } } }; // The current thread will be the last thread to process modules. final int threadsToCreate = threadCount-1; final Thread[] threads = new Thread[threadsToCreate]; for (int i = 0; i < threadsToCreate; ++i) { final Thread t = new Thread(parallelBuildWorker); threads[i] = t; t.start(); } try { // The current thread is one of the threads that process the modules. parallelBuildWorker.run(); } finally { /* Waiting for all worker threads to finish even if the build fails on * a module that was being processed by this thread. This will allow the * 'build failed' message to be the last one. */ joinThreads(threads); } if (buildFailed.get()) { /* buildFailureException could contain either RuntimeException or Error because this is what could be thrown in thread#run(). */ final Throwable ex = buildFailureException.get(); if (ex instanceof RuntimeException) { throw (RuntimeException) ex; // includes properly initialised BuildException } else { throw (Error) ex; } } } private static void joinThreads(final Thread[] threads) { /* parallelBuildWorker preserves the interrupted status of the current thread * so an InterruptedException is thrown if this thread starts waiting * for a helper thread to join. This leads to all helper threads interrupted * so that the build finished rapidly and gracefully. */ try { for (final Thread t : threads) { t.join(); } } catch (InterruptedException ex) { /* Interrupting all the activities so that the build finishes as quick as possible. * This is fine if an already finished thread is interrupted. */ for (final Thread t : threads) { t.interrupt(); } Thread.currentThread().interrupt(); throw new BuildException("The build thread was interrupted."); } } /** * <p>Creates a new {@link ModuleElement} container that backs the nested element * {@code <module>} of this {@code <callTargetForModules>} task. Multiple nested * {@code <module>} elements are allowed.</p> * * @return the {@code ModuleElement} created. It is never {@code null}. */ public ModuleElement createModule() { final ModuleElement module = new ModuleElement(); moduleElements.add(module); return module; } /** * <p>Sets a {@link ModuleLoader} that is to be used by this {@code <callTargetForModules>} * task. One and only one module loader must be defined for a {@code <callTargetForModules>} * task. The name of the nested element is defined by the name of the Ant type used to pass * this instance of {@code ModuleLoader}.</p> * * @param moduleLoader the {@code ModuleLoader} instance to be used by this * {@code <callTargetForModules>} task. {@code null} value is not allowed. * * @throws BuildException if more than one {@code ModuleLoader} is defined for this * {@code <callTargetForModules>} task. * @throws NullPointerException if <em>moduleLoader</em> is {@code null}. */ public void addConfigured(final ModuleLoader moduleLoader) { if (moduleLoader == null) { throw new NullPointerException("moduleLoader"); } if (this.moduleLoader != null) { throw new BuildException("Only a single module loader element is allowed."); } this.moduleLoader = moduleLoader; } /** * <p>Sets the number of threads to be used by this {@code <callTargetForModules>} * task to build independent modules in parallel. If <em>1</em> is passed then * modules are built sequentally. By default, the number of threads used is * <em>1</em>.</p> * * <p>This setter is accessible via the attribute {@code threadCount} of this * {@code <callTargetForModules>} task.</p> * * @param threadCount the number of threads to be set. It must be a positive value. * * @throws BuildException if <em>threadCount</em> is non-positive. * * @see SerialDependencyResolver * @see ParallelDependencyResolver */ public void setThreadCount(final int threadCount) { if (threadCount <= 0) { throw new BuildException(MessageFormat.format( "Invalid thread count: ''{0}''. It must be a positive value.", String.valueOf(threadCount))); } this.threadCount = threadCount; } public void setModuleProperty(final String propertyName) { moduleProperty = propertyName; } public void setTarget(final String target) { this.target = target; } public void setInheritAll(final boolean inheritAll) { this.inheritAll = inheritAll; } public void setInheritRefs(final boolean inheritRefs) { this.inheritRefs = inheritRefs; } /** * <p>Creates a new {@link ParamElement} container that backs the nested element * {@code <param>} of this {@code <callTargetForModules>} task. Multiple nested * {@code <param>} elements are allowed.</p> * * <p>This element represents a property set that is passed to the Ant project * created for each module or any project created in that project regardless of what * is set to {@code inheritAll}. This property set overrides the properties with the * same name defined in the project it is passed to. However, it does not override * the user-defined properties with the same name. This allows you to parameterise * targets that are invoked for modules.</p> * * @return the {@code ParamElement} created. It is never {@code null}. */ public ParamElement createParam() { final ParamElement param = new ParamElement(); param.setProject(getProject()); params.add(param); return param; } public void addReference(final Reference reference) { references.add(reference); } public void addPropertyset(final PropertySet propertySet) { this.propertySet.addPropertyset(propertySet); } /** * <p>Serves as the nested element {@code <module>} of the task * {@link CallTargetForModules &lt;callTargetForModules&gt;} and defines the root modules * to start build with. All modules this module depend upon (directly or indirectly) * are included into the build process.</p> * * <h3>Attributes</h3> * <table border="1"> * <thead> * <tr><th>Attribute</th> * <th>Required?</th> * <th>Description</th></tr> * </thead> * <tbody> * <tr><td>path</td> * <td>yes</td> * <td>The path of the module to be included. Non-normalised paths are allowed.</td></tr> * <tr><td>target</td> * <td>no</td> * <td>Specifies the name of the target that must be invoked for this module by * {@code <callTargetForModules>}. If this attribute is undefined then the * target defined in {@code <callTargetForModules>} is used. * This target name is not propagated to the dependee modules.</td></tr> * </tbody> * </table> */ // TODO support defining modules using regular expressions public static class ModuleElement { private String path; private String target; /** * <p>Sets the path of the module to be included into the build process.</p> * * @param path the module path. Non-normalised paths are allowed. * {@code null} should not be set because this leads to build failure. */ public void setPath(final String path) { this.path = path; } /** * <p>Sets the target to be invoked for the module defined by this * {@code <module>} element. If the module-specific target is undefined then * the target defined in {@code <callTargetForModules>} is used.</p> * * @param target the name of the target to be invoked. */ public void setTarget(final String target) { this.target = target; } } public static class ParamElement extends ProjectComponent { private String name; private String value; private File location; private File file; private URL url; private String resource; private Path classpathAttribute; private Path classpath; private Reference classpathRef; private String environment; private Reference reference; private String prefix; // relative and basedir introduced in Ant 1.8.0 are not available because Ant 1.6+ is supported. // prefixValues introduced in Ant 1.8.2 is not available because Ant 1.6+ is supported. private boolean nameSet; private boolean valueSet; private boolean locationSet; private boolean fileSet; private boolean urlSet; private boolean resourceSet; private boolean classpathAttributeSet; private boolean classpathRefSet; private boolean environmentSet; private boolean referenceSet; private boolean prefixSet; public void setName(final String name) { this.name = name; nameSet = true; } public void setValue(final String value) { this.value = value; valueSet = true; } public void setLocation(final File location) { this.location = location; locationSet = true; } public void setFile(final File file) { this.file = file; fileSet = true; } public void setUrl(final URL url) { this.url = url; urlSet = true; } public void setResource(final String resource) { this.resource = resource; resourceSet = true; } public void setClasspath(final Path classpath) { classpathAttribute = classpath; classpathAttributeSet = true; } public Path createClasspath() { if (classpath == null) { return classpath = new Path(getProject()); } else { return classpath.createPath(); } } public void setClasspathRef(final Reference reference) { classpathRef = reference; classpathRefSet = true; } public void setEnvironment(final String environment) { this.environment = environment; environmentSet = true; } public void setRefid(final Reference reference) { this.reference = reference; referenceSet = true; } public void setPrefix(final String prefix) { this.prefix = prefix; prefixSet = true; } private void populate(final Property property) { if (nameSet) { property.setName(name); } if (valueSet) { property.setValue(value); } if (locationSet) { property.setLocation(location); } if (fileSet) { property.setFile(file); } if (urlSet) { property.setUrl(url); } if (resourceSet) { property.setResource(resource); } if (classpathAttributeSet) { property.setClasspath(classpathAttribute); } if (classpath != null) { property.createClasspath().add(classpath); } if (classpathRefSet) { property.setClasspathRef(classpathRef); } if (environmentSet) { property.setEnvironment(environment); } if (referenceSet) { property.setRefid(reference); } if (prefixSet) { property.setPrefix(prefix); } } } }
package VASSAL.build.module; import VASSAL.configure.NamedKeyStrokeArrayConfigurer; import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import VASSAL.build.AbstractToolbarItem; import VASSAL.build.AutoConfigurable; import VASSAL.build.GameModule; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.properties.MutableProperty; import VASSAL.command.Command; import VASSAL.command.NullCommand; import VASSAL.command.PlayAudioClipCommand; import VASSAL.configure.AudioClipConfigurer; import VASSAL.configure.Configurer; import VASSAL.configure.ConfigurerFactory; import VASSAL.configure.FormattedExpressionConfigurer; import VASSAL.configure.IconConfigurer; import VASSAL.configure.ListConfigurer; import VASSAL.configure.NamedHotKeyConfigurer; import VASSAL.configure.PlayerIdFormattedStringConfigurer; import VASSAL.configure.PropertyExpression; import VASSAL.configure.StringEnumConfigurer; import VASSAL.configure.VisibilityCondition; import VASSAL.i18n.Resources; import VASSAL.i18n.TranslatableConfigurerFactory; import VASSAL.search.HTMLImageFinder; import VASSAL.tools.FormattedString; import VASSAL.tools.LaunchButton; import VASSAL.tools.LoopControl; import VASSAL.tools.NamedKeyStroke; import VASSAL.tools.RecursionLimitException; import VASSAL.tools.RecursionLimiter; import VASSAL.tools.SequenceEncoder; import org.apache.commons.lang3.ArrayUtils; /** * This component places a button into the controls window toolbar. * Pressing the button displays a message, plays a sound and/or sends hotkeys */ public class DoActionButton extends AbstractToolbarItem implements RecursionLimiter.Loopable { public static final String DO_REPORT = "doReport"; //$NON-NLS-1$ public static final String REPORT_FORMAT = "reportFormat"; //$NON-NLS-1$ public static final String DO_SOUND = "doSound"; //$NON-NLS-1$ public static final String SOUND_CLIP = "soundClip"; //$NON-NLS-1$ public static final String DO_HOTKEY = "doHotkey"; //$NON-NLS-1$ public static final String HOTKEYS = "hotkeys"; //$NON-NLS-1$ public static final String DO_LOOP = "doLoop"; //$NON-NLS-1$ public static final String LOOP_TYPE = "loopType"; //$NON-NLS-1$ public static final String LOOP_COUNT = "loopCount"; //$NON-NLS-1$ public static final String WHILE_EXPRESSION = "whileExpression"; //$NON-NLS-1$ public static final String UNTIL_EXPRESSION = "untilExpression"; //$NON-NLS-1$ public static final String PRE_LOOP_HOTKEY = "preLoopKey"; //$NON-NLS-1$ public static final String POST_LOOP_HOTKEY = "postLoopKey"; //$NON-NLS-1$ public static final String INDEX = "index"; //$NON-NLS-1$ public static final String INDEX_PROPERTY = "indexProperty"; //$NON-NLS-1$ public static final String INDEX_START = "indexStart"; //$NON-NLS-1$ public static final String INDEX_STEP = "indexStep"; //$NON-NLS-1$ // These 5 items are identical to those in AbstractToolItem and exist only for "clirr purposes" @Deprecated (since = "2020-10-21", forRemoval = true) public static final String BUTTON_TEXT = "text"; //$NON-NLS-1$ @Deprecated (since = "2020-10-21", forRemoval = true) public static final String TOOLTIP = "tooltip"; //$NON-NLS-1$ @Deprecated (since = "2020-10-21", forRemoval = true) public static final String NAME = "name"; //$NON-NLS-1$ @Deprecated (since = "2020-10-21", forRemoval = true) public static final String HOTKEY = "hotkey"; //$NON-NLS-1$ @Deprecated (since = "2020-10-21", forRemoval = true) public static final String ICON = "icon"; //$NON-NLS-1$ protected LaunchButton launch; protected boolean doReport = false; protected FormattedString reportFormat = new FormattedString(GameModule.getGameModule()); protected boolean doSound = false; protected String soundClip = ""; //$NON-NLS-1$ protected boolean doHotkey = false; protected List<NamedKeyStroke> hotkeys = new ArrayList<>(); protected boolean doLoop = false; protected String loopType = LoopControl.LOOP_COUNTED; protected FormattedString loopCount = new FormattedString("1"); //$NON-NLS-1$ protected PropertyExpression whileExpression = new PropertyExpression(); protected PropertyExpression untilExpression = new PropertyExpression(); protected NamedKeyStroke preLoopKey = NamedKeyStroke.NULL_KEYSTROKE; protected NamedKeyStroke postLoopKey = NamedKeyStroke.NULL_KEYSTROKE; protected boolean hasIndex = false; protected String indexProperty = ""; //$NON-NLS-1$ protected int indexStart = 1; protected int indexStep = 1; protected int indexValue; protected MutableProperty.Impl loopIndexProperty = new MutableProperty.Impl("", this); protected boolean loopPropertyRegistered = false; public DoActionButton() { final ActionListener rollAction = e -> { try { doActions(); } catch (RecursionLimitException ex) { RecursionLimiter.infiniteLoop(ex); } }; launch = makeLaunchButton(getConfigureTypeName(), getConfigureTypeName(), "", rollAction); } public static String getConfigureTypeName() { return Resources.getString("Editor.DoAction.component_type"); //$NON-NLS-1$ } @Override public String[] getAttributeNames() { return ArrayUtils.addAll(super.getAttributeNames(), DO_REPORT, REPORT_FORMAT, DO_SOUND, SOUND_CLIP, DO_HOTKEY, HOTKEYS, DO_LOOP, LOOP_TYPE, LOOP_COUNT, WHILE_EXPRESSION, UNTIL_EXPRESSION, PRE_LOOP_HOTKEY, POST_LOOP_HOTKEY, INDEX, INDEX_PROPERTY, INDEX_START, INDEX_STEP ); } @Override public String[] getAttributeDescriptions() { return ArrayUtils.addAll(super.getAttributeDescriptions(), Resources.getString("Editor.DoAction.display_message"), //$NON-NLS-1$ Resources.getString("Editor.report_format"), //$NON-NLS-1$ Resources.getString("Editor.DoAction.play_sound"), //$NON-NLS-1$ Resources.getString("Editor.DoAction.sound_clip"), //$NON-NLS-1$ Resources.getString("Editor.DoAction.send_hotkeys"), //$NON-NLS-1$ Resources.getString("Editor.DoAction.hotkeys"), //$NON-NLS-1$ Resources.getString("Editor.DoAction.repeat_actions"), //$NON-NLS-1$ Resources.getString("Editor.LoopControl.type_of_loop"), //$NON-NLS-1$ Resources.getString("Editor.LoopControl.loop_how_many"), //$NON-NLS-1$ Resources.getString("Editor.LoopControl.looping_continues"), //$NON-NLS-1$ Resources.getString("Editor.LoopControl.looping_ends"), //$NON-NLS-1$ Resources.getString("Editor.DoAction.perform_before"), //$NON-NLS-1$ Resources.getString("Editor.DoAction.perform_after"), //$NON-NLS-1$ Resources.getString("Editor.LoopControl.loop_index"), //$NON-NLS-1$ Resources.getString("Editor.LoopControl.index_name"), //$NON-NLS-1$ Resources.getString("Editor.LoopControl.index_start"), //$NON-NLS-1$ Resources.getString("Editor.LoopControl.index_step") //$NON-NLS-1$ ); } @Override @SuppressWarnings("unchecked") public Class<?>[] getAttributeTypes() { return ArrayUtils.addAll(super.getAttributeTypes(), Boolean.class, ReportFormatConfig.class, Boolean.class, SoundConfig.class, Boolean.class, HotkeyConfig.class, Boolean.class, LoopConfig.class, LoopCountConfig.class, PropertyExpression.class, PropertyExpression.class, NamedKeyStroke.class, NamedKeyStroke.class, Boolean.class, String.class, Integer.class, Integer.class ); } @Deprecated(since = "2020-10-01", forRemoval = true) public static class IconConfig implements ConfigurerFactory { @Override public Configurer getConfigurer(AutoConfigurable c, String key, String name) { return new IconConfigurer(key, name, null); } } public static class SoundConfig implements ConfigurerFactory { @Override public Configurer getConfigurer(AutoConfigurable c, String key, String name) { return new AudioClipConfigurer(key, name, GameModule.getGameModule().getArchiveWriter()); } } public static class ReportFormatConfig implements TranslatableConfigurerFactory { @Override public Configurer getConfigurer(AutoConfigurable c, String key, String name) { return new PlayerIdFormattedStringConfigurer(key, name, new String[]{}); } } public static class HotkeyConfig implements ConfigurerFactory { @Override public Configurer getConfigurer(AutoConfigurable c, String key, String name) { return new NamedKeyStrokeArrayConfigurer(key, name, ((DoActionButton) c).hotkeys); } } /** * @deprecated not replaced */ @Deprecated (since = "2020-10-21", forRemoval = true) public static class NamedHotkeyListConfigurer extends ListConfigurer { public NamedHotkeyListConfigurer(String key, String name, List<NamedKeyStroke> list) { super(key, name, list); } @Override protected Configurer buildChildConfigurer() { return new NamedHotKeyConfigurer(null, Resources.getString(Resources.HOTKEY_LABEL)); } } public static class LoopConfig implements ConfigurerFactory { @Override public Configurer getConfigurer(AutoConfigurable c, String key, String name) { return new LoopTypeConfig(key, name, ((DoActionButton) c).loopType); } } public static class LoopTypeConfig extends StringEnumConfigurer { public LoopTypeConfig(String key, String name, String loopType) { super(key, name, LoopControl.LOOP_TYPE_DESCS); setValue(LoopControl.loopTypeToDesc(loopType)); } public String[] getValidValues(AutoConfigurable target) { return LoopControl.LOOP_TYPE_DESCS; } @Override public String getValueString() { return LoopControl.loopDescToType(super.getValueString()); } } public static class LoopCountConfig implements ConfigurerFactory { @Override public Configurer getConfigurer(AutoConfigurable c, String key, String name) { return new FormattedExpressionConfigurer(key, name, ((DoActionButton) c).loopCount); } } @Override @SuppressWarnings("unchecked") public void setAttribute(String key, Object o) { if (DO_REPORT.equals(key)) { if (o instanceof String) { o = Boolean.valueOf((String) o); } doReport = (Boolean) o; } else if (REPORT_FORMAT.equals(key)) { reportFormat.setFormat((String) o); } else if (DO_SOUND.equals(key)) { if (o instanceof String) { o = Boolean.valueOf((String) o); } doSound = (Boolean) o; } if (SOUND_CLIP.equals(key)) { if (o instanceof File) { o = ((File) o).getName(); } soundClip = (String) o; } else if (DO_HOTKEY.equals(key)) { if (o instanceof String) { o = Boolean.valueOf((String) o); } doHotkey = (Boolean) o; } else if (HOTKEYS.equals(key)) { if (o instanceof String) { o = decodeHotkeys((String) o); } else if (o instanceof NamedKeyStroke[]) { o = Arrays.asList((NamedKeyStroke[]) o); } hotkeys = (List<NamedKeyStroke>) o; } else if (DO_LOOP.equals(key)) { if (o instanceof String) { o = Boolean.valueOf((String) o); } doLoop = (Boolean) o; updateLoopPropertyRegistration(); } else if (LOOP_TYPE.equals(key)) { loopType = LoopControl.loopDescToType((String) o); } else if (LOOP_COUNT.equals(key)) { loopCount.setFormat((String) o); } else if (WHILE_EXPRESSION.equals(key)) { whileExpression.setExpression((String) o); } else if (UNTIL_EXPRESSION.equals(key)) { untilExpression.setExpression((String) o); } else if (PRE_LOOP_HOTKEY.equals(key)) { if (o instanceof String) { o = NamedHotKeyConfigurer.decode((String) o); } preLoopKey = (NamedKeyStroke) o; } else if (POST_LOOP_HOTKEY.equals(key)) { if (o instanceof String) { o = NamedHotKeyConfigurer.decode((String) o); } postLoopKey = (NamedKeyStroke) o; } else if (INDEX.equals(key)) { if (o instanceof String) { o = Boolean.valueOf((String) o); } hasIndex = (Boolean) o; updateLoopPropertyRegistration(); } else if (INDEX_PROPERTY.equals(key)) { indexProperty = (String) o; loopIndexProperty.setPropertyName(indexProperty); updateLoopPropertyRegistration(); } else if (INDEX_START.equals(key)) { if (o instanceof String) { o = Integer.valueOf((String) o); } indexStart = (Integer) o; } else if (INDEX_STEP.equals(key)) { if (o instanceof String) { o = Integer.valueOf((String) o); } indexStep = (Integer) o; } else { super.setAttribute(key, o); } } @Override public String getAttributeValueString(String key) { if (DO_REPORT.equals(key)) { return String.valueOf(doReport); } else if (REPORT_FORMAT.equals(key)) { return reportFormat.getFormat(); } else if (DO_SOUND.equals(key)) { return String.valueOf(doSound); } else if (SOUND_CLIP.equals(key)) { return soundClip; } else if (DO_HOTKEY.equals(key)) { return String.valueOf(doHotkey); } else if (HOTKEYS.equals(key)) { return encodeHotkeys(); } else if (DO_LOOP.equals(key)) { return String.valueOf(doLoop); } else if (LOOP_TYPE.equals(key)) { return loopType; } else if (LOOP_COUNT.equals(key)) { return loopCount.getFormat(); } else if (WHILE_EXPRESSION.equals(key)) { return whileExpression.getExpression(); } else if (UNTIL_EXPRESSION.equals(key)) { return untilExpression.getExpression(); } else if (PRE_LOOP_HOTKEY.equals(key)) { return NamedHotKeyConfigurer.encode(preLoopKey); } else if (POST_LOOP_HOTKEY.equals(key)) { return NamedHotKeyConfigurer.encode(postLoopKey); } else if (INDEX.equals(key)) { return String.valueOf(hasIndex); } else if (INDEX_PROPERTY.equals(key)) { return indexProperty; } else if (INDEX_START.equals(key)) { return String.valueOf(indexStart); } else if (INDEX_STEP.equals(key)) { return String.valueOf(indexStep); } else { return super.getAttributeValueString(key); } } @Override public VisibilityCondition getAttributeVisibility(String name) { if (REPORT_FORMAT.equals(name)) { return () -> doReport; } else if (SOUND_CLIP.equals(name)) { return () -> doSound; } else if (HOTKEYS.equals(name)) { return () -> doHotkey; } else if (LOOP_COUNT.equals(name)) { return () -> doLoop && LoopControl.LOOP_COUNTED.equals(loopType); } else if (WHILE_EXPRESSION.equals(name)) { return () -> doLoop && LoopControl.LOOP_WHILE.equals(loopType); } else if (UNTIL_EXPRESSION.equals(name)) { return () -> doLoop && LoopControl.LOOP_UNTIL.equals(loopType); } else if (List.of(LOOP_TYPE, PRE_LOOP_HOTKEY, POST_LOOP_HOTKEY, INDEX).contains(name)) { return () -> doLoop; } else if (List.of(INDEX_PROPERTY, INDEX_START, INDEX_STEP).contains(name)) { return () -> doLoop && hasIndex; } else { return null; } } protected String encodeHotkeys() { final SequenceEncoder se = new SequenceEncoder(','); for (final NamedKeyStroke key : hotkeys) { se.append(NamedHotKeyConfigurer.encode(key)); } final String val = se.getValue(); return val == null ? "" : val; //$NON-NLS-1$ } protected List<NamedKeyStroke> decodeHotkeys(String s) { final List<NamedKeyStroke> list = new ArrayList<>(); final SequenceEncoder.Decoder sd = new SequenceEncoder.Decoder(s, ','); while (sd.hasMoreTokens()) { final NamedKeyStroke key = NamedHotKeyConfigurer.decode(sd.nextToken()); list.add(key); } return list; } @Override public Class<?>[] getAllowableConfigureComponents() { return new Class<?>[0]; } @Override public HelpFile getHelpFile() { return HelpFile.getReferenceManualPage("DoActionButton.html"); //$NON-NLS-1$ } /** * Register/Deregister the Global Property exposing the index property. It * is only visible if looping is turned on and an Index Property is specified */ protected void updateLoopPropertyRegistration() { final boolean shouldBeRegistered = doLoop && hasIndex && indexProperty.length() > 0; if (shouldBeRegistered && !loopPropertyRegistered) { loopIndexProperty.addTo(GameModule.getGameModule()); loopPropertyRegistered = true; } else if (!shouldBeRegistered && loopPropertyRegistered) { loopIndexProperty.removeFromContainer(); loopPropertyRegistered = false; } } protected void setIndexPropertyValue() { loopIndexProperty.setPropertyValue(String.valueOf(indexValue)); } protected void doActions() throws RecursionLimitException { final Command c = new NullCommand(); final GameModule mod = GameModule.getGameModule(); // Non looping case if (! doLoop) { executeActions(c); mod.sendAndLog(c); return; } // Set up Index Property indexValue = indexStart; setIndexPropertyValue(); // Issue the Pre-loop key doHotKey(c, preLoopKey); // Set up counters for a counted loop int loopCounter = 0; int loopCountLimit = 0; if (LoopControl.LOOP_COUNTED.equals(loopType)) { loopCountLimit = loopCount.getTextAsInt(mod, Resources.getString("Editor.LoopControl.loop_count"), this); //$NON-NLS-1$ } RecursionLimitException loopException = null; for (;;) { // While loop - test condition is still true before actions if (LoopControl.LOOP_WHILE.equals(loopType)) { if (!whileExpression.isTrue(mod)) { break; } } // Execute the actions and catch and looping. Save any // loop Exception to be thrown after the post-loop code // to ensure post-loop key is executed. try { executeActions(c); } catch (RecursionLimitException ex) { loopException = ex; break; } // Until loop - test condition is not false after loop if (LoopControl.LOOP_UNTIL.equals(loopType)) { if (untilExpression.isTrue(mod)) { break; } } // Counted loop - Check if looped enough times loopCounter++; if (LoopControl.LOOP_COUNTED.equals(loopType)) { if (loopCounter >= loopCountLimit) { break; } } // Otherwise check for too much looping. else { if (loopCounter >= LoopControl.LOOP_LIMIT) { loopException = new RecursionLimitException(this); break; } } // Increment the Index Variable indexValue += indexStep; setIndexPropertyValue(); } // Issue the Post-loop key doHotKey(c, postLoopKey); // Send the accumulated commands to the log mod.sendAndLog(c); // If the loop ended due to excessive looping, throw the // Exception out to the caller. if (loopException != null) { throw loopException; } } /** * Execute the set of actions that make up this button and * return the set of Commands generated. * * @param command command to execute * @throws RecursionLimitException recursion protection */ protected void executeActions(Command command) throws RecursionLimitException { final GameModule mod = GameModule.getGameModule(); // GameModule.pauseLogging() returns false if logging is already paused by // a higher level component. final boolean loggingPaused = mod.pauseLogging(); try { RecursionLimiter.startExecution(this); if (doReport) { final String report = "* " + reportFormat.getLocalizedText(); //$NON-NLS-1$ final Command c = new Chatter.DisplayText(mod.getChatter(), report); c.execute(); mod.sendAndLog(c); } if (doSound) { final String clipName = new FormattedString(soundClip).getText(mod); final Command c = new PlayAudioClipCommand(clipName); c.execute(); mod.sendAndLog(c); } // Send the hotkeys. Individual hotkeys have already executed // the commands they generated. if (doHotkey) { for (final NamedKeyStroke key : hotkeys) { mod.fireKeyStroke(key); } } } finally { RecursionLimiter.endExecution(); // If we paused the log, then retrieve the accumulated commands // generated by all actions and restart logging. if (loggingPaused) { command.append(mod.resumeLogging()); } } } // Perform an individual Hotkey and return any generated commands // if logging has not already been paused. protected void doHotKey(Command c, NamedKeyStroke key) { if (!key.isNull()) { final GameModule mod = GameModule.getGameModule(); final boolean loggingPaused = mod.pauseLogging(); try { mod.fireKeyStroke(key); } finally { if (loggingPaused) { c.append(mod.resumeLogging()); } } } } // Implement Loopable @Override public String getComponentTypeName() { return getConfigureTypeName(); } @Override public String getComponentName() { return getConfigureName(); } /** * Implement PropertyNameSource - Expose loop index property if looping turned on */ @Override public List<String> getPropertyNames() { if (doLoop && hasIndex) { final ArrayList<String> l = new ArrayList<>(); l.add(indexProperty); return l; } else { return super.getPropertyNames(); } } /** * @return a list of the Configurables string/expression fields if any (for search) */ @Override public List<String> getExpressionList() { final List<String> l = new ArrayList<>(); if (doLoop) { if (LoopControl.LOOP_WHILE.equals(loopType)) { l.add(whileExpression.getExpression()); } else if (LoopControl.LOOP_UNTIL.equals(loopType)) { l.add(untilExpression.getExpression()); } else if (LoopControl.LOOP_COUNTED.equals(loopType)) { l.add(loopCount.getFormat()); } } return l; } /** * @return a list of any Message Format strings referenced in the Configurable, if any (for search) */ @Override public List<String> getFormattedStringList() { return List.of(reportFormat.getFormat()); } /** * @return a list of any Property Names referenced in the Configurable, if any (for search) */ @Override public List<String> getPropertyList() { return List.of(indexProperty); } /** * @return a list of any Named KeyStrokes referenced in the Configurable, if any (for search) */ @Override public List<NamedKeyStroke> getNamedKeyStrokeList() { final List<NamedKeyStroke> l = new ArrayList<>(super.getNamedKeyStrokeList()); Collections.addAll(l, preLoopKey, postLoopKey); return l; } /** * In case reports use HTML and refer to any image files * @param s Collection to add image names to */ @Override public void addLocalImageNames(Collection<String> s) { final HTMLImageFinder h = new HTMLImageFinder(reportFormat.getFormat()); h.addImageNames(s); } }
package org.jaxen.function; import java.util.Iterator; import java.util.List; import org.jaxen.Context; import org.jaxen.Function; import org.jaxen.FunctionCallException; import org.jaxen.Navigator; import org.jaxen.UnsupportedAxisException; public class LangFunction implements Function { private static final String LANG_LOCALNAME = "lang"; private static final String XMLNS_URI = "http: /** * <p> * Determines whether or not the context node is written in the language specified * by the XPath string-value of <code>args.get(0)</code>, * as determined by the nearest <code>xml:lang</code> attribute in scope. * </p> * * @param context the context in which to evaluate the <code>lang()</code> function * @param args the arguments to the lang function * @return a <code>Boolean</code> indicating whether the context node is written in * the specified language * @throws FunctionCallException if <code>args</code> does not have length one * */ public Object call(Context context, List args) throws FunctionCallException { if (args.size() != 1) { throw new FunctionCallException("lang() requires exactly one argument."); } Object arg = args.get(0); try { return evaluate(context.getNodeSet(), arg, context.getNavigator() ); } catch(UnsupportedAxisException e) { throw new FunctionCallException("Can't evaluate lang()", e); } } private static Boolean evaluate(List contextNodes, Object lang, Navigator nav) throws UnsupportedAxisException { return evaluate(contextNodes.get(0), StringFunction.evaluate(lang, nav), nav) ? Boolean.TRUE : Boolean.FALSE; } private static boolean evaluate(Object node, String lang, Navigator nav) throws UnsupportedAxisException { Object element = node; if (! nav.isElement(element)) { element = nav.getParentNode(node); } while (element != null && nav.isElement(element)) { Iterator attrs = nav.getAttributeAxisIterator(element); while(attrs.hasNext()) { Object attr = attrs.next(); if(LANG_LOCALNAME.equals(nav.getAttributeName(attr)) && XMLNS_URI.equals(nav.getAttributeNamespaceUri(attr))) { return isSublang(nav.getAttributeStringValue(attr), lang); } } element = nav.getParentNode(element); } return false; } private static boolean isSublang(String sublang, String lang) { if(sublang.equalsIgnoreCase(lang)) { return true; } int ll = lang.length(); return sublang.length() > ll && sublang.charAt(ll) == '-' && sublang.substring(0, ll).equalsIgnoreCase(lang); } }
package com.scg.net.server; import java.net.Socket; import java.util.List; import com.scg.domain.ClientAccount; import com.scg.domain.Consultant; /** * The command processor for the invoice server. Implements the receiver role in the * Command design pattern, provides the execute method for all of the supported commands. * Is provided with the client and consultant lists from the Invoice server, maintains * its own time card list. * * @author Brian Stamm */ public class CommandProcessor { /** Something */ Socket connection; /** Something */ List<ClientAccount> clientList; /** Something */ List<Consultant> consultantList; /** Something */ InvoiceServer server; /** Something */ private String outPutDirectoryName; /** * Construct a CommandProcessor. * @param connection - the Socket connecting the server to the client. * @param clientList - the ClientList to add Clients to. * @param consultantList - the ConsultantList to add Consultants to. * @param server - the server that created this command processor */ public CommandProcessor(Socket connection,List<ClientAccount> clientList,List<Consultant> consultantList, InvoiceServer server) { this.connection = connection; this.clientList = new ArrayList<>(clientList); this.consultantList = new ArrayList<>(consultantList); this.server = server; } /** * Set the output directory name. * @param outPutDirectoryName - the output directory name. */ public void setOutPutDirectoryName(String outPutDirectoryName) { this.outPutDirectoryName = outPutDirectoryName; } /** * Execute and AddTimeCardCommand. * @param command - the command to execute. */ public void execute(AddTimeCardCommand command) { } /** * Execute an AddClientCommand. * @param command - the command to execute. */ public void execute(AddClientCommand command) { } /** * Execute and AddConsultantCommand. * @param command - the command to execute. */ public void execute(AddConsultantCommand command) { } /** * Execute a CreateInvoicesCommand. * @param command - the command to execute. */ public void execute(CreateInvoicesCommand command) { } /** * Execute a DisconnectCommand. * @param command - the input DisconnectCommand. */ public void execute(DisconnectCommand command) { } /** * Execute a ShutdownCommand. Closes any current connections, stops listening for * connections and then terminates the server, without calling System.exit. * @param command- the input ShutdownCommand. */ public void execute(ShutdownCommand command) { } }
package org.ggp.base.util.reflection; import java.io.File; import java.io.FilenameFilter; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Stack; import com.google.common.collect.Lists; import org.ggp.base.player.gamer.Gamer; import org.ggp.base.util.configuration.ProjectConfiguration; public class ProjectSearcher { public static void main(String[] args) { System.out.println(getAllClassesThatAre(Gamer.class)); } public static List<Class<?>> getAllClassesThatAre(Class<?> ofThisType) { return getAllClassesThatAre(ofThisType, true); } public static List<Class<?>> getAllClassesThatAre(Class<?> ofThisType, boolean mustBeConcrete) { List<Class<?>> rval = new ArrayList<Class<?>>(); findClassesInList(allClasses, ofThisType, mustBeConcrete, rval); findClassesInList(injectedClasses, ofThisType, mustBeConcrete, rval); return rval; } private static void findClassesInList(List<String> listToSearch, Class<?> ofThisType, boolean mustBeConcrete, List<Class<?>> rval) { for(String name : allClasses) { if(name.contains("Test_")) continue; Class<?> c = null; try { c = Class.forName(name); } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } if(ofThisType.isAssignableFrom(c) && (!mustBeConcrete || !Modifier.isAbstract(c.getModifiers())) ) rval.add(c); } } private static List<String> allClasses = findAllClasses(); private static List<String> injectedClasses = Lists.newArrayList(); public static <T> void injectClass(Class<T> klass) { injectedClasses.add(klass.getCanonicalName()); } private static List<String> findAllClasses() { FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { return !name.startsWith("."); } }; List<String> rval = new ArrayList<String>(); Stack<File> toProcess = new Stack<File>(); for(String classDirName : ProjectConfiguration.classRoots) toProcess.add(new File(classDirName)); while(!toProcess.empty()) { File f = toProcess.pop(); if(!f.exists()) System.out.println("Could not find expected file: [" + f + "] when running ProjectSearcher."); if(f.isDirectory()) toProcess.addAll(Arrays.asList(f.listFiles(filter))); else { if(f.getName().endsWith(".class")) { String fullyQualifiedName = f.getPath(); for(String classDirName : ProjectConfiguration.classRoots) { fullyQualifiedName = fullyQualifiedName.replaceAll("^" + classDirName.replace(File.separatorChar, '.'), ""); } fullyQualifiedName = fullyQualifiedName.replaceAll("\\.class$",""); fullyQualifiedName = fullyQualifiedName.replaceAll("^[\\\\/]", ""); fullyQualifiedName = fullyQualifiedName.replaceAll("[\\\\/]", "."); rval.add(fullyQualifiedName); } } } return rval; } }
package org.apache.commons.logging; import java.lang.reflect.Constructor; import java.util.Hashtable; import org.apache.commons.logging.impl.NoOpLog; /** * <p>Factory for creating {@link Log} instances. Applications should call * the <code>makeNewLogInstance()</code> method to instantiate new instances * of the configured {@link Log} implementation class.</p> * * <p>By default, calling <code>getInstance()</code> will use the following * algorithm:</p> * <ul> * <li>If Log4J is available, return an instance of * <code>org.apache.commons.logging.impl.Log4JCategoryLog</code>.</li> * <li>If JDK 1.4 or later is available, return an instance of * <code>org.apache.commons.logging.impl.Jdk14Logger</code>.</li> * <li>Otherwise, return an instance of * <code>org.apache.commons.logging.impl.NoOpLog</code>.</li> * </ul> * * <p>You can change the default behavior in one of two ways:</p> * <ul> * <li>On the startup command line, set the system property * <code>org.apache.commons.logging.log</code> to the name of the * <code>org.apache.commons.logging.Log</code> implementation class * you want to use.</li> * <li>At runtime, call <code>LogSource.setLogImplementation()</code>.</li> * </ul> * * @author Rod Waldhoff * @version $Id: LogSource.java,v 1.12 2002/02/03 01:31:54 sanders Exp $ */ public class LogSource { static protected Hashtable logs = new Hashtable(); /** Is log4j available (in the current classpath) */ static protected boolean log4jIsAvailable = false; /** Is JD 1.4 logging available */ static protected boolean jdk14IsAvailable = false; /** Constructor for current log class */ static protected Constructor logImplctor = null; static { // Is Log4J Available? try { if (null != Class.forName("org.apache.log4j.Category")) { log4jIsAvailable = true; } else { log4jIsAvailable = false; } } catch (Throwable t) { log4jIsAvailable = false; } // Is JDK 1.4 Logging Available? try { if (null != Class.forName("java.util.logging.Logger")) { jdk14IsAvailable = true; } else { jdk14IsAvailable = false; } } catch (Throwable t) { jdk14IsAvailable = false; } // Set the default Log implementation String name = null; try { name = System.getProperty("org.apache.commons.logging.log"); } catch (Throwable t) { } if (name != null) { try { setLogImplementation(name); } catch (Throwable t) { try { setLogImplementation ("org.apache.commons.logging.impl.NoOpLog"); } catch (Throwable u) { ; } } } else { try { if (log4jIsAvailable) { setLogImplementation ("org.apache.commons.logging.impl.Log4JCategoryLog"); } else if (jdk14IsAvailable) { setLogImplementation ("org.apache.commons.logging.impl.Jdk14Logger"); } else { setLogImplementation ("org.apache.commons.logging.impl.NoOpLog"); } } catch (Throwable t) { try { setLogImplementation ("org.apache.commons.logging.impl.NoOpLog"); } catch (Throwable u) { ; } } } } /** Don't allow others to create instances */ private LogSource() { } /** * Set the log implementation/log implementation factory * by the name of the class. The given class * must implement {@link Log}, and provide a constructor that * takes a single {@link String} argument (containing the name * of the log). */ static public void setLogImplementation(String classname) throws LinkageError, ExceptionInInitializerError, NoSuchMethodException, SecurityException, ClassNotFoundException { try { Class logclass = Class.forName(classname); Class[] argtypes = new Class[1]; argtypes[0] = "".getClass(); logImplctor = logclass.getConstructor(argtypes); } catch (Throwable t) { logImplctor = null; } } /** * Set the log implementation/log implementation factory * by class. The given class must implement {@link Log}, * and provide a constructor that takes a single {@link String} * argument (containing the name of the log). */ static public void setLogImplementation(Class logclass) throws LinkageError, ExceptionInInitializerError, NoSuchMethodException, SecurityException { Class[] argtypes = new Class[1]; argtypes[0] = "".getClass(); logImplctor = logclass.getConstructor(argtypes); } /** Get a <code>Log</code> instance by class name */ static public Log getInstance(String name) { Log log = (Log) (logs.get(name)); if (null == log) { log = makeNewLogInstance(name); logs.put(name, log); } return log; } /** Get a <code>Log</code> instance by class */ static public Log getInstance(Class clazz) { return getInstance(clazz.getName()); } /** * Create a new {@link Log} implementation, based * on the given <i>name</i> * <p> * The specific {@link Log} implementation returned * is determined by the value of the * <tt>org.apache.commons.logging.log</tt> property. * The value of <tt>org.apache.commons.logging.log</tt> may be set to * the fully specified name of a class that implements * the {@link Log} interface. This class must also * have a public constructor that takes a single * {@link String} argument (containing the <i>name</i> * of the {@link Log} to be constructed. * <p> * When <tt>org.apache.commons.logging.log</tt> is not set, * or when no corresponding class can be found, * this method will return a {@link Log4JCategoryLog} * if the log4j {@link org.apache.log4j.Category} class is * available in the {@link LogSource}'s classpath, or a * {@link Jdk14Logger} if we are on a JDK 1.4 or later system, or * a {@link NoOpLog} if neither of the above conditions is true. * * @param name the log name (or category) */ static public Log makeNewLogInstance(String name) { Log log = null; try { Object[] args = new Object[1]; args[0] = name; log = (Log) (logImplctor.newInstance(args)); } catch (Throwable t) { log = null; } if (null == log) { log = new NoOpLog(name); } return log; } /** * Returns a {@link String} array containing the names of * all logs known to me. */ static public String[] getLogNames() { return (String[]) (logs.keySet().toArray(new String[logs.size()])); } }
package org.jitsi.videobridge; import java.beans.*; import java.io.*; import java.net.*; import java.util.*; import javax.media.rtp.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.jingle.*; import net.java.sip.communicator.impl.protocol.jabber.extensions.jingle.CandidateType; import net.java.sip.communicator.service.netaddr.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.media.*; import net.java.sip.communicator.util.*; import org.ice4j.*; import org.ice4j.ice.*; import org.ice4j.ice.harvest.*; import org.ice4j.socket.*; import org.jitsi.impl.neomedia.*; import org.jitsi.impl.neomedia.transform.dtls.*; import org.jitsi.service.configuration.*; import org.jitsi.service.neomedia.*; import org.jitsi.util.Logger; import org.jitsi.videobridge.eventadmin.*; import org.osgi.framework.*; /** * Implements the Jingle ICE-UDP transport. * * @author Lyubomir Marinov * @author Pawel Domas * @author Boris Grozev */ public class IceUdpTransportManager extends TransportManager { /** * The name default of the single <tt>IceStream</tt> that this * <tt>TransportManager</tt> will create/use. */ private static final String DEFAULT_ICE_STREAM_NAME = "stream"; /** * Contains the name of the property flag that may indicate that AWS address * harvesting should be explicitly disabled. */ private static final String DISABLE_AWS_HARVESTER = "org.jitsi.videobridge.DISABLE_AWS_HARVESTER"; /** * The name of the property which disables the use of a * <tt>MultiplexingTcpHostHarvester</tt>. */ private static final String DISABLE_TCP_HARVESTER = "org.jitsi.videobridge.DISABLE_TCP_HARVESTER"; /** * The name of the property which controls the port number used for * <tt>SinglePortUdpHarvester</tt>s. */ private static final String SINGLE_PORT_HARVESTER_PORT = "org.jitsi.videobridge.SINGLE_PORT_HARVESTER_PORT"; /** * Contains the name of the property flag that may indicate that AWS address * harvesting should be forced without first trying to auto detect it. */ private static final String FORCE_AWS_HARVESTER = "org.jitsi.videobridge.FORCE_AWS_HARVESTER"; /** * The <tt>Logger</tt> used by the <tt>IceUdpTransportManager</tt> class and * its instances to print debug information. */ private static final Logger logger = Logger.getLogger(IceUdpTransportManager.class); /** * Contains the name of the property that would tell us if we should use * address mapping as one of our NAT traversal options as well as the local * address that we should be mapping. */ private static final String NAT_HARVESTER_LOCAL_ADDRESS = "org.jitsi.videobridge.NAT_HARVESTER_LOCAL_ADDRESS"; /** * Contains the name of the property that would tell us if we should use * address mapping as one of our NAT traversal options as well as the public * address that we should be using in addition to our local one. */ private static final String NAT_HARVESTER_PUBLIC_ADDRESS = "org.jitsi.videobridge.NAT_HARVESTER_PUBLIC_ADDRESS"; /** * The default port that the <tt>MultiplexingTcpHostHarvester</tt> will * bind to. */ private static final int TCP_DEFAULT_PORT = 443; /** * The port on which the <tt>MultiplexingTcpHostHarvester</tt> will bind to * if no port is specifically configured, and binding to * <tt>DEFAULT_TCP_PORT</tt> fails (for example, if the process doesn't have * the required privileges to bind to a port below 1024). */ private static final int TCP_FALLBACK_PORT = 4443; /** * The name of the property which specifies an additional port to be * advertised by the TCP harvester. */ private static final String TCP_HARVESTER_MAPPED_PORT = "org.jitsi.videobridge.TCP_HARVESTER_MAPPED_PORT"; /** * The name of the property which controls the port to which the * <tt>MultiplexingTcpHostHarvester</tt> will bind. */ private static final String TCP_HARVESTER_PORT = "org.jitsi.videobridge.TCP_HARVESTER_PORT"; /** * The name of the property which controls the use of ssltcp candidates by * <tt>MultiplexingTcpHostHarvester</tt>. */ private static final String TCP_HARVESTER_SSLTCP = "org.jitsi.videobridge.TCP_HARVESTER_SSLTCP"; /** * The default value of the <tt>TCP_HARVESTER_SSLTCP</tt> property. */ private static final boolean TCP_HARVESTER_SSLTCP_DEFAULT = true; /** * The single <tt>MultiplexingTcpHostHarvester</tt> instance for the * application. */ private static MultiplexingTcpHostHarvester tcpHostHarvester = null; /** * The <tt>SinglePortUdpHarvester</tt>s which will be appended to ICE * <tt>Agent</tt>s managed by <tt>IceUdpTransportManager</tt> instances. */ private static List<SinglePortUdpHarvester> singlePortHarvesters = null; /** * The flag which indicates whether application-wide harvesters, stored * in the static fields {@link #tcpHostHarvester} and * {@link #singlePortHarvesters} have been initialized. */ private static boolean staticHarvestersInitialized = false; /** * The "mapped port" added to {@link #tcpHostHarvester}, or -1. */ private static int tcpHostHarvesterMappedPort = -1; /** * Logs a specific <tt>String</tt> at debug level. * * @param s the <tt>String</tt> to log at debug level */ private static void logd(String s) { logger.info(s); } /** * The single (if any) <tt>Channel</tt> instance, whose sockets are * currently configured to accept DTLS packets. */ private Channel channelForDtls = null; /** * Whether this <tt>TransportManager</tt> has been closed. */ private boolean closed = false; /** * The <tt>Conference</tt> object that this <tt>TransportManager</tt> is * associated with. */ private final Conference conference; /** * The <tt>Thread</tt> used by this <tt>TransportManager</tt> to wait until * {@link #iceAgent} has established a connection. */ private Thread connectThread; /** * Used to synchronize access to {@link #connectThread}. */ private final Object connectThreadSyncRoot = new Object(); /** * The <tt>DtlsControl</tt> that this <tt>TransportManager</tt> uses. */ private final DtlsControlImpl dtlsControl; /** * The <tt>Agent</tt> which implements the ICE protocol and which is used * by this instance to implement the Jingle ICE-UDP transport. */ private Agent iceAgent; /** * The <tt>PropertyChangeListener</tt> which is (to be) notified about * changes in the <tt>state</tt> of {@link #iceAgent}. */ private final PropertyChangeListener iceAgentStateChangeListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent ev) { iceAgentStateChange(ev); } }; /** * Whether ICE connectivity has been established. */ private boolean iceConnected = false; /** * The <tt>IceMediaStream</tt> of {@link #iceAgent} associated with the * <tt>Channel</tt> of this instance. */ private final IceMediaStream iceStream; /** * The <tt>PropertyChangeListener</tt> which is (to be) notified about * changes in the properties of the <tt>CandidatePair</tt>s of * {@link #iceStream}. */ private final PropertyChangeListener iceStreamPairChangeListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent ev) { iceStreamPairChange(ev); } }; /** * Whether this <tt>IceUdpTransportManager</tt> will serve as the the * controlling or controlled ICE agent. */ private final boolean isControlling; /** * The number of {@link org.ice4j.ice.Component}-s to create in * {@link #iceStream}. */ private int numComponents; /** * Whether we're using rtcp-mux or not. */ private boolean rtcpmux = false; /** * The <tt>SctpConnection</tt> instance, if any, added as a <tt>Channel</tt> * to this <tt>IceUdpTransportManager</tt>. * * Currently we support a single <tt>SctpConnection</tt> in one * <tt>IceUdpTransportManager</tt> and if it exists, it will receive all * DTLS packets. */ private SctpConnection sctpConnection = null; /** * Initializes a new <tt>IceUdpTransportManager</tt> instance. * * @param conference the <tt>Conference</tt> which created this * <tt>TransportManager</tt>. * @param isControlling whether the new instance is to server as a * controlling or controlled ICE agent. * @throws IOException */ public IceUdpTransportManager(Conference conference, boolean isControlling) throws IOException { this(conference, isControlling, 2, DEFAULT_ICE_STREAM_NAME); } public IceUdpTransportManager(Conference conference, boolean isControlling, int numComponents) throws IOException { this(conference, isControlling, numComponents, DEFAULT_ICE_STREAM_NAME); } public IceUdpTransportManager(Conference conference, boolean isControlling, int numComponents, String iceStreamName) throws IOException { super(); this.conference = conference; this.numComponents = numComponents; this.rtcpmux = numComponents == 1; this.isControlling = isControlling; this.dtlsControl = new DtlsControlImpl(false); dtlsControl.registerUser(this); iceAgent = createIceAgent(isControlling, iceStreamName, rtcpmux); iceAgent.addStateChangeListener(iceAgentStateChangeListener); iceStream = iceAgent.getStream(iceStreamName); iceStream.addPairChangeListener(iceStreamPairChangeListener); EventAdmin eventAdmin = conference.getVideobridge().getEventAdmin(); if (eventAdmin != null) { eventAdmin.sendEvent(EventFactory.transportCreated(this)); } } public IceUdpTransportManager(Conference conference, boolean isControlling, String iceStreamName) throws IOException { this(conference, isControlling, 2, iceStreamName); } /** * {@inheritDoc} * * Assures that no more than one <tt>SctpConnection</tt> is added. Keeps * {@link #sctpConnection} and {@link #channelForDtls} up to date. */ @Override public boolean addChannel(Channel channel) { if (closed) return false; if (channel instanceof SctpConnection && sctpConnection != null && sctpConnection != channel) { logd("Not adding a second SctpConnection to TransportManager."); return false; } if (!super.addChannel(channel)) return false; if (channel instanceof SctpConnection) { // When an SctpConnection is added, it automatically replaces // channelForDtls, because it needs DTLS packets for the application // data inside them. sctpConnection = (SctpConnection) channel; if (channelForDtls != null) { /* * channelForDtls is necessarily an RtpChannel, because we don't * add more than one SctpConnection. The SctpConnection socket * will automatically accept DTLS. */ RtpChannel rtpChannelForDtls = (RtpChannel) channelForDtls; rtpChannelForDtls.getDatagramFilter(false).setAcceptNonRtp( false); rtpChannelForDtls.getDatagramFilter(true).setAcceptNonRtp( false); } channelForDtls = sctpConnection; } else if (channelForDtls == null) { channelForDtls = channel; RtpChannel rtpChannel = (RtpChannel) channel; // The new channelForDtls will always accept DTLS packets on its // RTP socket. rtpChannel.getDatagramFilter(false).setAcceptNonRtp(true); // If we use rtcpmux, we don't want to accept DTLS packets on the // RTCP socket, because they will be duplicated from the RTP socket, // because both sockets are actually filters on the same underlying // socket. rtpChannel.getDatagramFilter(true).setAcceptNonRtp(!rtcpmux); } updatePayloadTypeFilters(); if (iceConnected) channel.transportConnected(); EventAdmin eventAdmin = conference.getVideobridge().getEventAdmin(); if (eventAdmin != null) { eventAdmin.sendEvent(EventFactory.transportChannelAdded(channel)); } return true; } /** * Adds to <tt>iceAgent</tt> videobridge specific candidate harvesters such * as an Amazon AWS EC2 specific harvester. * * @param iceAgent the {@link Agent} that we'd like to append new harvesters * to. * @param rtcpmux whether rtcp will be used by this * <tt>IceUdpTransportManager</tt>. */ private void appendVideobridgeHarvesters(Agent iceAgent, boolean rtcpmux) { if (rtcpmux) { initializeStaticHarvesters(); if (tcpHostHarvester != null) iceAgent.addCandidateHarvester(tcpHostHarvester); if (singlePortHarvesters != null) for (CandidateHarvester harvester : singlePortHarvesters) iceAgent.addCandidateHarvester(harvester); } AwsCandidateHarvester awsHarvester = null; //does this look like an Amazon AWS EC2 machine? if(AwsCandidateHarvester.smellsLikeAnEC2()) awsHarvester = new AwsCandidateHarvester(); ConfigurationService cfg = ServiceUtils.getService( getBundleContext(), ConfigurationService.class); //if no configuration is found then we simply log and bail if (cfg == null) { logger.info("No configuration found. " + "Will continue without custom candidate harvesters"); return; } //now that we have a conf service, check if AWS use is forced and //comply if necessary. if (awsHarvester == null && cfg.getBoolean(FORCE_AWS_HARVESTER, false)) { //ok. this doesn't look like an EC2 machine but since you //insist ... we'll behave as if it is. logger.info("Forcing use of AWS candidate harvesting."); awsHarvester = new AwsCandidateHarvester(); } //append the AWS harvester for AWS machines. if( awsHarvester != null && !cfg.getBoolean(DISABLE_AWS_HARVESTER, false)) { logger.info("Appending an AWS harvester to the ICE agent."); iceAgent.addCandidateHarvester(awsHarvester); } //if configured, append a mapping harvester. String localAddressStr = cfg.getString(NAT_HARVESTER_LOCAL_ADDRESS); String publicAddressStr = cfg.getString(NAT_HARVESTER_PUBLIC_ADDRESS); if (localAddressStr == null || publicAddressStr == null) return; TransportAddress localAddress; TransportAddress publicAddress; try { // port 9 is "discard", but the number here seems to be ignored. localAddress = new TransportAddress(localAddressStr, 9, Transport.UDP); publicAddress = new TransportAddress(publicAddressStr, 9, Transport.UDP); logger.info("Will append a NAT harvester for " + localAddress + "=>" + publicAddress); } catch(Exception exc) { logger.info("Failed to create a NAT harvester for" + " local address=" + localAddressStr + " and public address=" + publicAddressStr); return; } MappingCandidateHarvester natHarvester = new MappingCandidateHarvester(publicAddress, localAddress); iceAgent.addCandidateHarvester(natHarvester); } /** * Determines whether at least one <tt>LocalCandidate</tt> of a specific ICE * <tt>Component</tt> can reach (in the terms of the ice4j library) a * specific <tt>RemoteCandidate</tt> * * @param component the ICE <tt>Component</tt> which contains the * <tt>LocalCandidate</tt>s to check whether at least one of them can reach * the specified <tt>remoteCandidate</tt> * @param remoteCandidate the <tt>RemoteCandidate</tt> to check whether at * least one of the <tt>LocalCandidate</tt>s of the specified * <tt>component</tt> can reach it * @return <tt>true</tt> if at least one <tt>LocalCandidate</tt> of the * specified <tt>component</tt> can reach the specified * <tt>remoteCandidate</tt> */ private boolean canReach( Component component, RemoteCandidate remoteCandidate) { for (LocalCandidate localCandidate : component.getLocalCandidates()) { if (localCandidate.canReach(remoteCandidate)) return true; } return false; } /** * {@inheritDoc} * TODO: in the case of multiple <tt>Channel</tt>s in one TransportManager * it is not clear how to handle changes to the 'initiator' property * from individual channels. */ @Override protected void channelPropertyChange(PropertyChangeEvent ev) { super.channelPropertyChange(ev); /* if (Channel.INITIATOR_PROPERTY.equals(ev.getPropertyName()) && (iceAgent != null)) { Channel channel = (Channel) ev.getSource(); iceAgent.setControlling(channel.isInitiator()); } */ } /** * {@inheritDoc} */ @Override public synchronized void close() { if (!closed) { // Set this early to prevent double closing when the last channel // is removed. closed = true; for (Channel channel : getChannels()) close(channel); if (dtlsControl != null) { dtlsControl.start(null); //stop dtlsControl.cleanup(this); } //DatagramSocket[] datagramSockets = getStreamConnectorSockets(); if (iceStream != null) { iceStream.removePairStateChangeListener( iceStreamPairChangeListener); } if (iceAgent != null) { iceAgent.removeStateChangeListener(iceAgentStateChangeListener); iceAgent.free(); iceAgent = null; } /* * It seems that the ICE agent takes care of closing these if (datagramSockets != null) { if (datagramSockets[0] != null) datagramSockets[0].close(); if (datagramSockets[1] != null) datagramSockets[1].close(); } */ synchronized (connectThreadSyncRoot) { if (connectThread != null) connectThread.interrupt(); } super.close(); } } /** * {@inheritDoc} * * Keeps {@link #sctpConnection} and {@link #channelForDtls} up to date. */ @Override public boolean close(Channel channel) { boolean removed = super.close(channel); if (removed) { if (channel == sctpConnection) { sctpConnection = null; } if (channel == channelForDtls) { if (sctpConnection != null) { channelForDtls = sctpConnection; } else if (channel instanceof RtpChannel) { RtpChannel newChannelForDtls = null; for (Channel c : getChannels()) { if (c instanceof RtpChannel) newChannelForDtls = (RtpChannel) c; } if (newChannelForDtls != null) { newChannelForDtls.getDatagramFilter(false) .setAcceptNonRtp(true); newChannelForDtls.getDatagramFilter(true) .setAcceptNonRtp(!rtcpmux); } channelForDtls = newChannelForDtls; } if (channel instanceof RtpChannel) { RtpChannel rtpChannel = (RtpChannel) channel; rtpChannel.getDatagramFilter(false).setAcceptNonRtp(false); rtpChannel.getDatagramFilter(true).setAcceptNonRtp(false); } } try { StreamConnector connector = channel.getStreamConnector(); if (connector != null) { DatagramSocket datagramSocket = connector.getDataSocket(); if (datagramSocket != null) datagramSocket.close(); datagramSocket = connector.getControlSocket(); if (datagramSocket != null) datagramSocket.close(); Socket socket = connector.getDataTCPSocket(); if (socket != null) socket.close(); socket = connector.getControlTCPSocket(); if (socket != null) socket.close(); } } catch (IOException ioe) { logd( "Failed to close sockets when closing a channel:" + ioe); } updatePayloadTypeFilters(); EventAdmin eventAdmin = conference.getVideobridge().getEventAdmin(); if (eventAdmin != null) { eventAdmin.sendEvent( EventFactory.transportChannelRemoved(channel)); } channel.transportClosed(); } if (getChannels().isEmpty()) close(); return removed; } /** * Initializes a new <tt>Agent</tt> instance which implements the ICE * protocol and which is to be used by this instance to implement the Jingle * ICE-UDP transport. * * @return a new <tt>Agent</tt> instance which implements the ICE protocol * and which is to be used by this instance to implement the Jingle ICE-UDP * transport * @throws IOException if initializing a new <tt>Agent</tt> instance for the * purposes of this <tt>TransportManager</tt> fails */ private Agent createIceAgent(boolean isControlling, String iceStreamName, boolean rtcpmux) throws IOException { NetworkAddressManagerService nams = ServiceUtils.getService( getBundleContext(), NetworkAddressManagerService.class); Agent iceAgent = nams.createIceAgent(); //add videobridge specific harvesters such as a mapping and an Amazon //AWS EC2 harvester appendVideobridgeHarvesters(iceAgent, rtcpmux); iceAgent.setControlling(isControlling); iceAgent.setPerformConsentFreshness(true); PortTracker portTracker = JitsiTransportManager.getPortTracker(null); int portBase = portTracker.getPort(); IceMediaStream iceStream = nams.createIceStream( numComponents, portBase, iceStreamName, iceAgent); // Attempt to minimize subsequent bind retries. try { portTracker.setNextPort( 1 + iceStream.getComponent( numComponents > 1 ? Component.RTCP : Component.RTP) .getLocalCandidates() .get(0).getTransportAddress().getPort()); } catch (Throwable t) { if (t instanceof InterruptedException) Thread.currentThread().interrupt(); else if (t instanceof ThreadDeath) throw (ThreadDeath) t; else portTracker.setNextPort(numComponents + portBase); } return iceAgent; } /** * {@inheritDoc} */ @Override protected void describe(IceUdpTransportPacketExtension pe) { if (!closed) { pe.setPassword(iceAgent.getLocalPassword()); pe.setUfrag(iceAgent.getLocalUfrag()); for (Component component : iceStream.getComponents()) { List<LocalCandidate> candidates = component.getLocalCandidates(); if ((candidates != null) && !candidates.isEmpty()) { for (LocalCandidate candidate : candidates) { if (candidate.getTransport() == Transport.TCP && tcpHostHarvesterMappedPort != -1 && (candidate.getTransportAddress().getPort() != tcpHostHarvesterMappedPort)) { // In case we use a mapped port with the TCP // harvester, do not advertise the candidates with // the actual port that we listen on. continue; } describe(candidate, pe); } } } if (rtcpmux) pe.addChildExtension(new RtcpmuxPacketExtension()); describeDtlsControl(pe); } } /** * Adds a new <tt>CandidatePacketExtension</tt> to <tt>pe</tt>, sets the * values of its properties to the values of the respective properties of * <tt>candidate</tt>. * * @param candidate the <tt>LocalCandidate</tt> from which to take the values * of the properties to set. * @param pe the <tt>IceUdpTransportPacketExtension</tt> to which to add a * new <tt>CandidatePacketExtension</tt>. */ private void describe( LocalCandidate candidate, IceUdpTransportPacketExtension pe) { CandidatePacketExtension candidatePE = new CandidatePacketExtension(); org.ice4j.ice.Component component = candidate.getParentComponent(); candidatePE.setComponent(component.getComponentID()); candidatePE.setFoundation(candidate.getFoundation()); candidatePE.setGeneration( component.getParentStream().getParentAgent().getGeneration()); candidatePE.setID(generateCandidateID(candidate)); candidatePE.setNetwork(0); candidatePE.setPriority(candidate.getPriority()); // Advertise 'tcp' candidates for which SSL is enabled as 'ssltcp' // (although internally their transport protocol remains "tcp") Transport transport = candidate.getTransport(); if (transport == Transport.TCP && candidate.isSSL()) { transport = Transport.SSLTCP; } candidatePE.setProtocol(transport.toString()); if (transport == Transport.TCP || transport == Transport.SSLTCP) { candidatePE.setTcpType(candidate.getTcpType()); } candidatePE.setType( CandidateType.valueOf(candidate.getType().toString())); TransportAddress transportAddress = candidate.getTransportAddress(); candidatePE.setIP(transportAddress.getHostAddress()); candidatePE.setPort(transportAddress.getPort()); TransportAddress relatedAddress = candidate.getRelatedAddress(); if (relatedAddress != null) { candidatePE.setRelAddr(relatedAddress.getHostAddress()); candidatePE.setRelPort(relatedAddress.getPort()); } pe.addChildExtension(candidatePE); } /** * Sets the values of the properties of a specific * <tt>IceUdpTransportPacketExtension</tt> to the values of the * respective properties of {@link #dtlsControl} * * @param transportPE the <tt>IceUdpTransportPacketExtension</tt> on which * to set the values of the properties of <tt>dtlsControl</tt> */ private void describeDtlsControl(IceUdpTransportPacketExtension transportPE) { String fingerprint = dtlsControl.getLocalFingerprint(); String hash = dtlsControl.getLocalFingerprintHashFunction(); DtlsFingerprintPacketExtension fingerprintPE = transportPE.getFirstChildOfType( DtlsFingerprintPacketExtension.class); if (fingerprintPE == null) { fingerprintPE = new DtlsFingerprintPacketExtension(); transportPE.addChildExtension(fingerprintPE); } fingerprintPE.setFingerprint(fingerprint); fingerprintPE.setHash(hash); } /** * Sets up {@link #dtlsControl} according to <tt>transport</tt>, * adds all (supported) remote candidates from <tt>transport</tt> * to {@link #iceAgent} and starts {@link #iceAgent} if it isn't already * started. */ private synchronized void doStartConnectivityEstablishment( IceUdpTransportPacketExtension transport) { if (closed) return; if (transport.isRtcpMux()) { rtcpmux = true; if (channelForDtls != null && channelForDtls instanceof RtpChannel) { ((RtpChannel) channelForDtls) .getDatagramFilter(true).setAcceptNonRtp(false); } } List<DtlsFingerprintPacketExtension> dfpes = transport.getChildExtensionsOfType( DtlsFingerprintPacketExtension.class); if (!dfpes.isEmpty()) { Map<String, String> remoteFingerprints = new LinkedHashMap<String, String>(); for (DtlsFingerprintPacketExtension dfpe : dfpes) { remoteFingerprints.put( dfpe.getHash(), dfpe.getFingerprint()); } dtlsControl.setRemoteFingerprints(remoteFingerprints); } IceProcessingState state = iceAgent.getState(); if (IceProcessingState.COMPLETED.equals(state) || IceProcessingState.TERMINATED.equals(state)) { // Adding candidates to a completed Agent is unnecessary and has // been observed to cause problems. return; } /* * If ICE is running already, we try to update the checklists with the * candidates. Note that this is a best effort. */ boolean iceAgentStateIsRunning = IceProcessingState.RUNNING.equals(state); int remoteCandidateCount = 0; if (rtcpmux) { Component rtcpComponent = iceStream.getComponent(Component.RTCP); if (rtcpComponent != null) iceStream.removeComponent(rtcpComponent); } // Different stream may have different ufrag/password String ufrag = transport.getUfrag(); if (ufrag != null) iceStream.setRemoteUfrag(ufrag); String password = transport.getPassword(); if (password != null) iceStream.setRemotePassword(password); List<CandidatePacketExtension> candidates = transport.getChildExtensionsOfType( CandidatePacketExtension.class); if (iceAgentStateIsRunning && (candidates.size() == 0)) return; // Sort the remote candidates (host < reflexive < relayed) in order // to create first the host, then the reflexive, the relayed // candidates and thus be able to set the relative-candidate // matching the rel-addr/rel-port attribute. Collections.sort(candidates); int generation = iceAgent.getGeneration(); for (CandidatePacketExtension candidate : candidates) { /* * Is the remote candidate from the current generation of the * iceAgent? */ if (candidate.getGeneration() != generation) continue; if (rtcpmux && Component.RTCP == candidate.getComponent()) { logger.warn("Received an RTCP candidate, but we're using" + " rtcp-mux. Ignoring."); continue; } Component component = iceStream.getComponent(candidate.getComponent()); String relAddr; int relPort; TransportAddress relatedAddress = null; if (((relAddr = candidate.getRelAddr()) != null) && ((relPort = candidate.getRelPort()) != -1)) { relatedAddress = new TransportAddress( relAddr, relPort, Transport.parse(candidate.getProtocol())); } RemoteCandidate relatedCandidate = component.findRemoteCandidate(relatedAddress); RemoteCandidate remoteCandidate = new RemoteCandidate( new TransportAddress( candidate.getIP(), candidate.getPort(), Transport.parse( candidate.getProtocol())), component, org.ice4j.ice.CandidateType.parse( candidate.getType().toString()), candidate.getFoundation(), candidate.getPriority(), relatedCandidate); /* * XXX IceUdpTransportManager harvests host candidates only and * the ICE Components utilize the UDP protocol/transport only at * the time of this writing. The ice4j library will, of course, * check the theoretical reachability between the local and the * remote candidates. However, we would like (1) to not mess * with a possibly running iceAgent and (2) to return a * consistent return value. */ if (!canReach(component, remoteCandidate)) continue; if (iceAgentStateIsRunning) component.addUpdateRemoteCandidates(remoteCandidate); else component.addRemoteCandidate(remoteCandidate); remoteCandidateCount++; } if (iceAgentStateIsRunning) { if (remoteCandidateCount == 0) { /* * XXX Effectively, the check above but realizing that all * candidates were ignored: iceAgentStateIsRunning * && (candidates.size() == 0). */ return; } else { // update all components of all streams for (IceMediaStream stream : iceAgent.getStreams()) { for (Component component : stream.getComponents()) component.updateRemoteCandidates(); } } } else if (remoteCandidateCount != 0) { /* * Once again because the ICE Agent does not support adding * candidates after the connectivity establishment has been started * and because multiple transport-info JingleIQs may be used to send * the whole set of transport candidates from the remote peer to the * local peer, do not really start the connectivity establishment * until we have at least one remote candidate per ICE Component. */ for (IceMediaStream stream : iceAgent.getStreams()) { for (Component component : stream.getComponents()) { if (component.getRemoteCandidateCount() < 1) { remoteCandidateCount = 0; break; } } if (remoteCandidateCount == 0) break; } if (remoteCandidateCount != 0) iceAgent.startConnectivityEstablishment(); } else { if (iceStream.getRemoteUfrag() != null && iceStream.getRemotePassword() != null) { // We don't have any remote candidates, but we already know the // remote ufrag and password, so we can start ICE. logger.info("Starting ICE agent without remote candidates."); iceAgent.startConnectivityEstablishment(); } } } /** * Generates an ID to be set on a <tt>CandidatePacketExtension</tt> to * represent a specific <tt>LocalCandidate</tt>. * * @param candidate the <tt>LocalCandidate</tt> whose ID is to be generated * @return an ID to be set on a <tt>CandidatePacketExtension</tt> to * represent the specified <tt>candidate</tt> */ private String generateCandidateID(LocalCandidate candidate) { StringBuilder candidateID = new StringBuilder(); candidateID.append(conference.getID()); candidateID.append(Long.toHexString(hashCode())); Agent iceAgent = candidate.getParentComponent().getParentStream().getParentAgent(); candidateID.append(Long.toHexString(iceAgent.hashCode())); candidateID.append(Long.toHexString(iceAgent.getGeneration())); candidateID.append(Long.toHexString(candidate.hashCode())); return candidateID.toString(); } /** * Gets the <tt>Conference</tt> object that this <tt>TransportManager</tt> * is associated with. */ public Conference getConference() { return conference; } /** * Gets the number of {@link org.ice4j.ice.Component}-s to create in * {@link #iceStream}. */ public int getNumComponents() { return numComponents; } /** * Gets the <tt>Agent</tt> which implements the ICE protocol and which is * used by this instance to implement the Jingle ICE-UDP transport. */ public Agent getAgent() { return iceAgent; } /** * Gets the <tt>IceMediaStream</tt> of {@link #iceAgent} associated with the * <tt>Channel</tt> of this instance. */ public IceMediaStream getIceStream() { return iceStream; } /** * Returns a boolean value determining whether this * <tt>IceUdpTransportManager</tt> will serve as the the controlling or * the controlled ICE agent. */ public boolean isControlling() { return isControlling; } /** * Gets the <tt>BundleContext</tt> associated with the <tt>Channel</tt> * that this {@link net.java.sip.communicator.service.protocol.media * .TransportManager} is servicing. The method is a * convenience which gets the <tt>BundleContext</tt> associated with the * XMPP component implementation in which the <tt>Videobridge</tt> * associated with this instance is executing. * * @return the <tt>BundleContext</tt> associated with this * <tt>IceUdpTransportManager</tt> */ public BundleContext getBundleContext() { return conference != null ? conference.getBundleContext() : null; } /** * {@inheritDoc} */ @Override public DtlsControl getDtlsControl(Channel channel) { return dtlsControl; } /** * Gets the <tt>IceSocketWrapper</tt> from the selected pair (if any) * from a specific {@link org.ice4j.ice.Component}. * @param component the <tt>Component</tt> from which to get a socket. * @return the <tt>IceSocketWrapper</tt> from the selected pair (if any) * from a specific {@link org.ice4j.ice.Component}. */ private IceSocketWrapper getSocketForComponent(Component component) { CandidatePair selectedPair = component.getSelectedPair(); if (selectedPair != null) { return selectedPair.getIceSocketWrapper(); } return null; } /** * {@inheritDoc} */ @Override public StreamConnector getStreamConnector(Channel channel) { if (!getChannels().contains(channel)) return null; IceSocketWrapper[] iceSockets = getStreamConnectorSockets(); IceSocketWrapper iceSocket0; if (iceSockets == null || (iceSocket0 = iceSockets[0]) == null) return null; if (channel instanceof SctpConnection) { DatagramSocket udpSocket = iceSocket0.getUDPSocket(); if (udpSocket != null) { if (udpSocket instanceof MultiplexingDatagramSocket) { MultiplexingDatagramSocket multiplexing = (MultiplexingDatagramSocket) udpSocket; try { DatagramSocket dtlsSocket = multiplexing.getSocket(new DTLSDatagramFilter()); return new DefaultStreamConnector(dtlsSocket, null); } catch (IOException ioe) { logger.warn("Failed to create DTLS socket: " + ioe); } } } else { Socket tcpSocket = iceSocket0.getTCPSocket(); if (tcpSocket != null && tcpSocket instanceof MultiplexingSocket) { MultiplexingSocket multiplexing = (MultiplexingSocket) tcpSocket; try { Socket dtlsSocket = multiplexing.getSocket(new DTLSDatagramFilter()); return new DefaultTCPStreamConnector(dtlsSocket, null); } catch(IOException ioe) { logger.warn("Failed to create DTLS socket: " + ioe); } } } return null; } if (! (channel instanceof RtpChannel)) return null; DatagramSocket udpSocket0; IceSocketWrapper iceSocket1 = iceSockets[1]; RtpChannel rtpChannel = (RtpChannel) channel; if ((udpSocket0 = iceSocket0.getUDPSocket()) != null) { DatagramSocket udpSocket1 = (iceSocket1 == null) ? null : iceSocket1.getUDPSocket(); return getUDPStreamConnector( rtpChannel, new DatagramSocket[] { udpSocket0, udpSocket1 }); } else { Socket tcpSocket0 = iceSocket0.getTCPSocket(); Socket tcpSocket1 = (iceSocket1 == null) ? null : iceSocket1.getTCPSocket(); return getTCPStreamConnector( rtpChannel, new Socket[] { tcpSocket0, tcpSocket1 }); } } /** * Gets the <tt>IceSocketWrapper</tt>s from the selected * <tt>CandidatePair</tt>(s) of the ICE agent. * TODO cache them in this instance? * @return the <tt>IceSocketWrapper</tt>s from the selected * <tt>CandidatePair</tt>(s) of the ICE agent. */ private IceSocketWrapper[] getStreamConnectorSockets() { IceSocketWrapper[] streamConnectorSockets = new IceSocketWrapper[2]; Component rtpComponent = iceStream.getComponent(Component.RTP); if (rtpComponent != null) { streamConnectorSockets[0 /* RTP */] = getSocketForComponent(rtpComponent); } if (numComponents > 1 && !rtcpmux) { Component rtcpComponent = iceStream.getComponent(Component.RTCP); if (rtcpComponent != null) { streamConnectorSockets[1 /* RTCP */] = getSocketForComponent(rtcpComponent); } } return streamConnectorSockets; } private MediaStreamTarget getStreamTarget() { MediaStreamTarget streamTarget = null; InetSocketAddress[] streamTargetAddresses = new InetSocketAddress[2]; int streamTargetAddressCount = 0; Component rtpComponent = iceStream.getComponent(Component.RTP); if (rtpComponent != null) { CandidatePair selectedPair = rtpComponent.getSelectedPair(); if (selectedPair != null) { InetSocketAddress streamTargetAddress = selectedPair .getRemoteCandidate() .getTransportAddress(); if (streamTargetAddress != null) { streamTargetAddresses[0] = streamTargetAddress; streamTargetAddressCount++; } } } if (numComponents > 1 && !rtcpmux) { Component rtcpComponent = iceStream.getComponent(Component.RTCP); if (rtcpComponent != null) { CandidatePair selectedPair = rtcpComponent.getSelectedPair(); if (selectedPair != null) { InetSocketAddress streamTargetAddress = selectedPair .getRemoteCandidate() .getTransportAddress(); if (streamTargetAddress != null) { streamTargetAddresses[1] = streamTargetAddress; streamTargetAddressCount++; } } } } if (rtcpmux) { streamTargetAddresses[1] = streamTargetAddresses[0]; streamTargetAddressCount++; } if (streamTargetAddressCount > 0) { streamTarget = new MediaStreamTarget( streamTargetAddresses[0 /* RTP */], streamTargetAddresses[1 /* RTCP */]); } return streamTarget; } /** * {@inheritDoc} */ @Override public MediaStreamTarget getStreamTarget(Channel channel) { return getStreamTarget(); } /** * Creates and returns a TCP <tt>StreamConnector</tt> to be used by a * specific <tt>RtpChannel</tt>, using <tt>iceSockets</tt> as the * underlying <tt>Socket</tt>s. * * Does not use <tt>iceSockets</tt> directly, but creates * <tt>MultiplexedSocket</tt> instances on top of them. * * @param rtpChannel the <tt>RtpChannel</tt> which is to use the created * <tt>StreamConnector</tt>. * @param iceSockets the <tt>Socket</tt>s which are to be used by the * created <tt>StreamConnector</tt>. * @return a TCP <tt>StreamConnector</tt> with the <tt>Socket</tt>s * given in <tt>iceSockets</tt> to be used by a specific * <tt>RtpChannel</tt>. */ private StreamConnector getTCPStreamConnector(RtpChannel rtpChannel, Socket[] iceSockets) { StreamConnector connector = null; if (iceSockets != null) { Socket iceSocket0 = iceSockets[0]; Socket channelSocket0 = null; if (iceSocket0 != null && iceSocket0 instanceof MultiplexingSocket) { MultiplexingSocket multiplexing = (MultiplexingSocket) iceSocket0; try { channelSocket0 = multiplexing.getSocket( rtpChannel.getDatagramFilter(false /* RTP */)); } catch (SocketException se) // never thrown {} } Socket iceSocket1 = rtcpmux ? iceSocket0 : iceSockets[1]; Socket channelSocket1 = null; if (iceSocket1 != null && iceSocket1 instanceof MultiplexingSocket) { MultiplexingSocket multiplexing = (MultiplexingSocket) iceSocket1; try { channelSocket1 = multiplexing.getSocket( rtpChannel.getDatagramFilter(true /* RTCP */)); } catch (SocketException se) // never thrown {} } if (channelSocket0 != null || channelSocket1 != null) { connector = new DefaultTCPStreamConnector( channelSocket0, channelSocket1, rtcpmux); } } return connector; } /** * Creates and returns a UDP <tt>StreamConnector</tt> to be used by a * specific <tt>RtpChannel</tt>, using <tt>iceSockets</tt> as the * underlying <tt>DatagramSocket</tt>s. * * Does not use <tt>iceSockets</tt> directly, but creates * <tt>MultiplexedDatagramSocket</tt> instances on top of them. * * @param rtpChannel the <tt>RtpChannel</tt> which is to use the created * <tt>StreamConnector</tt>. * @param iceSockets the <tt>DatagramSocket</tt>s which are to be used by the * created <tt>StreamConnector</tt>. * @return a UDP <tt>StreamConnector</tt> with the <tt>DatagramSocket</tt>s * given in <tt>iceSockets</tt> to be used by a specific * <tt>RtpChannel</tt>. */ private StreamConnector getUDPStreamConnector(RtpChannel rtpChannel, DatagramSocket[] iceSockets) { StreamConnector connector = null; if (iceSockets != null) { DatagramSocket iceSocket0 = iceSockets[0]; DatagramSocket channelSocket0 = null; if (iceSocket0 != null && iceSocket0 instanceof MultiplexingDatagramSocket) { MultiplexingDatagramSocket multiplexing = (MultiplexingDatagramSocket) iceSocket0; try { channelSocket0 = multiplexing.getSocket( rtpChannel.getDatagramFilter(false /* RTP */)); } catch (SocketException se) // never thrown {} } DatagramSocket iceSocket1 = rtcpmux ? iceSocket0 : iceSockets[1]; DatagramSocket channelSocket1 = null; if (iceSocket1 != null && iceSocket1 instanceof MultiplexingDatagramSocket) { MultiplexingDatagramSocket multiplexing = (MultiplexingDatagramSocket) iceSocket1; try { channelSocket1 = multiplexing.getSocket( rtpChannel.getDatagramFilter(true /* RTCP */)); } catch (SocketException se) // never thrown {} } if (channelSocket0 != null || channelSocket1 != null) { connector = new DefaultStreamConnector( channelSocket0, channelSocket1, rtcpmux); } } return connector; } /** * {@inheritDoc} */ @Override public String getXmlNamespace() { return IceUdpTransportPacketExtension.NAMESPACE; } /** * Notifies this instance about a change of the value of the <tt>state</tt> * property of {@link #iceAgent}. * * @param ev a <tt>PropertyChangeEvent</tt> which specifies the old and new * values of the <tt>state</tt> property of {@link #iceAgent}. */ private void iceAgentStateChange(PropertyChangeEvent ev) { /* * Log the changes in the ICE processing state of this * IceUdpTransportManager for the purposes of debugging. */ boolean interrupted = false; try { IceProcessingState oldState = (IceProcessingState) ev.getOldValue(); IceProcessingState newState = (IceProcessingState) ev.getNewValue(); StringBuilder s = new StringBuilder("ICE processing state of ") .append(getClass().getSimpleName()).append(" .append(Integer.toHexString(hashCode())) .append(" (for channels"); for (Channel channel : getChannels()) s.append(" ").append(channel.getID()); s.append(") of conference ").append(conference.getID()) .append(" changed from ").append(oldState) .append(" to ").append(newState).append("."); logd(s.toString()); EventAdmin eventAdmin = conference.getVideobridge().getEventAdmin(); if (eventAdmin != null) { eventAdmin.sendEvent(EventFactory.transportStateChanged( this, oldState, newState)); } } catch (Throwable t) { if (t instanceof InterruptedException) interrupted = true; else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } finally { if (interrupted) Thread.currentThread().interrupt(); } } /** * Notifies this instance about a change of the value of a property of a * <tt>CandidatePair</tt> of {@link #iceStream}. * * @param ev a <tt>PropertyChangeEvent</tt> which specifies the * <tt>CandidatePair</tt>, the name of the <tt>CandidatePair</tt> property, * and its old and new values */ private void iceStreamPairChange(PropertyChangeEvent ev) { if (IceMediaStream.PROPERTY_PAIR_CONSENT_FRESHNESS_CHANGED.equals( ev.getPropertyName())) { // TODO we might not necessarily want to keep all channels alive by // the ICE connection. for (Channel channel : getChannels()) channel.touch(); } } /** * Initializes the static <tt>Harvester</tt> instances used by all * <tt>IceUdpTransportManager</tt> instances, that is * {@link #tcpHostHarvester} and {@link #singlePortHarvesters}. */ private void initializeStaticHarvesters() { synchronized (IceUdpTransportManager.class) { if (staticHarvestersInitialized) return; staticHarvestersInitialized = true; ConfigurationService cfg = conference.getVideobridge().getConfigurationService(); int singlePort = -1; if ((singlePort = cfg.getInt(SINGLE_PORT_HARVESTER_PORT, -1)) != -1) { singlePortHarvesters = SinglePortUdpHarvester.createHarvesters(singlePort); if (singlePortHarvesters.isEmpty()) { singlePortHarvesters = null; logger.info("No single-port harvesters created."); } } boolean fallback = false; if (!cfg.getBoolean(DISABLE_TCP_HARVESTER, false)) { boolean ssltcp = cfg.getBoolean(TCP_HARVESTER_SSLTCP, TCP_HARVESTER_SSLTCP_DEFAULT); int port = cfg.getInt(TCP_HARVESTER_PORT, -1); if (port == -1) { fallback = true; port = TCP_DEFAULT_PORT; } try { tcpHostHarvester = new MultiplexingTcpHostHarvester(port, ssltcp); } catch (IOException ioe) { logger.warn("Failed to initialize TCP harvester on port " + port + ": " + ioe + (fallback ? ". Retrying on port " + TCP_FALLBACK_PORT : "") + "."); } if (tcpHostHarvester == null && fallback) { port = TCP_FALLBACK_PORT; try { tcpHostHarvester = new MultiplexingTcpHostHarvester( port, ssltcp); } catch (IOException e) { logger.warn("Failed to initialize TCP harvester on " + "fallback port " + port + ": " + e); return; } } if (logger.isInfoEnabled()) { logger.info("Initialized TCP harvester on port " + port + ", using SSLTCP:" + ssltcp); } String localAddressStr = cfg.getString(NAT_HARVESTER_LOCAL_ADDRESS); String publicAddressStr = cfg.getString(NAT_HARVESTER_PUBLIC_ADDRESS); if (localAddressStr != null && publicAddressStr != null) { try { tcpHostHarvester.addMappedAddress( InetAddress.getByName(publicAddressStr), InetAddress.getByName(localAddressStr)); } catch (UnknownHostException uhe) { logger.warn("Failed to add mapped address for " + publicAddressStr + " -> " + localAddressStr + ": " + uhe); } } int mappedPort = cfg.getInt(TCP_HARVESTER_MAPPED_PORT, -1); if (mappedPort != -1) { tcpHostHarvesterMappedPort = mappedPort; tcpHostHarvester.addMappedPort(mappedPort); } if (AwsCandidateHarvester.smellsLikeAnEC2()) { TransportAddress localAddress = AwsCandidateHarvester.getFace(); TransportAddress publicAddress = AwsCandidateHarvester.getMask(); if (localAddress != null && publicAddress != null) { tcpHostHarvester.addMappedAddress( publicAddress.getAddress(), localAddress.getAddress()); } } } } } /** * Notifies all channels of this <tt>TransportManager</tt> that connectivity * has been established (and they can now obtain valid values through * {@link #getStreamConnector(Channel)} and * {@link #getStreamTarget(Channel)}. */ private void onIceConnected() { iceConnected = true; EventAdmin eventAdmin = conference.getVideobridge().getEventAdmin(); if (eventAdmin != null) eventAdmin.sendEvent(EventFactory.transportConnected(this)); for (Channel channel : getChannels()) { channel.transportConnected(); } } /** * {@inheritDoc} */ @Override public void startConnectivityEstablishment( IceUdpTransportPacketExtension transport) { doStartConnectivityEstablishment(transport); synchronized (connectThreadSyncRoot) { if (connectThread == null) { connectThread = new Thread() { @Override public void run() { try { wrapupConnectivityEstablishment(); } catch (OperationFailedException ofe) { logd("Failed to connect IceUdpTransportManager: " + ofe); synchronized (connectThreadSyncRoot) { connectThread = null; return; } } IceProcessingState state = iceAgent.getState(); if (IceProcessingState.COMPLETED.equals(state) || IceProcessingState.TERMINATED.equals(state)) { startDtls(); onIceConnected(); } else { logger.warn("Failed to establish ICE connectivity," + " state: " + state); } } }; connectThread.setDaemon(true); connectThread.setName("IceUdpTransportManager connect thread"); connectThread.start(); } } } /** * Sets up {@link #dtlsControl} with a proper target (the remote sockets * from the pair(s) selected by the ICE agent) and starts it. */ private void startDtls() { dtlsControl.setSetup( isControlling ? DtlsControl.Setup.PASSIVE : DtlsControl.Setup.ACTIVE); dtlsControl.setRtcpmux(rtcpmux); // Setup the connector IceSocketWrapper[] iceSockets = getStreamConnectorSockets(); if (iceSockets == null || iceSockets[0] == null) { logd("Cannot start DTLS, no sockets from ICE."); return; } StreamConnector streamConnector; AbstractRTPConnector rtpConnector; DatagramSocket udpSocket = iceSockets[0].getUDPSocket(); if (udpSocket != null) { streamConnector = new DefaultStreamConnector( udpSocket, iceSockets[1] == null ? null : iceSockets[1].getUDPSocket(), rtcpmux); rtpConnector = new RTPConnectorUDPImpl(streamConnector); } else { //Assume/try TCP streamConnector = new DefaultTCPStreamConnector( iceSockets[0].getTCPSocket(), iceSockets[1] == null ? null : iceSockets[1].getTCPSocket(), rtcpmux); rtpConnector = new RTPConnectorTCPImpl(streamConnector); } MediaStreamTarget target = getStreamTarget(); if (target != null) { try { rtpConnector.addTarget( new SessionAddress(target.getDataAddress().getAddress(), target.getDataAddress().getPort())); } catch (IOException ioe) { logger.warn("Failed to add target to DTLS connector: " + ioe); // But do go on, because it is not necessary in all cases } } dtlsControl.setConnector(rtpConnector); dtlsControl.registerUser(this); // For DTLS, the media type doesn't matter (as long as it's not // null). dtlsControl.start(MediaType.AUDIO); } /** * Updates the states of the <tt>RtpChannelDatagramFilters</tt> for our * RTP channels, according to whether we are (effectively) using bundle * (that is, we have more than one <tt>RtpChannel</tt>). The filters are * configured to check the RTP payload type and the RTCP Sender SSRC fields * if and only if bundle is used. * * This allows non-bundled channels to work correctly without the need for * the focus to explicitly specify via COLIBRI the payload types to be used * by each channel. */ private void updatePayloadTypeFilters() { List<RtpChannel> rtpChannels = new LinkedList<RtpChannel>(); for (Channel channel : getChannels()) if (channel instanceof RtpChannel) rtpChannels.add((RtpChannel) channel); int numRtpChannels = rtpChannels.size(); if (numRtpChannels > 0) { boolean bundle = numRtpChannels > 1; for (RtpChannel channel : rtpChannels) { // Enable filtering by PT iff we are (effectively) using bundle channel.getDatagramFilter(false).setCheckRtpPayloadType(bundle); // Enable RTCP filtering by SSRC iff we are bundle channel.getDatagramFilter(true).setCheckRtcpSsrc(bundle); } } } /** * Waits until {@link #iceAgent} exits the RUNNING or WAITING state. */ private void wrapupConnectivityEstablishment() throws OperationFailedException { final Object syncRoot = new Object(); PropertyChangeListener propertyChangeListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent ev) { Object newValue = ev.getNewValue(); if (IceProcessingState.COMPLETED.equals(newValue) || IceProcessingState.FAILED.equals(newValue) || IceProcessingState.TERMINATED.equals(newValue)) { Agent iceAgent = (Agent) ev.getSource(); iceAgent.removeStateChangeListener(this); if (iceAgent == IceUdpTransportManager.this.iceAgent) { synchronized (syncRoot) { syncRoot.notify(); } } } } }; Agent iceAgent = this.iceAgent; if (iceAgent == null) { // The TransportManager has been closed, so we should return and // let the thread finish. return; } iceAgent.addStateChangeListener(propertyChangeListener); // Wait for the connectivity checks to finish if they have been started. boolean interrupted = false; IceProcessingState state = iceAgent.getState(); synchronized (syncRoot) { while (IceProcessingState.RUNNING.equals(state) || IceProcessingState.WAITING.equals(state)) { try { syncRoot.wait(1000); } catch (InterruptedException ie) { interrupted = true; } finally { state = iceAgent.getState(); if (this.iceAgent == null) break; } } } if (interrupted) Thread.currentThread().interrupt(); /* * Make sure stateChangeListener is removed from iceAgent in case its * #propertyChange(PropertyChangeEvent) has never been executed. */ iceAgent.removeStateChangeListener(propertyChangeListener); // Check the state of ICE processing and throw an exception if failed. if (this.iceAgent == null) { throw new OperationFailedException( "TransportManager closed", OperationFailedException.GENERAL_ERROR); } else if (IceProcessingState.FAILED.equals(state)) { throw new OperationFailedException( "ICE failed", OperationFailedException.GENERAL_ERROR); } } /** * Extends * <tt>net.java.sip.communicator.service.protocol.media.TransportManager</tt> * in order to get access to certain protected static methods and thus avoid * duplicating their implementations here. * * @author Lyubomir Marinov */ private static class JitsiTransportManager extends net.java.sip.communicator.service.protocol.media.TransportManager <MediaAwareCallPeer<?,?,?>> { public static PortTracker getPortTracker(MediaType mediaType) { return net.java.sip.communicator.service.protocol.media.TransportManager .getPortTracker(mediaType); } public static void initializePortNumbers() { net.java.sip.communicator.service.protocol.media.TransportManager .initializePortNumbers(); } private JitsiTransportManager(MediaAwareCallPeer<?,?,?> callPeer) { super(callPeer); } @Override public long getHarvestingTime(String arg0) { // TODO Auto-generated method stub return 0; } @Override public String getICECandidateExtendedType(String arg0) { // TODO Auto-generated method stub return null; } @Override public InetSocketAddress getICELocalHostAddress(String arg0) { // TODO Auto-generated method stub return null; } @Override public InetSocketAddress getICELocalReflexiveAddress(String arg0) { // TODO Auto-generated method stub return null; } @Override public InetSocketAddress getICELocalRelayedAddress(String arg0) { // TODO Auto-generated method stub return null; } @Override public InetSocketAddress getICERemoteHostAddress(String arg0) { // TODO Auto-generated method stub return null; } @Override public InetSocketAddress getICERemoteReflexiveAddress(String arg0) { // TODO Auto-generated method stub return null; } @Override public InetSocketAddress getICERemoteRelayedAddress(String arg0) { // TODO Auto-generated method stub return null; } @Override public String getICEState() { // TODO Auto-generated method stub return null; } @Override protected InetAddress getIntendedDestination( MediaAwareCallPeer<?,?,?> arg0) { // TODO Auto-generated method stub return null; } @Override public int getNbHarvesting() { // TODO Auto-generated method stub return 0; } @Override public int getNbHarvesting(String arg0) { // TODO Auto-generated method stub return 0; } @Override public long getTotalHarvestingTime() { // TODO Auto-generated method stub return 0; } } }
package org.apache.velocity.util; import java.io.File; import java.io.FileReader; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.StringTokenizer; import java.util.Map; /** * This class provides some methods for dynamically * invoking methods in objects, and some string * manipulation methods used by torque. The string * methods will soon be moved into the turbine * string utilities class. * * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a> * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a> * @version $Id: StringUtils.java,v 1.16 2002/02/20 11:35:11 geirm Exp $ */ public class StringUtils { /** * Line separator for the OS we are operating on. */ private static final String EOL = System.getProperty("line.separator"); /** * Length of the line separator. */ private static final int EOL_LENGTH = EOL.length(); /** * Concatenates a list of objects as a String. * * @param list The list of objects to concatenate. * @return A text representation of the concatenated objects. */ public String concat(List list) { StringBuffer sb = new StringBuffer(); int size = list.size(); for (int i = 0; i < size; i++) { sb.append(list.get(i).toString()); } return sb.toString(); } /** * Return a package name as a relative path name * * @param String package name to convert to a directory. * @return String directory path. */ static public String getPackageAsPath(String pckge) { return pckge.replace( '.', File.separator.charAt(0) ) + File.separator; } /** * <p> * Remove underscores from a string and replaces first * letters with capitals. Other letters are changed to lower case. * </p> * * <p> * For example <code>foo_bar</code> becomes <code>FooBar</code> * but <code>foo_barBar</code> becomes <code>FooBarbar</code>. * </p> * * @param data string to remove underscores from. * @return String * @deprecated Use the org.apache.commons.util.StringUtils class * instead. Using its firstLetterCaps() method in conjunction * with a StringTokenizer will achieve the same result. */ static public String removeUnderScores (String data) { String temp = null; StringBuffer out = new StringBuffer(); temp = data; StringTokenizer st = new StringTokenizer(temp, "_"); while (st.hasMoreTokens()) { String element = (String) st.nextElement(); out.append ( firstLetterCaps(element)); } return out.toString(); } /** * <p> * 'Camels Hump' replacement of underscores. * </p> * * <p> * Remove underscores from a string but leave the capitalization of the * other letters unchanged. * </p> * * <p> * For example <code>foo_barBar</code> becomes <code>FooBarBar</code>. * </p> * * @param data string to hump * @return String */ static public String removeAndHump (String data) { return removeAndHump(data,"_"); } /** * <p> * 'Camels Hump' replacement. * </p> * * <p> * Remove one string from another string but leave the capitalization of the * other letters unchanged. * </p> * * <p> * For example, removing "_" from <code>foo_barBar</code> becomes <code>FooBarBar</code>. * </p> * * @param data string to hump * @param replaceThis string to be replaced * @return String */ static public String removeAndHump (String data,String replaceThis) { String temp = null; StringBuffer out = new StringBuffer(); temp = data; StringTokenizer st = new StringTokenizer(temp, replaceThis); while (st.hasMoreTokens()) { String element = (String) st.nextElement(); out.append ( capitalizeFirstLetter(element)); }//while return out.toString(); } /** * <p> * Makes the first letter caps and the rest lowercase. * </p> * * <p> * For example <code>fooBar</code> becomes <code>Foobar</code>. * </p> * * @param data capitalize this * @return String */ static public String firstLetterCaps ( String data ) { String firstLetter = data.substring(0,1).toUpperCase(); String restLetters = data.substring(1).toLowerCase(); return firstLetter + restLetters; } /** * <p> * Capitalize the first letter but leave the rest as they are. * </p> * * <p> * For example <code>fooBar</code> becomes <code>FooBar</code>. * </p> * * @param data capitalize this * @return String */ static public String capitalizeFirstLetter ( String data ) { String firstLetter = data.substring(0,1).toUpperCase(); String restLetters = data.substring(1); return firstLetter + restLetters; } /** * Create a string array from a string separated by delim * * @param line the line to split * @param delim the delimter to split by * @return a string array of the split fields */ public static String [] split(String line, String delim) { List list = new ArrayList(); StringTokenizer t = new StringTokenizer(line, delim); while (t.hasMoreTokens()) { list.add(t.nextToken()); } return (String []) list.toArray(new String[list.size()]); } /** * Chop i characters off the end of a string. * This method assumes that any EOL characters in String s * and the platform EOL will be the same. * A 2 character EOL will count as 1 character. * * @param string String to chop. * @param i Number of characters to chop. * @return String with processed answer. */ public static String chop(String s, int i) { return chop(s, i, EOL); } /** * Chop i characters off the end of a string. * A 2 character EOL will count as 1 character. * * @param string String to chop. * @param i Number of characters to chop. * @param eol A String representing the EOL (end of line). * @return String with processed answer. */ public static String chop(String s, int i, String eol) { if ( i == 0 || s == null || eol == null ) { return s; } int length = s.length(); /* * if it is a 2 char EOL and the string ends with * it, nip it off. The EOL in this case is treated like 1 character */ if ( eol.length() == 2 && s.endsWith(eol )) { length -= 2; i -= 1; } if ( i > 0) { length -= i; } if ( length < 0) { length = 0; } return s.substring( 0, length); } public static StringBuffer stringSubstitution( String argStr, Hashtable vars ) { return stringSubstitution( argStr, (Map) vars ); } /** * Perform a series of substitutions. The substitions * are performed by replacing $variable in the target * string with the value of provided by the key "variable" * in the provided hashtable. * * @param String target string * @param Hashtable name/value pairs used for substitution * @return String target string with replacements. */ public static StringBuffer stringSubstitution(String argStr, Map vars) { StringBuffer argBuf = new StringBuffer(); for (int cIdx = 0 ; cIdx < argStr.length();) { char ch = argStr.charAt(cIdx); switch (ch) { case '$': StringBuffer nameBuf = new StringBuffer(); for (++cIdx ; cIdx < argStr.length(); ++cIdx) { ch = argStr.charAt(cIdx); if (ch == '_' || Character.isLetterOrDigit(ch)) nameBuf.append(ch); else break; } if (nameBuf.length() > 0) { String value = (String) vars.get(nameBuf.toString()); if (value != null) { argBuf.append(value); } } break; default: argBuf.append(ch); ++cIdx; break; } } return argBuf; } /** * Read the contents of a file and place them in * a string object. * * @param String path to file. * @return String contents of the file. */ public static String fileContentsToString(String file) { String contents = ""; File f = new File(file); if (f.exists()) { try { FileReader fr = new FileReader(f); char[] template = new char[(int) f.length()]; fr.read(template); contents = new String(template); } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } return contents; } /** * Remove/collapse multiple newline characters. * * @param String string to collapse newlines in. * @return String */ public static String collapseNewlines(String argStr) { char last = argStr.charAt(0); StringBuffer argBuf = new StringBuffer(); for (int cIdx = 0 ; cIdx < argStr.length(); cIdx++) { char ch = argStr.charAt(cIdx); if (ch != '\n' || last != '\n') { argBuf.append(ch); last = ch; } } return argBuf.toString(); } /** * Remove/collapse multiple spaces. * * @param String string to remove multiple spaces from. * @return String */ public static String collapseSpaces(String argStr) { char last = argStr.charAt(0); StringBuffer argBuf = new StringBuffer(); for (int cIdx = 0 ; cIdx < argStr.length(); cIdx++) { char ch = argStr.charAt(cIdx); if (ch != ' ' || last != ' ') { argBuf.append(ch); last = ch; } } return argBuf.toString(); } /** * Replaces all instances of oldString with newString in line. * Taken from the Jive forum package. * * @param String original string. * @param String string in line to replace. * @param String replace oldString with this. * @return String string with replacements. */ public static final String sub(String line, String oldString, String newString) { int i = 0; if ((i = line.indexOf(oldString, i)) >= 0) { char [] line2 = line.toCharArray(); char [] newString2 = newString.toCharArray(); int oLength = oldString.length(); StringBuffer buf = new StringBuffer(line2.length); buf.append(line2, 0, i).append(newString2); i += oLength; int j = i; while ((i = line.indexOf(oldString, i)) > 0) { buf.append(line2, j, i - j).append(newString2); i += oLength; j = i; } buf.append(line2, j, line2.length - j); return buf.toString(); } return line; } /** * Returns the output of printStackTrace as a String. * * @param e A Throwable. * @return A String. */ public static final String stackTrace(Throwable e) { String foo = null; try { // And show the Error Screen. ByteArrayOutputStream ostr = new ByteArrayOutputStream(); e.printStackTrace( new PrintWriter(ostr,true) ); foo = ostr.toString(); } catch (Exception f) { // Do nothing. } return foo; } /** * Return a context-relative path, beginning with a "/", that represents * the canonical version of the specified path after ".." and "." elements * are resolved out. If the specified path attempts to go outside the * boundaries of the current context (i.e. too many ".." path elements * are present), return <code>null</code> instead. * * @param path Path to be normalized * @return String normalized path */ public static final String normalizePath(String path) { // Normalize the slashes and add leading slash if necessary String normalized = path; if (normalized.indexOf('\\') >= 0) { normalized = normalized.replace('\\', '/'); } if (!normalized.startsWith("/")) { normalized = "/" + normalized; } // Resolve occurrences of "//" in the normalized path while (true) { int index = normalized.indexOf(" if (index < 0) break; normalized = normalized.substring(0, index) + normalized.substring(index + 1); } // Resolve occurrences of "%20" in the normalized path while (true) { int index = normalized.indexOf("%20"); if (index < 0) break; normalized = normalized.substring(0, index) + " " + normalized.substring(index + 3); } // Resolve occurrences of "/./" in the normalized path while (true) { int index = normalized.indexOf("/./"); if (index < 0) break; normalized = normalized.substring(0, index) + normalized.substring(index + 2); } // Resolve occurrences of "/../" in the normalized path while (true) { int index = normalized.indexOf("/../"); if (index < 0) break; if (index == 0) return (null); // Trying to go outside our context int index2 = normalized.lastIndexOf('/', index - 1); normalized = normalized.substring(0, index2) + normalized.substring(index + 3); } // Return the normalized path that we have completed return (normalized); } /** * If state is true then return the trueString, else * return the falseString. * * @param boolean * @param String trueString * @param String falseString */ public String select(boolean state, String trueString, String falseString) { if (state) { return trueString; } else { return falseString; } } /** * Check to see if all the string objects passed * in are empty. * * @param list A list of {@link java.lang.String} objects. * @return Whether all strings are empty. */ public boolean allEmpty(List list) { int size = list.size(); for (int i = 0; i < size; i++) { if (list.get(i) != null && list.get(i).toString().length() > 0) { return false; } } return true; } }
package org.mockito.internal.debugging; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.mockito.internal.invocation.Invocation; import org.mockito.internal.invocation.InvocationMatcher; import org.mockito.internal.util.MockitoLogger; public class DebuggingInfo { private final List<Invocation> stubbedInvocations = new LinkedList<Invocation>(); private final List<InvocationMatcher> potentiallyUnstubbedInvocations = new LinkedList<InvocationMatcher>(); //TODO this code is crap. Use different field to maintain unusedInvocations private final List<InvocationMatcher> unusedInvocations = new LinkedList<InvocationMatcher>(); private boolean collectingData; public void addStubbedInvocation(Invocation invocation) { if (!collectingData) { return; } //TODO test //this is required because we don't know if unstubbedInvocation was really stubbed later... Iterator<InvocationMatcher> unstubbedIterator = potentiallyUnstubbedInvocations.iterator(); while(unstubbedIterator.hasNext()) { InvocationMatcher unstubbed = unstubbedIterator.next(); if (unstubbed.getInvocation().equals(invocation)) { unstubbedIterator.remove(); } } stubbedInvocations.add(invocation); } public void addPotentiallyUnstubbed(InvocationMatcher invocationMatcher) { if (!collectingData) { return; } potentiallyUnstubbedInvocations.add(invocationMatcher); } public void collectData() { collectingData = true; } public void clearData() { collectingData = false; potentiallyUnstubbedInvocations.clear(); stubbedInvocations.clear(); } public void printWarnings(MockitoLogger logger) { if (hasData()) { WarningsPrinter warningsPrinter = new WarningsPrinter(stubbedInvocations, potentiallyUnstubbedInvocations); warningsPrinter.print(logger); } } public boolean hasData() { return !stubbedInvocations.isEmpty() || !potentiallyUnstubbedInvocations.isEmpty(); } @Override public String toString() { return "unusedInvocations: " + stubbedInvocations + "\nunstubbed invocations:" + potentiallyUnstubbedInvocations; } }
package org.mozilla.mozstumbler.cellscanner; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.telephony.CellLocation; import android.telephony.NeighboringCellInfo; import android.telephony.TelephonyManager; import android.telephony.cdma.CdmaCellLocation; import android.telephony.gsm.GsmCellLocation; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; public class CellInfo implements Parcelable { private static final String LOGTAG = CellInfo.class.getName(); public static final String RADIO_GSM = "gsm"; public static final String RADIO_CDMA = "cdma"; public static final String RADIO_WCDMA = "wcdma"; public static final String CELL_RADIO_GSM = "gsm"; public static final String CELL_RADIO_UMTS = "umts"; public static final String CELL_RADIO_CDMA = "cdma"; public static final String CELL_RADIO_LTE = "lte"; static final int UNKNOWN_CID = -1; static final int UNKNOWN_SIGNAL = -1000; public static final Parcelable.Creator<CellInfo> CREATOR = new Parcelable.Creator<CellInfo>() { public CellInfo createFromParcel(Parcel in) { return new CellInfo(in); } public CellInfo[] newArray(int size) { return new CellInfo[size]; } }; private String mRadio; private String mCellRadio; private int mMcc; private int mMnc; private int mCid; private int mLac; private int mSignal; private int mAsu; private int mTa; private int mPsc; CellInfo(int phoneType) { reset(); setRadio(phoneType); } private CellInfo(Parcel in) { mRadio = in.readString(); mCellRadio = in.readString(); mMcc = in.readInt(); mMnc = in.readInt(); mCid = in.readInt(); mLac = in.readInt(); mSignal = in.readInt(); mAsu = in.readInt(); mTa = in.readInt(); mPsc = in.readInt(); } public String getRadio() { return mRadio; } public String getCellRadio() { return mCellRadio; } public int getMcc() { return mMcc; } public int getMnc() { return mMnc; } public int getCid() { return mCid; } public int getLac() { return mLac; } public int getPsc() { return mPsc; } public JSONObject toJSONObject() { final JSONObject obj = new JSONObject(); try { obj.put("radio", getCellRadio()); obj.put("mcc", mMcc); obj.put("mnc", mMnc); if (mLac != UNKNOWN_CID) obj.put("lac", mLac); if (mCid != UNKNOWN_CID) obj.put("cid", mCid); if (mSignal != UNKNOWN_SIGNAL) obj.put("signal", mSignal); if (mAsu != UNKNOWN_SIGNAL) obj.put("asu", mAsu); if (mTa != UNKNOWN_CID) obj.put("ta", mTa); if (mPsc != UNKNOWN_CID) obj.put("psc", mPsc); } catch (JSONException jsonE) { throw new IllegalStateException(jsonE); } return obj; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mRadio); dest.writeString(mCellRadio); dest.writeInt(mMcc); dest.writeInt(mMnc); dest.writeInt(mCid); dest.writeInt(mLac); dest.writeInt(mSignal); dest.writeInt(mAsu); dest.writeInt(mTa); dest.writeInt(mPsc); } void reset() { mRadio = RADIO_GSM; mCellRadio = CELL_RADIO_GSM; mMcc = UNKNOWN_CID; mMnc = UNKNOWN_CID; mLac = UNKNOWN_CID; mCid = UNKNOWN_CID; mSignal = UNKNOWN_SIGNAL; mAsu = UNKNOWN_SIGNAL; mTa = UNKNOWN_CID; mPsc = UNKNOWN_CID; } void setRadio(int phoneType) { String radio = getRadioTypeName(phoneType); if (radio == null) { throw new IllegalArgumentException("Unexpected Phone Type: " + phoneType); } mRadio = radio; } void setCellLocation(CellLocation cl, int networkType, String networkOperator, Integer gsmSignalStrength, Integer cdmaRssi) { if (cl instanceof GsmCellLocation) { final int lac, cid; final GsmCellLocation gcl = (GsmCellLocation) cl; reset(); mCellRadio = getCellRadioTypeName(networkType); setNetworkOperator(networkOperator); lac = gcl.getLac(); cid = gcl.getCid(); if (lac >= 0) mLac = lac; if (cid >= 0) mCid = cid; if (Build.VERSION.SDK_INT >= 9) { final int psc = gcl.getPsc(); if (psc >= 0) mPsc = psc; } if (gsmSignalStrength != null) { mAsu = gsmSignalStrength; } } else if (cl instanceof CdmaCellLocation) { final CdmaCellLocation cdl = (CdmaCellLocation) cl; reset(); mCellRadio = getCellRadioTypeName(networkType); setNetworkOperator(networkOperator); mMnc = cdl.getSystemId(); mLac = cdl.getNetworkId(); mCid = cdl.getBaseStationId(); if (cdmaRssi != null) { mSignal = cdmaRssi; } } else { throw new IllegalArgumentException("Unexpected CellLocation type: " + cl.getClass().getName()); } } void setNeighboringCellInfo(NeighboringCellInfo nci, String networkOperator) { final int lac, cid, psc, rssi; reset(); mCellRadio = getCellRadioTypeName(nci.getNetworkType()); setNetworkOperator(networkOperator); lac = nci.getLac(); cid = nci.getCid(); psc = nci.getPsc(); rssi = nci.getRssi(); if (lac >= 0) mLac = lac; if (cid >= 0) mCid = cid; if (psc >= 0) mPsc = psc; if (rssi != NeighboringCellInfo.UNKNOWN_RSSI) mAsu = rssi; } void setGsmCellInfo(int mcc, int mnc, int lac, int cid, int asu) { mCellRadio = CELL_RADIO_GSM; mMcc = mcc != Integer.MAX_VALUE ? mcc : UNKNOWN_CID; mMnc = mnc != Integer.MAX_VALUE ? mnc : UNKNOWN_CID; mLac = lac != Integer.MAX_VALUE ? lac : UNKNOWN_CID; mCid = cid != Integer.MAX_VALUE ? cid : UNKNOWN_CID; mAsu = asu; } void setWcmdaCellInfo(int mcc, int mnc, int lac, int cid, int psc, int asu) { mCellRadio = CELL_RADIO_UMTS; mMcc = mcc != Integer.MAX_VALUE ? mcc : UNKNOWN_CID; mMnc = mnc != Integer.MAX_VALUE ? mnc : UNKNOWN_CID; mLac = lac != Integer.MAX_VALUE ? lac : UNKNOWN_CID; mCid = cid != Integer.MAX_VALUE ? cid : UNKNOWN_CID; mPsc = psc != Integer.MAX_VALUE ? psc : UNKNOWN_CID; mAsu = asu; } /** * * @param mcc Mobile Country Code, Integer.MAX_VALUE if unknown * @param mnc Mobile Network Code, Integer.MAX_VALUE if unknown * @param ci Cell Identity, Integer.MAX_VALUE if unknown * @param pci Physical Cell Id, Integer.MAX_VALUE if unknown * @param tac Tracking Area Code, Integer.MAX_VALUE if unknown * @param asu Arbitrary strength unit * @param ta Timing advance */ void setLteCellInfo(int mcc, int mnc, int ci, int pci, int tac, int asu, int ta) { mCellRadio = CELL_RADIO_LTE; mMcc = mcc != Integer.MAX_VALUE ? mcc : UNKNOWN_CID; mMnc = mnc != Integer.MAX_VALUE ? mnc : UNKNOWN_CID; mLac = tac != Integer.MAX_VALUE ? tac : UNKNOWN_CID; mCid = ci != Integer.MAX_VALUE ? ci : UNKNOWN_CID; mPsc = pci != Integer.MAX_VALUE ? pci : UNKNOWN_CID; mAsu = asu; mTa = ta; } void setCdmaCellInfo(int baseStationId, int networkId, int systemId, int dbm) { mCellRadio = CELL_RADIO_CDMA; mMnc = systemId != Integer.MAX_VALUE ? systemId : UNKNOWN_CID; mLac = networkId != Integer.MAX_VALUE ? networkId : UNKNOWN_CID; mCid = baseStationId != Integer.MAX_VALUE ? baseStationId : UNKNOWN_CID; mSignal = dbm; } void setNetworkOperator(String mccMnc) { if (mccMnc == null || mccMnc.length() < 5 || mccMnc.length() > 8) { throw new IllegalArgumentException("Bad mccMnc: " + mccMnc); } mMcc = Integer.parseInt(mccMnc.substring(0, 3)); mMnc = Integer.parseInt(mccMnc.substring(3)); } static String getCellRadioTypeName(int networkType) { switch (networkType) { // If the network is either GSM or any high-data-rate variant of it, the radio // field should be specified as `gsm`. This includes `GSM`, `EDGE` and `GPRS`. case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: return CELL_RADIO_GSM; // If the network is either UMTS or any high-data-rate variant of it, the radio // field should be specified as `umts`. This includes `UMTS`, `HSPA`, `HSDPA`, // `HSPA+` and `HSUPA`. case TelephonyManager.NETWORK_TYPE_UMTS: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_HSPAP: return CELL_RADIO_UMTS; case TelephonyManager.NETWORK_TYPE_LTE: return CELL_RADIO_LTE; // If the network is either CDMA or one of the EVDO variants, the radio // field should be specified as `cdma`. This includes `1xRTT`, `CDMA`, `eHRPD`, // `EVDO_0`, `EVDO_A`, `EVDO_B`, `IS95A` and `IS95B`. case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_EVDO_B: case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_EHRPD: case TelephonyManager.NETWORK_TYPE_IDEN: return CELL_RADIO_CDMA; default: Log.e(LOGTAG, "", new IllegalArgumentException("Unexpected network type: " + networkType)); return String.valueOf(networkType); } } private static String getRadioTypeName(int phoneType) { switch (phoneType) { case TelephonyManager.PHONE_TYPE_CDMA: return RADIO_CDMA; case TelephonyManager.PHONE_TYPE_GSM: return RADIO_GSM; case TelephonyManager.PHONE_TYPE_NONE: case TelephonyManager.PHONE_TYPE_SIP: // These devices have no radio. default: return null; } } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof CellInfo)) return false; CellInfo ci = (CellInfo) o; return mRadio.equals(ci.mRadio) && mCellRadio.equals(ci.mCellRadio) && mMcc == ci.mMcc && mMnc == ci.mMnc && mCid == ci.mCid && mLac == ci.mLac && mSignal == ci.mSignal && mAsu == ci.mAsu && mTa == ci.mTa && mPsc == ci.mPsc; } @Override public int hashCode() { int result = 17; result = 31 * result + mRadio.hashCode(); result = 31 * result + mCellRadio.hashCode(); result = 31 * result + mMcc; result = 31 * result + mMnc; result = 31 * result + mCid; result = 31 * result + mLac; result = 31 * result + mSignal; result = 31 * result + mAsu; result = 31 * result + mTa; result = 31 * result + mPsc; return result; } }
package joshua.decoder.hypergraph; import joshua.corpus.SymbolTable; import joshua.decoder.Support; import joshua.decoder.ff.FFTransitionResult; import joshua.decoder.ff.FeatureFunction; import joshua.decoder.ff.tm.Rule; import joshua.util.FileUtility; import java.io.BufferedWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.PriorityQueue; import java.util.logging.Logger; /** * this class implement: lazy k-best extraction on a hyper-graph *to seed the kbest extraction, it only needs that each deduction should have the best_cost properly set, and it does not require any list being sorted *instead, the priority queue heap_cands will do internal sorting *In fact, the real crucial cost is the transition-cost at each deduction. We store the best-cost instead of the transition cost since it is easy to do pruning and *find one-best. Moreover, the transition cost can be recovered by get_transition_cost(), though somewhat expensive * * to recover the model cost for each individual model, we should either have access to the model, or store the model cost in the deduction * (for example, in the case of disk-hypergraph, we need to store all these model cost at each deduction) * * @author Zhifei Li, <zhifei.work@gmail.com> * @version $LastChangedDate$ */ public class KbestExtraction { @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(KbestExtraction.class.getName()); private final HashMap<HGNode,VirtualItem> tbl_virtual_items = new HashMap<HGNode,VirtualItem>(); private final SymbolTable p_symbolTable;// = null; private final boolean performSanityCheck; static String root_sym = "ROOT"; static int root_id;//TODO: bug public KbestExtraction(SymbolTable symbolTable) { this(symbolTable, true); } public KbestExtraction(SymbolTable symbolTable, boolean performSanityCheck){ this.p_symbolTable = symbolTable; this.performSanityCheck = performSanityCheck; root_id = p_symbolTable.addNonterminal(root_sym); } // public void lazy_k_best_extract_hg(HyperGraph hg, ArrayList<FeatureFunction> l_models, int global_n, boolean extract_unique_nbest, int sent_id, BufferedWriter out, boolean extract_nbest_tree, boolean add_combined_score){ //long start = System.currentTimeMillis(); reset_state(); if(hg.goal_item==null)return; BufferedWriter out2= FileUtility.handle_null_writer(out); //VirtualItem virtual_goal_item = add_virtual_item( hg.goal_item); int next_n=0; while(true){ /* DerivationState cur = virtual_goal_item.lazy_k_best_extract_item(this ,++next_n,extract_unique_nbest,extract_nbest_tree);//global_n is not used at all if( cur==null || virtual_goal_item.l_nbest.size()<next_n //do not have more hypthesis || virtual_goal_item.l_nbest.size()>global_n)//get enough hyps break; String hyp_str = get_kth_hyp(cur, sent_id, l_models, extract_nbest_tree, add_combined_score); */ String hyp_str = get_kth_hyp(hg.goal_item, ++next_n, sent_id, l_models, extract_unique_nbest, extract_nbest_tree, add_combined_score); if(hyp_str==null || next_n > global_n) break; //write to files FileUtility.write_lzf(out2,hyp_str); FileUtility.write_lzf(out2,"\n"); } //g_time_kbest_extract += System.currentTimeMillis()-start; //Support.write_log_line("time_kbest_extract: "+ Chart.g_time_kbest_extract, Support.INFO); } //the only difference from the above function is: we store the nbest into an arraylist, instead of a file public void lazy_k_best_extract_hg(HyperGraph hg, ArrayList<FeatureFunction> l_models, int global_n, boolean extract_unique_nbest, int sent_id, ArrayList<String> out, boolean extract_nbest_tree, boolean add_combined_score){ //long start = System.currentTimeMillis(); reset_state(); if(hg.goal_item==null)return; //VirtualItem virtual_goal_item = add_virtual_item( hg.goal_item); int next_n=0; while(true){ /* DerivationState cur = virtual_goal_item.lazy_k_best_extract_item(this ,++next_n,extract_unique_nbest,extract_nbest_tree);//global_n is not used at all if( cur==null || virtual_goal_item.l_nbest.size()<next_n //do not have more hypthesis || virtual_goal_item.l_nbest.size()>global_n)//get enough hyps break; String hyp_str = get_kth_hyp(cur, sent_id, l_models, extract_nbest_tree, add_combined_score); */ String hyp_str = get_kth_hyp(hg.goal_item, ++next_n, sent_id, l_models, extract_unique_nbest, extract_nbest_tree, add_combined_score); if(hyp_str==null || next_n > global_n) break; //write to files out.add(hyp_str); } //g_time_kbest_extract += System.currentTimeMillis()-start; //Support.write_log_line("time_kbest_extract: "+ Chart.g_time_kbest_extract, Support.INFO); } /*TODO: this function does not work properly, do not use it !!!!!!!!!!!!!!!!!!!!!!*/ //(ROOT (S (S (S (S (S (S (S (X scientists)) (X to (X vital))) (X early)) (X untransltedword)) (X the chromosome)) (X completed)) (X has))) public static String get_hyp_string_from_tree(String tree_string){ String[] words = tree_string.split("\\s+"); StringBuffer res = new StringBuffer(); boolean first=true; for(String wrd : words){ if(wrd.matches("^\\([A-Z]+$")==false){ if(first==true) first=false; else res.append(" "); if(wrd.matches("^\\)$")==false)//not just a single ")" res.append(wrd.replaceAll("\\)", "")); } } return res.toString(); } public void reset_state(){ tbl_virtual_items.clear(); } /*get the k-th hyp at the item it * format: sent_id ||| hyp ||| individual model cost ||| combined cost * sent_id<0: do not add sent_id * l_models==null: do not add model cost * add_combined_score==f: do not add combined model cost * */ /* non-recursive function * format: sent_id ||| hyp ||| individual model cost ||| combined cost * sent_id<0: do not add sent_id * l_models==null: do not add model cost * add_combined_score==f: do not add combined model cost * */ private String convert_hyp_2_string(int sent_id, DerivationState cur, ArrayList<FeatureFunction> l_models, String str_hyp_numeric, boolean extract_nbest_tree, boolean add_combined_score, double[] model_cost){ String[] tem = str_hyp_numeric.split("\\s+"); StringBuffer str_hyp =new StringBuffer(); // if(sent_id>=0){//valid sent id must be >=0 str_hyp.append(sent_id); str_hyp.append(" ||| "); } //TODO: consider_start_sym // for(int t=0; t<tem.length; t++){ tem[t] = tem[t].trim(); if(extract_nbest_tree==true && ( tem[t].startsWith("(") || tem[t].endsWith(")"))){//tree tag if(tem[t].startsWith("(")==true){ String tag = this.p_symbolTable.getWord(new Integer(tem[t].substring(1))); str_hyp.append("("); str_hyp.append(tag); }else{ //note: it may have more than two ")", e.g., "3499))" int first_bracket_pos = tem[t].indexOf(")");//TODO: assume the tag/terminal does not have ")" String tag = this.p_symbolTable.getWord(new Integer(tem[t].substring(0,first_bracket_pos))); str_hyp.append(tag); str_hyp.append(tem[t].substring(first_bracket_pos)); } }else{//terminal symbol str_hyp.append(this.p_symbolTable.getWord(new Integer(tem[t]))); } if(t<tem.length-1) str_hyp.append(" "); } // if(model_cost!=null){ str_hyp.append(" |||"); double tem_sum=0.0; for(int k=0; k<model_cost.length; k++){/*note that all the transition cost (including finaltransition cost) is already stored in the deduction*/ str_hyp.append(String.format(" %.3f", -model_cost[k])); tem_sum += model_cost[k]*l_models.get(k).getWeight(); } //sanity check if (performSanityCheck) { if (Math.abs(cur.cost - tem_sum) > 1e-2) { System.out.println("In nbest extraction, Cost does not match; cur.cost: " + cur.cost + "; temsum: " +tem_sum); for (int k = 0; k < model_cost.length; k++) { System.out.println("model weight: " + l_models.get(k).getWeight() + "; cost: " +model_cost[k]); } System.exit(1); } } } // if(add_combined_score==true) str_hyp.append(String.format(" ||| %.3f",-cur.cost)); return str_hyp.toString(); } //add the virtualitem is necessary private VirtualItem add_virtual_item(HGNode it){ VirtualItem res = tbl_virtual_items.get(it); if(res == null){ res = new VirtualItem(it); tbl_virtual_items.put(it, res); } return res; } // /*to seed the kbest extraction, it only needs that each deduction should have the best_cost properly set, and it does not require any list being sorted *instead, the priority queue heap_cands will do internal sorting*/ private static class VirtualItem { public ArrayList<DerivationState> l_nbest = new ArrayList<DerivationState>();//sorted ArrayList of DerivationState, in the paper is: D(^) [v] private PriorityQueue<DerivationState> heap_cands = null; // remember frontier states, best-first; in the paper, it is called cand[v] private HashMap<String, Integer> derivation_tbl = null; // rememeber which DerivationState has been explored; why duplicate, e.g., 1 2 + 1 0 == 2 1 + 0 1 private HashMap<String,Integer> nbest_str_tbl = null; HGNode p_item = null; public VirtualItem(HGNode it) { this.p_item = it; } //return: the k-th hyp or null; k is started from one private DerivationState lazy_k_best_extract_item(SymbolTable p_symbol, KbestExtraction kbest_extator, int k, boolean extract_unique_nbest, boolean extract_nbest_tree ) { if (l_nbest.size() >= k) { // no need to continue return l_nbest.get(k-1); } //### we need to fill in the l_nest in order to get k-th hyp DerivationState res = null; if (null == heap_cands) { get_candidates(p_symbol, kbest_extator, extract_unique_nbest, extract_nbest_tree); } int t_added = 0; //sanity check while (l_nbest.size() < k) { if (heap_cands.size() > 0) { res = heap_cands.poll(); //derivation_tbl.remove(res.get_signature());//TODO: should remove? note that two state may be tied because the cost is the same if (extract_unique_nbest) { String res_str = res.get_hyp(p_symbol,kbest_extator, false,null,null); // We pass false for extract_nbest_tree because we want // to check that the hypothesis *strings* are unique, // not the trees. if (! nbest_str_tbl.containsKey(res_str)) { l_nbest.add(res); nbest_str_tbl.put(res_str,1); } } else { l_nbest.add(res); } lazy_next(p_symbol, kbest_extator, res, extract_unique_nbest, extract_nbest_tree);//always extend the last, add all new hyp into heap_cands //debug: sanity check t_added++; if ( ! extract_unique_nbest && t_added > 1){//this is possible only when extracting unique nbest Support.write_log_line("In lazy_k_best_extract, add more than one time, k is " + k, Support.ERROR); System.exit(1); } } else { break; } } if (l_nbest.size() < k) { res = null;//in case we do not get to the depth of k } //debug: sanity check //if(l_nbest.size()>=k && l_nbest.get(k-1)!=res){System.out.println("In lazy_k_best_extract, ranking is not correct ");System.exit(1);} return res; } //last: the last item that has been selected, we need to extend it //get the next hyp at the "last" deduction private void lazy_next(SymbolTable p_symbol, KbestExtraction kbest_extator, DerivationState last, boolean extract_unique_nbest, boolean extract_nbest_tree){ if(last.p_edge.get_ant_items()==null) return; for(int i=0; i < last.p_edge.get_ant_items().size();i++){//slide the ant item HGNode it = (HGNode) last.p_edge.get_ant_items().get(i); VirtualItem virtual_it = kbest_extator.add_virtual_item(it); int[] new_ranks = new int[last.ranks.length]; for(int c=0; c<new_ranks.length;c++) new_ranks[c]=last.ranks[c]; new_ranks[i]=last.ranks[i]+1; String new_sig = DerivationState.get_signature(last.p_edge, new_ranks, last.deduction_pos); //why duplicate, e.g., 1 2 + 1 0 == 2 1 + 0 1 if(derivation_tbl.containsKey(new_sig)==true){ continue; } virtual_it.lazy_k_best_extract_item(p_symbol, kbest_extator, new_ranks[i], extract_unique_nbest,extract_nbest_tree); if(new_ranks[i]<=virtual_it.l_nbest.size()//exist the new_ranks[i] derivation /*&& "t" is not in heap_cands*/ ){//already checked before, check this condition double cost= last.cost - ((DerivationState)virtual_it.l_nbest.get(last.ranks[i]-1)).cost + ((DerivationState)virtual_it.l_nbest.get(new_ranks[i]-1)).cost; DerivationState t = new DerivationState(last.p_parent_node, last.p_edge, new_ranks, cost, last.deduction_pos); heap_cands.add(t); derivation_tbl.put(new_sig,1); } } } //this is the seeding function, for example, it will get down to the leaf, and sort the terminals //get a 1best from each deduction, and add them into the heap_cands private void get_candidates(SymbolTable p_symbol, KbestExtraction kbest_extator, boolean extract_unique_nbest,boolean extract_nbest_tree){ heap_cands=new PriorityQueue<DerivationState>(); derivation_tbl = new HashMap<String, Integer> (); if(extract_unique_nbest==true) nbest_str_tbl=new HashMap<String,Integer> (); //sanity check if (null == p_item.l_deductions) { System.out.println("Error, l_deductions is null in get_candidates, must be wrong"); System.exit(1); } int pos=0; for(HyperEdge hyper_edge : p_item.l_deductions){ DerivationState t = get_best_derivation(p_symbol,kbest_extator, p_item, hyper_edge,pos, extract_unique_nbest, extract_nbest_tree); // why duplicate, e.g., 1 2 + 1 0 == 2 1 + 0 1 , but here we should not get duplicate if(derivation_tbl.containsKey(t.get_signature())==false){ heap_cands.add(t); derivation_tbl.put(t.get_signature(),1); }else{//sanity check System.out.println("Error: get duplicate derivation in get_candidates, this should not happen"); System.out.println("signature is " + t.get_signature()); System.out.println("l_deduction size is " + p_item.l_deductions.size()); System.exit(1); } pos++; } // TODO: if tem.size is too large, this may cause unnecessary computation, we comment the segment to accormodate the unique nbest extraction /*if(tem.size()>global_n){ heap_cands=new PriorityQueue<DerivationState>(); for(int i=1; i<=global_n; i++) heap_cands.add(tem.poll()); }else heap_cands=tem; */ } //get my best derivation, and recursively add 1best for all my children, used by get_candidates only private DerivationState get_best_derivation(SymbolTable p_symbol, KbestExtraction kbest_extator, HGNode parent_item, HyperEdge hyper_edge, int deduct_pos, boolean extract_unique_nbest,boolean extract_nbest_tree){ int[] ranks; double cost=0; if(hyper_edge.get_ant_items()==null){//axiom ranks=null; cost=hyper_edge.best_cost;//seeding: this Deduction only have one single translation for the terminal symbol }else{//best combination ranks = new int[hyper_edge.get_ant_items().size()]; for(int i=0; i < hyper_edge.get_ant_items().size();i++){//make sure the 1best at my children is ready ranks[i]=1;//rank start from one HGNode child_it = (HGNode) hyper_edge.get_ant_items().get(i);//add the 1best for my children VirtualItem virtual_child_it = kbest_extator.add_virtual_item(child_it); virtual_child_it.lazy_k_best_extract_item(p_symbol, kbest_extator, ranks[i], extract_unique_nbest,extract_nbest_tree); } cost = hyper_edge.best_cost;//seeding } DerivationState t = new DerivationState(parent_item, hyper_edge, ranks, cost, deduct_pos ); return t; } }; // /*each Item will maintain a list of this, each of which corresponds to a deduction and its children's ranks * remember the ranks of a deduction node * used for kbest extraction*/ //each DerivationState rougly correponds a hypothesis private static class DerivationState implements Comparable<DerivationState> { HGNode p_parent_node; HyperEdge p_edge;//in the paper, it is "e" /* //TODO: we assume at most one lm, and the LM is the only non-stateles model //another potential difficulty in handling multiple LMs: symbol synchronization among the LMs //accumulate deduction cost into model_cost[], used by get_hyp() private void compute_cost_not_used(HyperEdge dt, double[] model_cost, ArrayList l_models){ if(model_cost==null) return; //System.out.println("Rule is: " + dt.rule.toString()); double stateless_transition_cost =0; FeatureFunction lm_model =null; int lm_model_index = -1; for(int k=0; k< l_models.size(); k++){ FeatureFunction m = (FeatureFunction) l_models.get(k); double t_res =0; if(m.isStateful() == false){//stateless feature if(dt.get_rule()!=null){//deductions under goal item do not have rules FFTransitionResult tem_tbl = m.transition(dt.get_rule(), null, -1, -1); t_res = tem_tbl.getTransitionCost(); }else{//final transtion t_res = m.finalTransition(null); } model_cost[k] += t_res; stateless_transition_cost += t_res*m.getWeight(); }else{ lm_model = m; lm_model_index = k; } } if(lm_model_index!=-1)//have lm model model_cost[lm_model_index] += (dt.get_transition_cost(false)-stateless_transition_cost)/lm_model.getWeight(); } */ private void compute_cost(HGNode parent_item, HyperEdge dt, double[] model_cost, ArrayList<FeatureFunction> l_models){ if(model_cost==null) return; //System.out.println("Rule is: " + dt.rule.toString()); for(int k=0; k< l_models.size(); k++){ FeatureFunction m = (FeatureFunction) l_models.get(k); double t_res =0; if(dt.get_rule()!=null){//deductions under goal item do not have rules FFTransitionResult tem_tbl = HyperGraph.computeTransition(dt, m, parent_item.i, parent_item.j); t_res = tem_tbl.getTransitionCost(); }else{//final transtion t_res = HyperGraph.computeFinalTransition(dt, m); } model_cost[k] += t_res; } } //natual order by cost public int compareTo(DerivationState another) throws ClassCastException { if (!(another instanceof DerivationState)) throw new ClassCastException("An Derivation object expected."); if(this.cost < ((DerivationState)another).cost) return -1; else if(this.cost == ((DerivationState)another).cost) return 0; else return 1; } }//end of Class DerivationState }
package io.lumify.web; import com.altamiracorp.miniweb.App; import com.altamiracorp.miniweb.Handler; import com.altamiracorp.miniweb.HandlerChain; import com.google.common.base.Preconditions; import io.lumify.core.config.Configuration; import io.lumify.core.exception.LumifyAccessDeniedException; import io.lumify.core.exception.LumifyException; import io.lumify.core.model.user.UserRepository; import io.lumify.core.model.workspace.WorkspaceRepository; import io.lumify.core.user.Privilege; import io.lumify.core.user.ProxyUser; import io.lumify.core.user.User; import org.apache.commons.codec.binary.Hex; import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.JSONObject; import org.securegraph.Authorizations; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import java.io.*; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; /** * Represents the base behavior that a {@link Handler} must support * and provides common methods for handler usage */ public abstract class BaseRequestHandler implements Handler { public static final String LUMIFY_WORKSPACE_ID_HEADER_NAME = "Lumify-Workspace-Id"; public static final String LOCALE_LANGUAGE_PARAMETER = "localeLanguage"; public static final String LOCALE_COUNTRY_PARAMETER = "localeCountry"; public static final String LOCALE_VARIANT_PARAMETER = "localeVariant"; protected static final int EXPIRES_1_HOUR = 60 * 60; protected static final int EXPIRES_1_DAY = 24 * 60 * 60; private static final String RFC1123_DATE_PATTERN = "EEE, dd MMM yyyy HH:mm:ss zzz"; private final UserRepository userRepository; private final WorkspaceRepository workspaceRepository; private final Configuration configuration; protected BaseRequestHandler(UserRepository userRepository, WorkspaceRepository workspaceRepository, Configuration configuration) { this.userRepository = userRepository; this.workspaceRepository = workspaceRepository; this.configuration = configuration; } @Override public abstract void handle(HttpServletRequest request, HttpServletResponse response, HandlerChain chain) throws Exception; protected Locale getLocale(HttpServletRequest request) { String language = getOptionalParameter(request, LOCALE_LANGUAGE_PARAMETER); String country = getOptionalParameter(request, LOCALE_COUNTRY_PARAMETER); String variant = getOptionalParameter(request, LOCALE_VARIANT_PARAMETER); if (language != null) { return WebApp.getLocal(language, country, variant); } return request.getLocale(); } protected ResourceBundle getBundle(HttpServletRequest request) { WebApp webApp = getWebApp(request); Locale locale = getLocale(request); return webApp.getBundle(locale); } protected String getString(HttpServletRequest request, String key) { ResourceBundle resourceBundle = getBundle(request); return resourceBundle.getString(key); } /** * Attempts to extract the specified parameter from the provided request * * @param request The request instance containing the parameter * @param parameterName The name of the parameter to extract * @return The value of the specified parameter * @throws RuntimeException Thrown if the required parameter was not in the request */ protected String getRequiredParameter(final HttpServletRequest request, final String parameterName) { Preconditions.checkNotNull(request, "The provided request was invalid"); return getParameter(request, parameterName, false); } protected String[] getRequiredParameterArray(HttpServletRequest request, String parameterName) { Preconditions.checkNotNull(request, "The provided request was invalid"); String[] value = request.getParameterValues(parameterName); if (value == null) { throw new LumifyException(String.format("Parameter: '%s' is required in the request", parameterName)); } return value; } protected long getOptionalParameterLong(final HttpServletRequest request, final String parameterName, long defaultValue) { String val = getOptionalParameter(request, parameterName); if (val == null) { return defaultValue; } return Long.parseLong(val); } protected boolean getOptionalParameterBoolean(final HttpServletRequest request, final String parameterName, boolean defaultValue) { String val = getOptionalParameter(request, parameterName); if (val == null) { return defaultValue; } return Boolean.parseBoolean(val); } protected double getOptionalParameterDouble(final HttpServletRequest request, final String parameterName, double defaultValue) { String val = getOptionalParameter(request, parameterName); if (val == null) { return defaultValue; } return Double.parseDouble(val); } /** * Attempts to extract the specified parameter from the provided request and convert it to a long value * * @param request The request instance containing the parameter * @param parameterName The name of the parameter to extract * @return The long value of the specified parameter * @throws RuntimeException Thrown if the required parameter was not in the request */ protected long getRequiredParameterAsLong(final HttpServletRequest request, final String parameterName) { return Long.parseLong(getRequiredParameter(request, parameterName)); } /** * Attempts to extract the specified parameter from the provided request and convert it to a double value * * @param request The request instance containing the parameter * @param parameterName The name of the parameter to extract * @return The double value of the specified parameter * @throws RuntimeException Thrown if the required parameter was not in the request */ protected double getRequiredParameterAsDouble(final HttpServletRequest request, final String parameterName) { return Double.parseDouble(getRequiredParameter(request, parameterName)); } /** * Attempts to extract the specified parameter from the provided request, if available * * @param request The request instance containing the parameter * @param parameterName The name of the parameter to extract * @return The value of the specified parameter if found, null otherwise */ protected String getOptionalParameter(final HttpServletRequest request, final String parameterName) { Preconditions.checkNotNull(request, "The provided request was invalid"); return getParameter(request, parameterName, true); } protected String[] getOptionalParameterAsStringArray(final HttpServletRequest request, final String parameterName) { Preconditions.checkNotNull(request, "The provided request was invalid"); return getParameterValues(request, parameterName, true); } protected String[] getParameterValues(final HttpServletRequest request, final String parameterName, final boolean optional) { final String[] paramValues = request.getParameterValues(parameterName); if (paramValues == null) { if (!optional) { throw new RuntimeException(String.format("Parameter: '%s' is required in the request", parameterName)); } return null; } for (int i = 0; i < paramValues.length; i++) { paramValues[i] = paramValues[i]; } return paramValues; } private String getParameter(final HttpServletRequest request, final String parameterName, final boolean optional) { final String paramValue = request.getParameter(parameterName); if (paramValue == null) { if (!optional) { throw new LumifyException(String.format("Parameter: '%s' is required in the request", parameterName)); } return null; } return paramValue; } protected String getAttributeString(final HttpServletRequest request, final String name) { String attr = (String) request.getAttribute(name); if (attr != null) { return attr; } return getRequiredParameter(request, name); } protected String getActiveWorkspaceId(final HttpServletRequest request) { String workspaceId = getWorkspaceIdOrDefault(request); if (workspaceId == null || workspaceId.trim().length() == 0) { throw new LumifyException(LUMIFY_WORKSPACE_ID_HEADER_NAME + " is a required header."); } return workspaceId; } protected String getWorkspaceIdOrDefault(final HttpServletRequest request) { String workspaceId = (String) request.getAttribute("workspaceId"); if (workspaceId == null || workspaceId.trim().length() == 0) { workspaceId = request.getHeader(LUMIFY_WORKSPACE_ID_HEADER_NAME); if (workspaceId == null || workspaceId.trim().length() == 0) { workspaceId = getOptionalParameter(request, "workspaceId"); if (workspaceId == null || workspaceId.trim().length() == 0) { return null; } } } return workspaceId; } protected Authorizations getAuthorizations(final HttpServletRequest request, final User user) { String workspaceId = getWorkspaceIdOrDefault(request); if (workspaceId != null) { if (!this.workspaceRepository.hasReadPermissions(workspaceId, user)) { throw new LumifyAccessDeniedException("You do not have access to workspace: " + workspaceId, user, workspaceId); } return getUserRepository().getAuthorizations(user, workspaceId); } return getUserRepository().getAuthorizations(user); } protected Set<Privilege> getPrivileges(User user) { return getUserRepository().getPrivileges(user); } public static void setMaxAge(final HttpServletResponse response, int numberOfSeconds) { response.setHeader("Cache-Control", "max-age=" + numberOfSeconds); } public static String generateETag(byte[] data) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); byte[] md5 = digest.digest(data); return Hex.encodeHexString(md5); } catch (NoSuchAlgorithmException e) { throw new LumifyException("Could not find MD5", e); } } public static void addETagHeader(final HttpServletResponse response, String eTag) { response.setHeader("ETag", "\"" + eTag + "\""); } public boolean testEtagHeaders(HttpServletRequest request, HttpServletResponse response, String eTag) throws IOException { String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null) { if (ifNoneMatch.startsWith("\"") && ifNoneMatch.length() > 2) { ifNoneMatch = ifNoneMatch.substring(1, ifNoneMatch.length() - 1); } if (eTag.equalsIgnoreCase(ifNoneMatch)) { addETagHeader(response, eTag); respondWithNotModified(response); return true; } } return false; } protected void respondWithNotFound(final HttpServletResponse response) throws IOException { response.sendError(HttpServletResponse.SC_NOT_FOUND); } protected void respondWithNotModified(final HttpServletResponse response) throws IOException { response.sendError(HttpServletResponse.SC_NOT_MODIFIED); } protected void respondWithNotFound(final HttpServletResponse response, String message) throws IOException { response.sendError(HttpServletResponse.SC_NOT_FOUND, message); } protected void respondWithAccessDenied(final HttpServletResponse response, String message) throws IOException { response.sendError(HttpServletResponse.SC_FORBIDDEN, message); } /** * Send a Bad Request response with JSON object mapping field error messages * * @param response * @param parameterName * @param errorMessage * @param invalidValue */ protected void respondWithBadRequest(final HttpServletResponse response, final String parameterName, final String errorMessage, final String invalidValue) throws IOException { List<String> values = null; if (invalidValue != null) { values = new ArrayList<String>(); values.add(invalidValue); } respondWithBadRequest(response, parameterName, errorMessage, values); } /** * Send a Bad Request response with JSON object mapping field error messages * * @param response * @param parameterName * @param errorMessage * @param invalidValues */ protected void respondWithBadRequest(final HttpServletResponse response, final String parameterName, final String errorMessage, final List<String> invalidValues) throws IOException { JSONObject error = new JSONObject(); error.put(parameterName, errorMessage); if (invalidValues != null) { JSONArray values = new JSONArray(); for (String v : invalidValues) { values.put(v); } error.put("invalidValues", values); } response.sendError(HttpServletResponse.SC_BAD_REQUEST, error.toString()); } /** * Send a Bad Request response with JSON object mapping field error messages * * @param response * @param parameterName * @param errorMessage */ protected void respondWithBadRequest(final HttpServletResponse response, final String parameterName, final String errorMessage) throws IOException { respondWithBadRequest(response, parameterName, errorMessage, new ArrayList<String>()); } /** * Configures the content type for the provided response to contain {@link JSONObject} data * * @param response The response instance to modify * @param jsonObject The JSON data to include in the response */ protected void respondWithJson(final HttpServletResponse response, final JSONObject jsonObject) { configureResponse(ResponseTypes.JSON_OBJECT, response, jsonObject); } /** * Configures the content type for the provided response to contain {@link JSONArray} data * * @param response The response instance to modify * @param jsonArray The JSON data to include in the response */ protected void respondWithJson(final HttpServletResponse response, final JSONArray jsonArray) { configureResponse(ResponseTypes.JSON_ARRAY, response, jsonArray); } protected void respondWithPlaintext(final HttpServletResponse response, final String plaintext) { configureResponse(ResponseTypes.PLAINTEXT, response, plaintext); } protected void respondWithHtml(final HttpServletResponse response, final String html) { configureResponse(ResponseTypes.HTML, response, html); } protected User getUser(HttpServletRequest request) { return new ProxyUser(CurrentUser.get(request), this.userRepository); } private void configureResponse(final ResponseTypes type, final HttpServletResponse response, final Object responseData) { Preconditions.checkNotNull(response, "The provided response was invalid"); Preconditions.checkNotNull(responseData, "The provided data was invalid"); try { switch (type) { case JSON_OBJECT: response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(responseData.toString()); break; case JSON_ARRAY: response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(responseData.toString()); break; case PLAINTEXT: response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(responseData.toString()); break; case HTML: response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(responseData.toString()); break; default: throw new RuntimeException("Unsupported response type encountered"); } } catch (IOException e) { throw new RuntimeException("Error occurred while writing response", e); } } protected void copyPartToOutputStream(Part part, OutputStream out) throws IOException { InputStream in = part.getInputStream(); try { IOUtils.copy(in, out); } finally { out.close(); in.close(); } } protected void copyPartToFile(Part part, File outFile) throws IOException { FileOutputStream out = new FileOutputStream(outFile); copyPartToOutputStream(part, out); } public UserRepository getUserRepository() { return userRepository; } public Configuration getConfiguration() { return configuration; } public WorkspaceRepository getWorkspaceRepository() { return workspaceRepository; } public WebApp getWebApp(HttpServletRequest request) { return (WebApp) App.getApp(request); } }
package org.rlcommunity.critter.svg; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.net.URI; import org.rlcommunity.critter.Vector2D; import com.kitfox.svg.SVGDiagram; import com.kitfox.svg.SVGElement; import com.kitfox.svg.SVGElementException; import com.kitfox.svg.SVGException; import com.kitfox.svg.animation.AnimationElement; public class ShapeDrawing { private final URI rootUrl; private SVGDiagram diagram = null; private SVGElement element = null; private String nativeTransformation = null; private final Vector2D nativeTranslation = new Vector2D(); private Vector2D position = new Vector2D(); private double direction = 0; public ShapeDrawing(String pictureName) { rootUrl = Loader.load(pictureName); if (rootUrl == null) { return; } diagram = Loader.universe.getDiagram(rootUrl); diagram.setIgnoringClipHeuristic(true); element = Loader.universe.getElement(rootUrl); nativeTransformation = Loader.getNativeTransformation(element); setNativeTranslation(); } private void setNativeTranslation() { Rectangle2D boundingBox = diagram.getViewRect(); nativeTranslation.x = boundingBox.getWidth() * -0.5; nativeTranslation.y = boundingBox.getHeight() * -0.5; } public void resetNativeTranslation() { nativeTranslation.x = 0; nativeTranslation.y = 0; } public void draw(Graphics g, Vector2D position, double direction) { if (diagram == null) return; try { updatePosition(position, direction); diagram.render((Graphics2D) g); } catch (SVGException e) { e.printStackTrace(); return; } } public void updatePosition(Vector2D position, double direction) { if ((position.x != this.position.x) || (position.y != this.position.y) || (direction != this.direction)) { this.position = position; this.direction = direction; setTransform(position, direction); } } private void setTransform(Vector2D position, double direction) { // Transformations are applied from right to left, cool isn't it ? String transformation = String.format("translate(%s,%s) rotate(%s) translate(%s,%s) %s", position.x, position.y, Math.toDegrees(direction), nativeTranslation.x, nativeTranslation.y, nativeTransformation); try { element.setAttribute("transform", AnimationElement.AT_XML, transformation); Loader.universe.updateTime(); } catch (SVGElementException e) { e.printStackTrace(); } catch (SVGException e) { e.printStackTrace(); } } public URI root() { return rootUrl; } }
package org.opencraft.server.task.impl; import org.opencraft.server.task.ScheduledTask; import org.opencraft.server.io.WorldManager; import org.opencraft.server.model.World; import org.slf4j.*; /** * A Task that will automatically save a World. * @author Adam Liszka */ public final class SaveWorldTask extends ScheduledTask { private static final long DELAY = 120 * 1000; // Every 2 minutes private World m_lvl; private Logger logger = LoggerFactory.getLogger(SaveWorldTask.class); public SaveWorldTask(World lvl) { super(DELAY); m_lvl = lvl; } public void execute() { logger.info("Saving " + m_lvl.getName()); if (this.getDelay() == 0) { this.setDelay(DELAY); } WorldManager.save(m_lvl); } }
package org.pentaho.ui.xul.impl; import java.util.ResourceBundle; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.XulException; import org.pentaho.ui.xul.XulLoader; import org.pentaho.ui.xul.components.XulMessageBox; import org.pentaho.ui.xul.dom.Document; /** * @author OEM * */ public class XulFragmentContainer extends AbstractXulDomContainer { private static final Log logger = LogFactory.getLog(XulFragmentContainer.class); private Document fragment; public XulFragmentContainer(XulLoader xulLoader){ super(); this.xulLoader = xulLoader; } public Document getDocumentRoot(){ return fragment; } public void addDocument(Document document){ this.fragment = document; } @Override public XulMessageBox createMessageBox(String message) { return null; } @Override public void close() { } public boolean isClosed(){ return false; } @Override public XulFragmentContainer loadFragment(String xulLocation) throws XulException{ logger.error("loadFragment not implemented in XulFragmentContainer"); throw new XulException("loadFragment not implemented in XulFragmentContainer"); } public XulMessageBox createErrorMessageBox(String title, String message, Throwable throwable) { return null; } public XulDomContainer loadFragment(String xulLocation, ResourceBundle res) throws XulException { System.out.println("loadFragment not implemented in XulFragmentContainer"); return null; } public Document getDocument(int idx) { if (idx > 0){ return null; } else { return fragment; } } }
package org.scoverage; import org.gradle.api.logging.Logger; import scala.Some; import scala.collection.JavaConverters; import scala.collection.mutable.Buffer; import scoverage.Constants; import scoverage.Coverage; import scoverage.report.CoberturaXmlWriter; import scoverage.report.ScoverageHtmlWriter; import scoverage.report.ScoverageXmlWriter; import java.io.File; import java.util.Arrays; /** * Util for generating and saving coverage files. * <p/> * Copied from sbt-scoverage and converted to Java to avoid dependency to Scala. */ public class ScoverageWriter { private final Logger logger; public ScoverageWriter(Logger logger) { this.logger = logger; } /** * Generates all reports from given data. * * @param sourceDir directory with project sources * @param reportDir directory for generate reports * @param coverage coverage data * @param sourceEncoding the encoding of the source files * @param coverageOutputCobertura switch for Cobertura output * @param coverageOutputXML switch for Scoverage XML output * @param coverageOutputHTML switch for Scoverage HTML output * @param coverageDebug switch for Scoverage Debug output */ public void write(File sourceDir, File reportDir, Coverage coverage, String sourceEncoding, Boolean coverageOutputCobertura, Boolean coverageOutputXML, Boolean coverageOutputHTML, Boolean coverageDebug) { logger.info("[scoverage] Generating scoverage reports..."); reportDir.mkdirs(); if (coverageOutputCobertura) { new CoberturaXmlWriter(sourceDir, reportDir).write(coverage); logger.info("[scoverage] Written Cobertura XML report to " + reportDir.getAbsolutePath() + File.separator + "cobertura.xml"); } if (coverageOutputXML) { new ScoverageXmlWriter(sourceDir, reportDir, /* debug = */ false).write(coverage); logger.info("[scoverage] Written XML report to " + reportDir.getAbsolutePath() + File.separator + Constants.XMLReportFilename()); if (coverageDebug) { new ScoverageXmlWriter(sourceDir, reportDir, /* debug = */ true).write(coverage); logger.info("[scoverage] Written XML report with debug information to " + reportDir.getAbsolutePath() + File.separator + Constants.XMLReportFilenameWithDebug()); } } if (coverageOutputHTML) { Buffer<File> sources = JavaConverters.asScalaBufferConverter(Arrays.asList(sourceDir)).asScala(); new ScoverageHtmlWriter(sources, reportDir, new Some<>(sourceEncoding)).write(coverage); logger.info("[scoverage] Written HTML report to " + reportDir.getAbsolutePath() + File.separator + "index.html"); } logger.info("[scoverage] Coverage reports completed"); } }
package CustomOreGen.Server; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.ParserConfigurationException; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.ChunkProviderEnd; import net.minecraft.world.gen.ChunkProviderFlat; import net.minecraft.world.gen.ChunkProviderGenerate; import net.minecraft.world.gen.ChunkProviderHell; import net.minecraft.world.storage.SaveHandler; import net.minecraft.world.storage.WorldInfo; import org.xml.sax.SAXException; import com.google.common.collect.Maps; import CustomOreGen.CustomOreGenBase; import CustomOreGen.ForgeInterface; import CustomOreGen.MystcraftSymbolData; import CustomOreGen.Config.ConfigParser; import CustomOreGen.Config.PropertyIO; import CustomOreGen.Util.BiomeDescriptor; import CustomOreGen.Util.BlockDescriptor; import CustomOreGen.Util.CIStringMap; import CustomOreGen.Util.MapCollection; public class WorldConfig { public static Collection<ConfigOption>[] loadedOptionOverrides = new Collection[3]; public final World world; public final WorldInfo worldInfo; public final File globalConfigDir; public final File worldBaseDir; public final File dimensionDir; public int deferredPopulationRange; public boolean debuggingMode; public boolean vanillaOreGen; public boolean custom; private Map<String,IOreDistribution> oreDistributions; private Map<String,ConfigOption> configOptions; private Map<String,String> loadedOptions; private Map<String,Integer> worldProperties; private Map cogSymbolData; private Map<String,BiomeDescriptor> biomeSets; private BlockDescriptor equivalentBlockDescriptor; private int idCounter; public static WorldConfig createEmptyConfig() { try { return new WorldConfig((File)null, (WorldInfo)null, (File)null, (World)null, (File)null); } catch (Exception var1) { throw new RuntimeException(var1); } } public WorldConfig() throws IOException, ParserConfigurationException, SAXException { this(CustomOreGenBase.getConfigDir(), (WorldInfo)null, (File)null, (World)null, (File)null); } public WorldConfig(WorldInfo worldInfo, File worldBaseDir) throws IOException, ParserConfigurationException, SAXException { this(CustomOreGenBase.getConfigDir(), worldInfo, worldBaseDir, (World)null, (File)null); } public WorldConfig(World world) throws IOException, ParserConfigurationException, SAXException { this(CustomOreGenBase.getConfigDir(), (WorldInfo)null, (File)null, world, (File)null); } private WorldConfig(File globalConfigDir, WorldInfo worldInfo, File worldBaseDir, World world, File dimensionDir) throws IOException, ParserConfigurationException, SAXException { this.deferredPopulationRange = 0; this.debuggingMode = false; this.vanillaOreGen = false; this.oreDistributions = new LinkedHashMap(); this.configOptions = new CIStringMap(new LinkedHashMap()); this.loadedOptions = new CIStringMap(new LinkedHashMap()); this.worldProperties = new CIStringMap(new LinkedHashMap()); this.cogSymbolData = new CIStringMap(new LinkedHashMap()); this.biomeSets = new CIStringMap<BiomeDescriptor>(); String dimensionBasename; if (world != null) { if (world.getSaveHandler() != null && world.getSaveHandler() instanceof SaveHandler) { worldBaseDir = ((SaveHandler)world.getSaveHandler()).getWorldDirectory(); } else { worldBaseDir = null; } dimensionBasename = "DIM" + world.provider.dimensionId; if (world.provider.dimensionId != 0) { dimensionBasename = ForgeInterface.getWorldDimensionFolder(world); } if (worldBaseDir == null) { dimensionDir = new File(dimensionBasename); } else { dimensionDir = new File(worldBaseDir, dimensionBasename); } worldInfo = world.getWorldInfo(); } if (dimensionDir == null && worldBaseDir != null) { dimensionDir = new File(worldBaseDir, "DIM0"); if (!dimensionDir.exists()) dimensionDir.mkdir(); } this.world = world; this.worldInfo = worldInfo; populateWorldProperties(this.worldProperties, world, worldInfo); this.worldBaseDir = worldBaseDir; this.dimensionDir = dimensionDir; this.globalConfigDir = globalConfigDir; if (dimensionDir != null) { CustomOreGenBase.log.info("Loading config data for dimension \'" + dimensionDir + "\' ..."); } else { if (globalConfigDir == null) { return; } CustomOreGenBase.log.info("Loading global config \'" + globalConfigDir + "\' ..."); } File configFile = null; File[] configFileList = new File[3]; int configFileDepth = this.buildFileList(CustomOreGenBase.BASE_CONFIG_FILENAME, configFileList, true); if (configFileDepth >= 0) { configFile = configFileList[configFileDepth]; } else { File defaultConfigFile = new File(globalConfigDir, CustomOreGenBase.DEFAULT_BASE_CONFIG_FILENAME); if (defaultConfigFile.exists()) { configFile = defaultConfigFile; configFileDepth = 0; } else { if (dimensionDir != null) { CustomOreGenBase.log.warn("No config file found for dimension \'" + dimensionDir + "\' at any scope!"); } else { CustomOreGenBase.log.info("No global config file found."); } } } if (configFile != null) { File[] optionsFileList = new File[3]; this.buildFileList(CustomOreGenBase.OPTIONS_FILENAME, optionsFileList, false); File optionsFile = optionsFileList[2]; ConfigOption vangen; for (int defpopOption = configFileDepth; defpopOption < optionsFileList.length; ++defpopOption) { loadOptions(optionsFileList[defpopOption], this.loadedOptionOverrides[defpopOption], this.loadedOptions); } (new ConfigParser(this)).parseFile(configFile); ConfigOption var20; Map<String,String> saveLevelOptions = new LinkedHashMap(); if (optionsFileList[1] != null) { if (!optionsFileList[1].exists()) { loadOptions(optionsFileList[0], this.loadedOptionOverrides[0], saveLevelOptions); saveOptions(optionsFileList[1], saveLevelOptions); this.loadedOptionOverrides[0] = null; } else { loadOptions(optionsFileList[1], null, saveLevelOptions); } } if (optionsFile != null) { putOptions(this.configOptions.values(), this.loadedOptions); Map<String,String> dimLevelOptions = setdiffOptions(this.loadedOptions, saveLevelOptions); loadOptions(optionsFile, this.loadedOptionOverrides[2], dimLevelOptions); saveOptions(optionsFile, dimLevelOptions); } ConfigOption var21 = (ConfigOption)this.configOptions.get("deferredPopulationRange"); if (var21 != null && var21 instanceof NumericOption) { Double var18 = (Double)var21.getValue(); this.deferredPopulationRange = var18 != null && var18.doubleValue() > 0.0D ? (int)Math.ceil(var18.doubleValue()) : 0; } else { CustomOreGenBase.log.warn("Numeric Option \'" + var21 + "\' not found in config file - defaulting to \'" + this.deferredPopulationRange + "\'."); } var20 = (ConfigOption)this.configOptions.get("debugMode"); if (var20 != null && var20 instanceof ChoiceOption) { String var22 = (String)var20.getValue(); this.debuggingMode = var22 == null ? false : var22.equalsIgnoreCase("on") || var22.equalsIgnoreCase("true"); } else { CustomOreGenBase.log.warn("Choice Option \'" + var20 + "\' not found in config file - defaulting to \'" + this.debuggingMode + "\'."); } vangen = (ConfigOption)this.configOptions.get("vanillaOreGen"); if (vangen != null && vangen instanceof ChoiceOption) { String value = (String)vangen.getValue(); this.vanillaOreGen = value == null ? false : value.equalsIgnoreCase("on") || value.equalsIgnoreCase("true"); } else { CustomOreGenBase.log.warn("Choice Option \'" + vangen + "\' not found in config file - defaulting to \'" + this.vanillaOreGen + "\'."); } } } private Map<String, String> setdiffOptions(Map<String, String> x, Map<String, String> y) { return new LinkedHashMap(Maps.difference(x, y).entriesOnlyOnLeft()); } private void loadOptions(File file, Collection<ConfigOption> overrides, Map<String, String> map) throws FileNotFoundException, IOException { if (file != null && file.exists()) { PropertyIO.load(map, new FileInputStream(file)); } if (overrides != null) { putOptions(overrides, map); } } private void putOptions(Collection<ConfigOption> options, Map<String, String> map) { for (ConfigOption option : options) { if (option.getValue() != null) { map.put(option.getName(), option.getValue().toString()); } } } private void saveOptions(File optionsFile, Map<String, String> options) throws IOException { optionsFile.createNewFile(); String header = CustomOreGenBase.getDisplayString() + " Config Options"; PropertyIO.save(options, new FileOutputStream(optionsFile), header); } private int buildFileList(String fileName, File[] files, boolean mustExist) { if (files == null) { files = new File[3]; } if (this.globalConfigDir != null) { files[0] = new File(this.globalConfigDir, fileName); } if (this.worldBaseDir != null) { files[1] = new File(this.worldBaseDir, fileName); } if (this.dimensionDir != null && dimensionDir.exists()) { files[2] = new File(this.dimensionDir, fileName); } for (int i = files.length - 1; i >= 0; --i) { if (files[i] != null && (!mustExist || files[i].exists())) { return i; } } return -1; } private static void populateWorldProperties(Map properties, World world, WorldInfo worldInfo) { properties.put("world", worldInfo == null ? "" : worldInfo.getWorldName()); properties.put("world.seed", Long.valueOf(worldInfo == null ? 0L : worldInfo.getSeed())); properties.put("world.version", Integer.valueOf(worldInfo == null ? 0 : worldInfo.getSaveVersion())); properties.put("world.isHardcore", Boolean.valueOf(worldInfo == null ? false : worldInfo.isHardcoreModeEnabled())); properties.put("world.hasFeatures", Boolean.valueOf(worldInfo == null ? false : worldInfo.isMapFeaturesEnabled())); properties.put("world.hasCheats", Boolean.valueOf(worldInfo == null ? false : worldInfo.areCommandsAllowed())); properties.put("world.gameMode", worldInfo == null ? "" : worldInfo.getGameType().getName()); properties.put("world.gameMode.id", Integer.valueOf(worldInfo == null ? 0 : worldInfo.getGameType().getID())); properties.put("world.type", worldInfo == null ? "" : worldInfo.getTerrainType().getWorldTypeName()); properties.put("world.type.version", Integer.valueOf(worldInfo == null ? 0 : worldInfo.getTerrainType().getGeneratorVersion())); String genName = "RandomLevelSource"; String genClass = "ChunkProviderGenerate"; if (world != null) { IChunkProvider chunkProvider = world.provider.createChunkGenerator(); genName = chunkProvider.makeString(); genClass = chunkProvider.getClass().getSimpleName(); if (chunkProvider instanceof ChunkProviderGenerate) { genClass = "ChunkProviderGenerate"; } else if (chunkProvider instanceof ChunkProviderFlat) { genClass = "ChunkProviderFlat"; } else if (chunkProvider instanceof ChunkProviderHell) { genClass = "ChunkProviderHell"; } else if (chunkProvider instanceof ChunkProviderEnd) { genName = "EndRandomLevelSource"; genClass = "ChunkProviderEnd"; } } properties.put("dimension.generator", genName); properties.put("dimension.generator.class", genClass); properties.put("dimension", world == null ? "" : world.provider.getDimensionName()); properties.put("dimension.id", Integer.valueOf(world == null ? 0 : world.provider.dimensionId)); properties.put("dimension.isSurface", Boolean.valueOf(world == null ? false : world.provider.isSurfaceWorld())); properties.put("dimension.groundLevel", Integer.valueOf(world == null ? 0 : world.provider.getAverageGroundLevel())); properties.put("dimension.height", Integer.valueOf(world == null ? 0 : world.getHeight())); properties.put("age", Boolean.FALSE); } public Collection<IOreDistribution> getOreDistributions() { return this.oreDistributions.values(); } public Collection<IOreDistribution> getOreDistributions(String namePattern) { LinkedList<IOreDistribution> matches = new LinkedList(); if (namePattern != null) { Pattern pattern = Pattern.compile(namePattern, 2); Matcher matcher = pattern.matcher(""); for (IOreDistribution dist : this.oreDistributions.values()) { matcher.reset(dist.toString()); if (matcher.matches()) { matches.add(dist); } } } return Collections.unmodifiableCollection(matches); } public ConfigOption getConfigOption(String optionName) { return this.configOptions.get(optionName); } public Collection<ConfigOption> getConfigOptions() { return new MapCollection<String,ConfigOption>(this.configOptions) { protected String getKey(ConfigOption v) { return v.getName(); } }; } public Collection<ConfigOption> getConfigOptions(String namePattern) { LinkedList<ConfigOption> matches = new LinkedList(); if (namePattern != null) { Pattern pattern = Pattern.compile(namePattern, 2); Matcher matcher = pattern.matcher(""); for (ConfigOption option : this.configOptions.values()) { matcher.reset(option.getName()); if (matcher.matches()) { matches.add(option); } } } return Collections.unmodifiableCollection(matches); } public String loadConfigOption(String optionName) { return (String)this.loadedOptions.get(optionName); } public Object getWorldProperty(String propertyName) { return this.worldProperties.get(propertyName); } public MystcraftSymbolData getMystcraftSymbol(String symbolName) { return (MystcraftSymbolData)this.cogSymbolData.get(symbolName); } public Collection getMystcraftSymbols() { return new MapCollection<String,MystcraftSymbolData>(this.cogSymbolData) { protected String getKey(MystcraftSymbolData v) { return v.symbolName; } public boolean add(MystcraftSymbolData v) { String key = "age." + v.symbolName; Integer count = worldProperties.get(key); if (count == null) { worldProperties.put("age." + v.symbolName, 0); } else { v.count = count.intValue(); } return super.add(v); } }; } public BiomeDescriptor getBiomeSet(String namePattern) { return this.biomeSets.get(namePattern); } public BlockDescriptor getEquivalentBlockDescriptor() { if (this.equivalentBlockDescriptor == null) { this.equivalentBlockDescriptor = this.makeEquivalentBlockDescriptor(); } return this.equivalentBlockDescriptor; } private BlockDescriptor makeEquivalentBlockDescriptor() { double totalWeight = 0; for (IOreDistribution dist : this.oreDistributions.values()) { totalWeight += dist.getOresPerChunk(); } BlockDescriptor desc = new BlockDescriptor(); for (IOreDistribution dist : this.oreDistributions.values()) { BlockDescriptor oreBlock = (BlockDescriptor)dist.getDistributionSetting("OreBlock"); desc.add(oreBlock, (float)(dist.getOresPerChunk() / totalWeight)); } return desc; } public void registerDistribution(String newName, IOreDistribution distribution) { if (this.oreDistributions.containsKey(newName)) { this.oreDistributions.remove(newName); // otherwise, order is not updated } this.oreDistributions.put(newName, distribution); } public void registerBiomeSet(BiomeDescriptor biomeSet) { this.biomeSets.put(biomeSet.getName(), biomeSet); } public int nextDistributionID() { return this.idCounter++; } }
package org.plugins.simplefreeze.managers; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; import org.plugins.simplefreeze.SimpleFreezeMain; import org.plugins.simplefreeze.util.MySQL; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class SQLManager { private final SimpleFreezeMain plugin; private final MySQL mySQL; private final FreezeManager freezeManager; private final PlayerManager playerManager; private BukkitTask freezeTask; private BukkitTask unfreezeTask; public SQLManager(SimpleFreezeMain plugin, MySQL mySQL, FreezeManager freezeManager, PlayerManager playerManager) { this.plugin = plugin; this.mySQL = mySQL; this.freezeManager = freezeManager; this.playerManager = playerManager; } public void setupTables() { Connection connection = null; PreparedStatement ps = null; String update = "CREATE TABLE IF NOT EXISTS sf_" + this.plugin.getServerID() + "_freezes (freezee_name VARCHAR(16) NOT NULL UNIQUE, freezee_uuid VARCHAR(36) NOT NULL UNIQUE, freezer_name VARCHAR(16) NOT NULL, freezer_uuid VARCHAR(36), unfreeze_date LONG, reason VARCHAR(100), servers VARCHAR(100), source_server VARCHAR(50));"; try { connection = this.mySQL.getConnection(); ps = connection.prepareStatement(update); ps.execute(); ps.close(); update = "CREATE TABLE IF NOT EXISTS sf_" + this.plugin.getServerID() + "_unfreezes (unfreezee_name VARCHAR(16) NOT NULL UNIQUE, unfreezee_uuid VARCHAR(36) NOT NULL UNIQUE, unfreezer_name VARCHAR(16), source_server VARCHAR(50));"; ps = connection.prepareStatement(update); ps.execute(); update = "CREATE TABLE IF NOT EXISTS sf_" + this.plugin.getServerID() + "_frozenlist (player_uuid VARCHAR(36) NOT NULL UNIQUE);"; ps = connection.prepareStatement(update); ps.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public void setupTasks() { this.freezeTask = new BukkitRunnable() { @Override public void run() { Connection connection = null; PreparedStatement ps = null; ResultSet res = null; String request = "SELECT * FROM sf_" + plugin.getServerID() + "_freezes;"; try { connection = mySQL.getConnection(); ps = connection.prepareStatement(request); if (ps != null) { res = ps.executeQuery(); List<String> names = new ArrayList<>(); if (res != null) { while (res.next()) { String freezeeName = res.getString("freezee_name"); String reason = res.getString("reason"); String serversString = res.getString("servers"); String sourceServer = res.getString("source_server"); Long unfreezeDate = res.getLong("unfreeze_date"); UUID freezeeUUID = null; UUID freezerUUID = null; if (res.getString("freezer_uuid") != null) { freezerUUID = UUID.fromString(res.getString("freezer_uuid")); } if (res.getString("freezee_uuid") != null) { freezeeUUID = UUID.fromString(res.getString("freezee_uuid")); } else { Player onlineP = Bukkit.getPlayer(freezeeName); OfflinePlayer offlineP = Bukkit.getOfflinePlayer(freezeeName); if (onlineP != null) { freezeeUUID = onlineP.getUniqueId(); } else if (offlineP != null) { if (offlineP.hasPlayedBefore()) { freezeeUUID = offlineP.getUniqueId(); } } } names.add(freezeeName); if (!playerManager.isFrozen(freezeeUUID)) { if (unfreezeDate != null && unfreezeDate > 0) { freezeManager.tempFreeze(freezeeUUID, freezerUUID, null, (unfreezeDate - System.currentTimeMillis() + 1000L) / 1000L, reason, serversString); } else { freezeManager.freeze(freezeeUUID, freezerUUID, null, reason, serversString); } freezeManager.notifyOfSQLFreeze(freezeeUUID, serversString, sourceServer); } } try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } for (String name : names) { String update = "DELETE FROM sf_" + plugin.getServerID() + "_freezes WHERE freezee_name = '" + name + "';"; ps = connection.prepareStatement(update); ps.execute(); ps.close(); } } request = "SELECT * FROM sf_" + plugin.getServerID() + "_unfreezes;"; ps = connection.prepareStatement(request); if (ps != null) { res = ps.executeQuery(); List<String> names = new ArrayList<>(); List<UUID> uuids = new ArrayList<>(); if (res != null) { while (res.next()) { String unfreezeeName = res.getString("unfreezee_name"); String unfreezerName = res.getString("unfreezer_name"); String sourceServer = res.getString("source_server"); UUID unfreezeeUUID = null; if (res.getString("unfreezee_uuid") != null) { unfreezeeUUID = UUID.fromString(res.getString("unfreezee_uuid")); } else { Player onlineP = Bukkit.getPlayer(unfreezeeName); OfflinePlayer offlineP = Bukkit.getOfflinePlayer(unfreezeeName); if (onlineP != null) { unfreezeeUUID = onlineP.getUniqueId(); } else if (offlineP != null) { if (offlineP.hasPlayedBefore()) { unfreezeeUUID = offlineP.getUniqueId(); } } } names.add(unfreezeeName); if (unfreezeeUUID != null) { uuids.add(unfreezeeUUID); } if (playerManager.isFrozen(unfreezeeUUID)) { freezeManager.unfreeze(unfreezeeUUID); } freezeManager.notifyOfUnfreeze(unfreezeeUUID, unfreezeeName, unfreezerName, sourceServer); } res.close(); } try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } for (String name : names) { String update = "DELETE FROM sf_" + plugin.getServerID() + "_unfreezes WHERE unfreezee_name = '" + name + "';"; ps = connection.prepareStatement(update); ps.execute(); ps.close(); } for (UUID uuid : uuids) { String update = "DELETE FROM sf_" + plugin.getServerID() + "_frozenlist WHERE player_uuid = '" + uuid + "';"; ps = connection.prepareStatement(update); ps.execute(); ps.close(); } } } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }.runTaskTimer(this.plugin, 20L, 20L); } public List<String> getServerIDs() { List<String> serverIDs = new ArrayList<>(); if (!this.plugin.usingMySQL()) { return serverIDs; } Connection connection = null; PreparedStatement ps = null; ResultSet res = null; String request = "SHOW TABLES;"; try { connection = this.mySQL.getConnection(); ps = connection.prepareStatement(request); if (ps != null) { res = ps.executeQuery(); if (res != null) { while (res.next()) { String tableName = res.getString(1); String serverID = null; if (tableName.startsWith("sf_") && tableName.endsWith("_freezes")) { serverID = tableName.substring(3, tableName.length() - 8); } if (serverID != null) { serverIDs.add(serverID); } } } } } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (res != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } return serverIDs; } public void addFreeze(String freezeeName, UUID freezeeUUID, String freezerName, UUID freezerUUID, Long unfreezeDate, String reason, List<String> servers) { Connection connection = null; PreparedStatement ps = null; String serversString = ""; for (String server : servers) { serversString += server + ", "; } serversString = serversString.length() > 1 ? serversString.substring(0, serversString.length() - 2) : serversString; int commaIndex = serversString.indexOf(","); if (commaIndex > 0) { serversString = serversString.substring(0, commaIndex) + " and" + serversString.substring(commaIndex + 1, serversString.length()); } String valuesString = "(freezee_name, freezee_uuid, freezer_name, freezer_uuid, unfreeze_date, reason, servers, source_server) VALUES ('" + freezeeName + "', '" + freezeeUUID.toString() + "', '" + freezerName + "', ?, ?, '" + reason + "', '" + serversString + "', '" + this.plugin.getServerID() + "')"; try { connection = this.mySQL.getConnection(); for (String server : servers) { try { String update = "INSERT INTO sf_" + server.toLowerCase() + "_freezes " + valuesString + ";"; ps = connection.prepareStatement(update); if (freezerUUID == null) { ps.setNull(1, Types.VARCHAR); } else { ps.setString(1, freezerUUID.toString()); } if (unfreezeDate == null) { ps.setNull(2, Types.BLOB); } else { ps.setLong(2, unfreezeDate); } ps.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public void addUnfreeze(String unfreezeeName, UUID unfreezeeUUID, String unfreezerName) { Connection connection = null; PreparedStatement ps = null; String valuesString = "(unfreezee_name, unfreezee_uuid, unfreezer_name, source_server) VALUES ('" + unfreezeeName + "', '" + unfreezeeUUID.toString() + "', '" + unfreezerName + "', '" + plugin.getServerID() + "')"; try { connection = this.mySQL.getConnection(); for (String server : this.getServerIDs()) { try { String request = "SELECT * FROM sf_" + server.toLowerCase() + "_frozenlist WHERE player_uuid = '" + unfreezeeUUID.toString() + "';"; ps = connection.prepareStatement(request); ResultSet rs = ps.executeQuery(); boolean frozen = false; if (rs.next()) { frozen = true; } if (frozen) { String update = "INSERT INTO sf_" + server.toLowerCase() + "_unfreezes " + valuesString + ";"; ps = connection.prepareStatement(update); ps.execute(); } } catch (SQLException e) { e.printStackTrace(); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public boolean checkIfFrozen(UUID uuid) { Connection connection = null; PreparedStatement ps = null; ResultSet res = null; String request; String uuidStr = uuid.toString(); boolean frozen = false; try { connection = mySQL.getConnection(); serverLoop: for (String server : this.getServerIDs()) { request = "SELECT * FROM sf_" + server + "_frozenlist;"; ps = connection.prepareStatement(request); res = ps.executeQuery(); if (res != null) { while (res.next()) { if (uuidStr.equals(res.getString("player_uuid"))) { frozen = true; break serverLoop; } } try { res.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } } catch (SQLException e) { e.printStackTrace(); } finally { if (res != null) { try { res.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } return frozen; } public void syncFrozenList(List<UUID> frozenList) { Connection connection = null; PreparedStatement ps = null; ResultSet res = null; String request; List<UUID> removeList = new ArrayList<>(); try { connection = this.mySQL.getConnection(); request = "SELECT * FROM sf_" + this.plugin.getServerID() + "_frozenlist;"; ps = connection.prepareStatement(request); res = ps.executeQuery(); if (res != null) { while (res.next()) { UUID playerUUID = UUID.fromString(res.getString("player_uuid")); if (!frozenList.contains(playerUUID)) { removeList.add(playerUUID); } else { frozenList.remove(playerUUID); } } try { res.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } for (UUID uuid : frozenList) { String update = "INSERT INTO sf_" + this.plugin.getServerID() + "_frozenlist (player_uuid) VALUES ('" + uuid.toString() + "');"; try { ps = connection.prepareStatement(update); if (ps != null) { ps.execute(); ps.close(); } } catch (SQLException e) { e.printStackTrace(); } } for (UUID uuid : removeList) { String update = "DELETE FROM sf_" + this.plugin.getServerID() + "_frozenlist WHERE player_uuid = '" + uuid.toString() + "';"; try { ps = connection.prepareStatement(update); if (ps != null) { ps.execute(); ps.close(); } } catch (SQLException e) { e.printStackTrace(); } } } catch (SQLException e) { e.printStackTrace(); } finally { if (res != null) { try { res.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public void addToFrozenList(UUID uuid) { Connection connection = null; PreparedStatement ps = null; try { connection = this.mySQL.getConnection(); String update = "INSERT INTO sf_" + this.plugin.getServerID() + "_frozenlist (player_uuid) VALUES ('" + uuid.toString() + "');"; ps = connection.prepareStatement(update); ps.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public void removeFromFrozenList(UUID uuid) { Connection connection = null; PreparedStatement ps = null; try { connection = this.mySQL.getConnection(); String update = "DELETE FROM sf_" + this.plugin.getServerID() + "_frozenlist WHERE player_uuid = '" + uuid.toString() + "';"; ps = connection.prepareStatement(update); ps.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
package HxCKDMS.HxCSkills.Events; import HxCKDMS.HxCCore.Handlers.NBTFileIO; import HxCKDMS.HxCCore.HxCCore; import HxCKDMS.HxCSkills.Config; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.BlockPos; import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.event.entity.living.LivingFallEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import java.io.File; import java.util.UUID; public class Events { public static UUID HealthUUID = UUID.fromString("fe15f490-62d7-11e4-b116-123b93f75cba"); public static UUID SpeedUUID = UUID.fromString("fe15f490-62d7-11e4-b116-123b93f75cbb"); public static UUID DamageUUID = UUID.fromString("fe15f490-62d7-11e4-b116-123b93f75cbc"); int HSpeed = Config.HealSpeed; int HTimer; int FTimer; double Speed; double Damage; double HPBuff; int SkillPoints; int StrengthArms; int StrengthLegs; int StrengthFeet; int StrengthTorso; int StrengthHead; int Health; int Stamina; int FlySkillLevel; @SubscribeEvent public void onLivingUpdate(LivingEvent.LivingUpdateEvent event){ if (HTimer != 0) { --HTimer; } if (FTimer != 0) { --FTimer; } if (event.entityLiving instanceof EntityPlayerMP){ EntityPlayerMP player = (EntityPlayerMP)event.entityLiving; String pUUID = player.getUniqueID().toString(); File CustomPlayerData = new File(HxCCore.HxCCoreDir, "HxC-" + pUUID + ".dat"); NBTTagCompound Skills = NBTFileIO.getNbtTagCompound(CustomPlayerData, "skills"); SkillPoints = 0; StrengthLegs = 0; StrengthArms = 0; StrengthFeet = 0; StrengthTorso = 0; StrengthHead = 0; Stamina = 0; Health = 0; FlySkillLevel = 0; SkillPoints = Skills.getInteger("SkillPoints"); StrengthArms = Skills.getInteger("ArmStrengthLevel"); StrengthLegs = Skills.getInteger("LegStrengthLevel"); StrengthFeet = Skills.getInteger("FootStrengthLevel"); StrengthTorso = Skills.getInteger("TorsoStrengthLevel"); StrengthHead = Skills.getInteger("HeadStrengthLevel"); Health = Skills.getInteger("HealthLevel"); Stamina = Skills.getInteger("StaminaLevel"); FlySkillLevel = Skills.getInteger("FlyLevel"); if (SkillPoints < 0) {Skills.setInteger("SkillPoints", 0);} NBTFileIO.setNbtTagCompound(CustomPlayerData, "skills", Skills); IAttributeInstance playerhp = player.getAttributeMap().getAttributeInstance(SharedMonsterAttributes.maxHealth); IAttributeInstance playerspeed = player.getAttributeMap().getAttributeInstance(SharedMonsterAttributes.movementSpeed); IAttributeInstance playerstrength = player.getAttributeMap().getAttributeInstance(SharedMonsterAttributes.attackDamage); if (StrengthLegs > 0){ Speed = (playerspeed.getBaseValue() + ((StrengthLegs/5)*.15)); }else{ Speed = 0; } if (StrengthArms > 0){ Damage = (playerstrength.getBaseValue() + ((StrengthArms)*.15)); }else{ Damage = 0; } if (Health > 0 && Health <= HxCKDMS.HxCCore.Config.HPMax){ HPBuff = Health*0.1; }else if (Health > HxCKDMS.HxCCore.Config.HPMax) { HPBuff = 10; }else{ HPBuff = 0; } if (!player.capabilities.allowFlying) { player.capabilities.allowFlying = FlySkillLevel>0; } if (StrengthHead >= 10 && !(player.worldObj.canSeeSky(new BlockPos(player.posX, player.posY, player.posZ))) && (player.worldObj.getLight(new BlockPos(player.posX, player.posY, player.posZ)) == 0)) { player.addPotionEffect(new PotionEffect(Potion.nightVision.getId(), 60, 0, false, false)); } if (StrengthArms >= 5) { int Haste = Math.round((float)(StrengthArms/5)); player.addPotionEffect(new PotionEffect(Potion.digSpeed.getId(), 5, Haste-1, false, false)); } if (Stamina >= 5) { int dt = 120; int fud = Math.round((float)(Stamina/25)); int FudT = Math.round((float)(dt/fud)); if (FTimer <= 0) { player.addPotionEffect(new PotionEffect(Potion.saturation.getId(), 1, fud-1, false, false)); FTimer = FudT; } } AttributeModifier HealthBuff = new AttributeModifier(HealthUUID, "HealthSkill", HPBuff, 1); AttributeModifier SpeedBuff = new AttributeModifier(SpeedUUID, "LegStrengthSkill", Speed, 1); AttributeModifier DamageBuff = new AttributeModifier(DamageUUID, "ArmStrengthSkill", Damage, 1); playerhp.removeModifier(HealthBuff); playerspeed.removeModifier(SpeedBuff); playerstrength.removeModifier(DamageBuff); playerhp.applyModifier(HealthBuff); playerspeed.applyModifier(SpeedBuff); playerstrength.applyModifier(DamageBuff); player.sendPlayerAbilities(); if (Health > 15 && player.getHealth() < player.getMaxHealth()){ if (HTimer <= 0){ player.heal(2); HTimer = (HSpeed-Health); } } if (StrengthTorso >= 1) { int ResistanceLevel = Math.round(StrengthTorso/25); player.addPotionEffect(new PotionEffect(Potion.resistance.getId(), 5, ResistanceLevel-1, true, false)); } } } @SubscribeEvent public void LivingFallEvent(LivingFallEvent event){ if (event.entityLiving instanceof EntityPlayerMP){ EntityPlayerMP playerMP = (EntityPlayerMP)event.entityLiving; String pUUID = playerMP.getUniqueID().toString(); File CustomPlayerData = new File(HxCCore.HxCCoreDir, "HxC-" + pUUID + ".dat"); NBTTagCompound Skills = NBTFileIO.getNbtTagCompound(CustomPlayerData, "skills"); int StrengthLegs = Skills.getInteger("LegStrengthLevel"); int StrengthFeet = Skills.getInteger("FootStrengthLevel"); if (StrengthFeet > 5 || StrengthLegs > 5) { double dmg = 0; double pwr = ((StrengthFeet + StrengthLegs)/5); double sneakmod = 0; if (playerMP.isSneaking()) { sneakmod = 0.50; } int p = Math.round((float) pwr); if (p > 0 && p < 21) { dmg = (-0.05 * p); } else if (p > 20) { dmg = 1; } else { dmg = 0; } double fdmg = (event.damageMultiplier + dmg) - sneakmod; if (fdmg < 0) { event.damageMultiplier = 0; } else { event.damageMultiplier = (float) fdmg; } } } } @SubscribeEvent public void LivingJumpEvent(LivingEvent.LivingJumpEvent event){ if (event.entityLiving instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) event.entityLiving; String pUUID = player.getUniqueID().toString(); File CustomPlayerData = new File(HxCCore.HxCCoreDir, "HxC-" + pUUID + ".dat"); NBTTagCompound Skills = NBTFileIO.getNbtTagCompound(CustomPlayerData, "skills"); int StrengthLegs = Skills.getInteger("LegStrengthLevel"); if (StrengthLegs > 5 && StrengthLegs < 50) { double JumpBuff = (0.1 * (StrengthLegs / 10)); player.motionY += JumpBuff; } } } }
package org.springframework.web.servlet.tags; import java.beans.PropertyEditor; import java.util.List; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import org.springframework.context.NoSuchMessageException; import org.springframework.validation.BindException; import org.springframework.validation.Errors; import org.springframework.validation.ObjectError; import org.springframework.web.util.ExpressionEvaluationUtils; import org.springframework.web.util.HtmlUtils; public class BindTag extends RequestContextAwareTag { public static final String STATUS_VARIABLE_NAME = "status"; private String path; private String property; private Errors errors; private PropertyEditor editor; /** * Set the path that this tag should apply. * Can be a bean (e.g. "person"), or a bean property * (e.g. "person.name"), also supporting nested beans. */ public void setPath(String path) throws JspException { this.path = ExpressionEvaluationUtils.evaluateString("path", path, pageContext); } /** * Retrieve the property that this tag is currently bound to, * or null if bound to an object rather than a specific property. * Intended for cooperating nesting tags. */ public String getProperty() { return property; } /** * Retrieve the path that this tag should apply to * @return the path that this tag should apply to or <code>null</code> * if it is not set * @see #setPath(String) */ public String getPath() { return path; } /** * Retrieve the Errors instance that this tag is currently bound to. * Intended for cooperating nesting tags. * @return an instance of Errors */ public Errors getErrors() { return errors; } /** * Retrieve the property editor for the property that this tag is * currently bound to. Intended for cooperating nesting tags. * @return the property editor, or null if none applicable */ public PropertyEditor getEditor() { return editor; } protected int doStartTagInternal() throws Exception { // determine name of the object and property String name = null; this.property = null; int dotPos = this.path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself name = this.path; } else { name = this.path.substring(0, dotPos); this.property = this.path.substring(dotPos + 1); } // retrieve Errors object this.errors = getRequestContext().getErrors(name, false); if (this.errors == null) { throw new JspTagException("Could not find Errors instance for bean '" + name + "' in request"); } List fes = null; Object value = null; if (this.property != null) { if ("*".equals(this.property)) { fes = this.errors.getAllErrors(); } else { fes = this.errors.getFieldErrors(this.property); value = this.errors.getFieldValue(this.property); if (this.errors instanceof BindException) { this.editor = ((BindException) this.errors).getCustomEditor(this.property); } else { logger.warn("Cannot not expose custom property editor because Errors instance [" + this.errors + "] is not of type BindException"); } if (isHtmlEscape() && value instanceof String) { value = HtmlUtils.htmlEscape((String)value); } } } else { fes = this.errors.getGlobalErrors(); } // instantiate the bindstatus object BindStatus status = new BindStatus(this.property, value, getErrorCodes(fes), getErrorMessages(fes)); this.pageContext.setAttribute(STATUS_VARIABLE_NAME, status); return EVAL_BODY_INCLUDE; } /** * Extract the error codes from the given ObjectError list. */ private String[] getErrorCodes(List fes) { String[] codes = new String[fes.size()]; for (int i = 0; i < fes.size(); i++) { ObjectError error = (ObjectError)fes.get(i); codes[i] = error.getCode(); } return codes; } /** * Extract the error messages from the given ObjectError list. */ private String[] getErrorMessages(List fes) throws NoSuchMessageException { String[] messages = new String[fes.size()]; for (int i = 0; i < fes.size(); i++) { ObjectError error = (ObjectError)fes.get(i); messages[i] = getRequestContext().getMessage(error, isHtmlEscape()); } return messages; } public void release() { super.release(); this.path = null; this.errors = null; this.property = null; } }
package ch.openech.model; import static ch.openech.xml.read.StaxEch.skip; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.HashSet; import java.util.Set; import javax.xml.namespace.QName; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import ch.openech.xml.write.EchNamespaceUtil; public class EchXmlDownload { private final Set<String> locations = new HashSet<>(); private EchXmlDownload() { } public void download(int rootNumber) { int major = 1; MAJOR: while (true) { int minor = 0; MINOR: while (true) { if (!download(rootNumber, major, minor)) { break MINOR; } minor++; } if (minor == 0 && major > 3) { break MAJOR; } major++; } } public boolean download(int rootNumber, int major, int minor) { String rootNamespaceURI = EchNamespaceUtil.schemaURI(rootNumber, "" + major); String rootNamespaceLocation = EchNamespaceUtil.schemaLocation(rootNamespaceURI, "" + minor); if (locations.contains(rootNamespaceLocation)) { return false; } locations.add(rootNamespaceLocation); try { return download(rootNamespaceLocation); } catch (Exception x) { x.printStackTrace(); return false; } } private boolean download(String namespaceLocation) throws XMLStreamException, IOException { String fileName = namespaceLocation.substring(namespaceLocation.lastIndexOf("/")); File file = new File("src/main/xml/ch/ech/xmlns" + fileName); if (!file.exists()) { URL url = new URL(namespaceLocation); try (ReadableByteChannel rbc = Channels.newChannel(url.openStream())) { try (FileOutputStream fos = new FileOutputStream(file)) { fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } } catch (FileNotFoundException f) { return false; } } process(file); return true; } private void process(File file) throws XMLStreamException, IOException { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLEventReader xml = inputFactory.createXMLEventReader(new FileInputStream(file)); process(xml); } private void process(XMLEventReader xml) throws XMLStreamException, IOException { while (true) { XMLEvent event = xml.nextEvent(); if (event.isStartElement()) { StartElement startElement = event.asStartElement(); String startName = startElement.getName().getLocalPart(); if (startName.equals("schema")) { schema(xml); } else skip(xml); } else if (event.isEndElement() || event.isEndDocument()) { return; } // else skip } } private void schema(XMLEventReader xml) throws XMLStreamException, IOException { while (true) { XMLEvent event = xml.nextEvent(); if (event.isStartElement()) { StartElement startElement = event.asStartElement(); String startName = startElement.getName().getLocalPart(); if (startName.equals("import")) { imprt(startElement); skip(xml); } else { skip(xml); } } else if (event.isEndElement()) { return; } // else skip } } private void imprt(StartElement startElement) throws XMLStreamException, IOException { String schemaLocation = startElement.getAttributeByName(new QName("schemaLocation")).getValue(); int schema = EchNamespaceUtil.extractSchemaNumber(schemaLocation); download(schema); } public static void main(String... args) { EchXmlDownload download = new EchXmlDownload(); download.download(46); download.download(21); download.download(78); download.download(93); download.download(101); download.download(108); download.download(129); download.download(148); download.download(173); download.download(196); download.download(201); } }
package cn.momia.mapi.api.v1; import cn.momia.mapi.web.response.ResponseMessage; import cn.momia.api.deal.DealServiceApi; import cn.momia.api.user.UserServiceApi; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; 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.RestController; @RestController @RequestMapping("/v1/order") public class OrderV1Api extends AbstractV1Api { @RequestMapping(method = RequestMethod.POST) public ResponseMessage placeOrder(@RequestParam String utoken, @RequestParam String order, @RequestParam(required = false, defaultValue = "") String invite) { if (StringUtils.isBlank(utoken) || StringUtils.isBlank(order)) return ResponseMessage.BAD_REQUEST; JSONObject orderJson = JSON.parseObject(order); orderJson.put("customerId", UserServiceApi.USER.get(utoken).getId()); if (!StringUtils.isBlank(invite)) orderJson.put("inviteCode", invite); return ResponseMessage.SUCCESS(processOrder(DealServiceApi.ORDER.add(orderJson))); } @RequestMapping(value = "/check/dup", method = RequestMethod.GET) public ResponseMessage checkDup(@RequestParam String utoken, @RequestParam String order) { return ResponseMessage.SUCCESS(DealServiceApi.ORDER.checkDup(utoken, order)); } @RequestMapping(value = "/delete", method = RequestMethod.POST) public ResponseMessage deleteOrder(@RequestParam String utoken, @RequestParam long id) { if (StringUtils.isBlank(utoken) || id <= 0) return ResponseMessage.BAD_REQUEST; DealServiceApi.ORDER.delete(utoken, id); return ResponseMessage.SUCCESS; } }
package org.usfirst.frc.team4915.stronghold; import edu.wpi.first.wpilibj.CANTalon; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Solenoid; public class RobotMap { // If you are using multiple modules, make sure to define both the port // number and the module. For example you with a rangefinder: // public static int rangefinderPort = 1; // public static int rangefinderModule = 1; // Define channels for the motors public static final int driveTrainLeftBackMotor = 11; public static final int driveTrainRightBackMotor = 13; // inverted public static final int driveTrainLeftFrontMotor = 10; public static final int driveTrainRightFrontMotor = 12; public static final CANTalon leftBackMotor = new CANTalon(driveTrainLeftBackMotor); public static final CANTalon rightBackMotor = new CANTalon(driveTrainRightBackMotor); public static final CANTalon leftFrontMotor = new CANTalon(driveTrainLeftFrontMotor); public static final CANTalon rightFrontMotor = new CANTalon(driveTrainRightFrontMotor); public static final int INTAKE_LEFT_MOTOR_PORT = -1; //TODO public static final int INTAKE_RIGHT_MOTOR_PORT = -1; //TODO public static final int LAUNCHER_LEFT_MOTOR_PORT = -1; //TODO public static final int LAUNCHER_RIGHT_MOTOR_PORT = -1; //TODO public static final int BOULDER_SWITCH_PORT = -1; //TODO public static final int LAUNCHER_BOTTOM_SWITCH_PORT = -1; //TODO public static final int LAUNCHER_TOP_SWITCH_PORT = -1; //TODO public static final int LAUNCHER_ANGLE_ENCODER_PORT_1 = -1; //TODO public static final int LAUNCHER_ANGLE_ENCODER_PORT_2 = -1; //TODO public static final int LAUNCHER_SOLENOID_PORT = -1; //TODO public static final int LAUNCHER_COMPRESSOR_PORT = -1; //TODO // not actual port values public static CANTalon intakeLeftMotor = new CANTalon(INTAKE_LEFT_MOTOR_PORT); public static CANTalon intakeRightMotor = new CANTalon(INTAKE_RIGHT_MOTOR_PORT); public static CANTalon launcherLeftMotor = new CANTalon(LAUNCHER_LEFT_MOTOR_PORT); public static CANTalon launcherRightMotor = new CANTalon(LAUNCHER_RIGHT_MOTOR_PORT); public static DigitalInput boulderSwitch = new DigitalInput(BOULDER_SWITCH_PORT); public static DigitalInput launcherTopSwitch = new DigitalInput(LAUNCHER_TOP_SWITCH_PORT); public static DigitalInput launcherBottomSwitch = new DigitalInput(LAUNCHER_BOTTOM_SWITCH_PORT); public static Encoder launcherAngleEndoder = new Encoder(LAUNCHER_ANGLE_ENCODER_PORT_1, LAUNCHER_ANGLE_ENCODER_PORT_2); public static Solenoid launcherSolenoid = new Solenoid(LAUNCHER_SOLENOID_PORT); public static Compressor launcherCompressor = new Compressor(LAUNCHER_COMPRESSOR_PORT); }
package com.anor.behaviortree; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Random; public abstract class Composite<Context extends Object> extends Node<Context> { private List<Node<Context>> children; public Composite() { children = new LinkedList<Node<Context>>(); } public final void addChild(Node node) { children.add(node); } protected final List<Node<Context>> getChildren() { return children; } public static class InOrderSequence<Context extends Object> extends Composite<Context> { @Override public final NodeStatus process(Context Context) { NodeStatus toRet = NodeStatus.FAILURE; for(Node<Context> child : getChildren()) { toRet = child.process(Context); if(failed(toRet) || running(toRet)) { return toRet; } } return toRet; } } public static class RandomSequence<Context extends Object> extends Composite<Context> { @Override public NodeStatus process(Context Context) { // maintain the original order List<Node<Context>> children = new ArrayList<Node<Context>>(getChildren()); Collections.shuffle(getChildren()); NodeStatus toRet = NodeStatus.FAILURE; for(Node<Context> child : getChildren()) { toRet = child.process(Context); if(failed(toRet) || running(toRet)) { return toRet; } } return toRet; } } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc692.AerialAssist2014; import edu.wpi.first.wpilibj.*; import edu.wpi.first.wpilibj.CounterBase.EncodingType; import edu.wpi.first.wpilibj.PIDSource.PIDSourceParameter; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import java.util.Vector; /** * The RobotMap is a mapping from the ports sensors and actuators are wired into * to a variable name. This provides flexibility changing wiring, makes checking * the wiring easier and significantly reduces the number of magic numbers * floating around. */ public class RobotMap { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static SpeedController driveTrainlefttDriveVictor1; public static SpeedController driveTrainleftDriveVictor2; public static SpeedController driveTrainrightDriveVictor1; public static SpeedController driveTrainrightDriveVictor2; public static RobotDrive driveTrainRobotDrive; public static Encoder driveTrainleftEncoder; public static Encoder driveTrainrightEncoder; public static DoubleSolenoid driveTrainhighAndLowShift; public static SpeedController shootershooterMotor1; public static DigitalInput shootershooterLimit; public static SpeedController gatherergathererMotor; public static DoubleSolenoid gathererpasserPusher; public static DoubleSolenoid gathererupAndDownGatherer; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public static void init() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS driveTrainlefttDriveVictor1 = new Victor(1, 4); LiveWindow.addActuator("DriveTrain", "lefttDriveVictor1", (Victor) driveTrainlefttDriveVictor1); driveTrainleftDriveVictor2 = new Victor(1, 3); LiveWindow.addActuator("DriveTrain", "leftDriveVictor2", (Victor) driveTrainleftDriveVictor2); driveTrainrightDriveVictor1 = new Victor(1, 1); LiveWindow.addActuator("DriveTrain", "rightDriveVictor1", (Victor) driveTrainrightDriveVictor1); driveTrainrightDriveVictor2 = new Victor(1, 2); LiveWindow.addActuator("DriveTrain", "rightDriveVictor2", (Victor) driveTrainrightDriveVictor2); driveTrainRobotDrive = new RobotDrive(driveTrainlefttDriveVictor1, driveTrainleftDriveVictor2, driveTrainrightDriveVictor1, driveTrainrightDriveVictor2); driveTrainRobotDrive.setSafetyEnabled(true); driveTrainRobotDrive.setExpiration(0.1); driveTrainRobotDrive.setSensitivity(0.5); driveTrainRobotDrive.setMaxOutput(1.0); driveTrainleftEncoder = new Encoder(1, 6, 1, 7, false, EncodingType.k4X); LiveWindow.addSensor("DriveTrain", "leftEncoder", driveTrainleftEncoder); driveTrainleftEncoder.setDistancePerPulse(1.0); driveTrainleftEncoder.setPIDSourceParameter(PIDSourceParameter.kRate); driveTrainleftEncoder.start(); driveTrainrightEncoder = new Encoder(1, 8, 1, 9, false, EncodingType.k4X); LiveWindow.addSensor("DriveTrain", "rightEncoder", driveTrainrightEncoder); driveTrainrightEncoder.setDistancePerPulse(1.0); driveTrainrightEncoder.setPIDSourceParameter(PIDSourceParameter.kRate); driveTrainrightEncoder.start(); driveTrainhighAndLowShift = new DoubleSolenoid(1, 1, 2); shootershooterMotor1 = new Victor(1, 5); LiveWindow.addActuator("Shooter", "shooterMotor1", (Victor) shootershooterMotor1); shootershooterLimit = new DigitalInput(1, 2); LiveWindow.addSensor("Shooter", "shooterLimit", shootershooterLimit); gatherergathererMotor = new Victor(1, 7); LiveWindow.addActuator("Gatherer", "gathererMotor", (Victor) gatherergathererMotor); gathererpasserPusher = new DoubleSolenoid(2, 1, 2); gathererupAndDownGatherer = new DoubleSolenoid(1, 3, 4); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS } }
package com.aol.cyclops.control; import java.util.Iterator; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; import org.jooq.lambda.Seq; import org.jooq.lambda.tuple.Tuple2; import org.reactivestreams.Publisher; import com.aol.cyclops.Monoid; import com.aol.cyclops.Reducer; import com.aol.cyclops.Semigroup; import com.aol.cyclops.control.Matchable.CheckValue1; import com.aol.cyclops.data.collections.extensions.CollectionX; import com.aol.cyclops.data.collections.extensions.standard.ListX; import com.aol.cyclops.types.ConvertableFunctor; import com.aol.cyclops.types.Filterable; import com.aol.cyclops.types.FlatMap; import com.aol.cyclops.types.MonadicValue; import com.aol.cyclops.types.MonadicValue1; import com.aol.cyclops.types.Value; import com.aol.cyclops.types.applicative.ApplicativeFunctor; import com.aol.cyclops.types.stream.reactive.ValueSubscriber; import com.aol.cyclops.util.ExceptionSoftener; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; /** * A Wrapper around CompletableFuture that implements cyclops-react interfaces and provides a more standard api * * e.g. * map instead of thenApply * flatMap instead of thenCompose * combine instead of thenCombine (applicative functor ap) * * @author johnmcclean * * @param <T> Type of wrapped future value */ @AllArgsConstructor @EqualsAndHashCode public class FutureW<T> implements ConvertableFunctor<T>, ApplicativeFunctor<T>, MonadicValue1<T>, FlatMap<T>, Filterable<T> { /** * An empty FutureW * * @return A FutureW that wraps a CompletableFuture with a null result */ public static <T> FutureW<T> empty() { return new FutureW( CompletableFuture.completedFuture(null)); } /** * Construct a FutureW asyncrhonously that contains a single value extracted from the supplied reactive-streams Publisher * * @param pub Publisher to extract value from * @param ex Executor to extract value on * @return FutureW populated asyncrhonously from Publisher */ public static <T> FutureW<T> fromPublisher(final Publisher<T> pub, final Executor ex) { final ValueSubscriber<T> sub = ValueSubscriber.subscriber(); pub.subscribe(sub); return sub.toFutureWAsync(ex); } /** * Construct a FutureW asyncrhonously that contains a single value extracted from the supplied Iterable * * @param iterable Iterable to generate a FutureW from * @param ex Executor to extract value on * @return FutureW populated asyncrhonously from Iterable */ public static <T> FutureW<T> fromIterable(final Iterable<T> iterable, final Executor ex) { return FutureW.ofSupplier(() -> Eval.fromIterable(iterable)) .map(e -> e.get()); } /** * Construct a FutureW syncrhonously that contains a single value extracted from the supplied reactive-streams Publisher * * @param pub Publisher to extract value from * @return FutureW populated syncrhonously from Publisher */ public static <T> FutureW<T> fromPublisher(final Publisher<T> pub) { final ValueSubscriber<T> sub = ValueSubscriber.subscriber(); pub.subscribe(sub); return sub.toFutureW(); } /** * Construct a FutureW syncrhonously that contains a single value extracted from the supplied Iterable * * @param iterable Iterable to extract value from * @return FutureW populated syncrhonously from Iterable */ public static <T> FutureW<T> fromIterable(final Iterable<T> iterable) { iterable.iterator(); return FutureW.ofResult(Eval.fromIterable(iterable)) .map(e -> e.get()); } /** * Create a FutureW instance from the supplied CompletableFuture * * @param f CompletableFuture to wrap as a FutureW * @return FutureW wrapping the supplied CompletableFuture */ public static <T> FutureW<T> of(final CompletableFuture<T> f) { return new FutureW<>( f); } /** * Construct a FutureW asyncrhonously from the Supplied Try * * @param value Try to populate Future from * @param ex Executor to execute * @return FutureW populated with either the value or error in provided Try */ @Deprecated public static <T, X extends Throwable> FutureW<T> fromTry(final Try<T, X> value, final Executor ex) { return FutureW.ofSupplier(value, ex); } /** * Construct a FutureW syncrhonously from the Supplied Try * * @param value Try to populate Future from * @return FutureW populated with either the value or error in provided Try */ public static <T, X extends Throwable> FutureW<T> fromTry(final Try<T, X> value) { return FutureW.ofSupplier(value); } /** * Schedule the population of a FutureW from the provided Supplier, the provided Cron (Quartz format) expression will be used to * trigger the population of the FutureW. The provided ScheduledExecutorService provided the thread on which the * Supplier will be executed. * * <pre> * {@code * * FutureW<String> future = FutureW.schedule("* * * * * ?", Executors.newScheduledThreadPool(1), ()->"hello") * * }</pre> * * * @param cron Cron expression in Quartz format * @param ex ScheduledExecutorService used to execute the provided Supplier * @param t The Supplier to execute to populate the FutureW * @return FutureW populated on a Cron based Schedule */ public static <T> FutureW<T> schedule(final String cron, final ScheduledExecutorService ex, final Supplier<T> t) { final CompletableFuture<T> future = new CompletableFuture<>(); final FutureW<T> wrapped = FutureW.of(future); ReactiveSeq.generate(() -> { try { future.complete(t.get()); } catch (final Throwable t1) { future.completeExceptionally(t1); } return 1; }) .limit(1) .schedule(cron, ex); return wrapped; } /** * Schedule the population of a FutureW from the provided Supplier after the specified delay. The provided ScheduledExecutorService provided the thread on which the * Supplier will be executed. * * @param delay Delay after which the FutureW should be populated * @param ex ScheduledExecutorService used to execute the provided Supplier * @param t he Supplier to execute to populate the FutureW * @return FutureW populated after the specified delay */ public static <T> FutureW<T> schedule(final long delay, final ScheduledExecutorService ex, final Supplier<T> t) { final CompletableFuture<T> future = new CompletableFuture<>(); final FutureW<T> wrapped = FutureW.of(future); ReactiveSeq.generate(() -> { try { future.complete(t.get()); } catch (final Throwable t1) { future.completeExceptionally(t1); } return 1; }) .limit(1) .scheduleFixedDelay(delay, ex); return wrapped; } /** * Sequence operation that convert a Collection of FutureWs to a FutureW with a List * * <pre> * {@code * FutureW<ListX<Integer>> futures =FutureW.sequence(ListX.of(FutureW.ofResult(10),FutureW.ofResult(1))); //ListX.of(10,1) * * } * </pre> * * * @param fts Collection of Futures to Sequence into a Future with a List * @return Future with a List */ public static <T> FutureW<ListX<T>> sequence(final CollectionX<FutureW<T>> fts) { return sequence(fts.stream()).map(s -> s.toListX()); } /** * Sequence operation that convert a Stream of FutureWs to a FutureW with a Stream * * <pre> * {@code * FutureW<Integer> just = FutureW.ofResult(10); * FutureW<ReactiveSeq<Integer>> futures =FutureW.sequence(Stream.of(just,FutureW.ofResult(1))); //ListX.of(10,1) * * } * </pre> * * @param fts Strean of Futures to Sequence into a Future with a Stream * @return Future with a Stream */ public static <T> FutureW<ReactiveSeq<T>> sequence(final Stream<FutureW<T>> fts) { return AnyM.sequence(fts.map(f -> AnyM.fromFutureW(f)), () -> AnyM.fromFutureW(FutureW.ofResult(Stream.<T> empty()))) .map(s -> ReactiveSeq.fromStream(s)) .unwrap(); } public static <T, R> FutureW<R> accumulateSuccess(final CollectionX<FutureW<T>> fts, final Reducer<R> reducer) { final FutureW<ListX<T>> sequenced = AnyM.sequence(fts.map(f -> AnyM.fromFutureW(f))) .unwrap(); return sequenced.map(s -> s.mapReduce(reducer)); } public static <T, R> FutureW<R> accumulate(final CollectionX<FutureW<T>> fts, final Reducer<R> reducer) { return sequence(fts).map(s -> s.mapReduce(reducer)); } public static <T, R> FutureW<R> accumulate(final CollectionX<FutureW<T>> fts, final Function<? super T, R> mapper, final Semigroup<R> reducer) { return sequence(fts).map(s -> s.map(mapper) .reduce(reducer.reducer()) .get()); } public static <T> FutureW<T> accumulate(final CollectionX<FutureW<T>> fts, final Semigroup<T> reducer) { return sequence(fts).map(s -> s.reduce(reducer.reducer()) .get()); } public <R> Eval<R> matches(final Function<CheckValue1<T, R>, CheckValue1<T, R>> secondary, final Function<CheckValue1<Throwable, R>, CheckValue1<Throwable, R>> primary, final Supplier<? extends R> otherwise) { return toXor().swap() .matches(secondary, primary, otherwise); } @Getter private final CompletableFuture<T> future; /* * (non-Javadoc) * * @see * com.aol.cyclops.types.MonadicValue#coflatMap(java.util.function.Function) */ @Override public <R> FutureW<R> coflatMap(final Function<? super MonadicValue<T>, R> mapper) { return (FutureW<R>) MonadicValue1.super.coflatMap(mapper); } /* * cojoin (non-Javadoc) * * @see com.aol.cyclops.types.MonadicValue#nest() */ @Override public FutureW<MonadicValue<T>> nest() { return (FutureW<MonadicValue<T>>) MonadicValue1.super.nest(); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.MonadicValue2#combine(com.aol.cyclops.Monoid, * com.aol.cyclops.types.MonadicValue2) */ @Override public FutureW<T> combineEager(final Monoid<T> monoid, final MonadicValue<? extends T> v2) { return (FutureW<T>) MonadicValue1.super.combineEager(monoid, v2); } /* * (non-Javadoc) * * @see * com.aol.cyclops.types.ConvertableFunctor#map(java.util.function.Function) */ @Override public <R> FutureW<R> map(final Function<? super T, ? extends R> fn) { return new FutureW<R>( future.thenApply(fn)); } /* * (non-Javadoc) * * @see * com.aol.cyclops.types.Functor#patternMatch(java.util.function.Function, * java.util.function.Supplier) */ @Override public <R> FutureW<R> patternMatch(final Function<CheckValue1<T, R>, CheckValue1<T, R>> case1, final Supplier<? extends R> otherwise) { return (FutureW<R>) ApplicativeFunctor.super.patternMatch(case1, otherwise); } /* * (non-Javadoc) * * @see java.util.function.Supplier#get() */ @Override public T get() { try { return future.join(); } catch (final Throwable t) { throw ExceptionSoftener.throwSoftenedException(t.getCause()); } } /** * @return true if this FutureW is both complete, and completed without an * Exception */ public boolean isSuccess() { return future.isDone() && !future.isCompletedExceptionally(); } /** * @return true if this FutureW is complete, but completed with an Exception */ public boolean isFailed() { return future.isCompletedExceptionally(); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Value#iterator() */ @Override public Iterator<T> iterator() { return toStream().iterator(); } /* * (non-Javadoc) * * @see com.aol.cyclops.lambda.monads.Unit#unit(java.lang.Object) */ @Override public <T> FutureW<T> unit(final T unit) { return new FutureW<T>( CompletableFuture.completedFuture(unit)); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Value#stream() */ @Override public ReactiveSeq<T> stream() { return ReactiveSeq.generate(() -> Try.withCatch(() -> get())) .limit(1) .filter(t -> t.isSuccess()) .map(Value::get); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.FlatMap#flatten() */ @Override public <R> FutureW<R> flatten() { return FutureW.of(AnyM.fromCompletableFuture(future) .flatten() .unwrap()); } /* * (non-Javadoc) * * @see * com.aol.cyclops.types.MonadicValue1#flatMap(java.util.function.Function) */ @Override public <R> FutureW<R> flatMap(final Function<? super T, ? extends MonadicValue<? extends R>> mapper) { return FutureW.<R> of(future.<R> thenCompose(t -> (CompletionStage<R>) mapper.apply(t) .toFutureW() .getFuture())); } /** * A flatMap operation that accepts a CompleteableFuture CompletionStage as * the return type * * @param mapper * Mapping function * @return FlatMapped FutureW */ public <R> FutureW<R> flatMapCf(final Function<? super T, ? extends CompletionStage<? extends R>> mapper) { return FutureW.<R> of(future.<R> thenCompose(t -> (CompletionStage<R>) mapper.apply(t))); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Value#toXor() */ @Override public Xor<Throwable, T> toXor() { try { return Xor.primary(future.join()); } catch (final Throwable t) { return Xor.<Throwable, T> secondary(t.getCause()); } } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Value#toIor() */ @Override public Ior<Throwable, T> toIor() { try { return Ior.primary(future.join()); } catch (final Throwable t) { return Ior.<Throwable, T> secondary(t.getCause()); } } /* * (non-Javadoc) * * @see com.aol.cyclops.closures.Convertable#toFutureW() */ @Override public FutureW<T> toFutureW() { return this; } /* * (non-Javadoc) * * @see com.aol.cyclops.closures.Convertable#toCompletableFuture() */ @Override public CompletableFuture<T> toCompletableFuture() { return this.future; } /* * (non-Javadoc) * * @see com.aol.cyclops.closures.Convertable#toCompletableFutureAsync() */ @Override public CompletableFuture<T> toCompletableFutureAsync() { return this.future; } /* * (non-Javadoc) * * @see * com.aol.cyclops.closures.Convertable#toCompletableFutureAsync(java.util. * concurrent.Executor) */ @Override public CompletableFuture<T> toCompletableFutureAsync(final Executor exec) { return this.future; } /** * Returns a new FutureW that, when this FutureW completes exceptionally is * executed with this FutureW exception as the argument to the supplied * function. Otherwise, if this FutureW completes normally, then the * returned FutureW also completes normally with the same value. * * @param fn * the function to use to compute the value of the returned * FutureW if this FutureW completed exceptionally * @return the new FutureW */ public FutureW<T> recover(final Function<Throwable, ? extends T> fn) { return FutureW.of(toCompletableFuture().exceptionally(fn)); } /** * Map this FutureW differently depending on whether the previous stage * completed successfully or failed * * @param success * Mapping function for successful outcomes * @param failure * Mapping function for failed outcomes * @return New futureW mapped to a new state */ public <R> FutureW<R> map(final Function<? super T, R> success, final Function<Throwable, R> failure) { return FutureW.of(future.thenApply(success) .exceptionally(failure)); } /* * (non-Javadoc) * * @see com.aol.cyclops.lambda.monads.Functor#cast(java.lang.Class) */ @Override public <U> FutureW<U> cast(final Class<? extends U> type) { return (FutureW<U>) ApplicativeFunctor.super.cast(type); } /* * (non-Javadoc) * * @see * com.aol.cyclops.lambda.monads.Functor#peek(java.util.function.Consumer) */ @Override public FutureW<T> peek(final Consumer<? super T> c) { return (FutureW<T>) ApplicativeFunctor.super.peek(c); } /* * (non-Javadoc) * * @see com.aol.cyclops.lambda.monads.Functor#trampoline(java.util.function. * Function) */ @Override public <R> FutureW<R> trampoline(final Function<? super T, ? extends Trampoline<? extends R>> mapper) { return (FutureW<R>) ApplicativeFunctor.super.trampoline(mapper); } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return mkString(); } /** * Construct a successfully completed FutureW from the given value * * @param result * To wrap inside a FutureW * @return FutureW containing supplied result */ public static <T> FutureW<T> ofResult(final T result) { return FutureW.of(CompletableFuture.completedFuture(result)); } /** * Construct a completed-with-error FutureW from the given Exception * * @param error * To wrap inside a FutureW * @return FutureW containing supplied error */ public static <T> FutureW<T> ofError(final Throwable error) { final CompletableFuture<T> cf = new CompletableFuture<>(); cf.completeExceptionally(error); return FutureW.<T> of(cf); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Convertable#isPresent() */ @Override public boolean isPresent() { return !this.future.isCompletedExceptionally(); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Value#mkString() */ @Override public String mkString() { return "FutureW[" + future.toString() + "]"; } /* * (non-Javadoc) * * @see * com.aol.cyclops.types.Filterable#filter(java.util.function.Predicate) */ @Override public Maybe<T> filter(final Predicate<? super T> fn) { return toMaybe().filter(fn); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Filterable#ofType(java.lang.Class) */ @Override public <U> Maybe<U> ofType(final Class<? extends U> type) { return (Maybe<U>) Filterable.super.ofType(type); } /* * (non-Javadoc) * * @see * com.aol.cyclops.types.Filterable#filterNot(java.util.function.Predicate) */ @Override public Maybe<T> filterNot(final Predicate<? super T> fn) { return (Maybe<T>) Filterable.super.filterNot(fn); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Filterable#notNull() */ @Override public Maybe<T> notNull() { return (Maybe<T>) Filterable.super.notNull(); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Convertable#toOptional() */ @Override public Optional<T> toOptional() { if (future.isDone() && future.isCompletedExceptionally()) return Optional.empty(); try { return Optional.ofNullable(get()); } catch (final Throwable t) { return Optional.empty(); } } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Convertable#toFutureWAsync() */ @Override public FutureW<T> toFutureWAsync() { return this; } /* * (non-Javadoc) * * @see * com.aol.cyclops.types.Convertable#toFutureWAsync(java.util.concurrent. * Executor) */ @Override public FutureW<T> toFutureWAsync(final Executor ex) { return this; } /* * Apply a function across two values at once. (non-Javadoc) * * @see * com.aol.cyclops.types.applicative.ApplicativeFunctor#combine(com.aol. * cyclops.types.Value, java.util.function.BiFunction) */ @Override public <T2, R> FutureW<R> combine(final Value<? extends T2> app, final BiFunction<? super T, ? super T2, ? extends R> fn) { if (app instanceof FutureW) { return FutureW.of(future.thenCombine(((FutureW<T2>) app).getFuture(), fn)); } return (FutureW<R>) ApplicativeFunctor.super.zip(app, fn); } /* * Equivalent to combine, but accepts an Iterable and takes the first value * only from that iterable. (non-Javadoc) * * @see com.aol.cyclops.types.Zippable#zip(java.lang.Iterable, * java.util.function.BiFunction) */ @Override public <T2, R> FutureW<R> zip(final Iterable<? extends T2> app, final BiFunction<? super T, ? super T2, ? extends R> fn) { return (FutureW<R>) ApplicativeFunctor.super.zip(app, fn); } /* * Equivalent to combine, but accepts a Publisher and takes the first value * only from that publisher. * * (non-Javadoc) * * @see com.aol.cyclops.types.Zippable#zip(java.util.function.BiFunction, * org.reactivestreams.Publisher) */ @Override public <T2, R> FutureW<R> zip(final BiFunction<? super T, ? super T2, ? extends R> fn, final Publisher<? extends T2> app) { return (FutureW<R>) ApplicativeFunctor.super.zip(fn, app); } /** * Create a FutureW object that asyncrhonously populates using the Common * ForkJoinPool from the user provided Supplier * * @param s * Supplier to asynchronously populate results from * @return FutureW asynchronously populated from the Supplier */ public static <T> FutureW<T> ofSupplier(final Supplier<T> s) { return FutureW.of(CompletableFuture.supplyAsync(s)); } /** * Create a FutureW object that asyncrhonously populates using the provided * Executor and Supplier * * @param s * Supplier to asynchronously populate results from * @param ex * Executro to asynchronously populate results with * @return FutureW asynchronously populated from the Supplier */ public static <T> FutureW<T> ofSupplier(final Supplier<T> s, final Executor ex) { return FutureW.of(CompletableFuture.supplyAsync(s, ex)); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Zippable#zip(org.jooq.lambda.Seq, * java.util.function.BiFunction) */ @Override public <U, R> FutureW<R> zip(final Seq<? extends U> other, final BiFunction<? super T, ? super U, ? extends R> zipper) { return (FutureW<R>) ApplicativeFunctor.super.zip(other, zipper); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Zippable#zip(java.util.stream.Stream, * java.util.function.BiFunction) */ @Override public <U, R> FutureW<R> zip(final Stream<? extends U> other, final BiFunction<? super T, ? super U, ? extends R> zipper) { return (FutureW<R>) ApplicativeFunctor.super.zip(other, zipper); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Zippable#zip(java.util.stream.Stream) */ @Override public <U> FutureW<Tuple2<T, U>> zip(final Stream<? extends U> other) { return (FutureW) ApplicativeFunctor.super.zip(other); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Zippable#zip(org.jooq.lambda.Seq) */ @Override public <U> FutureW<Tuple2<T, U>> zip(final Seq<? extends U> other) { return (FutureW) ApplicativeFunctor.super.zip(other); } /* * (non-Javadoc) * * @see com.aol.cyclops.types.Zippable#zip(java.lang.Iterable) */ @Override public <U> FutureW<Tuple2<T, U>> zip(final Iterable<? extends U> other) { return (FutureW) ApplicativeFunctor.super.zip(other); } /* (non-Javadoc) * @see com.aol.cyclops.types.MonadicValue1#flatMapIterable(java.util.function.Function) */ @Override public <R> FutureW<R> flatMapIterable(final Function<? super T, ? extends Iterable<? extends R>> mapper) { return (FutureW<R>) MonadicValue1.super.flatMapIterable(mapper); } /* (non-Javadoc) * @see com.aol.cyclops.types.MonadicValue1#flatMapPublisher(java.util.function.Function) */ @Override public <R> FutureW<R> flatMapPublisher(final Function<? super T, ? extends Publisher<? extends R>> mapper) { return (FutureW<R>) MonadicValue1.super.flatMapPublisher(mapper); } }
package org.vitrivr.cineast.core.setup; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.vitrivr.cineast.core.config.Config; import org.vitrivr.cineast.core.data.entities.MediaObjectMetadataDescriptor; import org.vitrivr.cineast.core.data.entities.MediaObjectDescriptor; import org.vitrivr.cineast.core.data.entities.MediaSegmentDescriptor; import org.vitrivr.cineast.core.db.dao.TagHandler; import org.vitrivr.cineast.core.features.retriever.Retriever; import org.vitrivr.cineast.core.setup.AttributeDefinition.AttributeType; public interface EntityCreator extends AutoCloseable { /** * Logger instance used for logging. */ Logger LOGGER = LogManager.getLogger(); /** * Name of the 'clean' flag. */ public static final String SETUP_FLAG_CLEAN = "clean"; /** * Performs the setup of the persistent layer by executing all the necessary entity * creation steps in a sequence. * <p> * The options map supports the following flags: * <p> * - clean: Drops all entities before creating new ones. * * @param options Options that can be provided for setup. * @return boolean Indicating success or failure of the setup. */ default boolean setup(HashMap<String, String> options) { if (options.containsKey(SETUP_FLAG_CLEAN)) { LOGGER.info("Dropping all entities"); this.dropAllEntities(); } LOGGER.info("Setting up basic entities..."); this.createMultiMediaObjectsEntity(); this.createMetadataEntity(); this.createSegmentMetadataEntity(); this.createSegmentEntity(); this.createTagEntity(); LOGGER.info("...done"); LOGGER.info("Collecting retriever classes..."); HashSet<Retriever> retrievers = new HashSet<>(); for (String category : Config.sharedConfig().getRetriever().getRetrieverCategories()) { retrievers.addAll(Config.sharedConfig().getRetriever().getRetrieversByCategory(category).keySet()); } LOGGER.info("...done"); for (Retriever r : retrievers) { LOGGER.info("Setting up " + r.getClass().getSimpleName()); r.initalizePersistentLayer(() -> this); } System.out.println("Setup complete!"); return true; } /** * Drops all entities currently required by Cineast. */ default void dropAllEntities() { LOGGER.info("Dropping basic entities..."); this.dropMultiMediaObjectsEntity(); this.dropMetadataEntity(); this.dropSegmentEntity(); this.dropTagEntity(); LOGGER.info("...done"); HashSet<Retriever> retrievers = new HashSet<>(); for (String category : Config.sharedConfig().getRetriever().getRetrieverCategories()) { retrievers.addAll(Config.sharedConfig().getRetriever().getRetrieversByCategory(category).keySet()); } for (Retriever r : retrievers) { LOGGER.info("Dropping " + r.getClass().getSimpleName()); r.dropPersistentLayer(() -> this); } } /** * Initialises the main entity holding information about multimedia objects */ boolean createMultiMediaObjectsEntity(); /** * Initialises the entity responsible for holding metadata information about multimedia objects. */ boolean createMetadataEntity(); /** * Initialises the entity responsible for holding metadata information about multimedia segments. */ boolean createSegmentMetadataEntity(); /** * Initialises the entity responsible for holding the mapping between human readable tags and their descriptions to the internally used ids */ default boolean createTagEntity() { final Map<String, String> hints = new HashMap<>(1); hints.put("handler", "postgres"); return this.createIdEntity(TagHandler.TAG_ENTITY_NAME, new AttributeDefinition(TagHandler.TAG_NAME_COLUMNNAME, AttributeType.STRING, hints), new AttributeDefinition(TagHandler.TAG_DESCRIPTION_COLUMNNAME, AttributeType.STRING, hints)); } /** * Initializes the entity responsible for holding information about segments of a multimedia object */ boolean createSegmentEntity(); /** * Drops the main entity holding information about multimedia objects */ default boolean dropMultiMediaObjectsEntity() { if (this.dropEntity(MediaObjectDescriptor.ENTITY)) { LOGGER.info("Successfully dropped multimedia object entity."); return true; } else { LOGGER.error("Error occurred while dropping multimedia object entity"); return false; } } /** * Drops the entity responsible for holding information about segments of a multimedia object */ default boolean dropSegmentEntity() { if (this.dropEntity(MediaSegmentDescriptor.ENTITY)) { LOGGER.info("Successfully dropped segment entity."); return true; } else { LOGGER.error("Error occurred while dropping segment entity"); return false; } } /** * Drops the entity responsible for holding metadata information about multimedia objects. */ default boolean dropMetadataEntity() { if (this.dropEntity(MediaObjectMetadataDescriptor.ENTITY)) { LOGGER.info("Successfully dropped metadata entity."); return true; } else { LOGGER.error("Error occurred while dropping metadata entity"); return false; } } /** * Drops the entity responsible for holding metadata information about multimedia objects. */ default boolean dropTagEntity() { if (this.dropEntity(TagHandler.TAG_ENTITY_NAME)) { LOGGER.info("Successfully dropped tag entity."); return true; } else { LOGGER.error("Error occurred while dropping tag entity"); return false; } } /** * Creates and initializes an entity for a feature module with default parameters * * @param featurename the name of the feature module * @param unique true if the feature module produces at most one vector per segment */ default boolean createFeatureEntity(String featurename, boolean unique) { return createFeatureEntity(featurename, unique, "feature"); } boolean createFeatureEntity(String featurename, boolean unique, String... featureNames); boolean createFeatureEntity(String featurename, boolean unique, AttributeDefinition... attributes); /** * Creates and initializes an entity with the provided name and the provided attributes. The new entity will have an additional * field prepended, called "id", which is of type "string" and has an index. * * @param entityName Name of the new entity. * @param attributes List of {@link AttributeDefinition} objects specifying the new entities attributes. * @return True on success, false otherwise. */ boolean createIdEntity(String entityName, AttributeDefinition... attributes); /** * Creates and initializes an entity with the provided name and the provided attributes. * * @param entityName Name of the new entity. * @param attributes List of {@link AttributeDefinition} objects specifying the new entities attributes. * @return True on success, false otherwise. */ boolean createEntity(String entityName, AttributeDefinition... attributes); /** * @param entityName * @return */ boolean existsEntity(String entityName); /** * drops an entity, returns <code>true</code> if the entity was successfully dropped, <code>false</code> otherwise * * @param entityName the entity to drop */ boolean dropEntity(String entityName); @Override void close(); }
package com.constantcontact.util; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * Main Configuration structure in Constant Contact. * * @author ConstantContact * */ public final class Config { /** * Contains a list with all REST endpoints. * * @author ConstantContact */ public static final class Endpoints { /** * API access URL Host. */ public static final String BASE_URL_HOST; static { /* * Configures BASE_URL. Value can be loaded from property "constantcontact.api.dest.baseurl" * in properties file "dest.properties". Method will defer to default value * if file or property is not present. * Throws an IOException if the file is not readable. */ try { Properties prop = new Properties(); InputStream in; String baseUrl = "https://api.constantcontact.com"; in = Config.class.getClassLoader().getResourceAsStream("dest.properties"); if (in != null) { prop.load(in); try { in.close(); } catch (IOException ignoreMe) { } String baseUrlConfiguration = prop.getProperty("constantcontact.api.dest.baseurl"); if (baseUrlConfiguration != null) { baseUrl = baseUrlConfiguration; } } BASE_URL_HOST = baseUrl; } catch (IOException e) { throw new IllegalStateException("Cannot configure connection to Constant Contact", e); } } /** * API access URL. */ public static final String BASE_URL = BASE_URL_HOST + "/" + "v2/"; /** * Access a contact. */ public static final String CONTACT = "contacts/%1$s"; /** * Get all contacts. */ public static final String CONTACTS = "contacts"; /** * Get all lists. */ public static final String LISTS = "lists"; /** * Access a specified list. */ public static final String LIST = "lists/%1$s"; /** * Get the list of contacts from a list. */ public static final String LIST_CONTACTS = "lists/%1$s/contacts"; /** * Get contact lists. */ public static final String CONTACT_LISTS = "contacts/%1$s/lists"; /** * Get a list from contact lists. */ public static final String CONTACT_LIST = "contacts/%1$s/lists/%2$s"; /** * Get campaigns. */ public static final String EMAILCAMPAIGNS = "emailmarketing/campaigns"; /** * Access a campaign. */ public static final String EMAILCAMPAIGN_ID = "emailmarketing/campaigns/%1$s"; /** * Access a campaign. This is for PUT operations. */ public static final String EMAILCAMPAIGNS_ID = "emailmarketing/campaigns/%1$s"; /** * Get verified email addresses. */ public static final String VERIFIEDEMAILADDRESSES = "account/verifiedemailaddresses"; /** * Access a campaign schedule. */ public static final String EMAILCAMPAIGNS_SCHEDULES_ID = "emailmarketing/campaigns/%1$s/schedules/%2$s"; /** * Access all campaign schedules. */ public static final String EMAILCAMPAIGNS_SCHEDULES_ID_ALL = "emailmarketing/campaigns/%1$s/schedules"; /** * Access email campaign tracking reports summary for a given email campaign. */ public static final String EMAILCAMPAIGNS_TRACKING_REPORTS_SUMMARY = "emailmarketing/campaigns/%1$s/tracking/reports/summary"; /** * Access email campaign tracking bounces for a given email campaign. */ public static final String EMAILCAMPAIGNS_TRACKING_BOUNCES = "emailmarketing/campaigns/%1$s/tracking/bounces"; /** * Access email campaign tracking clicks for a given email campaign. */ public static final String EMAILCAMPAIGNS_TRACKING_CLICKS = "emailmarketing/campaigns/%1$s/tracking/clicks"; /** * Access email campaign tracking forwards for a given email campaign. */ public static final String EMAILCAMPAIGNS_TRACKING_FORWARDS = "emailmarketing/campaigns/%1$s/tracking/forwards"; /** * Access email campaign tracking opens for a given email campaign. */ public static final String EMAILCAMPAIGNS_TRACKING_OPENS = "emailmarketing/campaigns/%1$s/tracking/opens"; /** * Access email campaign tracking sends for a given email campaign. */ public static final String EMAILCAMPAIGNS_TRACKING_SENDS = "emailmarketing/campaigns/%1$s/tracking/sends"; /** * Access email campaign tracking unsubscribes for a given email campaign. */ public static final String EMAILCAMPAIGNS_TRACKING_UNSUBSCRIBES = "emailmarketing/campaigns/%1$s/tracking/unsubscribes"; /** * Access email campaign tracking clicks by link for a given email campaign. */ public static final String EMAILCAMPAIGNS_TRACKING_CLICKS_BY_LINK = "emailmarketing/campaigns/%1$s/tracking/clicks/%2$s"; /** * Access contact tracking reports summary for a given contact. */ public static final String CONTACTS_TRACKING_REPORTS_SUMMARY = "contacts/%1$s/tracking/reports/summary"; /** * Access contact tracking reports summary for a given contact. */ public static final String CONTACTS_TRACKING_REPORTS_BY_CAMPAIGN_SUMMARY = "contacts/%1$s/tracking/reports/summaryByCampaign"; /** * Access contact tracking activities for a given contact. */ public static final String CONTACTS_TRACKING_ALL = "contacts/%1$s/tracking/"; /** * Access contact tracking bounces for a given contact. */ public static final String CONTACTS_TRACKING_BOUNCES = "contacts/%1$s/tracking/bounces"; /** * Access contact tracking clicks for a given contact. */ public static final String CONTACTS_TRACKING_CLICKS = "contacts/%1$s/tracking/clicks"; /** * Access contact tracking forwards for a given contact. */ public static final String CONTACTS_TRACKING_FORWARDS = "contacts/%1$s/tracking/forwards"; /** * Access contact tracking opens for a given contact. */ public static final String CONTACTS_TRACKING_OPENS = "contacts/%1$s/tracking/opens"; /** * Access contact tracking sends for a given contact. */ public static final String CONTACTS_TRACKING_SENDS = "contacts/%1$s/tracking/sends"; /** * Access contact tracking unsubscribes for a given contact. */ public static final String CONTACTS_TRACKING_UNSUBSCRIBES = "contacts/%1$s/tracking/unsubscribes"; /** * Endpoint for the bulk contacts upload. */ public static final String ACTIVITIES_ADD_CONTACTS = "activities/addcontacts"; /** * Endpoint for the bulk contacts remove from lists. */ public static final String ACTIVITIES_REMOVE_FROM_LISTS = "activities/removefromlists"; /** * Endpoint for the bulk clear lists. */ public static final String ACTIVITIES_CLEAR_LISTS = "activities/clearlists"; /** * Endpoint for the bulk export contacts. */ public static final String ACTIVITIES_EXPORT_CONTACTS = "activities/exportcontacts"; /** * Endpoint for the bulk activities retrieve. */ public static final String ACTIVITIES = "activities"; public static final String LIBRARY_INFO = "library/info"; public static final String LIBRARY_FILES = "library/files"; public static final String LIBRARY_FOLDERS = "library/folders"; public static final String LIBRARY_FOLDER = LIBRARY_FOLDERS + "/%1$s"; public static final String LIBRARY_FOLDER_TRASH = LIBRARY_FOLDERS + "/trash/files"; public static final String LIBRARY_FILE = LIBRARY_FILES + "/%1$s"; public static final String LIBRARY_FILE_UPLOAD_STATUS = LIBRARY_FILES + "/uploadStatus/%1$s"; /** * Default constructor.<br/> * Made private to prevent instantiation.<br/> * This is unreachable from the outside, since current class is used only as a repository for constants. */ private Endpoints() { } } /** * OAuth2 Authorization related configuration options. <br/> * These are used for the authorize part of the authentication flow. * * @author ConstantContact */ public static final class Auth { /** * Authentication base URL. */ public static final String BASE_URL = "https://oauth2.constantcontact.com/oauth2/"; /** * Query code. <br/> * This should be used in server-type authentication handshake. */ public static final String RESPONSE_TYPE_CODE = "code"; /** * Query token. <br/> * This should be used in client-type authentication handshake.<br/> * This is what we use. */ public static final String RESPONSE_TYPE_TOKEN = "token"; /** * Query authorization code grant type. */ public static final String AUTHORIZATION_CODE_GRANT_TYPE = "authorization_code"; /** * The authorization endpoint. */ public static final String AUTHORIZATION_ENDPOINT = "oauth/siteowner/authorize"; /** * The token fetch endpoint. */ public static final String TOKEN_ENDPOINT = "oauth/token"; /** * Request host. */ public static final String HOST = "oauth2.constantcontact.com"; /** * Default constructor.<br/> * Made private to prevent instantiation.<br/> * This is unreachable from the outside, since current class is used only as a repository for constants. */ private Auth() { } } /** * Login related configuration options in Constant Contact.<br/> * These are used for the login part of the authentication flow. * * @author ConstantContact * */ public static final class Login { /** * The login base URL. */ public static final String BASE_URL = "https://login.constantcontact.com/login/"; /** * Login endpoint. */ public static final String LOGIN_ENDPOINT = "oauth/login"; /** * Request host. */ public static final String HOST = "login.constantcontact.com"; /** * Default constructor.<br/> * Made private to prevent instantiation.<br/> * This is unreachable from the outside, since current class is used only as a repository for constants. */ private Login() { } } /** * Errors to be returned for various exceptions in the Constant Contact flow. * * @author ConstantContact */ public static final class Errors { /** * Contact or id error. */ public static final String CONTACT_OR_ID = "Only an interger or Contact are allowed for this method."; /** * List or id error. */ public static final String LIST_OR_ID = "Only an integer or ContactList are allowed for this method."; /** * Id error. */ public static final String ID = "Only an mumeric String is allowed for this method."; /** * Status error. */ public static final String STATUS = "Status parameter must be one of the values: "; /** * EmailCampaignSchedule null error. */ public static final String EMAIL_CAMPAIGN_SCHEDULE_NULL = "EmailCampaignSchedule parameter must not be null."; /** * Contacts Request null error. */ public static final String BULK_CONTACTS_REQUEST_NULL = "ContactsRequest parameter must not be null."; /** * Contacts File Name null error. */ public static final String BULK_CONTACTS_FILE_NAME_NULL = "FileName parameter must not be null."; /** * Contacts File null error. */ public static final String BULK_CONTACTS_FILE_NULL = "File parameter must not be null."; /** * Contacts ListId null error. */ public static final String BULK_CONTACTS_LIST_NULL = "ListIds parameter must not be null."; /** * MyLibrary Folder null error; */ public static final String FOLDER_NULL = "Folder parameter must not be null"; /** * MyLibrary FolderId null error; */ public static final String FOLDER_ID_NULL = "FolderId parameter must not be null"; /** * Pagination null error */ public static final String PAGINATION_NULL = "Pagination parameter must not be null"; /** * Default constructor.<br/> * Made private to prevent instantiation.<br/> * This is unreachable from the outside, since current class is used only as a repository for constants. */ private Errors() { } } /** * HTTP Return Codes in Constant Contact flow. * * @author ConstantContact * */ public static final class HTTP_CODES { /** * Code for 201 Campaign Schedule was successfully created */ public static final int EMAIL_CAMPAIGN_SCHEDULE_CREATED = 201; /** * Default constructor.<br/> * Made private to prevent instantiation.<br/> * This is unreachable from the outside, since current class is used only as a repository for constants. */ private HTTP_CODES() { } } /** * Accept header value. */ public static final String HEADER_ACCEPT = "text/html, application/xhtml+xml, */*"; /** * ContentType header value. */ public static final String HEADER_CONTENT_TYPE = "application/x-www-form-urlencoded"; /** * UserAgent header value */ public static final String HEADER_USER_AGENT = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"; /** * UTF-8 */ public static final String UTF_8 = "UTF-8"; /** * Collumn names in Constant Contact Activities flow.<br/> * * These are used for {@link com.constantcontact.components.activities.contacts.request.ExportContactsRequest} and {@link com.constantcontact.components.activities.contacts.request.AddContactsRequest} requests in {@link com.constantcontact.services.activities.BulkActivitiesService}. * * @author ConstantContact */ public static final class COLUMN_NAMES { public static final String EMAIL = "EMAIL"; public static final String FIRST_NAME = "FIRST NAME"; public static final String MIDDLE_NAME = "MIDDLE NAME"; public static final String LAST_NAME = "LAST NAME"; public static final String JOB_TITLE = "JOB TITLE"; public static final String COMPANY_NAME = "COMPANY NAME"; public static final String WORK_PHONE = "WORK PHONE"; public static final String HOME_PHONE = "HOME PHONE"; public static final String ADDRESS1 = "ADDRESS LINE 1"; public static final String ADDRESS2 = "ADDRESS LINE 2"; public static final String ADDRESS3 = "ADDRESS LINE 3"; public static final String CITY = "CITY"; public static final String STATE = "STATE"; public static final String STATE_PROVINCE = "US STATE/CA PROVINCE"; public static final String COUNTRY = "COUNTRY"; public static final String POSTAL_CODE = "ZIP/POSTAL CODE"; public static final String SUB_POSTAL_CODE = "SUB ZIP/POSTAL CODE"; public static final String CUSTOM_FIELD_1 = "CUSTOM FIELD 1"; public static final String CUSTOM_FIELD_2 = "CUSTOM FIELD 2"; public static final String CUSTOM_FIELD_3 = "CUSTOM FIELD 3"; public static final String CUSTOM_FIELD_4 = "CUSTOM FIELD 4"; public static final String CUSTOM_FIELD_5 = "CUSTOM FIELD 5"; public static final String CUSTOM_FIELD_6 = "CUSTOM FIELD 6"; public static final String CUSTOM_FIELD_7 = "CUSTOM FIELD 7"; public static final String CUSTOM_FIELD_8 = "CUSTOM FIELD 8"; public static final String CUSTOM_FIELD_9 = "CUSTOM FIELD 9"; public static final String CUSTOM_FIELD_10 = "CUSTOM FIELD 10"; public static final String CUSTOM_FIELD_11 = "CUSTOM FIELD 11"; public static final String CUSTOM_FIELD_12 = "CUSTOM FIELD 12"; public static final String CUSTOM_FIELD_13 = "CUSTOM FIELD 13"; public static final String CUSTOM_FIELD_14 = "CUSTOM FIELD 14"; public static final String CUSTOM_FIELD_15 = "CUSTOM FIELD 15"; /** * Default constructor.<br/> * Made private to prevent instantiation.<br/> * This is unreachable from the outside, since current class is used only as a repository for constants. */ private COLUMN_NAMES() { } /** * Gets all defined collumn names. * * @return A List of String representing the list of all collumn names. */ public static final List<String> getAllCollums() { List<String> columnList = new ArrayList<String>(); columnList.add(EMAIL); columnList.add(FIRST_NAME); columnList.add(MIDDLE_NAME); columnList.add(LAST_NAME); columnList.add(JOB_TITLE); columnList.add(COMPANY_NAME); columnList.add(WORK_PHONE); columnList.add(HOME_PHONE); columnList.add(ADDRESS1); columnList.add(ADDRESS2); columnList.add(ADDRESS3); columnList.add(CITY); columnList.add(STATE); columnList.add(STATE_PROVINCE); columnList.add(COUNTRY); columnList.add(POSTAL_CODE); columnList.add(SUB_POSTAL_CODE); columnList.add(CUSTOM_FIELD_1); columnList.add(CUSTOM_FIELD_2); columnList.add(CUSTOM_FIELD_3); columnList.add(CUSTOM_FIELD_4); columnList.add(CUSTOM_FIELD_5); columnList.add(CUSTOM_FIELD_6); columnList.add(CUSTOM_FIELD_7); columnList.add(CUSTOM_FIELD_8); columnList.add(CUSTOM_FIELD_9); columnList.add(CUSTOM_FIELD_10); columnList.add(CUSTOM_FIELD_11); columnList.add(CUSTOM_FIELD_12); columnList.add(CUSTOM_FIELD_13); columnList.add(CUSTOM_FIELD_14); columnList.add(CUSTOM_FIELD_15); return columnList; } } /** * Default constructor.<br/> * Made private to prevent instantiation.<br/> * This is unreachable from the outside, since current class is used only as a repository for constants. */ private Config() { } }
package railo.runtime; import java.io.IOException; import java.io.OutputStream; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TimeZone; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyContent; import javax.servlet.jsp.tagext.BodyTag; import javax.servlet.jsp.tagext.Tag; import javax.servlet.jsp.tagext.TryCatchFinally; import org.apache.oro.text.regex.MalformedPatternException; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.PatternMatcherInput; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; import railo.commons.io.BodyContentStack; import railo.commons.io.IOUtil; import railo.commons.io.res.Resource; import railo.commons.io.res.util.ResourceUtil; import railo.commons.lang.SizeOf; import railo.commons.lang.StringUtil; import railo.commons.lang.SystemOut; import railo.commons.lang.mimetype.MimeType; import railo.commons.lang.types.RefBoolean; import railo.commons.lang.types.RefBooleanImpl; import railo.commons.lock.KeyLock; import railo.commons.lock.Lock; import railo.commons.net.HTTPUtil; import railo.intergral.fusiondebug.server.FDSignal; import railo.runtime.component.ComponentLoader; import railo.runtime.config.Config; import railo.runtime.config.ConfigImpl; import railo.runtime.config.ConfigWeb; import railo.runtime.config.ConfigWebImpl; import railo.runtime.config.Constants; import railo.runtime.db.DataSource; import railo.runtime.db.DataSourceManager; import railo.runtime.db.DatasourceConnection; import railo.runtime.db.DatasourceConnectionPool; import railo.runtime.db.DatasourceManagerImpl; import railo.runtime.debug.DebugCFMLWriter; import railo.runtime.debug.ActiveLock; import railo.runtime.debug.ActiveQuery; import railo.runtime.debug.DebugEntryTemplate; import railo.runtime.debug.Debugger; import railo.runtime.debug.DebuggerImpl; import railo.runtime.dump.DumpUtil; import railo.runtime.dump.DumpWriter; import railo.runtime.engine.ExecutionLog; import railo.runtime.engine.ThreadLocalPageContext; import railo.runtime.err.ErrorPage; import railo.runtime.err.ErrorPageImpl; import railo.runtime.err.ErrorPagePool; import railo.runtime.exp.Abort; import railo.runtime.exp.ApplicationException; import railo.runtime.exp.CasterException; import railo.runtime.exp.ExceptionHandler; import railo.runtime.exp.ExpressionException; import railo.runtime.exp.MissingIncludeException; import railo.runtime.exp.PageException; import railo.runtime.exp.PageExceptionBox; import railo.runtime.exp.PageServletException; import railo.runtime.functions.dynamicEvaluation.Serialize; import railo.runtime.interpreter.CFMLExpressionInterpreter; import railo.runtime.interpreter.VariableInterpreter; import railo.runtime.listener.AppListenerSupport; import railo.runtime.listener.ApplicationContext; import railo.runtime.listener.ApplicationContextPro; import railo.runtime.listener.ApplicationListener; import railo.runtime.listener.ClassicApplicationContext; import railo.runtime.listener.ModernAppListenerException; import railo.runtime.monitor.RequestMonitor; import railo.runtime.net.ftp.FTPPool; import railo.runtime.net.ftp.FTPPoolImpl; import railo.runtime.net.http.HTTPServletRequestWrap; import railo.runtime.net.http.ReqRspUtil; import railo.runtime.op.Caster; import railo.runtime.op.Decision; import railo.runtime.orm.ORMConfiguration; import railo.runtime.orm.ORMEngine; import railo.runtime.orm.ORMSession; import railo.runtime.query.QueryCache; import railo.runtime.rest.RestRequestListener; import railo.runtime.rest.RestUtil; import railo.runtime.security.Credential; import railo.runtime.security.CredentialImpl; import railo.runtime.tag.Login; import railo.runtime.tag.TagHandlerPool; import railo.runtime.type.Array; import railo.runtime.type.Collection; import railo.runtime.type.Collection.Key; import railo.runtime.type.Iterator; import railo.runtime.type.KeyImpl; import railo.runtime.type.Query; import railo.runtime.type.SVArray; import railo.runtime.type.Sizeable; import railo.runtime.type.Struct; import railo.runtime.type.StructImpl; import railo.runtime.type.UDF; import railo.runtime.type.it.ItAsEnum; import railo.runtime.type.ref.Reference; import railo.runtime.type.ref.VariableReference; import railo.runtime.type.scope.Application; import railo.runtime.type.scope.Argument; import railo.runtime.type.scope.ArgumentImpl; import railo.runtime.type.scope.CGI; import railo.runtime.type.scope.CGIImpl; import railo.runtime.type.scope.Client; import railo.runtime.type.scope.Cluster; import railo.runtime.type.scope.Cookie; import railo.runtime.type.scope.CookieImpl; import railo.runtime.type.scope.Form; import railo.runtime.type.scope.FormImpl; import railo.runtime.type.scope.Local; import railo.runtime.type.scope.LocalNotSupportedScope; import railo.runtime.type.scope.Request; import railo.runtime.type.scope.RequestImpl; import railo.runtime.type.scope.Scope; import railo.runtime.type.scope.ScopeContext; import railo.runtime.type.scope.ScopeFactory; import railo.runtime.type.scope.ScopeSupport; import railo.runtime.type.scope.Server; import railo.runtime.type.scope.Session; import railo.runtime.type.scope.Threads; import railo.runtime.type.scope.URL; import railo.runtime.type.scope.URLForm; import railo.runtime.type.scope.URLImpl; import railo.runtime.type.scope.Undefined; import railo.runtime.type.scope.UndefinedImpl; import railo.runtime.type.scope.UrlFormImpl; import railo.runtime.type.scope.Variables; import railo.runtime.type.scope.VariablesImpl; import railo.runtime.type.util.CollectionUtil; import railo.runtime.type.util.KeyConstants; import railo.runtime.util.VariableUtil; import railo.runtime.util.VariableUtilImpl; import railo.runtime.writer.CFMLWriter; import railo.runtime.writer.DevNullBodyContent; /** * page context for every page object. * the PageContext is a jsp page context expanded by CFML functionality. * for example you have the method getSession to get jsp combatible session object (HTTPSession) * and with sessionScope() you get CFML combatible session object (Struct,Scope). */ public final class PageContextImpl extends PageContext implements Sizeable { private static final RefBoolean DUMMY_BOOL = new RefBooleanImpl(false); private static int counter=0; /** * Field <code>pathList</code> */ private LinkedList<UDF> udfs=new LinkedList<UDF>(); private LinkedList<PageSource> pathList=new LinkedList<PageSource>(); private LinkedList<PageSource> includePathList=new LinkedList<PageSource>(); private Set<PageSource> includeOnce=new HashSet<PageSource>(); /** * Field <code>executionTime</code> */ protected int executionTime=0; private HTTPServletRequestWrap req; private HttpServletResponse rsp; private HttpServlet servlet; private JspWriter writer; private JspWriter forceWriter; private BodyContentStack bodyContentStack; private DevNullBodyContent devNull; private ConfigWebImpl config; //private DataSourceManager manager; //private CFMLCompilerImpl compiler; // Scopes private ScopeContext scopeContext; private Variables variablesRoot=new VariablesImpl();//ScopeSupport(false,"variables",Scope.SCOPE_VARIABLES); private Variables variables=variablesRoot;//new ScopeSupport("variables",Scope.SCOPE_VARIABLES); private Undefined undefined; private URLImpl _url=new URLImpl(); private FormImpl _form=new FormImpl(); private URLForm urlForm=new UrlFormImpl(_form,_url); private URL url; private Form form; private RequestImpl request=new RequestImpl(); private CGIImpl cgi=new CGIImpl(); private Argument argument=new ArgumentImpl(); private static LocalNotSupportedScope localUnsupportedScope=LocalNotSupportedScope.getInstance(); private Local local=localUnsupportedScope; private Session session; private Server server; private Cluster cluster; private CookieImpl cookie=new CookieImpl(); private Client client; private Application application; private DebuggerImpl debugger=new DebuggerImpl(); private long requestTimeout=-1; private short enablecfoutputonly=0; private int outputState; private String cfid; private String cftoken; private int id; private int requestId; private boolean psq; private Locale locale; private TimeZone timeZone; // Pools private ErrorPagePool errorPagePool=new ErrorPagePool(); private TagHandlerPool tagHandlerPool; private FTPPool ftpPool=new FTPPoolImpl(); private QueryCache queryCache; private Component activeComponent; private UDF activeUDF; //private ComponentScope componentScope=new ComponentScope(this); private Credential remoteUser; protected VariableUtilImpl variableUtil=new VariableUtilImpl(); private PageException exception; private PageSource base; ApplicationContext applicationContext; ApplicationContext defaultApplicationContext; private ScopeFactory scopeFactory=new ScopeFactory(); private Tag parentTag=null; private Tag currentTag=null; private Thread thread; private long startTime; private boolean isCFCRequest; private DatasourceManagerImpl manager; private Struct threads; private boolean hasFamily=false; //private CFMLFactoryImpl factory; private PageContextImpl parent; private Map<String,DatasourceConnection> conns=new HashMap<String,DatasourceConnection>(); private boolean fdEnabled; private ExecutionLog execLog; private boolean useSpecialMappings; private ORMSession ormSession; private boolean isChild; private boolean gatewayContext; private String serverPassword; private PageException pe; public long sizeOf() { return SizeOf.size(pathList)+ SizeOf.size(includePathList)+ SizeOf.size(executionTime)+ SizeOf.size(writer)+ SizeOf.size(forceWriter)+ SizeOf.size(bodyContentStack)+ SizeOf.size(variables)+ SizeOf.size(url)+ SizeOf.size(form)+ SizeOf.size(_url)+ SizeOf.size(_form)+ SizeOf.size(request)+ SizeOf.size(argument)+ SizeOf.size(local)+ SizeOf.size(cookie)+ SizeOf.size(debugger)+ SizeOf.size(requestTimeout)+ SizeOf.size(enablecfoutputonly)+ SizeOf.size(outputState)+ SizeOf.size(cfid)+ SizeOf.size(cftoken)+ SizeOf.size(id)+ SizeOf.size(psq)+ SizeOf.size(locale)+ SizeOf.size(errorPagePool)+ SizeOf.size(tagHandlerPool)+ SizeOf.size(ftpPool)+ SizeOf.size(activeComponent)+ SizeOf.size(activeUDF)+ SizeOf.size(remoteUser)+ SizeOf.size(exception)+ SizeOf.size(base)+ SizeOf.size(applicationContext)+ SizeOf.size(defaultApplicationContext)+ SizeOf.size(parentTag)+ SizeOf.size(currentTag)+ SizeOf.size(startTime)+ SizeOf.size(isCFCRequest)+ SizeOf.size(conns)+ SizeOf.size(serverPassword)+ SizeOf.size(ormSession); } /** * default Constructor * @param factoryImpl * @param scopeContext * @param config Configuration of the CFML Container * @param compiler CFML Compiler * @param queryCache Query Cache Object * @param id identity of the pageContext */ public PageContextImpl(ScopeContext scopeContext, ConfigWebImpl config, QueryCache queryCache,int id,HttpServlet servlet) { // must be first because is used after tagHandlerPool=config.getTagHandlerPool(); this.servlet=servlet; this.id=id; //this.factory=factory; bodyContentStack=new BodyContentStack(); devNull=bodyContentStack.getDevNullBodyContent(); this.config=config; manager=new DatasourceManagerImpl(config); this.scopeContext=scopeContext; undefined= new UndefinedImpl(this,config.getScopeCascadingType()); //this.compiler=compiler; //tagHandlerPool=config.getTagHandlerPool(); this.queryCache=queryCache; server=ScopeContext.getServerScope(this); defaultApplicationContext=new ClassicApplicationContext(config,"",true,null); } @Override public void initialize( Servlet servlet, ServletRequest req, ServletResponse rsp, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) throws IOException, IllegalStateException, IllegalArgumentException { initialize( (HttpServlet)servlet, (HttpServletRequest)req, (HttpServletResponse)rsp, errorPageURL, needsSession, bufferSize, autoFlush,false); } /** * initialize a existing page context * @param servlet * @param req * @param rsp * @param errorPageURL * @param needsSession * @param bufferSize * @param autoFlush */ public PageContextImpl initialize( HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush, boolean isChild) { requestId=counter++; rsp.setContentType("text/html; charset=UTF-8"); this.isChild=isChild; //rsp.setHeader("Connection", "close"); applicationContext=defaultApplicationContext; startTime=System.currentTimeMillis(); thread=Thread.currentThread(); isCFCRequest = StringUtil.endsWithIgnoreCase(req.getServletPath(),"."+config.getCFCExtension()); this.req=new HTTPServletRequestWrap(req); this.rsp=rsp; this.servlet=servlet; // Writers if(config.debugLogOutput()) { CFMLWriter w = config.getCFMLWriter(req,rsp); w.setAllowCompression(false); DebugCFMLWriter dcw = new DebugCFMLWriter(w); bodyContentStack.init(dcw); debugger.setOutputLog(dcw); } else { bodyContentStack.init(config.getCFMLWriter(req,rsp)); } writer=bodyContentStack.getWriter(); forceWriter=writer; // Scopes server=ScopeContext.getServerScope(this); if(hasFamily) { variablesRoot=new VariablesImpl(); variables=variablesRoot; request=new RequestImpl(); _url=new URLImpl(); _form=new FormImpl(); urlForm=new UrlFormImpl(_form,_url); undefined= new UndefinedImpl(this,config.getScopeCascadingType()); hasFamily=false; } else if(variables==null) { variablesRoot=new VariablesImpl(); variables=variablesRoot; } request.initialize(this); if(config.mergeFormAndURL()) { url=urlForm; form=urlForm; } else { url=_url; form=_form; } //url.initialize(this); //form.initialize(this); //undefined.initialize(this); psq=config.getPSQL(); fdEnabled=!config.allowRequestTimeout(); if(config.getExecutionLogEnabled()) this.execLog=config.getExecutionLogFactory().getInstance(this); if(config.debug()) debugger.init(config); return this; } @Override public void release() { if(config.getExecutionLogEnabled()){ execLog.release(); execLog=null; } if(config.debug()) { if(!gatewayContext)config.getDebuggerPool().store(this, debugger); debugger.reset(); } this.serverPassword=null; boolean isChild=parent!=null; parent=null; // Attention have to be before close if(client!=null){ client.touchAfterRequest(this); client=null; } if(session!=null){ session.touchAfterRequest(this); session=null; } // ORM if(ormSession!=null){ // flush orm session try { ORMEngine engine=ormSession.getEngine(); ORMConfiguration config=engine.getConfiguration(this); if(config==null || (config.flushAtRequestEnd() && config.autoManageSession())){ ormSession.flush(this); //ormSession.close(this); //print.err("2orm flush:"+Thread.currentThread().getId()); } ormSession.close(this); } catch (Throwable t) { //print.printST(t); } // release connection DatasourceConnectionPool pool = this.config.getDatasourceConnectionPool(); DatasourceConnection dc=ormSession.getDatasourceConnection(); if(dc!=null)pool.releaseDatasourceConnection(dc); ormSession=null; } close(); thread=null; base=null; //RequestImpl r = request; // Scopes if(hasFamily) { if(!isChild){ req.disconnect(); } request=null; _url=null; _form=null; urlForm=null; undefined=null; variables=null; variablesRoot=null; if(threads!=null && threads.size()>0) threads.clear(); } else { if(variables.isBind()) { variables=null; variablesRoot=null; } else { variables=variablesRoot; variables.release(this); } undefined.release(this); urlForm.release(this); request.release(); } cgi.release(); argument.release(this); local=localUnsupportedScope; cookie.release(); //if(cluster!=null)cluster.release(); //client=null; //session=null; application=null;// not needed at the moment -> application.releaseAfterRequest(); applicationContext=null; // Properties requestTimeout=-1; outputState=0; cfid=null; cftoken=null; locale=null; timeZone=null; url=null; form=null; // Pools errorPagePool.clear(); // transaction connection if(!conns.isEmpty()){ java.util.Iterator<Entry<String, DatasourceConnection>> it = conns.entrySet().iterator(); DatasourceConnectionPool pool = config.getDatasourceConnectionPool(); while(it.hasNext()) { pool.releaseDatasourceConnection((it.next().getValue())); } conns.clear(); } pathList.clear(); includePathList.clear(); executionTime=0; bodyContentStack.release(); //activeComponent=null; remoteUser=null; exception=null; ftpPool.clear(); parentTag=null; currentTag=null; // Req/Rsp //if(req!=null) req.clear(); req=null; rsp=null; servlet=null; // Writer writer=null; forceWriter=null; if(pagesUsed.size()>0)pagesUsed.clear(); activeComponent=null; activeUDF=null; gatewayContext=false; manager.release(); includeOnce.clear(); pe=null; } @Override public void write(String str) throws IOException { writer.write(str); } @Override public void forceWrite(String str) throws IOException { forceWriter.write(str); } @Override public void writePSQ(Object o) throws IOException, PageException { if(o instanceof Date || Decision.isDate(o, false)) { writer.write(Caster.toString(o)); } else { writer.write(psq?Caster.toString(o):StringUtil.replace(Caster.toString(o),"'","''",false)); } } @Override public void flush() { try { getOut().flush(); } catch (IOException e) {} } @Override public void close() { IOUtil.closeEL(getOut()); } public PageSource getRelativePageSource(String realPath) { SystemOut.print(config.getOutWriter(),"method getRelativePageSource is deprecated"); if(StringUtil.startsWith(realPath,'/')) return PageSourceImpl.best(getPageSources(realPath)); if(pathList.size()==0) return null; return pathList.getLast().getRealPage(realPath); } public PageSource getRelativePageSourceExisting(String realPath) { if(StringUtil.startsWith(realPath,'/')) return getPageSourceExisting(realPath); if(pathList.size()==0) return null; PageSource ps = pathList.getLast().getRealPage(realPath); if(PageSourceImpl.pageExist(ps)) return ps; return null; } public PageSource[] getRelativePageSources(String realPath) { if(StringUtil.startsWith(realPath,'/')) return getPageSources(realPath); if(pathList.size()==0) return null; return new PageSource[]{ pathList.getLast().getRealPage(realPath)}; } public PageSource getPageSource(String realPath) { SystemOut.print(config.getOutWriter(),"method getPageSource is deprecated"); return PageSourceImpl.best(config.getPageSources(this,applicationContext.getMappings(),realPath,false,useSpecialMappings,true)); } public PageSource[] getPageSources(String realPath) { return config.getPageSources(this,applicationContext.getMappings(),realPath,false,useSpecialMappings,true); } public PageSource getPageSourceExisting(String realPath) { return config.getPageSourceExisting(this,applicationContext.getMappings(),realPath,false,useSpecialMappings,true,false); } public boolean useSpecialMappings(boolean useTagMappings) { boolean b=this.useSpecialMappings; this.useSpecialMappings=useTagMappings; return b; } public boolean useSpecialMappings() { return useSpecialMappings; } public Resource getPhysical(String realPath, boolean alsoDefaultMapping){ return config.getPhysical(applicationContext.getMappings(),realPath, alsoDefaultMapping); } public PageSource toPageSource(Resource res, PageSource defaultValue){ return config.toPageSource(applicationContext.getMappings(),res, defaultValue); } @Override public void doInclude(String realPath) throws PageException { doInclude(getRelativePageSources(realPath),false); } @Override public void doInclude(String realPath, boolean runOnce) throws PageException { doInclude(getRelativePageSources(realPath),runOnce); } @Override public void doInclude(PageSource source) throws PageException { doInclude(new PageSource[]{source},false); } @Override public void doInclude(PageSource[] sources, boolean runOnce) throws PageException { // debug if(!gatewayContext && config.debug()) { int currTime=executionTime; long exeTime=0; long time=System.nanoTime(); Page currentPage = PageSourceImpl.loadPage(this, sources); if(runOnce && includeOnce.contains(currentPage.getPageSource())) return; DebugEntryTemplate debugEntry=debugger.getEntry(this,currentPage.getPageSource()); try { addPageSource(currentPage.getPageSource(),true); debugEntry.updateFileLoadTime((int)(System.nanoTime()-time)); exeTime=System.nanoTime(); currentPage.call(this); } catch(Throwable t){ PageException pe = Caster.toPageException(t); if(Abort.isAbort(pe)) { if(Abort.isAbort(pe,Abort.SCOPE_REQUEST))throw pe; } else { if(fdEnabled){ FDSignal.signal(pe, false); } pe.addContext(currentPage.getPageSource(),-187,-187, null);// TODO was soll das 187 throw pe; } } finally { includeOnce.add(currentPage.getPageSource()); int diff= ((int)(System.nanoTime()-exeTime)-(executionTime-currTime)); executionTime+=(int)(System.nanoTime()-time); debugEntry.updateExeTime(diff); removeLastPageSource(true); } } // no debug else { Page currentPage = PageSourceImpl.loadPage(this, sources); if(runOnce && includeOnce.contains(currentPage.getPageSource())) return; try { addPageSource(currentPage.getPageSource(),true); currentPage.call(this); } catch(Throwable t){ PageException pe = Caster.toPageException(t); if(Abort.isAbort(pe)) { if(Abort.isAbort(pe,Abort.SCOPE_REQUEST))throw pe; } else { pe.addContext(currentPage.getPageSource(),-187,-187, null); throw pe; } } finally { includeOnce.add(currentPage.getPageSource()); removeLastPageSource(true); } } } @Override public Array getTemplatePath() throws PageException { int len=includePathList.size(); SVArray sva = new SVArray(); PageSource ps; for(int i=0;i<len;i++) { ps=includePathList.get(i); if(i==0) { if(!ps.equals(getBasePageSource())) sva.append(ResourceUtil.getResource(this,getBasePageSource()).getAbsolutePath()); } sva.append(ResourceUtil.getResource(this, ps).getAbsolutePath()); } //sva.setPosition(sva.size()); return sva; } public List<PageSource> getPageSourceList() { return (List<PageSource>) pathList.clone(); } protected PageSource getPageSource(int index) { return includePathList.get(index-1); } public synchronized void copyStateTo(PageContextImpl other) { // private Debugger debugger=new DebuggerImpl(); other.requestTimeout=requestTimeout; other.locale=locale; other.timeZone=timeZone; other.fdEnabled=fdEnabled; other.useSpecialMappings=useSpecialMappings; other.serverPassword=serverPassword; hasFamily=true; other.hasFamily=true; other.parent=this; other.applicationContext=applicationContext; other.thread=Thread.currentThread(); other.startTime=System.currentTimeMillis(); other.isCFCRequest = isCFCRequest; // path other.base=base; java.util.Iterator<PageSource> it = includePathList.iterator(); while(it.hasNext()) { other.includePathList.add(it.next()); } it = pathList.iterator(); while(it.hasNext()) { other.pathList.add(it.next()); } // scopes //other.req.setAttributes(request); /*HttpServletRequest org = other.req.getOriginalRequest(); if(org instanceof HttpServletRequestDummy) { ((HttpServletRequestDummy)org).setAttributes(request); }*/ other.req=req; other.request=request; other.form=form; other.url=url; other.urlForm=urlForm; other._url=_url; other._form=_form; other.variables=variables; other.undefined=new UndefinedImpl(other,(short)other.undefined.getType()); // writers other.bodyContentStack.init(config.getCFMLWriter(other.req,other.rsp)); //other.bodyContentStack.init(other.req,other.rsp,other.config.isSuppressWhitespace(),other.config.closeConnection(), other.config.isShowVersion(),config.contentLength(),config.allowCompression()); other.writer=other.bodyContentStack.getWriter(); other.forceWriter=other.writer; other.psq=psq; other.gatewayContext=gatewayContext; // thread if(threads!=null){ synchronized (threads) { java.util.Iterator<Entry<Key, Object>> it2 = threads.entryIterator(); Entry<Key, Object> entry; while(it2.hasNext()) { entry = it2.next(); other.setThreadScope(entry.getKey(), (Threads)entry.getValue()); } } } } /*public static void setState(PageContextImpl other,ApplicationContext applicationContext, boolean isCFCRequest) { other.hasFamily=true; other.applicationContext=applicationContext; other.thread=Thread.currentThread(); other.startTime=System.currentTimeMillis(); other.isCFCRequest = isCFCRequest; // path other.base=base; java.util.Iterator it = includePathList.iterator(); while(it.hasNext()) { other.includePathList.add(it.next()); } // scopes other.request=request; other.form=form; other.url=url; other.urlForm=urlForm; other._url=_url; other._form=_form; other.variables=variables; other.undefined=new UndefinedImpl(other,(short)other.undefined.getType()); // writers other.bodyContentStack.init(other.rsp,other.config.isSuppressWhitespace(),other.config.closeConnection(),other.config.isShowVersion()); other.writer=other.bodyContentStack.getWriter(); other.forceWriter=other.writer; other.psq=psq; }*/ public int getCurrentLevel() { return includePathList.size()+1; } /** * @return the current template SourceFile */ public PageSource getCurrentPageSource() { return pathList.getLast(); } /** * @return the current template SourceFile */ public PageSource getCurrentTemplatePageSource() { return includePathList.getLast(); } /** * @return base template file */ public PageSource getBasePageSource() { return base; } @Override public Resource getRootTemplateDirectory() { return config.getResource(servlet.getServletContext().getRealPath("/")); //new File(servlet.getServletContext().getRealPath("/")); } @Override public Scope scope(int type) throws PageException { switch(type) { case Scope.SCOPE_UNDEFINED: return undefinedScope(); case Scope.SCOPE_URL: return urlScope(); case Scope.SCOPE_FORM: return formScope(); case Scope.SCOPE_VARIABLES: return variablesScope(); case Scope.SCOPE_REQUEST: return requestScope(); case Scope.SCOPE_CGI: return cgiScope(); case Scope.SCOPE_APPLICATION: return applicationScope(); case Scope.SCOPE_ARGUMENTS: return argumentsScope(); case Scope.SCOPE_SESSION: return sessionScope(); case Scope.SCOPE_SERVER: return serverScope(); case Scope.SCOPE_COOKIE: return cookieScope(); case Scope.SCOPE_CLIENT: return clientScope(); case Scope.SCOPE_LOCAL: case ScopeSupport.SCOPE_VAR: return localScope(); case Scope.SCOPE_CLUSTER:return clusterScope(); } return variables; } public Scope scope(String strScope,Scope defaultValue) throws PageException { if(strScope==null)return defaultValue; strScope=strScope.toLowerCase().trim(); if("variables".equals(strScope)) return variablesScope(); if("url".equals(strScope)) return urlScope(); if("form".equals(strScope)) return formScope(); if("request".equals(strScope)) return requestScope(); if("cgi".equals(strScope)) return cgiScope(); if("application".equals(strScope)) return applicationScope(); if("arguments".equals(strScope)) return argumentsScope(); if("session".equals(strScope)) return sessionScope(); if("server".equals(strScope)) return serverScope(); if("cookie".equals(strScope)) return cookieScope(); if("client".equals(strScope)) return clientScope(); if("local".equals(strScope)) return localScope(); if("cluster".equals(strScope)) return clusterScope(); return defaultValue; } @Override public Undefined undefinedScope() { if(!undefined.isInitalized()) undefined.initialize(this); return undefined; } /** * @return undefined scope, undefined scope is a placeholder for the scopecascading */ public Undefined us() { if(!undefined.isInitalized()) undefined.initialize(this); return undefined; } @Override public Variables variablesScope() { return variables; } @Override public URL urlScope() { if(!url.isInitalized())url.initialize(this); return url; } @Override public Form formScope() { if(!form.isInitalized())form.initialize(this); return form; } @Override public URLForm urlFormScope() { if(!urlForm.isInitalized())urlForm.initialize(this); return urlForm; } @Override public Request requestScope() { return request; } @Override public CGI cgiScope() { if(!cgi.isInitalized())cgi.initialize(this); return cgi; } @Override public Application applicationScope() throws PageException { if(application==null) { if(!applicationContext.hasName()) throw new ExpressionException("there is no application context defined for this application","you can define a application context with the tag "+railo.runtime.config.Constants.CFAPP_NAME+"/"+railo.runtime.config.Constants.APP_CFC); application=scopeContext.getApplicationScope(this,DUMMY_BOOL); } return application; } @Override public Argument argumentsScope() { return argument; } @Override public Argument argumentsScope(boolean bind) { //Argument a=argumentsScope(); if(bind)argument.setBind(true); return argument; } @Override public Local localScope() { //if(local==localUnsupportedScope) // throw new PageRuntimeException(new ExpressionException("Unsupported Context for Local Scope")); return local; } @Override public Local localScope(boolean bind) { if(bind)local.setBind(true); //if(local==localUnsupportedScope) // throw new PageRuntimeException(new ExpressionException("Unsupported Context for Local Scope")); return local; } public Object localGet() throws PageException { return localGet(false); } public Object localGet(boolean bind) throws PageException { // inside a local supported block if(undefined.getCheckArguments()){ return localScope(bind); } return undefinedScope().get(KeyConstants._local); } public Object localTouch() throws PageException { return localTouch(false); } public Object localTouch(boolean bind) throws PageException { // inside a local supported block if(undefined.getCheckArguments()){ return localScope(bind); } return touch(undefinedScope(), KeyConstants._local); //return undefinedScope().get(LOCAL); } /** * @param local sets the current local scope * @param argument sets the current argument scope */ public void setFunctionScopes(Local local,Argument argument) { this.argument=argument; this.local=local; undefined.setFunctionScopes(local,argument); } @Override public Session sessionScope() throws PageException { return sessionScope(true); } public Session sessionScope(boolean checkExpires) throws PageException { if(session==null) { checkSessionContext(); session=scopeContext.getSessionScope(this,DUMMY_BOOL); } return session; } public void invalidateUserScopes(boolean migrateSessionData,boolean migrateClientData) throws PageException { scopeContext.invalidateUserScope(this, migrateSessionData, migrateClientData); } private void checkSessionContext() throws ExpressionException { if(!applicationContext.hasName()) throw new ExpressionException("there is no session context defined for this application","you can define a session context with the tag "+Constants.CFAPP_NAME+"/"+Constants.APP_CFC); if(!applicationContext.isSetSessionManagement()) throw new ExpressionException("session scope is not enabled","you can enable session scope with tag "+Constants.CFAPP_NAME+"/"+Constants.APP_CFC); } @Override public Server serverScope() { //if(!server.isInitalized()) server.initialize(this); return server; } @Override public Cluster clusterScope() throws PageException { return clusterScope(true); } public Cluster clusterScope(boolean create) throws PageException { if(cluster==null && create) { cluster=ScopeContext.getClusterScope(config,create); //cluster.initialize(this); } //else if(!cluster.isInitalized()) cluster.initialize(this); return cluster; } @Override public Cookie cookieScope() { if(!cookie.isInitalized()) cookie.initialize(this); return cookie; } @Override public Client clientScope() throws PageException { if(client==null) { if(!applicationContext.hasName()) throw new ExpressionException("there is no client context defined for this application", "you can define a client context with the tag "+Constants.CFAPP_NAME+"/"+Constants.APP_CFC); if(!applicationContext.isSetClientManagement()) throw new ExpressionException("client scope is not enabled", "you can enable client scope with tag "+Constants.CFAPP_NAME+"/"+Constants.APP_CFC); client= scopeContext.getClientScope(this); } return client; } public Client clientScopeEL() { if(client==null) { if(applicationContext==null || !applicationContext.hasName()) return null; if(!applicationContext.isSetClientManagement()) return null; client= scopeContext.getClientScopeEL(this); } return client; } @Override public Object set(Object coll, String key, Object value) throws PageException { return variableUtil.set(this,coll,key,value); } public Object set(Object coll, Collection.Key key, Object value) throws PageException { return variableUtil.set(this,coll,key,value); } @Override public Object touch(Object coll, String key) throws PageException { Object o=getCollection(coll,key,null); if(o!=null) return o; return set(coll,key,new StructImpl()); } @Override public Object touch(Object coll, Collection.Key key) throws PageException { Object o=getCollection(coll,key,null); if(o!=null) return o; return set(coll,key,new StructImpl()); } /*private Object _touch(Scope scope, String key) throws PageException { Object o=scope.get(key,null); if(o!=null) return o; return scope.set(key, new StructImpl()); }*/ @Override public Object getCollection(Object coll, String key) throws PageException { return variableUtil.getCollection(this,coll,key); } @Override public Object getCollection(Object coll, Collection.Key key) throws PageException { return variableUtil.getCollection(this,coll,key); } @Override public Object getCollection(Object coll, String key, Object defaultValue) { return variableUtil.getCollection(this,coll,key,defaultValue); } @Override public Object getCollection(Object coll, Collection.Key key, Object defaultValue) { return variableUtil.getCollection(this,coll,key,defaultValue); } @Override public Object get(Object coll, String key) throws PageException { return variableUtil.get(this,coll,key); } @Override public Object get(Object coll, Collection.Key key) throws PageException { return variableUtil.get(this,coll,key); } @Override public Reference getReference(Object coll, String key) throws PageException { return new VariableReference(coll,key); } public Reference getReference(Object coll, Collection.Key key) throws PageException { return new VariableReference(coll,key); } @Override public Object get(Object coll, String key, Object defaultValue) { return variableUtil.get(this,coll,key, defaultValue); } @Override public Object get(Object coll, Collection.Key key, Object defaultValue) { return variableUtil.get(this,coll,key, defaultValue); } @Override public Object setVariable(String var, Object value) throws PageException { //return new CFMLExprInterpreter().interpretReference(this,new ParserString(var)).set(value); return VariableInterpreter.setVariable(this,var,value); } @Override public Object getVariable(String var) throws PageException { return VariableInterpreter.getVariable(this,var); } public void param(String type, String name, Object defaultValue,String regex) throws PageException { param(type, name, defaultValue,Double.NaN,Double.NaN,regex,-1); } public void param(String type, String name, Object defaultValue,double min, double max) throws PageException { param(type, name, defaultValue,min,max,null,-1); } public void param(String type, String name, Object defaultValue,int maxLength) throws PageException { param(type, name, defaultValue,Double.NaN,Double.NaN,null,maxLength); } public void param(String type, String name, Object defaultValue) throws PageException { param(type, name, defaultValue,Double.NaN,Double.NaN,null,-1); } private void param(String type, String name, Object defaultValue, double min,double max, String strPattern, int maxLength) throws PageException { // check attributes type if(type==null)type="any"; else type=type.trim().toLowerCase(); // check attributes name if(StringUtil.isEmpty(name)) throw new ExpressionException("The attribute name is required"); Object value=null; boolean isNew=false; // get value value=VariableInterpreter.getVariableEL(this,name,null);// NULL Support if(value==null) { if(defaultValue==null) throw new ExpressionException("The required parameter ["+name+"] was not provided."); value=defaultValue; isNew=true; } // cast and set value if(!"any".equals(type)) { // range if("range".equals(type)) { double number = Caster.toDoubleValue(value); if(!Decision.isValid(min)) throw new ExpressionException("Missing attribute [min]"); if(!Decision.isValid(max)) throw new ExpressionException("Missing attribute [max]"); if(number<min || number>max) throw new ExpressionException("The number ["+Caster.toString(number)+"] is out of range [min:"+Caster.toString(min)+";max:"+Caster.toString(max)+"]"); setVariable(name,Caster.toDouble(number)); } // regex else if("regex".equals(type) || "regular_expression".equals(type)) { String str=Caster.toString(value); if(strPattern==null) throw new ExpressionException("Missing attribute [pattern]"); try { Pattern pattern = new Perl5Compiler().compile(strPattern, Perl5Compiler.DEFAULT_MASK); PatternMatcherInput input = new PatternMatcherInput(str); if( !new Perl5Matcher().matches(input, pattern)) throw new ExpressionException("The value ["+str+"] doesn't match the provided pattern ["+strPattern+"]"); } catch (MalformedPatternException e) { throw new ExpressionException("The provided pattern ["+strPattern+"] is invalid",e.getMessage()); } setVariable(name,str); } else { if(!Decision.isCastableTo(type,value,true,true,maxLength)) { if(maxLength>-1 && ("email".equalsIgnoreCase(type) || "url".equalsIgnoreCase(type) || "string".equalsIgnoreCase(type))) { StringBuilder msg=new StringBuilder(CasterException.createMessage(value, type)); msg.append(" with a maximal length of "+maxLength+" characters"); throw new CasterException(msg.toString()); } throw new CasterException(value,type); } setVariable(name,value); //REALCAST setVariable(name,Caster.castTo(this,type,value,true)); } } else if(isNew) setVariable(name,value); } @Override public Object removeVariable(String var) throws PageException { return VariableInterpreter.removeVariable(this,var); } /** * * a variable reference, references to variable, to modifed it, with global effect. * @param var variable name to get * @return return a variable reference by string syntax ("scopename.key.key" -> "url.name") * @throws PageException */ public VariableReference getVariableReference(String var) throws PageException { return VariableInterpreter.getVariableReference(this,var); } @Override public Object getFunction(Object coll, String key, Object[] args) throws PageException { return variableUtil.callFunctionWithoutNamedValues(this,coll,key,args); } @Override public Object getFunction(Object coll, Key key, Object[] args) throws PageException { return variableUtil.callFunctionWithoutNamedValues(this,coll,key,args); } @Override public Object getFunctionWithNamedValues(Object coll, String key, Object[] args) throws PageException { return variableUtil.callFunctionWithNamedValues(this,coll,key,args); } @Override public Object getFunctionWithNamedValues(Object coll, Key key, Object[] args) throws PageException { return variableUtil.callFunctionWithNamedValues(this,coll,key,args); } @Override public ConfigWeb getConfig() { return config; } @Override public Iterator getIterator(String key) throws PageException { Object o=VariableInterpreter.getVariable(this,key); if(o instanceof Iterator) return (Iterator) o; throw new ExpressionException("["+key+"] is not a iterator object"); } @Override public Query getQuery(String key) throws PageException { Object value=VariableInterpreter.getVariable(this,key); if(Decision.isQuery(value)) return Caster.toQuery(value); throw new CasterException(value,Query.class);///("["+key+"] is not a query object, object is from type "); } @Override public Query getQuery(Object value) throws PageException { if(Decision.isQuery(value)) return Caster.toQuery(value); value=VariableInterpreter.getVariable(this,Caster.toString(value)); if(Decision.isQuery(value)) return Caster.toQuery(value); throw new CasterException(value,Query.class); } @Override public void setAttribute(String name, Object value) { try { if(value==null)removeVariable(name); else setVariable(name,value); } catch (PageException e) {} } @Override public void setAttribute(String name, Object value, int scope) { switch(scope){ case javax.servlet.jsp.PageContext.APPLICATION_SCOPE: if(value==null) getServletContext().removeAttribute(name); else getServletContext().setAttribute(name, value); break; case javax.servlet.jsp.PageContext.PAGE_SCOPE: setAttribute(name, value); break; case javax.servlet.jsp.PageContext.REQUEST_SCOPE: if(value==null) req.removeAttribute(name); else setAttribute(name, value); break; case javax.servlet.jsp.PageContext.SESSION_SCOPE: HttpSession s = req.getSession(true); if(value==null)s.removeAttribute(name); else s.setAttribute(name, value); break; } } @Override public Object getAttribute(String name) { try { return getVariable(name); } catch (PageException e) { return null; } } @Override public Object getAttribute(String name, int scope) { switch(scope){ case javax.servlet.jsp.PageContext.APPLICATION_SCOPE: return getServletContext().getAttribute(name); case javax.servlet.jsp.PageContext.PAGE_SCOPE: return getAttribute(name); case javax.servlet.jsp.PageContext.REQUEST_SCOPE: return req.getAttribute(name); case javax.servlet.jsp.PageContext.SESSION_SCOPE: HttpSession s = req.getSession(); if(s!=null)return s.getAttribute(name); break; } return null; } @Override public Object findAttribute(String name) { // page Object value=getAttribute(name); if(value!=null) return value; // request value=req.getAttribute(name); if(value!=null) return value; // session HttpSession s = req.getSession(); value=s!=null?s.getAttribute(name):null; if(value!=null) return value; // application value=getServletContext().getAttribute(name); if(value!=null) return value; return null; } @Override public void removeAttribute(String name) { setAttribute(name, null); } @Override public void removeAttribute(String name, int scope) { setAttribute(name, null,scope); } @Override public int getAttributesScope(String name) { // page if(getAttribute(name)!=null) return PageContext.PAGE_SCOPE; // request if(req.getAttribute(name) != null) return PageContext.REQUEST_SCOPE; // session HttpSession s = req.getSession(); if(s!=null && s.getAttribute(name) != null) return PageContext.SESSION_SCOPE; // application if(getServletContext().getAttribute(name)!=null) return PageContext.APPLICATION_SCOPE; return 0; } @Override public Enumeration getAttributeNamesInScope(int scope) { switch(scope){ case javax.servlet.jsp.PageContext.APPLICATION_SCOPE: return getServletContext().getAttributeNames(); case javax.servlet.jsp.PageContext.PAGE_SCOPE: return ItAsEnum.toStringEnumeration(variablesScope().keyIterator()); case javax.servlet.jsp.PageContext.REQUEST_SCOPE: return req.getAttributeNames(); case javax.servlet.jsp.PageContext.SESSION_SCOPE: return req.getSession(true).getAttributeNames(); } return null; } @Override public JspWriter getOut() { return forceWriter; } @Override public HttpSession getSession() { return getHttpServletRequest().getSession(); } @Override public Object getPage() { return variablesScope(); } @Override public ServletRequest getRequest() { return getHttpServletRequest(); } @Override public HttpServletRequest getHttpServletRequest() { return req; } @Override public ServletResponse getResponse() { return rsp; } @Override public HttpServletResponse getHttpServletResponse() { return rsp; } public OutputStream getResponseStream() throws IOException { return getRootOut().getResponseStream(); } @Override public Exception getException() { // TODO impl return exception; } @Override public ServletConfig getServletConfig() { return config; } @Override public ServletContext getServletContext() { return servlet.getServletContext(); } /*public static void main(String[] args) { repl(" susi #error.susi# sorglos","susi", "Susanne"); repl(" susi #error.Susi# sorglos","susi", "Susanne"); }*/ private static String repl(String haystack, String needle, String replacement) { //print.o(haystack); //print.o(needle); StringBuilder regex=new StringBuilder("#[\\s]*error[\\s]*\\.[\\s]*"); char[] carr = needle.toCharArray(); for(int i=0;i<carr.length;i++){ regex.append("["); regex.append(Character.toLowerCase(carr[i])); regex.append(Character.toUpperCase(carr[i])); regex.append("]"); } regex.append("[\\s]* //print.o(regex); haystack=haystack.replaceAll(regex.toString(), replacement); //print.o(haystack); return haystack; } @Override public void handlePageException(PageException pe) { if(!Abort.isSilentAbort(pe)) { String charEnc = rsp.getCharacterEncoding(); if(StringUtil.isEmpty(charEnc,true)) { rsp.setContentType("text/html"); } else { rsp.setContentType("text/html; charset=" + charEnc); } int statusCode=getStatusCode(pe); if(getConfig().getErrorStatusCode())rsp.setStatus(statusCode); ErrorPage ep=errorPagePool.getErrorPage(pe,ErrorPageImpl.TYPE_EXCEPTION); ExceptionHandler.printStackTrace(this,pe); ExceptionHandler.log(getConfig(),pe); // error page exception if(ep!=null) { try { Struct sct=pe.getErrorBlock(this,ep); variablesScope().setEL(KeyConstants._error,sct); variablesScope().setEL(KeyConstants._cferror,sct); doInclude(ep.getTemplate()); return; } catch (Throwable t) { if(Abort.isSilentAbort(t)) return; pe=Caster.toPageException(t); } } // error page request ep=errorPagePool.getErrorPage(pe,ErrorPageImpl.TYPE_REQUEST); if(ep!=null) { PageSource ps = ep.getTemplate(); if(ps.physcalExists()){ Resource res = ps.getResource(); try { String content = IOUtil.toString(res, getConfig().getTemplateCharset()); Struct sct=pe.getErrorBlock(this,ep); java.util.Iterator<Entry<Key, Object>> it = sct.entryIterator(); Entry<Key, Object> e; String v; while(it.hasNext()){ e = it.next(); v=Caster.toString(e.getValue(),null); if(v!=null)content=repl(content, e.getKey().getString(), v); } write(content); return; } catch (Throwable t) { pe=Caster.toPageException(t); } } else pe=new ApplicationException("The error page template for type request only works if the actual source file also exists . If the exception file is in an Railo archive (.rc/.rcs), you need to use type exception instead."); } try { if(statusCode!=404) forceWrite("<!-- Railo ["+Info.getVersionAsString()+"] Error -->"); String template=getConfig().getErrorTemplate(statusCode); if(!StringUtil.isEmpty(template)) { try { Struct catchBlock=pe.getCatchBlock(getConfig()); variablesScope().setEL(KeyConstants._cfcatch,catchBlock); variablesScope().setEL(KeyConstants._catch,catchBlock); doInclude(template); return; } catch (PageException e) { pe=e; } } if(!Abort.isSilentAbort(pe))forceWrite(getConfig().getDefaultDumpWriter(DumpWriter.DEFAULT_RICH).toString(this,pe.toDumpData(this, 9999,DumpUtil.toDumpProperties()),true)); } catch (Exception e) { } } } private int getStatusCode(PageException pe) { int statusCode=500; int maxDeepFor404=0; if(pe instanceof ModernAppListenerException){ pe=((ModernAppListenerException)pe).getPageException(); maxDeepFor404=1; } else if(pe instanceof PageExceptionBox) pe=((PageExceptionBox)pe).getPageException(); if(pe instanceof MissingIncludeException) { MissingIncludeException mie=(MissingIncludeException) pe; if(mie.getPageDeep()<=maxDeepFor404) statusCode=404; } // TODO Auto-generated method stub return statusCode; } @Override public void handlePageException(Exception e) { handlePageException(Caster.toPageException(e)); } @Override public void handlePageException(Throwable t) { handlePageException(Caster.toPageException(t)); } @Override public void setHeader(String name, String value) { rsp.setHeader(name,value); } @Override public BodyContent pushBody() { forceWriter=bodyContentStack.push(); if(enablecfoutputonly>0 && outputState==0) { writer=devNull; } else writer=forceWriter; return (BodyContent)forceWriter; } @Override public JspWriter popBody() { forceWriter=bodyContentStack.pop(); if(enablecfoutputonly>0 && outputState==0) { writer=devNull; } else writer=forceWriter; return forceWriter; } @Override public void outputStart() { outputState++; if(enablecfoutputonly>0 && outputState==1)writer=forceWriter; //if(enablecfoutputonly && outputState>0) unsetDevNull(); } @Override public void outputEnd() { outputState if(enablecfoutputonly>0 && outputState==0)writer=devNull; } @Override public void setCFOutputOnly(boolean boolEnablecfoutputonly) { if(boolEnablecfoutputonly)this.enablecfoutputonly++; else if(this.enablecfoutputonly>0)this.enablecfoutputonly setCFOutputOnly(enablecfoutputonly); //if(!boolEnablecfoutputonly)setCFOutputOnly(enablecfoutputonly=0); } @Override public void setCFOutputOnly(short enablecfoutputonly) { this.enablecfoutputonly=enablecfoutputonly; if(enablecfoutputonly>0) { if(outputState==0) writer=devNull; } else { writer=forceWriter; } } @Override public boolean setSilent() { boolean before=bodyContentStack.getDevNull(); bodyContentStack.setDevNull(true); forceWriter = bodyContentStack.getWriter(); writer=forceWriter; return before; } @Override public boolean unsetSilent() { boolean before=bodyContentStack.getDevNull(); bodyContentStack.setDevNull(false); forceWriter = bodyContentStack.getWriter(); if(enablecfoutputonly>0 && outputState==0) { writer=devNull; } else writer=forceWriter; return before; } @Override public Debugger getDebugger() { return debugger; } @Override public void executeRest(String realPath, boolean throwExcpetion) throws PageException { ApplicationListener listener=config.getApplicationListener(); try{ String pathInfo = req.getPathInfo(); // charset try{ String charset=HTTPUtil.splitMimeTypeAndCharset(req.getContentType())[1]; if(StringUtil.isEmpty(charset))charset=ThreadLocalPageContext.getConfig().getWebCharset(); java.net.URL reqURL = new java.net.URL(req.getRequestURL().toString()); String path=ReqRspUtil.decode(reqURL.getPath(),charset,true); String srvPath=req.getServletPath(); if(path.startsWith(srvPath)) { pathInfo=path.substring(srvPath.length()); } } catch (Exception e){} // Service mapping if(StringUtil.isEmpty(pathInfo) || pathInfo.equals("/")) {// ToDo // list available services (if enabled in admin) if(config.getRestList()) { try { HttpServletRequest _req = getHttpServletRequest(); write("Available sevice mappings are:<ul>"); railo.runtime.rest.Mapping[] mappings = config.getRestMappings(); String path; for(int i=0;i<mappings.length;i++){ path=_req.getContextPath()+ReqRspUtil.getScriptName(_req)+mappings[i].getVirtual(); write("<li>"+path+"</li>"); } write("</ul>"); } catch (IOException e) { throw Caster.toPageException(e); } } else RestUtil.setStatus(this, 404, null); return; } // check for matrix int index; String entry; Struct matrix=new StructImpl(); while((index=pathInfo.lastIndexOf(';'))!=-1){ entry=pathInfo.substring(index+1); pathInfo=pathInfo.substring(0,index); if(StringUtil.isEmpty(entry,true)) continue; index=entry.indexOf('='); if(index!=-1)matrix.setEL(entry.substring(0,index).trim(), entry.substring(index+1).trim()); else matrix.setEL(entry.trim(), ""); } // get accept List<MimeType> accept = ReqRspUtil.getAccept(this); MimeType contentType = ReqRspUtil.getContentType(this); // check for format extension //int format = getApplicationContext().getRestSettings().getReturnFormat(); int format; boolean hasFormatExtension=false; if(StringUtil.endsWithIgnoreCase(pathInfo, ".json")) { pathInfo=pathInfo.substring(0,pathInfo.length()-5); format = UDF.RETURN_FORMAT_JSON; accept.clear(); accept.add(MimeType.APPLICATION_JSON); hasFormatExtension=true; } else if(StringUtil.endsWithIgnoreCase(pathInfo, ".wddx")) { pathInfo=pathInfo.substring(0,pathInfo.length()-5); format = UDF.RETURN_FORMAT_WDDX; accept.clear(); accept.add(MimeType.APPLICATION_WDDX); hasFormatExtension=true; } else if(StringUtil.endsWithIgnoreCase(pathInfo, ".cfml")) { pathInfo=pathInfo.substring(0,pathInfo.length()-5); format = UDF.RETURN_FORMAT_SERIALIZE; accept.clear(); accept.add(MimeType.APPLICATION_CFML); hasFormatExtension=true; } else if(StringUtil.endsWithIgnoreCase(pathInfo, ".serialize")) { pathInfo=pathInfo.substring(0,pathInfo.length()-10); format = UDF.RETURN_FORMAT_SERIALIZE; accept.clear(); accept.add(MimeType.APPLICATION_CFML); hasFormatExtension=true; } else if(StringUtil.endsWithIgnoreCase(pathInfo, ".xml")) { pathInfo=pathInfo.substring(0,pathInfo.length()-4); format = UDF.RETURN_FORMAT_XML; accept.clear(); accept.add(MimeType.APPLICATION_XML); hasFormatExtension=true; } else { format = getApplicationContext().getRestSettings().getReturnFormat(); //MimeType mt=MimeType.toMimetype(format); //if(mt!=null)accept.add(mt); } if(accept.size()==0) accept.add(MimeType.ALL); // loop all mappings //railo.runtime.rest.Result result = null;//config.getRestSource(pathInfo, null); RestRequestListener rl=null; railo.runtime.rest.Mapping[] restMappings = config.getRestMappings(); railo.runtime.rest.Mapping m,mapping=null,defaultMapping=null; //String callerPath=null; if(restMappings!=null)for(int i=0;i<restMappings.length;i++) { m = restMappings[i]; if(m.isDefault())defaultMapping=m; if(pathInfo.startsWith(m.getVirtualWithSlash(),0)) { mapping=m; //result = m.getResult(this,callerPath=pathInfo.substring(m.getVirtual().length()),format,matrix,null); rl=new RestRequestListener(m,pathInfo.substring(m.getVirtual().length()),matrix,format,hasFormatExtension,accept,contentType,null); break; } } // default mapping if(mapping==null && defaultMapping!=null) { mapping=defaultMapping; //result = mapping.getResult(this,callerPath=pathInfo,format,matrix,null); rl=new RestRequestListener(mapping,pathInfo,matrix,format,hasFormatExtension,accept,contentType,null); } //base = PageSourceImpl.best(config.getPageSources(this,null,realPath,true,false,true)); if(mapping==null){ RestUtil.setStatus(this,404,"no rest service for ["+pathInfo+"] found"); } else { base=config.toPageSource(null, mapping.getPhysical(), null); listener.onRequest(this, base,rl); } //RestRequestListener rl = new RestRequestListener(mapping,callerPath=pathInfo.substring(m.getVirtual().length()),format,matrix,null); /*if(result!=null){ //railo.runtime.rest.Source source=result.getSource(); //print.e(source.getPageSource()); //base=source.getPageSource(); //req.setAttribute("client", "railo-rest-1-0"); //req.setAttribute("rest-path", callerPath); //req.setAttribute("rest-result", result); listener.onRequest(this, base); //doInclude(source.getPageSource()); } else { if(mapping==null)RestUtil.setStatus(this,404,"no rest service for ["+pathInfo+"] found"); else RestUtil.setStatus(this,404,"no rest service for ["+pathInfo+"] found in mapping ["+mapping.getVirtual()+"]"); }*/ } catch(Throwable t) { PageException pe = Caster.toPageException(t); if(!Abort.isSilentAbort(pe)){ log(true); if(fdEnabled){ FDSignal.signal(pe, false); } listener.onError(this,pe); } else log(false); if(throwExcpetion) throw pe; } finally { if(enablecfoutputonly>0){ setCFOutputOnly((short)0); } base=null; } } @Override public void execute(String realPath, boolean throwExcpetion) throws PageException { execute(realPath, throwExcpetion, true); } public void execute(String realPath, boolean throwExcpetion, boolean onlyTopLevel) throws PageException { //SystemOut.printDate(config.getOutWriter(),"Call:"+realPath+" (id:"+getId()+";running-requests:"+config.getThreadQueue().size()+";)"); ApplicationListener listener=config.getApplicationListener(); if(realPath.startsWith("/mapping-")){ base=null; int index = realPath.indexOf('/',9); if(index>-1){ String type = realPath.substring(9,index); if(type.equalsIgnoreCase("tag")){ base=getPageSource( new Mapping[]{config.getTagMapping(),config.getServerTagMapping()}, realPath.substring(index) ); } else if(type.equalsIgnoreCase("customtag")){ base=getPageSource( config.getCustomTagMappings(), realPath.substring(index) ); } /*else if(type.equalsIgnoreCase("gateway")){ base=config.getGatewayEngine().getMapping().getPageSource(realPath.substring(index)); if(!base.exists())base=getPageSource(realPath.substring(index)); }*/ } if(base==null) base=PageSourceImpl.best(config.getPageSources(this,null,realPath,onlyTopLevel,false,true)); } else base=PageSourceImpl.best(config.getPageSources(this,null,realPath,onlyTopLevel,false,true)); try { listener.onRequest(this,base,null); log(false); } catch(Throwable t) { PageException pe = Caster.toPageException(t); if(!Abort.isSilentAbort(pe)){ this.pe=pe; log(true); if(fdEnabled){ FDSignal.signal(pe, false); } listener.onError(this,pe); } else log(false); if(throwExcpetion) throw pe; } finally { if(enablecfoutputonly>0){ setCFOutputOnly((short)0); } if(!gatewayContext && getConfig().debug()) { try { listener.onDebug(this); } catch (PageException pe) { if(!Abort.isSilentAbort(pe))listener.onError(this,pe); } } base=null; } } private void log(boolean error) { if(!isGatewayContext() && config.isMonitoringEnabled()) { RequestMonitor[] monitors = config.getRequestMonitors(); if(monitors!=null)for(int i=0;i<monitors.length;i++){ if(monitors[i].isLogEnabled()){ try { monitors[i].log(this,error); } catch (Throwable e) {} } } } } private PageSource getPageSource(Mapping[] mappings, String realPath) { PageSource ps; //print.err(mappings.length); for(int i=0;i<mappings.length;i++) { ps = mappings[i].getPageSource(realPath); //print.err(ps.getDisplayPath()); if(ps.exists()) return ps; } return null; } @Override public void include(String realPath) throws ServletException,IOException { HTTPUtil.include(this, realPath); } @Override public void forward(String realPath) throws ServletException, IOException { HTTPUtil.forward(this, realPath); } public void include(PageSource ps) throws ServletException { try { doInclude(ps); } catch (PageException pe) { throw new PageServletException(pe); } } @Override public void clear() { try { //print.o(getOut().getClass().getName()); getOut().clear(); } catch (IOException e) {} } @Override public long getRequestTimeout() { if(requestTimeout==-1) requestTimeout=config.getRequestTimeout().getMillis(); return requestTimeout; } @Override public void setRequestTimeout(long requestTimeout) { this.requestTimeout = requestTimeout; } @Override public String getCFID() { if(cfid==null) initIdAndToken(); return cfid; } @Override public String getCFToken() { if(cftoken==null) initIdAndToken(); return cftoken; } @Override public String getURLToken() { if(getConfig().getSessionType()==Config.SESSION_TYPE_J2EE) { HttpSession s = getSession(); return "CFID="+getCFID()+"&CFTOKEN="+getCFToken()+"&jsessionid="+(s!=null?getSession().getId():""); } return "CFID="+getCFID()+"&CFTOKEN="+getCFToken(); } @Override public String getJSessionId() { if(getConfig().getSessionType()==Config.SESSION_TYPE_J2EE) { return getSession().getId(); } return null; } /** * initialize the cfid and the cftoken */ private void initIdAndToken() { boolean setCookie=true; // From URL Object oCfid = urlScope().get(KeyConstants._cfid,null); Object oCftoken = urlScope().get(KeyConstants._cftoken,null); // Cookie if((oCfid==null || !Decision.isGUIdSimple(oCfid)) || oCftoken==null) { setCookie=false; oCfid = cookieScope().get(KeyConstants._cfid,null); oCftoken = cookieScope().get(KeyConstants._cftoken,null); } if(oCfid!=null && !Decision.isGUIdSimple(oCfid) ) { oCfid=null; } // New One if(oCfid==null || oCftoken==null) { setCookie=true; cfid=ScopeContext.getNewCFId(); cftoken=ScopeContext.getNewCFToken(); } else { cfid=Caster.toString(oCfid,null); cftoken=Caster.toString(oCftoken,null); } if(setCookie && applicationContext.isSetClientCookies()) { cookieScope().setCookieEL(KeyConstants._cfid,cfid,CookieImpl.NEVER,false,"/",applicationContext.isSetDomainCookies()?(String) cgiScope().get(KeyConstants._server_name,null):null); cookieScope().setCookieEL(KeyConstants._cftoken,cftoken,CookieImpl.NEVER,false,"/",applicationContext.isSetDomainCookies()?(String) cgiScope().get(KeyConstants._server_name,null):null); } } public void resetIdAndToken() { cfid=ScopeContext.getNewCFId(); cftoken=ScopeContext.getNewCFToken(); if(applicationContext.isSetClientCookies()) { cookieScope().setCookieEL(KeyConstants._cfid,cfid,CookieImpl.NEVER,false,"/",applicationContext.isSetDomainCookies()?(String) cgiScope().get(KeyConstants._server_name,null):null); cookieScope().setCookieEL(KeyConstants._cftoken,cftoken,CookieImpl.NEVER,false,"/",applicationContext.isSetDomainCookies()?(String) cgiScope().get(KeyConstants._server_name,null):null); } } @Override public int getId() { return id; } /** * @return returns the root JSP Writer * */ public CFMLWriter getRootOut() { return bodyContentStack.getBase(); } public JspWriter getRootWriter() { return bodyContentStack.getBase(); } @Override public Locale getLocale() { if(locale==null) locale=config.getLocale(); return locale; } @Override public void setPsq(boolean psq) { this.psq=psq; } @Override public boolean getPsq() { return psq; } @Override public void setLocale(Locale locale) { //String old=GetLocale.call(pc); this.locale=locale; HttpServletResponse rsp = getHttpServletResponse(); String charEnc = rsp.getCharacterEncoding(); rsp.setLocale(locale); if(charEnc.equalsIgnoreCase("UTF-8")) { rsp.setContentType("text/html; charset=UTF-8"); } else if(!charEnc.equalsIgnoreCase(rsp.getCharacterEncoding())) { rsp.setContentType("text/html; charset=" + charEnc); } } @Override public void setLocale(String strLocale) throws ExpressionException { setLocale(Caster.toLocale(strLocale)); } @Override public void setErrorPage(ErrorPage ep) { errorPagePool.setErrorPage(ep); } @Override public Tag use(String tagClassName) throws PageException { parentTag=currentTag; currentTag= tagHandlerPool.use(tagClassName); if(currentTag==parentTag) throw new ApplicationException(""); currentTag.setPageContext(this); currentTag.setParent(parentTag); return currentTag; } @Override public Tag use(Class clazz) throws PageException { return use(clazz.getName()); } @Override public void reuse(Tag tag) throws PageException { currentTag=tag.getParent(); tagHandlerPool.reuse(tag); } @Override public QueryCache getQueryCache() { return queryCache; } @Override public void initBody(BodyTag bodyTag, int state) throws JspException { if (state != Tag.EVAL_BODY_INCLUDE) { bodyTag.setBodyContent(pushBody()); bodyTag.doInitBody(); } } @Override public void releaseBody(BodyTag bodyTag, int state) { if(bodyTag instanceof TryCatchFinally) { ((TryCatchFinally)bodyTag).doFinally(); } if (state != Tag.EVAL_BODY_INCLUDE)popBody(); } /* * * @return returns the cfml compiler * / public CFMLCompiler getCompiler() { return compiler; }*/ @Override public void setVariablesScope(Variables variables) { this.variables=variables; undefinedScope().setVariableScope(variables); if(variables instanceof ComponentScope) { activeComponent=((ComponentScope)variables).getComponent(); /*if(activeComponent.getAbsName().equals("jm.pixeltex.supersuperApp")){ print.dumpStack(); }*/ } else { activeComponent=null; } } @Override public Component getActiveComponent() { return activeComponent; } @Override public Credential getRemoteUser() throws PageException { if(remoteUser==null) { Key name = KeyImpl.init(Login.getApplicationName(applicationContext)); Resource roles = config.getConfigDir().getRealResource("roles"); if(applicationContext.getLoginStorage()==Scope.SCOPE_SESSION) { Object auth = sessionScope().get(name,null); if(auth!=null) { remoteUser=CredentialImpl.decode(auth,roles); } } else if(applicationContext.getLoginStorage()==Scope.SCOPE_COOKIE) { Object auth = cookieScope().get(name,null); if(auth!=null) { remoteUser=CredentialImpl.decode(auth,roles); } } } return remoteUser; } @Override public void clearRemoteUser() { if(remoteUser!=null)remoteUser=null; String name=Login.getApplicationName(applicationContext); cookieScope().removeEL(KeyImpl.init(name)); try { sessionScope().removeEL(KeyImpl.init(name)); } catch (PageException e) {} } @Override public void setRemoteUser(Credential remoteUser) { this.remoteUser = remoteUser; } @Override public VariableUtil getVariableUtil() { return variableUtil; } @Override public void throwCatch() throws PageException { if(exception!=null) throw exception; throw new ApplicationException("invalid context for tag/script expression rethow"); } @Override public PageException setCatch(Throwable t) { if(t==null) { exception=null; undefinedScope().removeEL(KeyConstants._cfcatch); } else { exception = Caster.toPageException(t); undefinedScope().setEL(KeyConstants._cfcatch,exception.getCatchBlock(config)); if(!gatewayContext && config.debug() && config.hasDebugOptions(ConfigImpl.DEBUG_EXCEPTION)) debugger.addException(config,exception); } return exception; } public void setCatch(PageException pe) { exception = pe; if(pe==null) { undefinedScope().removeEL(KeyConstants._cfcatch); } else { undefinedScope().setEL(KeyConstants._cfcatch,pe.getCatchBlock(config)); if(!gatewayContext && config.debug() && config.hasDebugOptions(ConfigImpl.DEBUG_EXCEPTION)) debugger.addException(config,exception); } } public void setCatch(PageException pe,boolean caught, boolean store) { if(fdEnabled){ FDSignal.signal(pe, caught); } exception = pe; if(store){ if(pe==null) { undefinedScope().removeEL(KeyConstants._cfcatch); } else { undefinedScope().setEL(KeyConstants._cfcatch,pe.getCatchBlock(config)); if(!gatewayContext && config.debug() && config.hasDebugOptions(ConfigImpl.DEBUG_EXCEPTION)) debugger.addException(config,exception); } } } /** * @return return current catch */ public PageException getCatch() { return exception; } @Override public void clearCatch() { exception = null; undefinedScope().removeEL(KeyConstants._cfcatch); } @Override public void addPageSource(PageSource ps, boolean alsoInclude) { pathList.add(ps); if(alsoInclude) includePathList.add(ps); } public void addPageSource(PageSource ps, PageSource psInc) { pathList.add(ps); if(psInc!=null) includePathList.add(psInc); } @Override public void removeLastPageSource(boolean alsoInclude) { if(!pathList.isEmpty())pathList.removeLast(); if(alsoInclude && !includePathList.isEmpty()) includePathList.removeLast(); } public UDF[] getUDFs() { return udfs.toArray(new UDF[udfs.size()]); } public void addUDF(UDF udf) { udfs.add(udf); } public void removeUDF() { if(!udfs.isEmpty())udfs.pop(); } @Override public FTPPool getFTPPool() { return ftpPool; } /* * * @return Returns the manager. * / public DataSourceManager getManager() { return manager; }*/ @Override public ApplicationContext getApplicationContext() { return applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) { session=null; application=null; client=null; this.applicationContext = applicationContext; int scriptProtect = applicationContext.getScriptProtect(); // ScriptProtecting if(config.mergeFormAndURL()) { form.setScriptProtecting(applicationContext, (scriptProtect&ApplicationContext.SCRIPT_PROTECT_FORM)>0 || (scriptProtect&ApplicationContext.SCRIPT_PROTECT_URL)>0); } else { form.setScriptProtecting(applicationContext,(scriptProtect&ApplicationContext.SCRIPT_PROTECT_FORM)>0); url.setScriptProtecting(applicationContext,(scriptProtect&ApplicationContext.SCRIPT_PROTECT_URL)>0); } cookie.setScriptProtecting(applicationContext,(scriptProtect&ApplicationContext.SCRIPT_PROTECT_COOKIE)>0); cgi.setScriptProtecting(applicationContext,(scriptProtect&ApplicationContext.SCRIPT_PROTECT_CGI)>0); undefined.reinitialize(this); } /** * @return return value of method "onApplicationStart" or true * @throws PageException */ public boolean initApplicationContext() throws PageException { boolean initSession=false; AppListenerSupport listener = (AppListenerSupport) config.getApplicationListener(); KeyLock<String> lock = config.getContextLock(); String name=StringUtil.emptyIfNull(applicationContext.getName()); String token=name+":"+getCFID(); Lock tokenLock = lock.lock(token,getRequestTimeout()); //print.o("outer-lock :"+token); try { // check session before executing any code initSession=applicationContext.isSetSessionManagement() && listener.hasOnSessionStart(this) && !scopeContext.hasExistingSessionScope(this); // init application Lock nameLock = lock.lock(name,getRequestTimeout()); //print.o("inner-lock :"+token); try { RefBoolean isNew=new RefBooleanImpl(false); application=scopeContext.getApplicationScope(this,isNew);// this is needed that the application scope is initilized if(isNew.toBooleanValue()) { try { if(!listener.onApplicationStart(this)) { scopeContext.removeApplicationScope(this); return false; } } catch (PageException pe) { scopeContext.removeApplicationScope(this); throw pe; } } } finally{ //print.o("inner-unlock:"+token); lock.unlock(nameLock); } // init session if(initSession) { scopeContext.getSessionScope(this, DUMMY_BOOL);// this is needed that the session scope is initilized listener.onSessionStart(this); } } finally{ //print.o("outer-unlock:"+token); lock.unlock(tokenLock); } return true; } /** * @return the scope factory */ public ScopeFactory getScopeFactory() { return scopeFactory; } @Override public Tag getCurrentTag() { return currentTag; } @Override public long getStartTime() { return startTime; } @Override public Thread getThread() { return thread; } public void setThread(Thread thread) { this.thread=thread; } @Override public int getExecutionTime() { return executionTime; } @Override public void setExecutionTime(int executionTime) { this.executionTime = executionTime; } @Override public synchronized void compile(PageSource pageSource) throws PageException { Resource classRootDir = pageSource.getMapping().getClassRootDirectory(); try { config.getCompiler().compile( config, pageSource, config.getTLDs(), config.getFLDs(), classRootDir, pageSource.getJavaName() ); } catch (Exception e) { throw Caster.toPageException(e); } } @Override public void compile(String realPath) throws PageException { SystemOut.printDate("method PageContext.compile(String) should no longer be used!"); compile(PageSourceImpl.best(getRelativePageSources(realPath))); } public HttpServlet getServlet() { return servlet; } @Override public railo.runtime.Component loadComponent(String compPath) throws PageException { return ComponentLoader.loadComponent(this,compPath,null,null); } /** * @return the base */ public PageSource getBase() { return base; } /** * @param base the base to set */ public void setBase(PageSource base) { this.base = base; } /** * @return the isCFCRequest */ public boolean isCFCRequest() { return isCFCRequest; } @Override public DataSourceManager getDataSourceManager() { return manager; } @Override public Object evaluate(String expression) throws PageException { return new CFMLExpressionInterpreter().interpret(this,expression); } @Override public String serialize(Object expression) throws PageException { return Serialize.call(this, expression); } /** * @return the activeUDF */ public UDF getActiveUDF() { return activeUDF; } /** * @param activeUDF the activeUDF to set */ public void setActiveUDF(UDF activeUDF) { this.activeUDF = activeUDF; } @Override public CFMLFactory getCFMLFactory() { return config.getFactory(); } @Override public PageContext getParentPageContext() { return parent; } @Override public String[] getThreadScopeNames() { if(threads==null)return new String[0]; return CollectionUtil.keysAsString(threads); //Set ks = threads.keySet(); //return (String[]) ks.toArray(new String[ks.size()]); } @Override public Threads getThreadScope(String name) { return getThreadScope(KeyImpl.init(name)); } public Threads getThreadScope(Collection.Key name) { if(threads==null)threads=new StructImpl(); Object obj = threads.get(name,null); if(obj instanceof Threads)return (Threads) obj; return null; } public Object getThreadScope(Collection.Key name,Object defaultValue) { if(threads==null)threads=new StructImpl(); if(name.equalsIgnoreCase(KeyConstants._cfthread)) return threads; return threads.get(name,defaultValue); } public Object getThreadScope(String name,Object defaultValue) { if(threads==null)threads=new StructImpl(); if(name.equalsIgnoreCase(KeyConstants._cfthread.getLowerString())) return threads; return threads.get(KeyImpl.init(name),defaultValue); } @Override public void setThreadScope(String name,Threads ct) { hasFamily=true; if(threads==null) threads=new StructImpl(); threads.setEL(KeyImpl.init(name), ct); } public void setThreadScope(Collection.Key name,Threads ct) { hasFamily=true; if(threads==null) threads=new StructImpl(); threads.setEL(name, ct); } @Override public boolean hasFamily() { return hasFamily; } public DatasourceConnection _getConnection(String datasource, String user,String pass) throws PageException { return _getConnection(config.getDataSource(datasource),user,pass); } public DatasourceConnection _getConnection(DataSource ds, String user,String pass) throws PageException { String id=DatasourceConnectionPool.createId(ds,user,pass); DatasourceConnection dc=conns.get(id); if(dc!=null && DatasourceConnectionPool.isValid(dc,null)){ return dc; } dc=config.getDatasourceConnectionPool().getDatasourceConnection(this,ds, user, pass); conns.put(id, dc); return dc; } @Override public TimeZone getTimeZone() { if(timeZone==null) timeZone=config.getTimeZone(); return timeZone; } @Override public void setTimeZone(TimeZone timeZone) { this.timeZone=timeZone; } /** * @return the requestId */ public int getRequestId() { return requestId; } private Set<String> pagesUsed=new HashSet<String>(); private ActiveQuery activeQuery; private ActiveLock activeLock; public boolean isTrusted(Page page) { if(page==null)return false; short it = config.getInspectTemplate(); if(it==ConfigImpl.INSPECT_NEVER)return true; if(it==ConfigImpl.INSPECT_ALWAYS)return false; return pagesUsed.contains(""+page.hashCode()); } public void setPageUsed(Page page) { pagesUsed.add(""+page.hashCode()); } @Override public void exeLogStart(int position,String id){ if(execLog!=null)execLog.start(position, id); } @Override public void exeLogEnd(int position,String id){ if(execLog!=null)execLog.end(position, id); } /** * @param create if set to true, railo creates a session when not exist * @return * @throws PageException */ public ORMSession getORMSession(boolean create) throws PageException { if(ormSession==null || !ormSession.isValid()) { if(!create) return null; ormSession=config.getORMEngine(this).createSession(this); } DatasourceManagerImpl manager = (DatasourceManagerImpl) getDataSourceManager(); manager.add(this,ormSession); return ormSession; } public void resetSession() { this.session=null; } /** * @return the gatewayContext */ public boolean isGatewayContext() { return gatewayContext; } /** * @param gatewayContext the gatewayContext to set */ public void setGatewayContext(boolean gatewayContext) { this.gatewayContext = gatewayContext; } public void setServerPassword(String serverPassword) { this.serverPassword=serverPassword; } public String getServerPassword() { return serverPassword; } public short getSessionType() { if(isGatewayContext())return Config.SESSION_TYPE_CFML; return applicationContext.getSessionType(); } // this is just a wrapper method for ACF public Scope SymTab_findBuiltinScope(String name) throws PageException { return scope(name, null); } // FUTURE add to PageContext public DataSource getDataSource(String datasource) throws PageException { DataSource ds = ((ApplicationContextPro)getApplicationContext()).getDataSource(datasource,null); if(ds==null) ds=getConfig().getDataSource(datasource); return ds; } public void setActiveQuery(ActiveQuery activeQuery) { this.activeQuery=activeQuery; } public ActiveQuery getActiveQuery() { return activeQuery; } public void releaseActiveQuery() { activeQuery=null; } public void setActiveLock(ActiveLock activeLock) { this.activeLock=activeLock; } public ActiveLock getActiveLock() { return activeLock; } public void releaseActiveLock() { activeLock=null; } public PageException getPageException() { return pe; } }
package com.vrg.rapid; import com.google.common.net.HostAndPort; import com.vrg.rapid.pb.ConsensusProposal; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import junitparams.naming.TestCaseName; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static org.junit.Assert.assertEquals; /** * Unit tests for the MembershipService class without the messaging. */ @RunWith(JUnitParamsRunner.class) public class MembershipServiceTest { private static final int K = 10; private static final int H = 8; private static final int L = 3; private final List<MembershipService> services = new ArrayList<>(); @After public void cleanup() throws InterruptedException { for (final MembershipService service: services) { service.shutdown(); } services.clear(); } /** * Verifies that a node makes a decision only after |quorum| identical proposals are received. * This test does not generate conflicting proposals. */ @Test @Parameters(method = "fastQuorumTestNoConflictsData") @TestCaseName("{method}[N={0},Q={1}]") public void fastQuorumTestNoConflicts(final int N, final int quorum) throws InterruptedException, IOException, ExecutionException { final int serverPort = 1234; final HostAndPort node = HostAndPort.fromParts("127.0.0.1", serverPort); final HostAndPort proposalNode = HostAndPort.fromParts("127.0.0.1", serverPort + 1); final MembershipView view = createView(serverPort, N); final MembershipService service = createAndStartMembershipService(node, view); assertEquals(N, service.getMembershipSize()); final long currentId = view.getCurrentConfigurationId(); final ConsensusProposal.Builder proposal = getProposal(currentId, Collections.singletonList(proposalNode)); for (int i = 0; i < quorum - 1; i++) { service.processConsensusProposal(proposal.setSender(addrForBase(i).toString()).build()); assertEquals(N, service.getMembershipSize()); } service.processConsensusProposal(proposal.setSender(addrForBase(quorum - 1).toString()).build()); assertEquals(N - 1, service.getMembershipSize()); } public static Iterable<Object[]> fastQuorumTestNoConflictsData() { return Arrays.asList(new Object[][] { {6, 5}, {48, 37}, {50, 38}, {100, 76}, {102, 77}, // Even N {5, 4}, {51, 39}, {49, 37}, {99, 75}, {101, 76} // Odd N }); } /** * Verifies that a node makes a decision only after |quorum| identical proposals are received. * This test generates conflicting proposals. */ @Test @Parameters(method = "fastQuorumTestWithConflicts") @TestCaseName("{method}[N={0},Q={1},Conflicts={2},ShouldChange={3}]") public void fastQuorumTestWithConflicts(final int N, final int quorum, final int numConflicts, final boolean changeExpected) throws InterruptedException, IOException, ExecutionException { final int serverPort = 1234; final HostAndPort node = HostAndPort.fromParts("127.0.0.1", serverPort); final HostAndPort proposalNode = HostAndPort.fromParts("127.0.0.1", serverPort + 1); final HostAndPort proposalNodeConflict = HostAndPort.fromParts("127.0.0.1", serverPort + 2); final MembershipView view = createView(serverPort, N); final MembershipService service = createAndStartMembershipService(node, view); assertEquals(N, service.getMembershipSize()); final long currentId = view.getCurrentConfigurationId(); final ConsensusProposal.Builder proposal = getProposal(currentId, Collections.singletonList(proposalNode)); final ConsensusProposal.Builder proposalConflict = getProposal(currentId, Collections.singletonList(proposalNodeConflict)); for (int i = 0; i < numConflicts; i++) { service.processConsensusProposal(proposalConflict.setSender(addrForBase(i).toString()).build()); assertEquals(N, service.getMembershipSize()); } final int nonConflictCount = Math.min(numConflicts + quorum - 1, N - 1); for (int i = numConflicts; i < nonConflictCount; i++) { service.processConsensusProposal(proposal.setSender(addrForBase(i).toString()).build()); assertEquals(N, service.getMembershipSize()); } service.processConsensusProposal(proposal.setSender(addrForBase(nonConflictCount) .toString()).build()); assertEquals(changeExpected ? N - 1 : N, service.getMembershipSize()); } public static Iterable<Object[]> fastQuorumTestWithConflicts() { // Format: (N, quorum size, number of conflicts, should-membership-change) // One conflicting message. Must lead to decision. final List<Object[]> oneConflictArray = Arrays.asList(new Object[][] { {6, 5, 1, true}, {48, 37, 1, true}, {50, 38, 1, true}, {100, 76, 1, true}, {102, 77, 1, true}, }); // Boundary case: F conflicts, and N-F non-conflicts. Must lead to decisions. final List<Object[]> boundaryCase = Arrays.asList(new Object[][] { {48, 37, 11, true}, {50, 38, 12, true}, {100, 76, 24, true}, {102, 77, 25, true}, }); // More conflicts than Fast Paxos quorum size. These must not lead to decisions. final List<Object[]> tooManyConflicts = Arrays.asList(new Object[][] { {6, 5, 2, false}, {48, 37, 14, false}, {50, 38, 13, false}, {100, 76, 25, false}, {102, 77, 26, false}, }); final ArrayList<Object[]> params = new ArrayList<>(); params.addAll(oneConflictArray); params.addAll(boundaryCase); params.addAll(tooManyConflicts); return params; } /** * Create a membership service listening on serverAddr */ private MembershipService createAndStartMembershipService(final HostAndPort serverAddr, final MembershipView view) throws IOException, MembershipView.NodeAlreadyInRingException { final WatermarkBuffer watermarkBuffer = new WatermarkBuffer(K, H, L); final SharedResources resources = new SharedResources(serverAddr); final MembershipService service = new MembershipService.Builder(serverAddr, watermarkBuffer, view, resources) .build(); services.add(service); return service; } /** * Populates a view with a sequence of HostAndPorts starting from basePort up to basePort + N - 1 */ private MembershipView createView(final int basePort, final int N) { final MembershipView view = new MembershipView(K); for (int i = basePort; i < basePort + N; i++) { view.ringAdd(HostAndPort.fromParts("127.0.0.1", i), UUID.randomUUID()); } return view; } /** * Returns a proposal message without the sender set. */ private ConsensusProposal.Builder getProposal(final long currentConfigurationId, final List<HostAndPort> proposal) { return ConsensusProposal.newBuilder() .setConfigurationId(currentConfigurationId) .addAllHosts(proposal .stream() .map(HostAndPort::toString) .sorted() .collect(Collectors.toList())); } private HostAndPort addrForBase(final int port) { return HostAndPort.fromParts("127.0.0.1", port); } }
package com.fastdtw.matrix; public class ColMajorCell { private final int col; private final int row; public int getCol() { return col; } public int getRow() { return row; } public ColMajorCell(int column, int row) { this.col = column; this.row = row; } // end Constructor @Override public boolean equals(Object o) { return (o instanceof ColMajorCell) && (((ColMajorCell) o).col == this.col) && (((ColMajorCell) o).row == this.row); } @Override public int hashCode() { return (1 << col) + row; } @Override public String toString() { return "(" + col + "," + row + ")"; } }
package com.filmon.maven; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.imgscalr.Scalr; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; @Mojo(name="scale", defaultPhase = LifecyclePhase.GENERATE_RESOURCES) public class ScaleImageMojo extends AbstractMojo { @Parameter( defaultValue = "${project.build.outputDirectory}", required = true ) private File outputDirectory; @Parameter(required = false) private List<Image> images; public File getOutputDirectory() { return outputDirectory; } public void setOutputDirectory(final File outputDirectory) { this.outputDirectory = outputDirectory; } public List<Image> getImages() { return images; } public void setImages(final List<Image> images) { this.images = images; } public void execute() throws MojoExecutionException { final Log log = getLog(); for (Image imageDefinition : images) { final File input = imageDefinition.getSource(); final String destination = imageDefinition.getDestination(); File output = new File(destination); if (!output.isAbsolute()) { output = new File(outputDirectory, destination); } if (!input.exists()) { throw new MojoExecutionException(String.format("Input file %s does not exists", input.getAbsolutePath())); } if (output.exists()) { log.info(String.format("Output file %s skipped because it already exists", output.getAbsolutePath())); continue; } final Integer width = imageDefinition.getWidth(); final BufferedImage thumbnail = Scalr.resize( getInputImage(input), Scalr.Method.ULTRA_QUALITY, width ); writeImage(thumbnail, getFormatName(input), output); log.info(String.format("%s:%s generated", output, width)); } } private String getFormatName(final File file) throws MojoExecutionException { final ImageInputStream imageStream = getInputStream(file); final Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageStream); if (!imageReaders.hasNext()) { closeStream(imageStream); throw notAnImage(file); } final ImageReader imageReader = imageReaders.next(); try { return imageReader.getFormatName(); } catch (IOException e) { throw notAnImage(file); } finally { closeStream(imageStream); imageReader.dispose(); } } private ImageInputStream getInputStream(final File file) throws MojoExecutionException { final ImageInputStream imageStream; try { imageStream = ImageIO.createImageInputStream(file); } catch (IOException e) { throw readFailed(file); } if (imageStream == null) { throw notAnImage(file); } return imageStream; } private void closeStream(final ImageInputStream imageStream) { try { imageStream.close(); } catch (IOException ignored) { } } private void writeImage(final BufferedImage thumbnail, final String format, final File output) throws MojoExecutionException { if (output.exists() && !output.canWrite()) { throw writeFailed(output); } final File dir = output.getParentFile(); if (!dir.exists() && !dir.mkdirs()) { throw writeFailed(output); } try { ImageIO.write(thumbnail, format, output); } catch (IOException e) { throw writeFailed(output); } catch (NullPointerException e) { throw writeFailed(output); } } private BufferedImage getInputImage(final File file) throws MojoExecutionException { if (!file.canRead()) { throw readFailed(file); } try { return ImageIO.read(file); } catch (IOException e) { throw notAnImage(file); } } private MojoExecutionException readFailed(final File file) { return new MojoExecutionException(String.format( "Cannot read input file %s", file.getAbsolutePath() )); } private MojoExecutionException writeFailed(final File file) { return new MojoExecutionException(String.format( "Cannot write output file %s", file.getAbsolutePath() )); } private MojoExecutionException notAnImage(final File file) { return new MojoExecutionException(String.format( "input file %s not an image/unknown format", file.getAbsolutePath() )); } }
package com.fishercoder.solutions; public class _1011 { public static class Solution1 { public int daysToShip(int[] weights, int capacity) { int days = 0; int currentShip = 0; for (int k : weights) { if (currentShip + k > capacity) { currentShip = 0; days += 1; } currentShip += k; } return days + 1; } public int shipWithinDays(int[] weights, int D) { int sum = 0; int max = 0; for (int k : weights) { sum += k; max = Math.max(max, k); } // Minimum possible capacity needs to be as much as the heaviest package int lower = max; // Maximum possible capacity is the total weight of all packages int upper = sum; if (daysToShip(weights, lower) <= D) { return lower; } // Guess is for capacity int currentGuess; int bestGuess = -1; // Binary search while (lower <= upper) { currentGuess = (upper + lower) / 2; if (daysToShip(weights, currentGuess) <= D) { bestGuess = currentGuess; upper = currentGuess - 1; } else { lower = currentGuess + 1; } } return bestGuess; } } }
package reactor.pipe; import reactor.pipe.concurrent.AVar; import reactor.pipe.concurrent.Atom; import reactor.pipe.key.Key; import org.junit.Test; import org.pcollections.TreePVector; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; public class MatchedPipeTest extends AbstractStreamTest { @Test public void mapTest() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(); AVar<Integer> res = new AVar<>(); pipe.matched(key -> key.getPart(0).equals("source")) .map(i -> i + 1) .map(i -> i * 2) .consume(res::set); pipe.notify(Key.wrap("source", "first"), 1); assertThat(res.get(1, TimeUnit.SECONDS), is(4)); } @Test public void statefulMapTest() throws InterruptedException { AVar<Integer> res = new AVar<>(3); NamedPipe<Integer> intPipe = new NamedPipe<>(); intPipe.matched((key) -> key.getPart(0).equals("source")) .map((i) -> i + 1) .map((Atom<Integer> state, Integer i) -> { return state.update(old -> old + i); }, 0) .consume(res::set); intPipe.notify(Key.wrap("source", "1"), 1); intPipe.notify(Key.wrap("source", "1"), 2); intPipe.notify(Key.wrap("source", "1"), 3); assertThat(res.get(LATCH_TIMEOUT, LATCH_TIME_UNIT), is(9)); } @Test public void testFilter() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(); AVar<Integer> res = new AVar<>(); pipe.matched(key -> key.getPart(0).equals("source")) .map(i -> i + 1) .filter(i -> i % 2 != 0) .map(i -> i * 2) .consume(res::set); pipe.notify(Key.wrap("source"), 1); pipe.notify(Key.wrap("source"), 2); assertThat(res.get(1, TimeUnit.SECONDS), is(6)); } @Test public void testPartition() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(); AVar<List<Integer>> res = new AVar<>(); pipe.matched(key -> key.getPart(0).equals("source")) .partition((i) -> { return i.size() == 5; }) .consume(res::set); pipe.notify(Key.wrap("source"), 1); pipe.notify(Key.wrap("source"), 2); pipe.notify(Key.wrap("source"), 3); pipe.notify(Key.wrap("source"), 4); pipe.notify(Key.wrap("source"), 5); pipe.notify(Key.wrap("source"), 6); pipe.notify(Key.wrap("source"), 7); assertThat(res.get(1, TimeUnit.SECONDS), is(TreePVector.from(Arrays.asList(1, 2, 3, 4, 5)))); } @Test public void testSlide() throws InterruptedException { NamedPipe<Integer> pipe = new NamedPipe<>(); AVar<List<Integer>> res = new AVar<>(6); pipe.matched(key -> key.getPart(0).equals("source")) .slide(i -> { return i.subList(i.size() > 5 ? i.size() - 5 : 0, i.size()); }) .consume(res::set); pipe.notify(Key.wrap("source"), 1); pipe.notify(Key.wrap("source"), 2); pipe.notify(Key.wrap("source"), 3); pipe.notify(Key.wrap("source"), 4); pipe.notify(Key.wrap("source"), 5); pipe.notify(Key.wrap("source"), 6); assertThat(res.get(1, TimeUnit.SECONDS), is(TreePVector.from(Arrays.asList(2,3,4,5,6)))); } }
package com.imcode.imcms.api; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor public class SourceFile implements Cloneable, Serializable { private String fileName; private String fullPath; private FileType fileType; private List<String> contents; public Object clone() throws CloneNotSupportedException { return super.clone(); } public enum FileType { DIRECTORY, FILE } }
package uk.gov.dvla.domain; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.google.code.morphia.annotations.Entity; import com.google.code.morphia.annotations.Indexed; import com.google.code.morphia.annotations.Property; @Entity(value="drivers", noClassnameStored=true) public class Driver extends Person { private List<DriverNumber> dlnHistory; private List<DriverFlag> flag; private List<Licence> licence; private List<Integer> stopMarker; private List<Integer> restrictionKey; private List<Integer> caseType; private Boolean carHireEnqPmt = null; private String statusCode = null; private Date photoExpiryDate; @Property("dln") @Indexed private String currentDriverNumber = null; public void addLicence(Licence lic){ if (null == licence){ licence = new ArrayList<Licence>(); } licence.add(lic); } public void addStopMarker(Integer marker){ if (null == stopMarker){ stopMarker = new ArrayList<Integer>(); } stopMarker.add(marker); } public void addRestrictionKey(Integer key){ if (null == restrictionKey){ restrictionKey = new ArrayList<Integer>(); } restrictionKey.add(key); } public void setLicence(List<Licence> lics) { licence = lics; } public List<Integer> getStopMarker(){ return stopMarker; } public void setStopMarker(List<Integer> markers){ this.stopMarker = markers; } public List<Integer> getRestrictionKey(){ return restrictionKey; } public void setRestrictionKey(List<Integer> keys){ this.restrictionKey = keys; } public List<Integer> getCaseType(){ return restrictionKey; } public void setgetCaseType(List<Integer> keys){ this.caseType = keys; } public void setCurrentDriverNumber(String dln){ this.currentDriverNumber = dln; } public String getCurrentDriverNumber(){ return this.currentDriverNumber; } public List<DriverNumber> getDriverNumberHistory() { return dlnHistory; } public void setDriverNumberHistory(List<DriverNumber> driverNumber) { this.dlnHistory = driverNumber; } public List<DriverFlag> getFlag() { return flag; } public void setFlag(List<DriverFlag> flag) { this.flag = flag; } public Boolean getCarHireEnqPmt() { return carHireEnqPmt; } public void setCarHireEnqPmt(Boolean carHireEnqPmt) { this.carHireEnqPmt = carHireEnqPmt; } public String getStatusCode() { return statusCode; } public void setStatusCode(String statusCode) { this.statusCode = statusCode; } public Date getPhotoExpiryDate() { return photoExpiryDate; } public void setPhotoExpiryDate(Date photoExpiryDate) { this.photoExpiryDate = photoExpiryDate; } }
package com.pengyifan.word2vec; import static com.google.common.base.Preconditions.checkArgument; import java.util.Map; import java.util.Set; import org.apache.commons.math3.linear.RealVector; public class Word2Vec { private final Map<String, RealVector> word2vec; private final int vocabSize; private final int layer1Size; public Word2Vec( int vocabSize, int layer1Size, Map<String, RealVector> word2vec) { this.vocabSize = vocabSize; this.layer1Size = layer1Size; this.word2vec = word2vec; } /** * Returns the vocabulary size. * * @return the vocabulary size */ public int getVocabSize() { return vocabSize; } /** * Returns the length of vector. * * @return the length of vector */ public int getLayer1Size() { return layer1Size; } /** * Returns a Set view of the words contained in this word2vec. * * @return a Set view of the words contained in this word2vec */ public Set<String> getVocab() { return word2vec.keySet(); } /** * Returns true if this word2vec contains a mapping for the specified word. * * @param word whose presence in this word2vec is to be tested * @return true if this word2vec contains a mapping for the specified word */ public boolean contains(String word) { return word2vec.containsKey(word); } /** * Returns the vector of the specified word, or null if this word2vec * contains no mapping for the word. * * @param word whose presence in this word2vec * @return Returns the vector of the specified word, or null if this word2vec * contains no mapping for the word */ public RealVector getRealVector(String word) { return word2vec.get(word); } public double cosine(String s, String t) { checkArgument(contains(s), "The word2vec doesn't contain word[%s]", s); checkArgument(contains(t), "The word2vec doesn't contain word[%s]", t); return getRealVector(s).cosine(getRealVector(t)); } }
package com.perimeterx.models; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.perimeterx.api.providers.CustomParametersProvider; import com.perimeterx.api.providers.HostnameProvider; import com.perimeterx.api.providers.IPProvider; import com.perimeterx.internals.cookie.AbstractPXCookie; import com.perimeterx.internals.cookie.DataEnrichmentCookie; import com.perimeterx.internals.cookie.RawCookieData; import com.perimeterx.internals.cookie.cookieparsers.CookieHeaderParser; import com.perimeterx.internals.cookie.cookieparsers.HeaderParser; import com.perimeterx.internals.cookie.cookieparsers.MobileCookieHeaderParser; import com.perimeterx.models.configuration.ModuleMode; import com.perimeterx.models.configuration.PXConfiguration; import com.perimeterx.models.risk.BlockReason; import com.perimeterx.models.risk.CustomParameters; import com.perimeterx.models.risk.PassReason; import com.perimeterx.models.risk.VidSource; import com.perimeterx.utils.*; import lombok.Data; import org.apache.commons.lang3.StringUtils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; @Data public class PXContext { private static final PXLogger logger = PXLogger.getLogger(PXContext.class); /** * Original HTTP request */ private final HttpServletRequest request; private String pxCookieRaw; /** * Original Captcha cookie */ private String pxCaptcha; /** * Request IP as extracted with IPProvider. * * @see com.perimeterx.api.providers.IPProvider#getRequestIP(HttpServletRequest) */ private String ip; private PXConfiguration pxConfiguration; // Additional fields extracted from the original HTTP request private String vid; private String uuid; private Map<String, String> headers; private String hostname; private String uri; private String userAgent; private String fullUrl; private String httpMethod; private String httpVersion; // PerimeterX computed data on the request private String riskCookie; private final String appId; private String cookieHmac; /** * Score for the current request - if riskScore is above configured {@link com.perimeterx.models.configuration.PXConfiguration#blockingScore} on * PXConfiguration then the {@link com.perimeterx.models.PXContext#verified} is set to false */ private int riskScore; /** * Reason for calling PX Service * * @see com.perimeterx.models.risk.S2SCallReason */ private String s2sCallReason; private boolean madeS2SApiCall; /** * Which action to take after being blocked */ private BlockAction blockAction; /** * if true - calling risk_api to verified request even if cookie data is valid */ private boolean sensitiveRoute; /** * Reason for request being verified * * @see com.perimeterx.models.risk.PassReason */ private PassReason passReason; /** * Risk api timing */ private long riskRtt; /** * Request verification status - if {@link com.perimeterx.models.PXContext#verified} is true, the request is safe to pass to server. */ private boolean verified; /** * Reason for why request should be blocked - relevant when request is not verified, meaning - verified {@link com.perimeterx.models.PXContext#verified} is false */ private BlockReason blockReason; /** * Contains the data that would be rendered on the response when score exceeds the threshold */ private String blockActionData; /** * Marks is the origin of the request comes from mobile client */ private boolean isMobileToken; /** * Marks the origin of the pxCookie */ private String cookieOrigin = Constants.COOKIE_HEADER_NAME; /** * Custom parameters from the requests, cusotm parameters are set via {@link com.perimeterx.api.providers.CustomParametersProvider#buildCustomParameters(PXConfiguration, PXContext)} * if exist, the custom parameters will be set when risk api is triggered */ private CustomParameters customParameters; /** * Simmilar to {@link com.perimeterx.models.PXContext#verified}, flags if to continue the filter chain or return * This will be set to true when the module will handle the request though proxy mode */ private boolean firstPartyRequest; /** * The original uuid of the request. */ private String originalUuid; /** * The original token decoded. */ private String decodedOriginalToken; /** * Errors encountered during the creation process of the cookie */ private String originalTokenError; /** * The original token cookie. */ private String originalTokenCookie; /** * The risk mode (monitor / active_blocking) of the request */ private String riskMode; private List<RawCookieData> tokens; private List<RawCookieData> originalTokens; private String cookieVersion; /** * PerimeterX data enrichment cookie payload */ private JsonNode pxde; private boolean pxdeVerified = false; /** * All the names of the cookies in the request */ private String[] requestCookieNames; /** * the source of the vid */ private VidSource vidSource = VidSource.NONE; /** * the pxhd cookie */ private String pxhd; private String responsePxhd; public PXContext(final HttpServletRequest request, final IPProvider ipProvider, final HostnameProvider hostnameProvider, PXConfiguration pxConfiguration) { this.pxConfiguration = pxConfiguration; logger.debug(PXLogger.LogReason.DEBUG_REQUEST_CONTEXT_CREATED); this.appId = pxConfiguration.getAppId(); initContext(request, pxConfiguration); this.ip = ipProvider.getRequestIP(request); this.hostname = hostnameProvider.getHostname(request); this.request = request; } private void initContext(final HttpServletRequest request, PXConfiguration pxConfiguration) { this.headers = PXCommonUtils.getHeadersFromRequest(request); if (headers.containsKey(Constants.MOBILE_SDK_AUTHORIZATION_HEADER) || headers.containsKey(Constants.MOBILE_SDK_TOKENS_HEADER)) { logger.debug(PXLogger.LogReason.DEBUG_MOBILE_SDK_DETECTED); this.isMobileToken = true; this.cookieOrigin = Constants.HEADER_ORIGIN; } parseCookies(request, isMobileToken); this.firstPartyRequest = false; this.userAgent = request.getHeader("user-agent"); this.uri = request.getRequestURI(); this.fullUrl = request.getRequestURL().toString(); this.blockReason = BlockReason.NONE; this.passReason = PassReason.NONE; this.madeS2SApiCall = false; this.riskRtt = 0; this.httpMethod = request.getMethod(); String protocolDetails[] = request.getProtocol().split("/"); if (protocolDetails.length > 1) { this.httpVersion = protocolDetails[1]; } else { this.httpMethod = StringUtils.EMPTY; } this.sensitiveRoute = checkSensitiveRoute(pxConfiguration.getSensitiveRoutes(), uri); CustomParametersProvider customParametersProvider = pxConfiguration.getCustomParametersProvider(); this.customParameters = customParametersProvider.buildCustomParameters(pxConfiguration, this); } private void parseCookies(HttpServletRequest request, boolean isMobileToken) { HeaderParser headerParser = new CookieHeaderParser(); List<RawCookieData> tokens = new ArrayList<>(); List<RawCookieData> originalTokens = new ArrayList<>(); if (isMobileToken) { headerParser = new MobileCookieHeaderParser(); String tokensHeader = request.getHeader(Constants.MOBILE_SDK_TOKENS_HEADER); tokens.addAll(headerParser.createRawCookieDataList(tokensHeader)); String authCookieHeader = request.getHeader(Constants.MOBILE_SDK_AUTHORIZATION_HEADER); tokens.addAll(headerParser.createRawCookieDataList(authCookieHeader)); String originalTokensHeader = request.getHeader(Constants.MOBILE_SDK_ORIGINAL_TOKENS_HEADER); originalTokens.addAll(headerParser.createRawCookieDataList(originalTokensHeader)); String originalTokenHeader = request.getHeader(Constants.MOBILE_SDK_ORIGINAL_TOKEN_HEADER); originalTokens.addAll(headerParser.createRawCookieDataList(originalTokenHeader)); this.tokens = tokens; if (!originalTokens.isEmpty()) { this.originalTokens = originalTokens; } ObjectMapper mapper = new ObjectMapper(); this.pxde = mapper.createObjectNode(); this.pxdeVerified = true; } else { Cookie[] cookies = request.getCookies(); String cookieHeader = request.getHeader(Constants.COOKIE_HEADER_NAME); this.requestCookieNames = CookieNamesExtractor.extractCookieNames(cookies); setVidAndPxhd(cookies); tokens.addAll(headerParser.createRawCookieDataList(cookieHeader)); this.tokens = tokens; DataEnrichmentCookie deCookie = headerParser.getRawDataEnrichmentCookie(this.tokens, this.pxConfiguration.getCookieKey()); this.pxde = deCookie.getJsonPayload(); this.pxdeVerified = deCookie.isValid(); } } private void setVidAndPxhd(Cookie[] cookies) { if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("_pxvid") || cookie.getName().equals("pxvid")) { this.vid = cookie.getValue(); this.vidSource = VidSource.VID_COOKIE; } if (cookie.getName().equals("_pxhd")) { try { this.pxhd = URLDecoder.decode(cookie.getValue(), "UTF-8"); } catch (UnsupportedEncodingException e) { logger.error("Failed while decoding the pxhd value"); } } } } } public String getPxOriginalTokenCookie() { return originalTokenCookie; } public Boolean isBlocking() { return pxConfiguration.getModuleMode().equals(ModuleMode.BLOCKING); } public String getRiskMode() { return this.isBlocking() ? "active_blocking" : "monitor"; } public void setOriginalTokenCookie(String originalTokenCookie) { this.originalTokenCookie = originalTokenCookie; } public void setRiskCookie(AbstractPXCookie riskCookie) { this.riskCookie = riskCookie.getDecodedCookie().toString(); } public void setBlockAction(String blockAction) { switch (blockAction) { case Constants.CAPTCHA_ACTION_CAPTCHA: this.blockAction = BlockAction.CAPTCHA; break; case Constants.BLOCK_ACTION_CAPTCHA: this.blockAction = BlockAction.BLOCK; break; case Constants.BLOCK_ACTION_CHALLENGE: this.blockAction = BlockAction.CHALLENGE; break; case Constants.BLOCK_ACTION_RATE: this.blockAction = BlockAction.RATE; break; default: this.blockAction = BlockAction.CAPTCHA; break; } } /** * Check if request is verified or not * * @return true if request is valid, false otherwise * @deprecated - Use {@link PXContext#isHandledResponse} */ @Deprecated public boolean isVerified() { return verified; } /** * Check if request is verified or not, this method should not be used as a condition if to pass the request to * the application, instead use {@link PXContext#isHandledResponse} for the reason that its not * handling a case where we already responded if this is a first party request * <p> * The {@link PXContext#isRequestLowScore} only indicates if the request was verified and should * called only if more details about the request is needed (like knowing the reason why shouldn't be passed) * * @return true if request is valid, false otherwise */ public boolean isRequestLowScore() { return verified; } /** * Check if PerimeterX already handled the response thus the request should not be passed to the application * In case true, you can check if {@link PXContext#isRequestLowScore()} or {@link PXContext#isFirstPartyRequest()} * for more information if the response was handled by first party or score was lower than the configured threshold * * @return true if response was handled */ public boolean isHandledResponse() { return !verified || firstPartyRequest; } private boolean checkSensitiveRoute(Set<String> sensitiveRoutes, String uri) { for (String sensitiveRoutePrefix : sensitiveRoutes) { if (uri.startsWith(sensitiveRoutePrefix)) { return true; } } return false; } public String getCollectorURL() { return String.format("%s%s%s", Constants.API_COLLECTOR_PREFIX, appId, Constants.API_COLLECTOR_POSTFIX); } public void setCookieVersion(String cookieVersion) { this.cookieVersion = cookieVersion; } }
package com.testfairy.uploader; import com.testfairy.uploader.command.JarSignerCommand; import com.testfairy.uploader.command.VerifyCommand; import com.testfairy.uploader.command.ZipAlignCommand; import com.testfairy.uploader.command.ZipCommand; import hudson.EnvVars; import net.sf.json.JSONObject; import org.apache.commons.httpclient.HttpHost; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.jenkinsci.plugins.testfairy.TestFairyAndroidRecorder; import org.jenkinsci.plugins.testfairy.TestFairyBaseRecorder; import org.jenkinsci.plugins.testfairy.Utils; import java.io.*; import java.util.List; import java.util.Scanner; public class Uploader { public static String VERSION = "2.4"; private static String SERVER = "http://api.testfairy.com"; private static final String UPLOAD_URL_PATH = "/api/upload"; private static final String UPLOAD_SIGNED_URL_PATH = "/api/upload-signed"; public static final String USER_AGENT = "TestFairy Jenkins Plugin VERSION:" + Uploader.VERSION; public static String JENKINS_URL = "[jenkinsURL]/"; private final PrintStream logger; public Uploader(PrintStream logger) { this.logger = logger; } private DefaultHttpClient buildHttpClient() { DefaultHttpClient httpClient = new DefaultHttpClient(); String proxyHost = System.getProperty("http.proxyHost"); if (proxyHost != null) { Integer proxyPort = Integer.parseInt(System.getProperty("http.proxyPort")); HttpHost proxy = new HttpHost(proxyHost, proxyPort); String proxyUser = System.getProperty("http.proxyUser"); if (proxyUser != null) { AuthScope authScope = new AuthScope(proxyUser, proxyPort); Credentials credentials = new UsernamePasswordCredentials(proxyUser, System.getProperty("http.proxyPassword")); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); } httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } return httpClient; } private JSONObject post(String url, MultipartEntity entity) throws IOException, TestFairyException { DefaultHttpClient httpClient = buildHttpClient(); // logger.println("post to --> " + url); HttpPost post = new HttpPost(url); post.addHeader("User-Agent", USER_AGENT); post.setEntity(entity); try { HttpResponse response = httpClient.execute(post); InputStream is = response.getEntity().getContent(); // Improved error handling. int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { String responseBody = new Scanner(is).useDelimiter("\\A").next(); throw new TestFairyException(responseBody); } StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, "UTF-8"); String responseString = writer.toString(); logger.println("post finished " + responseString); JSONObject json = JSONObject.fromObject(responseString); if (json.getString("status").equals("fail")) { String errorMessage = json.getString("message"); throw new TestFairyException(errorMessage); } return json; } catch (Throwable t) { // System.out.println("Post Throwable"); // t.printStackTrace(); if (t instanceof TestFairyException) { // The TestFairyException will be cached in the preform function (only the massage will be printed for the user) throw new TestFairyException(t.getMessage()); } else { throw new IOException("Post fail " + t.getMessage()); } } } /** * Downloads the entire page at a remote location, onto a local file. * * @param url * @param localFilename */ private void downloadFile(String url, String localFilename) throws IOException { DefaultHttpClient httpClient = buildHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); FileOutputStream fis = new FileOutputStream(localFilename); IOUtils.copy(entity.getContent(), fis); fis.close(); } /** * Upload an APK using /api/upload REST service. * @param apkFilename * @param changeLog * @param recorder * @return * @throws IOException */ public JSONObject uploadApp(String apkFilename, String changeLog, TestFairyBaseRecorder recorder) throws IOException, TestFairyException { logger.println("Uploading App..."); MultipartEntity entity = buildEntity(recorder, apkFilename , changeLog); return post(SERVER + UPLOAD_URL_PATH, entity); } /** * Upload a signed APK using /api/upload-signed REST service. * @param apkFilename * @param recorder * @return * @throws IOException */ public JSONObject uploadSignedApk(String apkFilename, TestFairyBaseRecorder recorder) throws IOException, TestFairyException { logger.println("Uploading SignedApk..."); MultipartEntity entity = new MultipartEntity(); addFileEntity(entity, "apk_file", apkFilename); addFileEntity(entity, "proguard_file", recorder.getMappingFile()); addEntity(entity, "api_key", recorder.getApiKey()); addEntity(entity, "testers-groups", recorder.getTestersGroups()); // if omitted, no emails will be sent to testers addEntity(entity, "notify", recorder.getNotifyTesters()); addEntity(entity, "auto-update", recorder.getAutoUpdate()); return post(SERVER + UPLOAD_SIGNED_URL_PATH, entity); } /** * Build MultipartEntity for API parameters on Upload of an APK * @param recorder * @param apkFilename * @param changeLog * @return * @throws IOException */ private MultipartEntity buildEntity(TestFairyBaseRecorder recorder, String apkFilename, String changeLog) throws IOException { MultipartEntity entity = new MultipartEntity(); addFileEntity(entity, "apk_file", apkFilename); addFileEntity(entity, "proguard_file", recorder.getMappingFile()); addEntity(entity, "api_key", recorder.getApiKey()); addEntity(entity, "changelog", changeLog); addEntity(entity, "video-quality", recorder.getVideoQuality()); // if omitted, default value is "high" addEntity(entity, "screenshot-interval", recorder.getScreenshotInterval()); // if omitted, default is 1 frame per second (videoRate = 1.0) addEntity(entity, "max-duration", recorder.getMaxDuration()); // override default value addEntity(entity, "testers-groups", recorder.getTestersGroups()); // if omitted, no emails will be sent to testers addEntity(entity, "advanced-options", recorder.getAdvancedOptions()); addEntity(entity, "data-only-wifi", recorder.getDataOnlyWifi()); // addEntity(entity, "auto-update", recorder.getAutoUpdate()); addEntity(entity, "record-on-background", recorder.getRecordOnBackground()); // enable record on background option addEntity(entity, "video", recorder.getIsVideoEnabled()); // addEntity(entity, "notify", recorder.getNotifyTesters()); //todo addEntity(entity, "icon-watermark", recorder.); entity.addPart("metrics", new StringBody(extractMetrics(recorder))); return entity; } private void addEntity(MultipartEntity entity, String name, String value) throws UnsupportedEncodingException { if (value != null && !value.isEmpty()) { logger.println("--add " +name + ": " + value.replace("\n", "")); entity.addPart(name, new StringBody(value)); } } private void addEntity(MultipartEntity entity, String name, Boolean value) throws UnsupportedEncodingException { logger.println("--add " +name + ": " + (value ? "on" : "off")); entity.addPart(name, new StringBody(value ? "on" : "off")); } private void addFileEntity(MultipartEntity entity, String name, String filePath) throws UnsupportedEncodingException { if (filePath != null && !filePath.isEmpty()) { logger.println("--add (file) " +name + ": " + filePath); entity.addPart(name, new FileBody(new File(filePath))); } } private String extractMetrics(TestFairyBaseRecorder baseRecorder) { StringBuilder stringBuilder = new StringBuilder(); String metrics = ""; if (baseRecorder.getCpu()) { stringBuilder.append(",cpu"); } if (baseRecorder.getMemory()) { stringBuilder.append(",memory"); } if (baseRecorder.getNetwork()) { stringBuilder.append(",network"); } if (baseRecorder.getLogs()) { stringBuilder.append(",logcat"); } if (baseRecorder.getPhoneSignal()) { stringBuilder.append(",phone-signal"); } if (baseRecorder.getWifi()) { stringBuilder.append(",wifi"); } if (baseRecorder.getGps()) { stringBuilder.append(",gps"); } if (baseRecorder.getBattery()) { stringBuilder.append(",battery"); } if (baseRecorder.getOpenGl()) { stringBuilder.append(",opengl"); } if(stringBuilder.length() > 0) { // remove the first char (it will be ",") metrics = stringBuilder.substring(1); } logger.println("Metrics: " + metrics); return metrics; } /** * return the path to the signed Apk * @param environment * @param apkFilename * @param recorder * @return the path to the signed Apk * @throws IOException * @throws InterruptedException */ public String signingApk(TestFairyAndroidRecorder.AndroidBuildEnvironment environment, String apkFilename, TestFairyAndroidRecorder recorder) throws IOException, InterruptedException, TestFairyException { String apkFilenameZipAlign = Utils.createEmptyInstrumentedAndSignedFile(); ZipCommand zipCommand = new ZipCommand(environment.zipPath, apkFilename); exec(zipCommand); JarSignerCommand jarSignerCommand = new JarSignerCommand(environment.jarsignerPath, recorder, apkFilename); String out = exec(jarSignerCommand); if (out.contains("error") || out.contains("unsigned")) { throw new TestFairyException(out); } VerifyCommand verifyCommand = new VerifyCommand(environment.jarsignerPath, apkFilename); exec(verifyCommand); ZipAlignCommand zipAlignCommand = new ZipAlignCommand(environment.zipalignPath, apkFilename, apkFilenameZipAlign); exec(zipAlignCommand); return apkFilenameZipAlign; } private String exec(List<String> command) throws IOException, InterruptedException , TestFairyException{ logger.println("exec command: " + command); String outputString; String outputStringToReturn = ""; ProcessBuilder pb = new ProcessBuilder(command); Process process = pb.start(); process.waitFor(); DataInputStream curlIn = new DataInputStream(process.getInputStream()); while ((outputString = curlIn.readLine()) != null) { outputStringToReturn = outputStringToReturn + outputString; } logger.println("Output: " + outputStringToReturn); logger.println("exitValue(): " + process.exitValue()); if (process.exitValue() > 0) { throw new TestFairyException((outputStringToReturn.isEmpty()) ? "Error on " + command : outputStringToReturn); } return outputStringToReturn; } public static void setServer(EnvVars vars, PrintStream logger) { String server = vars.expand("$TESTFAIRY_UPLOADER_SERVER"); if (server != null && !server.isEmpty() && !server.equals("$TESTFAIRY_UPLOADER_SERVER")) { SERVER = server; logger.println("The server will be " + SERVER); } } }
package com.wizzardo.http; import com.wizzardo.epoll.Connection; public interface InputListener<C extends Connection> { void onReadyToRead(C connection); default void onReady(C connection) { } default void onDisconnect(C connection) { } }
package com.yq.common.utils; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Hashtable; import java.util.regex.Matcher; import java.util.regex.Pattern; public class IDCardUtils { /** * 1 * 2( * ()GB/T2260 3 * GB/T7408 4 * 5 * 1 S = Sum(Ai * Wi), i = 0, ... , 16 17 * Ai:i Wi:i Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 * 2 Y = mod(S, 11) 3 Y: 0 1 2 3 4 5 6 7 8 9 10 : 1 0 X 9 8 7 6 5 4 3 2 */ /** * * * @param IDStr * * @return "" String * @throws ParseException */ @SuppressWarnings("rawtypes") public static String IDCardValidate(String IDStr) { IDStr = IDStr.toLowerCase(); String errorInfo = ""; String[] ValCodeArr = { "1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2" }; String[] Wi = { "7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9", "10", "5", "8", "4", "2" }; String Ai = ""; if (IDStr.length() != 15 && IDStr.length() != 18) { errorInfo = "1518"; return errorInfo; } if (IDStr.length() == 18) { Ai = IDStr.substring(0, 17); } else if (IDStr.length() == 15) { Ai = IDStr.substring(0, 6) + "19" + IDStr.substring(6, 15); } if (isNumeric(Ai) == false) { errorInfo = "15 ; 18"; return errorInfo; } String strYear = Ai.substring(6, 10); String strMonth = Ai.substring(10, 12); String strDay = Ai.substring(12, 14); if (isDate(strYear + "-" + strMonth + "-" + strDay) == false) { errorInfo = ""; return errorInfo; } GregorianCalendar gc = new GregorianCalendar(); SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd"); try { if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150 || (gc.getTime().getTime() - s.parse( strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) { errorInfo = ""; return errorInfo; } } catch (NumberFormatException e) { e.printStackTrace(); } catch (java.text.ParseException e) { e.printStackTrace(); } if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) == 0) { errorInfo = ""; return errorInfo; } if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) { errorInfo = ""; return errorInfo; } Hashtable h = GetAreaCode(); if (h.get(Ai.substring(0, 2)) == null) { errorInfo = ""; return errorInfo; } int TotalmulAiWi = 0; for (int i = 0; i < 17; i++) { TotalmulAiWi = TotalmulAiWi + Integer.parseInt(String.valueOf(Ai.charAt(i))) * Integer.parseInt(Wi[i]); } int modValue = TotalmulAiWi % 11; String strVerifyCode = ValCodeArr[modValue]; Ai = Ai + strVerifyCode; if (IDStr.length() == 18) { if (Ai.equals(IDStr) == false) { errorInfo = ""; return errorInfo; } } else { return ""; } return ""; } /** * * * @return Hashtable */ @SuppressWarnings({ "rawtypes", "unchecked" }) private static Hashtable GetAreaCode() { Hashtable hashtable = new Hashtable(); hashtable.put("11", ""); hashtable.put("12", ""); hashtable.put("13", ""); hashtable.put("14", ""); hashtable.put("15", ""); hashtable.put("21", ""); hashtable.put("22", ""); hashtable.put("23", ""); hashtable.put("31", ""); hashtable.put("32", ""); hashtable.put("33", ""); hashtable.put("34", ""); hashtable.put("35", ""); hashtable.put("36", ""); hashtable.put("37", ""); hashtable.put("41", ""); hashtable.put("42", ""); hashtable.put("43", ""); hashtable.put("44", ""); hashtable.put("45", ""); hashtable.put("46", ""); hashtable.put("50", ""); hashtable.put("51", ""); hashtable.put("52", ""); hashtable.put("53", ""); hashtable.put("54", ""); hashtable.put("61", ""); hashtable.put("62", ""); hashtable.put("63", ""); hashtable.put("64", ""); hashtable.put("65", ""); hashtable.put("71", ""); hashtable.put("81", ""); hashtable.put("82", ""); hashtable.put("91", ""); return hashtable; } /** * * * @param str * @return */ private static boolean isNumeric(String str) { Pattern pattern = Pattern.compile("[0-9]*"); Matcher isNum = pattern.matcher(str); if (isNum.matches()) { return true; } else { return false; } } /** * * * @param str * @return */ public static boolean isDate(String strDate) { Pattern pattern = Pattern .compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$"); Matcher m = pattern.matcher(strDate); if (m.matches()) { return true; } else { return false; } } /** * @param args * @throws ParseException */ public static void main(String[] args) { // String IDCardNum="210102820826411"; // String IDCardNum="210102198208264114"; String IDCardNum = "210181198807193116"; System.out.println(IDCardValidate(IDCardNum)); // System.out.println(cc.isDate("1996-02-29")); } }
package com.yq.user.service; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.commons.lang.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import com.google.common.base.Strings; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.Lists; import com.sr178.common.jdbc.bean.IPage; import com.sr178.common.jdbc.bean.SqlParamBean; import com.sr178.game.framework.context.ServiceCacheFactory; import com.sr178.game.framework.log.LogSystem; import com.sr178.module.sms.util.SubMailSendUtils; import com.yq.common.ProblemCode; import com.yq.common.exception.ServiceException; import com.yq.common.utils.DateStyle; import com.yq.common.utils.DateUtils; import com.yq.common.utils.IDCardUtils; import com.yq.common.utils.MD5Security; import com.yq.manager.service.AdminService; import com.yq.user.bo.BabyInfo; import com.yq.user.bo.Bdbdate; import com.yq.user.bo.Cpuser; import com.yq.user.bo.Datecj; import com.yq.user.bo.Datepay; import com.yq.user.bo.Ejbk; import com.yq.user.bo.Epkjdate; import com.yq.user.bo.Fcxt; import com.yq.user.bo.Gcuser; import com.yq.user.bo.Gpjy; import com.yq.user.bo.Jbk10; import com.yq.user.bo.Jbk100; import com.yq.user.bo.Jbk300; import com.yq.user.bo.Jbk50; import com.yq.user.bo.Jbk500; import com.yq.user.bo.Jfcp; import com.yq.user.bo.Jfkjdate; import com.yq.user.bo.Province; import com.yq.user.bo.Sgxt; import com.yq.user.bo.Txifok; import com.yq.user.bo.Txpay; import com.yq.user.bo.UserExtinfo; import com.yq.user.bo.Vipcjgl; import com.yq.user.bo.YouMingxi; import com.yq.user.bo.ZuoMingxi; import com.yq.user.dao.BabyInfoDao; import com.yq.user.dao.BdbDateDao; import com.yq.user.dao.CpuserDao; import com.yq.user.dao.DatePayDao; import com.yq.user.dao.DatecjDao; import com.yq.user.dao.DateipDao; import com.yq.user.dao.EjbkDao; import com.yq.user.dao.EptzbDao; import com.yq.user.dao.FcxtDao; import com.yq.user.dao.GcuserDao; import com.yq.user.dao.GpjyDao; import com.yq.user.dao.JbkDao; import com.yq.user.dao.JfcpDao; import com.yq.user.dao.JftzbDao; import com.yq.user.dao.ProvinceDao; import com.yq.user.dao.SgxtDao; import com.yq.user.dao.TduserDao; import com.yq.user.dao.TxPayDao; import com.yq.user.dao.TxifokDao; import com.yq.user.dao.UserDailyGainLogDao; import com.yq.user.dao.UserExtinfoDao; import com.yq.user.dao.VipcjglDao; import com.yq.user.dao.VipxtgcDao; import com.yq.user.dao.YouMingXiDao; import com.yq.user.dao.ZuoMingxiDao; import com.yq.user.utils.Ref; import com.yq.user.utils._99douInterface; public class UserService { @Autowired private GcuserDao gcuserDao; @Autowired private TduserDao tduserDao; @Autowired private ProvinceDao provinceDao; @Autowired private TxifokDao txifokDao; @Autowired private DateipDao dateipDao; @Autowired private ZuoMingxiDao zuoMingxiDao; @Autowired private YouMingXiDao youMingXiDao; @Autowired private SgxtDao sgxtDao; @Autowired private BdbDateDao bdbDateDao; @Autowired private VipxtgcDao vipxtgcDao; @Autowired private EptzbDao eptzbDao; @Autowired private LogService logService; @Autowired private ManagerService managerService; @Autowired private JfcpDao jfcpDao; @Autowired private CpuserDao cpuserDao; @Autowired private TxPayDao txPayDao; @Autowired private DatePayDao datePayDao; @Autowired private GpjyDao gpjyDao; @Autowired private EjbkDao ejbkDao; @Autowired private DatecjDao datecjDao; @Autowired private JbkDao jdbDao; @Autowired private JftzbDao jftzbDao; @Autowired private FcxtDao fcxtDao; @Autowired private VipcjglDao vipcjglDao; @Autowired private BabyInfoDao babyInfoDao; @Autowired private UserDailyGainLogDao userDailyGainLogDao; @Autowired private UserExtinfoDao userExtinfoDao; // Map<String,String> userSession = new ConcurrentHashMap<String,String>(); //idUserMappermap private Cache<String,String> userSession = CacheBuilder.newBuilder().expireAfterAccess(24, TimeUnit.HOURS).maximumSize(102400).build(); /** * * @param sessionId * @return */ public String isLogin(String sessionId){ return userSession.getIfPresent(sessionId); } public static final String INIT_SMS_CODE="00000000"; /** * * @param sessionId * @param userName * @param pwd * @return */ @ProblemCode public Gcuser login(String sessionId,String userName,String pwd,String ip){ /** * checkindex.asp * Dim allName allName=ygid Call CalculateQ(allName,ygid) Function CalculateQ(allName,userName) set rs_Calculate = Server.CreateObject("ADODB.Recordset") sql_Calculate = "SELECT * FROM gcuser where username = '"&userName&"'" rs_Calculate.open sql_Calculate,conn2,1,1 If rs_Calculate.eof Or rs_Calculate.bof Then rs_Calculate.close() 'Response.write "<br>" Exit Function End If if rs_Calculate("username")=userName Then if rs_Calculate("vip")>0 Then allName=rs_Calculate("username") Exit Function End if Call CalculateQ(allName,rs_Calculate("up")) rs_Calculate.close() Else rs_Calculate.close() 'Response.write "<br>" Exit Function' End if End Function <% response.cookies("regid")=rs_login("username") response.cookies("password")=rs_login("password") ygid=request.cookies("regid") ygpa=request.cookies("password") rs_login("vipname")=allName rs_login("logtime")=Now() rs_login.update rs_login.close conn2.close set conn2=nothing response.redirect "/vgo/vipdl.asp?dl="&ygid&"&pa="&ygpa&"" 'response.redirect "manager.asp" %> */ userName = userName.toLowerCase(); Gcuser gcUser = gcuserDao.getUser(userName); String md5pass = MD5Security.md5_16(pwd).toLowerCase(); if(gcUser!=null && gcUser.getPassword().equals(md5pass)){ userSession.put(sessionId, gcUser.getUsername()); gcuserDao.updateLoginTime(userName); this.addUserDateIpLog(userName, "", ip); return gcUser; } return null; } /** * * @param sessionId * @param id * @param pa * @param ip * @return */ public Gcuser loginByManager(String sessionId,String id,String pa,String ip){ Gcuser gcUser = gcuserDao.getUser(id); if(gcUser!=null && gcUser.getPassword().equals(pa)){ userSession.put(sessionId, gcUser.getUsername()); // gcuserDao.updateLoginTime(id); // this.addUserDateIpLog(id, "", ip); return gcUser; } return null; } /** * * @param loginUserName * @param sessionId */ public void relogin(String loginUserName,String sessionId,String ip){ String userName = userSession.getIfPresent(sessionId); userSession.invalidate(sessionId); Gcuser beforUser = gcuserDao.getUser(userName); Gcuser afterUser = gcuserDao.getUser(loginUserName); if(!beforUser.getUserid().equals(afterUser.getUserid())||!beforUser.getName().equals(afterUser.getName())){ throw new ServiceException(3000, ""); } userSession.put(sessionId, loginUserName); gcuserDao.updateLoginTime(loginUserName); this.addUserDateIpLog(loginUserName, "", ip); //vip try { resetVip(loginUserName); } catch (Exception e) { LogSystem.error(e, "vip!~~~"); } } /** * * @param sessionId * @return */ public boolean logout(String sessionId){ String userName = userSession.getIfPresent(sessionId); if(userName!=null){ userSession.invalidate(sessionId);; return dateipDao.updateLogout(userName); } return true; } public int checkNameAndIdCardAndUpUser(String ggname,String gguserid,String upvip,int lan){ if(!Strings.isNullOrEmpty(upvip)&&getUserByUserName(upvip)==null){ return 2; } if(lan==0&&!IDCardUtils.IDCardValidate(gguserid).equals("")){ return 4; } if(isForbidNameOrID(ggname, gguserid)){ return 5; } List<Gcuser> list = getUserByIdCard(gguserid); if(list!=null&&list.size()>0){ return 3;// ["&request.Form("ggname")&"]["&Request.Form("gguserid")&"]-[]-[] } return 0; } /** * * @param gguser * @param upvip * @param ggname * @param gguserid * @param ggpa1 * @param ggpa3 * @param ggbank * @param ggcard * @param ggcall * @param ggqq * @param provinceName * @param cityName * @param areaName * @return */ public int reg(String gguser,String upvip,String ggname,String gguserid,String ggpa1,String ggpa3,String ggbank,String ggcard,String ggcall,String ggqq,String provinceName,String cityName,String areaName,int lan){ gguser = gguser.trim(); ggname = ggname.trim(); if(getUserByUserName(gguser)!=null){ return 1; } if (Strings.isNullOrEmpty(gguser)|| Strings.isNullOrEmpty(ggname) || Strings.isNullOrEmpty(gguserid) || Strings.isNullOrEmpty(ggpa1) || Strings.isNullOrEmpty(ggpa3) || Strings.isNullOrEmpty(ggbank) || Strings.isNullOrEmpty(ggcard) || Strings.isNullOrEmpty(ggcall) || Strings.isNullOrEmpty(ggqq)) { return 1; } if(!Strings.isNullOrEmpty(upvip)&&getUserByUserName(upvip)==null){ return 2; } List<Gcuser> list = getUserByIdCard(gguserid); if(list!=null&&list.size()>0){ return 3;// ["&request.Form("ggname")&"]["&Request.Form("gguserid")&"]-[]-[] } if(lan==0&&!IDCardUtils.IDCardValidate(gguserid).equals("")){ return 4; } if(isForbidNameOrID(ggname, gguserid)){ return 5; } if(Strings.isNullOrEmpty(provinceName)||provinceName.equals("0")||Strings.isNullOrEmpty(cityName)||cityName.equals("0")||Strings.isNullOrEmpty(areaName)||areaName.equals("0")){ return 6; } Province province = provinceDao.getProvinceByB(provinceName); Gcuser user = new Gcuser(); user.setUsername(gguser); user.setPassword(MD5Security.md5_16(ggpa1).toLowerCase()); user.setPassword3(ggpa3); user.setName(ggname); user.setBank(ggbank); user.setCard(ggcard); user.setCall(ggcall); user.setQq(ggqq); user.setUp(upvip); user.setUserid(gguserid); user.setAddsheng(provinceName); user.setAddshi(cityName); user.setAddqu(areaName); user.setCxt(5); user.setRegtime(new Date()); if(lan!=0){ user.setGwuid(1); } if(province!=null){ user.setAddqu(province.getAreaNum()); user.setAdd9dqu(province.getAreaName()); } if(!gcuserDao.addUser(user)){ return 7; } Txifok txifok = new Txifok(); txifok.setUsername(gguser); txifok.setUp(upvip); txifok.setPassword3(ggpa3); txifok.setName(ggname); txifok.setCall(ggcall); txifokDao.add(txifok); return 0; } /** * * @param newUserName * @param oldUserName */ public void regTheSameUser(String newUserName,String oldUserName){ newUserName = newUserName.trim(); if(gcuserDao.getUser(newUserName)!=null){ throw new ServiceException(1, ""); } if(Strings.isNullOrEmpty(newUserName)){ throw new ServiceException(1, ""); } Gcuser oldUser = gcuserDao.getUser(oldUserName); Gcuser user = new Gcuser(); user.setUsername(newUserName); user.setPassword(oldUser.getPassword()); user.setPassword3(oldUser.getPassword3()); user.setName(oldUser.getName()); user.setBank(oldUser.getBank()); user.setCard(oldUser.getCard()); user.setCall(oldUser.getCall()); user.setQq(oldUser.getQq()); user.setUp(oldUserName); user.setUserid(oldUser.getUserid()); user.setAddsheng(oldUser.getAddsheng()); user.setAddshi(oldUser.getAddshi()); user.setAddqu(oldUser.getAddqu()); user.setRegtime(new Date()); user.setAddqu(oldUser.getAddqu()); user.setAdd9dqu(oldUser.getAdd9dqu()); gcuserDao.addUser(user); Txifok txifok = new Txifok(); txifok.setUsername(newUserName); txifok.setUp(oldUserName); txifok.setPassword3(user.getPassword3()); txifok.setName(user.getName()); txifok.setCall(user.getCall()); txifokDao.add(txifok); } /** * * @param userName * @param idCard * @param password * @param password3 * @param ganew * @param qq * @param call * @return */ public boolean updateUser(String userName,String name, String idCard, String password, String password3, int ganew, String qq,String call,String ip){ boolean result = gcuserDao.updateUser(name, idCard, password, password3, ganew, qq, call); if(result){ addUserDateIpLog(userName, "", ip); } gcuserDao.updateSmsCode(userName, INIT_SMS_CODE); return result; } public boolean updateUser(String userName,String name, String idCard, String password, String card, String bank,String addsheng,String addshi,String addqu,String ip){ boolean result = gcuserDao.updateUser(name, idCard, password, card, bank, addsheng, addshi, addqu); if(result){ addUserDateIpLog(userName, "", ip); } return result; } public boolean updateUser(String userName,String jdName,String jcUserId){ return gcuserDao.updateUser(userName, jdName, jcUserId); } /** * * @param userName * @return */ public Gcuser getUserByUserName(String userName){ return gcuserDao.getUser(userName); } /** * * @param name * @param idNum * @return */ public List<Gcuser> getUserByIdCard(String idNum){ return gcuserDao.getUserByIdCard(idNum); } /** * * @param name * @param idNum * @return */ public boolean isForbidNameOrID(String name,String idNum){ if(tduserDao.get(name, idNum)!=null){ return true; } return false; } /** * * @param userName * @param desc * @param ip * @return */ public boolean addUserDateIpLog(String userName,String desc,String ip){ return dateipDao.addDateIpLog(userName, desc, ip); } /** * * @param name * @param idCard * @param pageIndex * @param pageSize * @return */ public IPage<Gcuser> getTheSameNameUserPage(String name,String idCard,int pageIndex,int pageSize){ return gcuserDao.getUserPage(name, idCard, pageIndex, pageSize); } /** * * @param name * @param idCard * @param pageIndex * @param pageSize * @return */ public IPage<Gcuser> getTheSameNameUserPageByCondition(String userName,String name,String idCard,int pageIndex,int pageSize){ return gcuserDao.getUserPageByCondition(userName,name, idCard, pageIndex, pageSize); } /** * yb * @param username * @param changeNum * @return */ public boolean changeYb(String username,int changeNum,String desc,int newzBz,Integer kjqi){ boolean result = false; if(changeNum<0){ result = gcuserDao.reduceYb(username, changeNum*-1); if(result){ Gcuser gcuser = gcuserDao.getUser(username); Datepay datePay = new Datepay(); datePay.setUsername(username); datePay.setJc(changeNum*-1); datePay.setPay(gcuser.getPay()); datePay.setJydb(gcuser.getJydb()); datePay.setRegid(desc); datePay.setNewbz(newzBz); if(kjqi!=null){ datePay.setKjqi(kjqi); } datePay.setAbdate(new Date()); logService.addDatePay(datePay); } return result; }else if(changeNum>0){ result = gcuserDao.addYb(username, changeNum); if(result){ Gcuser gcuser = gcuserDao.getUser(username); Datepay datePay = new Datepay(); datePay.setUsername(gcuser.getUsername()); datePay.setSyjz(changeNum); datePay.setPay(gcuser.getPay()); datePay.setJydb(gcuser.getJydb()); datePay.setRegid(desc); datePay.setNewbz(newzBz); datePay.setAbdate(new Date()); logService.addDatePay(datePay); } return result; } return true; } /** * * @param username * @param changeNum * @param desc * @param newzBz * @param kjqi * @return */ public boolean changeYbCanFu(String username,int changeNum,String desc,int newzBz,Integer kjqi){ boolean result = false; if(changeNum<0){ result = gcuserDao.reduceYbCanFu(username, changeNum*-1); if(result){ Gcuser gcuser = gcuserDao.getUser(username); Datepay datePay = new Datepay(); datePay.setUsername(username); datePay.setJc(changeNum*-1); datePay.setPay(gcuser.getPay()); datePay.setJydb(gcuser.getJydb()); datePay.setRegid(desc); datePay.setNewbz(newzBz); if(kjqi!=null){ datePay.setKjqi(kjqi); } datePay.setAbdate(new Date()); logService.addDatePay(datePay); } return result; }else if(changeNum>0){ result = gcuserDao.addYb(username, changeNum); if(result){ Gcuser gcuser = gcuserDao.getUser(username); Datepay datePay = new Datepay(); datePay.setUsername(gcuser.getUsername()); datePay.setSyjz(changeNum); datePay.setPay(gcuser.getPay()); datePay.setJydb(gcuser.getJydb()); datePay.setRegid(desc); datePay.setNewbz(newzBz); datePay.setAbdate(new Date()); logService.addDatePay(datePay); } return result; } return true; } public ZuoMingxi getZuoMingxi(String tjuser,String down){ return zuoMingxiDao.get(tjuser, down); } public ZuoMingxi getZuoMingxi(String down){ return zuoMingxiDao.get(down); } public YouMingxi getYouMingxi(String tjuser,String down){ return youMingXiDao.get(tjuser, down); } public YouMingxi getYouMingxi(String down){ return youMingXiDao.get(down); } public Sgxt getSgxt(String username){ return sgxtDao.get(username); } public Sgxt getSgxtByAorBuid(String uid){ return sgxtDao.getByAOrBuid(uid); } public int getSumSjb(String name,String idNum){ return gcuserDao.getSumSjb(name, idNum); } /** * * @param userName id * @param up id * @param bduser id * @param cjpay * @param pa1j * @param pa2j * @param idCardNum * @param status 0 1 * @return */ @Transactional public synchronized String bdReg(String userName,String up,String bduser,int cjpay,String pa1j,String pa2j,String idCardNum,int status){ ManagerService managerService = ServiceCacheFactory.getServiceCache().getService(ManagerService.class); Fcxt fcxt = managerService.getFcxtById(2); if(fcxt!=null){ Date date = fcxt.getJsdate(); if(date!=null&&new Date().getTime()>date.getTime()){ throw new ServiceException(1,""); // super.setErroCodeNum(1);//alert('');;history.go(-1); // return SUCCESS; } } if(cjpay<1000){ throw new ServiceException(2,""); // super.setErroCodeNum(2);//alert('');history.go(-1); // return SUCCESS; } Gcuser operatorUser = gcuserDao.getUser(userName); if(!MD5Security.md5_16(pa1j).equals(operatorUser.getPassword())){ throw new ServiceException(3,""); // super.setErroCodeNum(3);//alert('');history.go(-1); // return SUCCESS; } if(!pa2j.equals(operatorUser.getPassword3())){ throw new ServiceException(4,""); // super.setErroCodeNum(4);//alert('');history.go(-1); // return SUCCESS; } if(operatorUser.getSjb()==0){ throw new ServiceException(5,""); // super.setErroCodeNum(5);//alert('');history.go(-1); // return SUCCESS; } if(cjpay>9000 && operatorUser.getSybdb()<cjpay){ throw new ServiceException(6,""+cjpay+""); // super.setErroCodeNum(6);//alert('"&cjpay&"');history.go(-1); // return SUCCESS; } if(cjpay<9000 && operatorUser.getPay()<cjpay){ throw new ServiceException(7,""+cjpay+""); // super.setErroCodeNum(7);//alert('"&cjpay&"');history.go(-1); // return SUCCESS; } int callLenght = operatorUser.getCall().length(); String callLeft = operatorUser.getCall().substring(0, 3); String CallRight = operatorUser.getCall().substring(callLenght-3, callLenght); String call = callLeft+"*****"+CallRight; UserService userService = ServiceCacheFactory.getServiceCache().getService(UserService.class); Gcuser bdGUser = gcuserDao.getUser(bduser); Fcxt fcxt2 = managerService.getFcxtById(10); if(bdGUser==null){ throw new ServiceException(8,""); // super.setErroCodeNum(8);//alert('');history.go(-1); // return SUCCESS; }else if(bdGUser.getRegtime().getTime()<fcxt2.getJsdate().getTime()){ throw new ServiceException(9,""); // super.setErroCodeNum(9);//alert('');history.go(-1); // return SUCCESS; } if(cjpay>49980){ int sumSjb = userService.getSumSjb(bdGUser.getName(), bdGUser.getUserid()); if(sumSjb>298){ throw new ServiceException(10,"535"); // super.setErroCodeNum(10);//alert('535');history.go(-1); // return SUCCESS; } } if(userService.getZuoMingxi(bduser)!=null||userService.getYouMingxi(bduser)!=null){ throw new ServiceException(11,""); // super.setErroCodeNum(11);//alert('');history.go(-1); // return SUCCESS; } if(userService.getSgxtByAorBuid(bduser)!=null){ throw new ServiceException(12,""); // super.setErroCodeNum(12);//alert('');history.go(-1); // return SUCCESS; }else if(!bduser.equals(operatorUser.getUsername())&&!bdGUser.getUp().equals(operatorUser.getUsername())){ throw new ServiceException(13,""); // super.setErroCodeNum(13);//alert('');history.go(-1); // return SUCCESS; } Sgxt tuser = userService.getSgxt(up); if(tuser==null){ throw new ServiceException(14,""); // super.setErroCodeNum(14);//alert('');history.go(-1); // return SUCCESS; }else{ if(!Strings.isNullOrEmpty(tuser.getAuid())&&!Strings.isNullOrEmpty(tuser.getBuid())){ throw new ServiceException(15,""); // super.setErroCodeNum(15);//alert('');history.go(-1); // return SUCCESS; } } if(status!=0){ int zjjb=0; int sjb=0; int fd=0; int cfd=0; String msg = cjpay+""; if(cjpay==500){ zjjb=200; sjb=1; fd=2000; cfd=20; msg = msg+"()"; }else if(cjpay==1000){ zjjb=450; sjb=2; fd=4000; cfd=40 ; msg = msg+"()"; }else if(cjpay==2000){ zjjb=960; sjb=4; fd=8000; cfd=60 ; msg = msg+"()"; }else if(cjpay==5000){ zjjb=2500; sjb=10; fd=20000; cfd=80; msg = msg+"()"; }else if(cjpay==10000){ zjjb=5000; sjb=20; fd=40000; cfd=100 ; msg = msg+"()"; }else if(cjpay==20000){ zjjb=11000; sjb=40; fd=80000; cfd=150 ; msg = msg+"()"; }else if(cjpay==50000){ zjjb=30000; sjb=100; fd=200000; cfd=200 ; msg = msg+"()"; } if(cjpay>=9000){ if(!updateSybdb(userName, -cjpay, ""+bduser+""+cjpay)){ throw new ServiceException(6,""+cjpay+""); } }else{ if(idCardNum==null||!idCardNum.equals(operatorUser.getVipsq())){ throw new ServiceException(16,""); // super.setErroCodeNum(16);//alert('');history.go(-1); // return SUCCESS; } gcuserDao.updateSmsCode(operatorUser.getUsername(), INIT_SMS_CODE); if(!this.changeYb(userName, -cjpay, ""+bduser+""+cjpay, 0,null)){ throw new ServiceException(7,""+cjpay+""); } } gcuserDao.updateSjb(bduser, sjb); updateJB(bduser,zjjb,""+cjpay+""+zjjb+"-"+userName+""); if(Strings.isNullOrEmpty(tuser.getAuid())){ sgxtDao.updateAuid(tuser.getUsername(), bduser); }else{ sgxtDao.updateBuid(tuser.getUsername(), bduser); } // int jszfh=0; int jsnew = 0; // double fhbl = 0; if(sjb>10){ // jszfh=sjb*250; jsnew=3; // fhbl=0.005; }else{ // jszfh=0; jsnew=0; // fhbl=0; } Sgxt sgxt = new Sgxt(); sgxt.setUsername(bduser); sgxt.setSjb(sjb); sgxt.setXxnew(jsnew); sgxt.setFdpay(fd); sgxt.setCfd(cfd); sgxt.setBddate(new Date()); sgxtDao.add(sgxt); int upPay = (int)(0.1*cjpay); gcuserDao.addOtherYb(userName,upPay); Gcuser upuser = gcuserDao.getUser(userName); Datepay datePay = new Datepay(); datePay.setUsername(userName); datePay.setRegid(""+bduser+""+cjpay+""); datePay.setSyjz(upPay); datePay.setPay(upuser.getPay()); datePay.setJydb(upuser.getJydb()); datePay.setNewbz(9); datePay.setAbdate(new Date()); logService.addDatePay(datePay); int zysjb = sgxt.getSjb(); List<ZuoMingxi> zTList = Lists.newArrayList(); List<YouMingxi> yTList = Lists.newArrayList(); cupUser(bduser,bduser,1,zysjb,zTList,yTList); if(zTList.size()>0){ zuoMingxiDao.batchInsert(zTList); } if(yTList.size()>0){ youMingXiDao.batchInsert(yTList); } List<ZuoMingxi> zList = zuoMingxiDao.getDownList(bduser); if(zList!=null&&!zList.isEmpty()){ for(ZuoMingxi zuoMingxi:zList){ int sjtjzb = zuoMingxiDao.getSumSjb(zuoMingxi.getTjuser(), zuoMingxi.getCount()); if(sjtjzb>0){ if(zuoMingxi.getCount()>0&&zuoMingxi.getCount()<=16){ sgxtDao.updateZfiled(zuoMingxi.getTjuser(), "z"+zuoMingxi.getCount(), sjtjzb,sjtjzb-sjb,zuoMingxi.getCount()); } } } } List<YouMingxi> yList = youMingXiDao.getDownList(bduser); if(yList!=null&&!yList.isEmpty()){ for(YouMingxi youMingxi:yList){ int sjtjzb = youMingXiDao.getSumSjb(youMingxi.getTjuser(), youMingxi.getCount()); if(sjtjzb>0){ if(youMingxi.getCount()>0&&youMingxi.getCount()<=16){ sgxtDao.updateYfiled(youMingxi.getTjuser(), "y"+youMingxi.getCount(), sjtjzb,sjtjzb-sjb,youMingxi.getCount()); } } } } List<Bdbdate> logList = Lists.newArrayList(); CalculateQ(bduser,sjb,bduser,logList); bdbDateDao.batchInsert(logList); this.sendBdSmsMsg(bduser, msg); } return call; } public void CalculateQ(String userName,int sjb,String bduser,List<Bdbdate> logList){ Sgxt sgxtBd = sgxtDao.getByAOrBuid(userName); if(sgxtBd==null){ return; } if(sgxtBd.getAuid().equals(userName)){ sgxtDao.updateZaq(sgxtBd.getUsername(), sjb); ZuoMingxi zuo = zuoMingxiDao.get(sgxtBd.getUsername(), bduser); int dqzuo = zuoMingxiDao.getSumSjb(sgxtBd.getUsername(), zuo.getCount())-sjb; int zyzj = 0; if(dqzuo<sgxtBd.getCfd()){ zyzj = sgxtBd.getCfd()-dqzuo; int addAmount = sjb; if(addAmount>zyzj){ addAmount = zyzj; } sgxtDao.updateAq(sgxtBd.getUsername(), addAmount); sgxtBd = sgxtDao.get(sgxtBd.getUsername()); Bdbdate bdbdate = new Bdbdate(); bdbdate.setZuser(sgxtBd.getUsername()); bdbdate.setZaq(sgxtBd.getZaq()); bdbdate.setZbq(sgxtBd.getZbq()); bdbdate.setAq(sgxtBd.getAq()); bdbdate.setBq(sgxtBd.getBq()); if(sjb>zyzj){ bdbdate.setBz(""+bduser+"("+sjb+")"+zuo.getCount()+"()-"+(sjb-zyzj)); }else{ bdbdate.setBz(""+bduser+"("+sjb+")"+zuo.getCount()+"()-"+sjb); } // bdbDateDao.add(bdbdate); logList.add(bdbdate); }else{ sgxtBd = sgxtDao.get(sgxtBd.getUsername()); Bdbdate bdbdate = new Bdbdate(); bdbdate.setZuser(sgxtBd.getUsername()); bdbdate.setZaq(sgxtBd.getZaq()); bdbdate.setZbq(sgxtBd.getZbq()); bdbdate.setAq(sgxtBd.getAq()); bdbdate.setBq(sgxtBd.getBq()); bdbdate.setBz(""+bduser+"("+sjb+")"+zuo.getCount()+"("+dqzuo+")-"); // bdbDateDao.add(bdbdate); logList.add(bdbdate); } CalculateQ(sgxtBd.getUsername(),sjb,bduser,logList); }else if(sgxtBd.getBuid().equals(userName)){ sgxtDao.updateZbq(sgxtBd.getUsername(), sjb); YouMingxi you = youMingXiDao.get(sgxtBd.getUsername(), bduser); int dqyou = youMingXiDao.getSumSjb(sgxtBd.getUsername(), you.getCount())-sjb; if(dqyou<sgxtBd.getCfd()){ int yyzj=sgxtBd.getCfd()-dqyou; int addAmount = sjb; if(sjb>yyzj){ addAmount = yyzj; } sgxtDao.updateBq(sgxtBd.getUsername(), addAmount); sgxtBd = sgxtDao.get(sgxtBd.getUsername()); Bdbdate bdbdate = new Bdbdate(); bdbdate.setZuser(sgxtBd.getUsername()); bdbdate.setZaq(sgxtBd.getZaq()); bdbdate.setZbq(sgxtBd.getZbq()); bdbdate.setAq(sgxtBd.getAq()); bdbdate.setBq(sgxtBd.getBq()); if(sjb>yyzj){ bdbdate.setBz(""+bduser+"("+sjb+")"+you.getCount()+"()-"+(sjb-yyzj)); }else{ bdbdate.setBz(""+bduser+"("+sjb+")"+you.getCount()+"()-"+sjb); } // bdbDateDao.add(bdbdate); logList.add(bdbdate); }else{ sgxtBd = sgxtDao.get(sgxtBd.getUsername()); Bdbdate bdbdate = new Bdbdate(); bdbdate.setZuser(sgxtBd.getUsername()); bdbdate.setZaq(sgxtBd.getZaq()); bdbdate.setZbq(sgxtBd.getZbq()); bdbdate.setAq(sgxtBd.getAq()); bdbdate.setBq(sgxtBd.getBq()); bdbdate.setBz(""+bduser+"("+sjb+")"+you.getCount()+"("+dqyou+")-"); // bdbDateDao.add(bdbdate); logList.add(bdbdate); } CalculateQ(sgxtBd.getUsername(),sjb,bduser,logList); } } private void cupUser(String userName,String constantUp,int count,int sjb,List<ZuoMingxi> zList,List<YouMingxi> yList){ Sgxt sgxtBd = sgxtDao.getByAOrBuid(userName); if(sgxtBd!=null){ if(userName.equals(sgxtBd.getAuid())){ ZuoMingxi zuoMingxi = new ZuoMingxi(); zuoMingxi.setTjuser(sgxtBd.getUsername()); zuoMingxi.setSjb(sjb); zuoMingxi.setDown(constantUp); zuoMingxi.setCount(count); //zuoMingxiDao.add(zuoMingxi); zList.add(zuoMingxi); }else{ YouMingxi youMingxi = new YouMingxi(); youMingxi.setCount(count); youMingxi.setDown(constantUp); youMingxi.setTjuser(sgxtBd.getUsername()); youMingxi.setSjb(sjb); // youMingXiDao.add(youMingxi); yList.add(youMingxi); } count = count+1; cupUser(sgxtBd.getUsername(),constantUp,count,sjb,zList,yList); } } /** * * @param userName * @param changeNum * @param desc * @return */ public boolean updateSybdb(String userName,int changeNum,String desc){ if(changeNum>=0){ boolean result = gcuserDao.addSybdb(userName, changeNum); if(result){ Gcuser gcuser = gcuserDao.getUser(userName); Bdbdate bdbdate = new Bdbdate(); bdbdate.setZuser(userName); bdbdate.setBz(desc); bdbdate.setSy(changeNum); bdbdate.setSybdb(gcuser.getSybdb()); bdbdate.setLjbdb(gcuser.getLjbdb()); bdbDateDao.add(bdbdate); } return result; }else{ changeNum = Math.abs(changeNum); boolean result = gcuserDao.reduceSybdb(userName, changeNum); if(result){ Gcuser gcuser = gcuserDao.getUser(userName); Bdbdate bdbdate = new Bdbdate(); bdbdate.setZuser(userName); bdbdate.setBz(desc); bdbdate.setJc(changeNum); bdbdate.setSybdb(gcuser.getSybdb()); bdbdate.setLjbdb(gcuser.getLjbdb()); bdbDateDao.add(bdbdate); } return result; } } /** * * @param userName * @param sjb * @param jydb * @param desc * @return */ public boolean updateJB(String userName,int jydb,String desc){ boolean result = gcuserDao.updateJB(userName, jydb); if(result){ Gcuser gcuser = gcuserDao.getUser(userName); Datepay datePay = new Datepay(); datePay.setUsername(userName); datePay.setJyjz(jydb); datePay.setJydb(gcuser.getJydb()); datePay.setRegid(desc); datePay.setPay(gcuser.getPay()); datePay.setNewbz(0); datePay.setAbdate(new Date()); logService.addDatePay(datePay); } return result; } /** * * @param userName * @param pageIndex * @param pageSize * @return */ public IPage<Gcuser> getMyDownUserPage(String userName,int pageIndex,int pageSize){ return gcuserDao.getMyDownUserPage(userName, pageIndex, pageSize); } /** * * @param fromUser * @param toUser * @param amount */ @Transactional public void trasferBdb(String fromUser,String toUser,int amount,String password3){ Gcuser from = gcuserDao.getUser(fromUser); if(from.getVip()==0){ throw new ServiceException(1, "vip"); } if(!from.getPassword3().equals(password3)){ throw new ServiceException(2, ""); } if(fromUser.equals(toUser)){ throw new ServiceException(3, ""); } if(!fromUser.equals("300fhk")){ if(zuoMingxiDao.get(fromUser, toUser)==null&&youMingXiDao.get(fromUser, toUser)==null){ throw new ServiceException(4, ""); } } if(amount<=0){ throw new ServiceException(5, "0"); } if(from.getSybdb()<amount){ throw new ServiceException(6, " "+from.getSybdb()+" "); } Gcuser to = gcuserDao.getUser(toUser); if(to==null){ throw new ServiceException(7, ""); } if(!this.updateSybdb(fromUser, -amount, "-"+toUser)){ throw new ServiceException(6, " "+from.getSybdb()+" "); } this.updateSybdb(toUser, amount, "-"+fromUser.substring(0,2)+"***"); vipxtgcDao.updateJcBdb(fromUser, DateUtils.getDate(new Date()), amount); } /** * * @param fromUser * @param toUser * @param amount */ @Transactional public void trasferBdbByAdmin(String fromUser,String toUser,int amount){ Gcuser from = gcuserDao.getUser(fromUser); if(from==null){ throw new ServiceException(5, ""); } if(fromUser.equals(toUser)){ throw new ServiceException(1, ""); } if(amount<=0){ throw new ServiceException(2, "0"); } if(from.getSybdb()<amount){ throw new ServiceException(3, " "+from.getSybdb()+" "); } Gcuser to = gcuserDao.getUser(toUser); if(to==null){ throw new ServiceException(4, ""); } if(!this.updateSybdb(fromUser, -amount, "-"+toUser)){ throw new ServiceException(3, " "+from.getSybdb()+" "); } this.updateSybdb(toUser, amount, "-"+fromUser); } @Transactional public void trasferYbForPresent(String fromUser,String toUser,String pa,String pa3,int amount){ Gcuser fUser = gcuserDao.getUser(fromUser); Gcuser tUser = gcuserDao.getUser(toUser); if(fUser==null){ throw new ServiceException(5, ""); } if(tUser==null){ throw new ServiceException(6, ""); } if(!fUser.getPassword().equals(MD5Security.md5_16(pa))){ throw new ServiceException(1, ""); } if(!fUser.getPassword3().equals(pa3)){ throw new ServiceException(2, ""); } if(amount<=0){ throw new ServiceException(3, "0"); } if(amount<100){ throw new ServiceException(4, "100"); } if(!this.changeYb(fromUser, -amount, "", 14,null)){ throw new ServiceException(100, "Yb"); } if(!gcuserDao.addWhenOtherPersionBuyJbCard(toUser, amount)){ throw new ServiceException(7, ""); } Datepay datePay = new Datepay(); datePay.setUsername(toUser); datePay.setSyjz(amount); datePay.setPay(tUser.getPay()+amount); datePay.setJydb(tUser.getJydb()); datePay.setRegid("-"+fromUser); datePay.setNewbz(14); datePay.setAbdate(new Date()); logService.addDatePay(datePay); } /** * yb * @param fromUser * @param toUser * @param amount */ private void trasferYb(String fromUser,String toUser,int amount){ if(!this.changeYb(fromUser, -amount, "-"+toUser, 6,null)){ throw new ServiceException(100, "Yb"); } this.changeYb(toUser, amount, "-"+fromUser, 6,null); } /** * * @param fromUsers * @param toUser * @param password3 */ @Transactional public void batchTrasferYb(List<String> fromUsers,String toUser,String password3){ Gcuser gcuser = gcuserDao.getUser(toUser); if(!gcuser.getPassword3().equals(password3)){ throw new ServiceException(1, ""); } if(gcuser.getPayok()==10){ throw new ServiceException(2, ""); } if(gcuser.getJygt1()==2 || gcuser.getDbt1()==2){ throw new ServiceException(3, ""); } if(gcuser.getSjb()==0){ throw new ServiceException(7, ""); } for(String fromUser: fromUsers){ Gcuser user = gcuserDao.getUser(fromUser); if(user==null){ throw new ServiceException(4, ""); } if(!gcuser.getName().equals(user.getName())||!gcuser.getUserid().trim().toLowerCase().equals(user.getUserid().trim().toLowerCase())){ throw new ServiceException(5, ",,from name=["+user.getName()+"]userid=["+user.getUserid().toLowerCase()+"],to name=["+gcuser.getName()+"],userId=["+gcuser.getUserid().toLowerCase()+"],=["+(gcuser.getName().equals(user.getName()))+"],=["+(gcuser.getUserid().toLowerCase().equals(user.getUserid().toLowerCase()))+"]"); } if(user.getPay()>0&&!fromUser.equals(toUser)){ trasferYb(fromUser,toUser,user.getPay()); } } } private static final String[] ARRAY_DESC = new String[]{""," ","",""}; public void guessYb(String userName,int type,int ybNum){ Gcuser gcuser = gcuserDao.getUser(userName); if(gcuser.getPay()==0 || gcuser.getPay()<10 || ybNum>gcuser.getPay()){ throw new ServiceException(1,""); } Epkjdate epkjdate = managerService.getEpkjdateBz0(); if(!this.changeYb(userName, -ybNum, ""+ARRAY_DESC[type-1], 0,epkjdate.getKid())){ throw new ServiceException(1,""); } if(type==1){ managerService.updateEpkjdateBz0(ybNum, 0, 0, 0); }else if(type==2){ managerService.updateEpkjdateBz0(0, ybNum, 0, 0); }else if(type==3){ managerService.updateEpkjdateBz0(0, 0, ybNum, 0); }else if(type==4){ managerService.updateEpkjdateBz0(0, 0, 0, ybNum); } eptzbDao.updateSumGuessByType(userName, type, ybNum); } public void guessJf(String userName,int type,int jfNum){ Gcuser gcuser = gcuserDao.getUser(userName); if(gcuser.getJyg()==0 || gcuser.getJyg()<10 || jfNum>gcuser.getJyg()){ throw new ServiceException(1,""); } Jfkjdate epkjdate = managerService.getJfkjdateBz0(); if(!gcuserDao.updateJyg(userName, jfNum)){ throw new ServiceException(1, ""); } Gpjy gpjy = new Gpjy(); gpjy.setUsername(userName); gpjy.setMcsl(Double.valueOf(jfNum)); gpjy.setSysl(Double.valueOf(gcuser.getJyg()-jfNum)); gpjy.setBz("-"+ARRAY_DESC[type-1]); gpjy.setKjqi(epkjdate.getKid()); gpjy.setCgdate(new Date()); gpjy.setJy(1); gpjy.setAbdate(new Date()); gpjyDao.add(gpjy); if(type==1){ managerService.updateEpkjdateBz0(jfNum, 0, 0, 0); }else if(type==2){ managerService.updateEpkjdateBz0(0, jfNum, 0, 0); }else if(type==3){ managerService.updateEpkjdateBz0(0, 0, jfNum, 0); }else if(type==4){ managerService.updateEpkjdateBz0(0, 0, 0, jfNum); } jftzbDao.updateSumGuessByType(userName, type, jfNum); } @Transactional public int yqQg(String userName,int goodsId,int buyNum,int price){ Gcuser gcuser = gcuserDao.getUser(userName); if(gcuser.getPay()==0 || price*buyNum>gcuser.getPay()){ throw new ServiceException(1,""); } boolean result = jfcpDao.update(goodsId, buyNum); if(!result){ throw new ServiceException(2,""); } Jfcp jfcp =jfcpDao.get(goodsId); if(!this.changeYb(userName, -price*buyNum, "-"+jfcp.getCpmq(), 0, null)){ throw new ServiceException(1,""); } if(jfcp.getDqep()==10||jfcp.getDqep()<21&&jfcp.getCglist()!=0){ if(!jfcpDao.updateDqepAndCglist(goodsId, buyNum)){ throw new ServiceException(3000,""); } } jfcp =jfcpDao.get(goodsId); if(jfcp.getDqep()==0||jfcp.getDqep()<0&&jfcp.getCglist()==0){ Cpuser cpuser = new Cpuser(); cpuser.setCguser(userName); cpuser.setCpmq("-"+jfcp.getCpmq()); cpuser.setJydate(new Date()); cpuser.setJyjf(jfcp.getZepsl()); cpuser.setJyname(gcuser.getName()); cpuser.setJyqq(gcuser.getQq()); cpuser.setJycall(gcuser.getCall()); cpuserDao.add(cpuser); Datepay datepay = new Datepay(); datepay.setUsername(userName); datepay.setRegid(""+jfcp.getCpmq()); datepay.setPay(gcuser.getPay()-buyNum*price); datepay.setJydb(gcuser.getJydb()); if(!jfcpDao.updateDqepOrCglistOrJysl(goodsId)){ throw new ServiceException(3000,""); } }else{ //throw new ServiceException(3,""+jfcp.getDqep()+""); return jfcp.getDqep(); } return -1; } /** * * @param userName * @param password3 * @param saleNum * @param smsCode * @param ip */ @Transactional public void saleYb(String userName,String password3,int saleNum,String smsCode,String ip){ if(saleNum<100){ throw new ServiceException(1,""); } Gcuser gcuser = this.gcuserDao.getUser(userName); int txqpay = gcuser.getPay(); Fcxt fcxt = managerService.getFcxtById(10); if(saleNum>gcuser.getPay()){ throw new ServiceException(2," "+gcuser.getPay()+" "); } if(saleNum>gcuser.getPay()-gcuser.getVippay() && gcuser.getRegtime().getTime()>fcxt.getJsdate().getTime()){ throw new ServiceException(3," "+gcuser.getVippay()+"-[][]"); } if(!password3.equals(gcuser.getPassword3())){ throw new ServiceException(4,""); } if(gcuser.getGanew()!=0&&!gcuser.getVipsq().equals(smsCode)){ throw new ServiceException(5,""); } if(saleNum<100){ throw new ServiceException(6,"100"); } if(gcuser.getPayok()==1){ throw new ServiceException(7,""); } double tgpay9 = 0d; int tgpay09 = 0; if(saleNum<1000){ tgpay9 = saleNum*0.85; tgpay09 = (int)tgpay9; }else{ tgpay9 = saleNum*0.9; tgpay09 = (int)tgpay9; } if(!gcuserDao.saleYb(userName, saleNum)){ throw new ServiceException(2," "+gcuser.getPay()+" "); } gcuser = gcuserDao.getUser(userName); Datepay datePay = new Datepay(); datePay.setUsername(userName); datePay.setJc(saleNum); datePay.setPay(gcuser.getPay()); datePay.setJydb(gcuser.getJydb()); datePay.setRegid(""+tgpay09); datePay.setNewbz(3); datePay.setTxbz(1); datePay.setAbdate(new Date()); int datePayId = logService.addDatePay(datePay); // int datePayId = logService.getLasterInsertId(); Txpay txpay = txPayDao.get(); int jypay = 1; if(txpay!=null){ jypay = txpay.getPayid()+1; } Txpay txpay2 = new Txpay(); txpay2.setPayusername(userName); txpay2.setCxt(gcuser.getCxt()); txpay2.setPaynum(saleNum); txpay2.setPaynum9(tgpay09); txpay2.setPayname(gcuser.getName()); txpay2.setPaybank(gcuser.getBank()); txpay2.setPaycard(gcuser.getCard()); txpay2.setPayonoff(""); txpay2.setBankbz(txqpay+""); txpay2.setBz(gcuser.getPay()+""); txpay2.setDqu(gcuser.getDqu()); txpay2.setQlid(datePayId); txpay2.setPdid(11); txpay2.setJyid(jypay); txpay2.setVipname(gcuser.getVipname()); // txpay2.setTxvip(gcuser.getTxlb()); txpay2.setTxvip(1); Txifok txifOk = txifokDao.get(userName); if(txifOk!=null&&!Strings.isNullOrEmpty(txifOk.getName())&&txifOk.getName().equals(txpay2.getPayname())){ UserExtinfo userExtinfo = userExtinfoDao.get(userName); if(userExtinfo!=null&&userExtinfo.getNeedVerify()==1){ txpay2.setTxvip(0); } } txpay2.setTxip(ip); txPayDao.add(txpay2); gcuserDao.updatePayOk(gcuser.getName(), gcuser.getUserid(), 1); gcuserDao.updateSmsCode(userName, INIT_SMS_CODE); } /** * * @param fromUser * @param toUser * @param amount */ @Transactional public void mallBack(String fromUser,String toUser,String password3,int amount,String orderId,String yy){ if(!password3.equals("yc201503yc")){ throw new ServiceException(1, ""); } if(yy==null)yy=""; String regId=null; String sct = ""; if(!Strings.isNullOrEmpty(orderId)){ regId = "-"+orderId; sct="()"; Datepay datepay = datePayDao.getDatepayByUserNameAndRegid(toUser, regId); if(datepay!=null){ throw new ServiceException(2, ""); } }else{ if(fromUser.equals("300fhk")){ regId = "-300***"+"-"+yy; }else{ regId = "-"+fromUser+"-"+yy; } } Gcuser toGcUser = gcuserDao.getUser(toUser); if(toGcUser==null){ throw new ServiceException(3, ""); } if(fromUser.equals(toUser)){ throw new ServiceException(4, ""); } if(amount<0 || amount==0){ throw new ServiceException(5,""); } Gcuser gcuser = gcuserDao.getUser(fromUser); if(gcuser.getPay()<amount){ throw new ServiceException(6, " "+gcuser.getPay()+" "); } if(!this.changeYb(fromUser, -amount, ""+sct+"-"+toUser+"-"+yy, 13, null)){ throw new ServiceException(6, " "+gcuser.getPay()+" "); } if(!this.changeYb(toUser, amount, regId, 6, null)){ throw new ServiceException(3000, ""); } } /** * * @param fromUser * @param toUser * @param amount */ @Transactional public void trasferYbToOtherPersion(String fromUser,String toUser,String password3,int amount){ if(amount<0 || amount==0 || amount >100000){ throw new ServiceException(1,"100000"); } if(amount%100!=0){ throw new ServiceException(2,"10010020030040050010005000"); } if(fromUser.equals(toUser)){ throw new ServiceException(3, ""); } if(!fromUser.equals("300fhk")){ if(zuoMingxiDao.get(fromUser, toUser)==null&&youMingXiDao.get(fromUser, toUser)==null){ throw new ServiceException(4, ""); } } Gcuser gcuser = gcuserDao.getUser(fromUser); if(!gcuser.getPassword3().equals(password3)){ throw new ServiceException(5, ""); } if(gcuser.getPay()<50000){ throw new ServiceException(6, "VIP50000"); } if(gcuser.getPay()<amount){ throw new ServiceException(7, " "+gcuser.getPay()+" "); } Gcuser toGcUser = gcuserDao.getUser(toUser); if(toGcUser==null){ throw new ServiceException(8, ""); } if(!gcuserDao.transferReduceYb(fromUser, amount)){ throw new ServiceException(6, " "+gcuser.getPay()+" "); } Datepay datePay = new Datepay(); datePay.setUsername(fromUser); datePay.setJc(amount); datePay.setPay(gcuser.getPay()-amount); datePay.setJydb(gcuser.getJydb()); datePay.setRegid("-"+toUser); datePay.setNewbz(0); datePay.setAbdate(new Date()); logService.addDatePay(datePay); if(!this.changeYb(toUser, amount, ""+fromUser.substring(0, 2)+"***", 0, null)){ throw new ServiceException(3000, ""); } vipxtgcDao.updateJcYb(fromUser, DateUtils.getDate(new Date()), amount); } /** * * @param pageIndex * @param pageSize * @return */ public IPage<Txpay> getTxpayPage(int pageIndex,int pageSize){ return txPayDao.getPageList(pageIndex, pageSize); } /** * * @param userName * @param pageIndex * @param pageSize * @return */ public IPage<Txpay> getTxpaySalesDetailsPage(String userName,int pageIndex,int pageSize){ return txPayDao.getPageListSalesDetails(userName, pageIndex, pageSize); } /** * * @param userName * @param pageIndex * @param pageSize * @return */ public IPage<Txpay> getTxpayBuyDetailsPage(String userName,int pageIndex,int pageSize){ return txPayDao.getPageListBuyDetails(userName, pageIndex, pageSize); } /** * * @param userName * @param payid * @param ip */ @Transactional public void cancleYbSale(String userName,int payid,String ip){ Txpay txpay = txPayDao.getByPayid(payid); if(txpay==null||!txpay.getPayusername().equals(userName)){ throw new ServiceException(1, ""); } if(txpay.getEp()>0 || txpay.getZftime()!=null || txpay.getKjygid()!=0){ throw new ServiceException(2, ""); } if(datePayDao.updateByQlid(txpay.getQlid())){ gcuserDao.backSaleYb(userName, txpay.getPaynum()); Gcuser gcuser = gcuserDao.getUser(userName); Datepay datePay = new Datepay(); datePay.setUsername(userName); datePay.setSyjz(txpay.getPaynum()); datePay.setPay(gcuser.getPay()); datePay.setJydb(gcuser.getJydb()); datePay.setRegid(""); datePay.setNewbz(3); datePay.setTxbz(1); datePay.setAbdate(new Date()); logService.addDatePay(datePay); if(!txPayDao.updateByPayid(payid, 0, new Date(), "", new Date(), "", ip)){ throw new ServiceException(3000, ""); } if(!gcuserDao.updatePayOk(gcuser.getName(), gcuser.getUserid(), 0)){ throw new ServiceException(3000, ""); } }else{ throw new ServiceException(2, ""); } } /** * * @param userName * @param payId */ public Txpay buyYbPre(String userName,int payId){ Txpay txpay = txPayDao.getByPayid(payId); if(txpay==null){ throw new ServiceException(1, ""); } Gcuser gcuser = gcuserDao.getUser(userName); if(gcuser.getSjb()==0){ throw new ServiceException(2, ""); } if(gcuser.getSjb()<20){ throw new ServiceException(3, "D\n\n95%"); } if(gcuser.getCxt()<4&&gcuser.getCxdate().getTime()>System.currentTimeMillis()){ throw new ServiceException(4, ""+gcuser.getCxt()+"[]"+DateUtils.getIntervalDays(new Date(),gcuser.getCxdate())+""); } if(userName.equals(txpay.getPayusername())){ throw new ServiceException(5, ""); } // if(gcuser.getJyg()<txpay.getPaynum()){ // throw new ServiceException(6, ""+txpay.getPaynum()+"\n\n95%"); return txpay; } public Txpay buyYb(String userName,int payId,String password3){ Txpay txpay = buyYbPre(userName,payId); Gcuser gcuser = gcuserDao.getUser(userName); if(!password3.equals(gcuser.getPassword3())){ throw new ServiceException(8, ""); } if(!txPayDao.updateEpToBeSalesPre(payId,DateUtils.addHour(new Date(), 2),userName,txpay.getPaynum())){ throw new ServiceException(7, ""); } // if(!gcuserDao.updateJyg(userName, txpay.getPaynum())){ // throw new ServiceException(6, ""+txpay.getPaynum()+"\n\n95%"); // Gpjy gpjy = new Gpjy(); // gpjy.setUsername(userName); // gpjy.setMcsl(Double.valueOf(txpay.getPaynum())); // gpjy.setSysl(Double.valueOf(gcuser.getJyg()-txpay.getPaynum())); // gpjy.setBz("--"+txpay.getPaynum()+"-"+txpay.getPayusername()); // gpjy.setCgdate(new Date()); // gpjy.setJy(1); // gpjy.setDfuser(payId+""); // gpjy.setNewjy(1); // gpjy.setAbdate(new Date()); // gpjyDao.add(gpjy); try { sendYbSaleSmsMsg(txpay.getPayusername(), 0); } catch (Exception e) { LogSystem.error(e, ""); } return txpay; } public Txpay getTxpayById(int payId){ return txPayDao.getByPayid(payId); } /** * * @param userName * @param payId */ public void sureIGivedMoney(String userName,int payId){ Txpay txpay = txPayDao.getByPayid(payId); if(!txpay.getDfuser().equals(userName)||txpay.getKjygid()==0){ throw new ServiceException(1, ""); }else{ if(!txPayDao.updateEpToHavePay(payId, DateUtils.addDay(new Date(), 2))){ throw new ServiceException(1, ""); } } sendYbSaleSmsMsg(txpay.getPayusername(), 1); } /** * * @param userName * @param payId * @param password3 * @param smsCode */ @Transactional public void sureIReceivedMoney(String userName,int payId,String password3,String smsCode,String ip){ Txpay txpay = txPayDao.getByPayid(payId); if(!txpay.getPayusername().equals(userName)){ throw new ServiceException(1, ""); } if(txpay.getEp()==0||txpay.getZftime()!=null){ throw new ServiceException(2, ""); } Gcuser gcuser = gcuserDao.getUser(userName); if(!gcuser.getPassword3().equals(password3)){ throw new ServiceException(3, ""); } if(gcuser.getGanew()!=0&&!gcuser.getVipsq().equals(smsCode)){ throw new ServiceException(4, ""); } gcuserDao.updateSmsCode(userName, INIT_SMS_CODE); if(!txPayDao.updateEpToHaveReceive(payId, ip)){ throw new ServiceException(8888, ""); } gcuserDao.addYbForBuyInMark(txpay.getDfuser(), txpay.getPaynum()); datePayDao.updateRegIdAndTxbzByQlid(txpay.getQlid(), "-"+txpay.getDfuser()+"-"+DateUtils.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS)); Gcuser dfuser = gcuserDao.getUser(txpay.getDfuser()); Datepay datepay = new Datepay(); datepay.setUsername(txpay.getDfuser()); datepay.setRegid("-"+txpay.getPayusername()+"-"+txpay.getPaynum()); datepay.setSyjz(txpay.getPaynum()); datepay.setPay(dfuser.getPay()); datepay.setJydb(dfuser.getJydb()); datepay.setNewbz(2); datePayDao.addDatePay(datepay); gcuserDao.updatePayOk(gcuser.getName(), gcuser.getUserid(), 0); } @Transactional public void sureIReceivedMoneyBySystem(int payId){ Txpay txpay = txPayDao.getByPayid(payId); if(txpay.getEp()==0||txpay.getZftime()!=null){ throw new ServiceException(2, ""); } if(!txPayDao.updateEpToHaveReceiveBySytstem(payId, "system")){ throw new ServiceException(8888, ""); } gcuserDao.addYbForBuyInMark(txpay.getDfuser(), txpay.getPaynum()); datePayDao.updateRegIdAndTxbzByQlid(txpay.getQlid(), "-"+txpay.getDfuser()+"-"+DateUtils.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS)); Gcuser dfuser = gcuserDao.getUser(txpay.getDfuser()); Datepay datepay = new Datepay(); datepay.setUsername(txpay.getDfuser()); datepay.setRegid("-"+txpay.getPayusername()+"-"+txpay.getPaynum()); datepay.setSyjz(txpay.getPaynum()); datepay.setPay(dfuser.getPay()); datepay.setJydb(dfuser.getJydb()); datepay.setNewbz(2); datePayDao.addDatePay(datepay); // Gcuser gcuser = gcuserDao.getUser(txpay.getPayusername()); // gcuserDao.updatePayOk(gcuser.getName(), gcuser.getUserid(), 0); } /** * * @param userName * @param mz * @param gmsl */ private static final double[] rations = new double[]{0.1,0.03,0.01}; private static final String[] descs = new String[]{"","",""}; @Transactional public void buyJb(String userName,int mz,int gmsl,String pa3){ double needYbCountDouble = (double)mz*(double)gmsl*1.5; int needYbCount = (int)needYbCountDouble; int jbCount = mz*gmsl; Gcuser gcuser = gcuserDao.getUser(userName); if(!pa3.equals(gcuser.getPassword3())){ throw new ServiceException(3, ""); } if(gcuser.getPay()<needYbCount){ throw new ServiceException(2, ""); } String d9 = gcuser.getAdd9dqu(); String sheng = gcuser.getAddsheng(); String shi = gcuser.getAddshi(); String qu = gcuser.getAddqu(); if(!this.changeYb(userName, -needYbCount, ""+jbCount, 0, null)){ throw new ServiceException(2, ""); } //gmdate gcuserDao.updateGmdate(userName, new Date()); Gcuser tempUser = gcuser; for(int i=0;i<rations.length;i++){ if(tempUser!=null){ updateUpJbAndYj(tempUser.getUp(), descs[i]+userName+""+jbCount, (int)(rations[i]*jbCount)); tempUser = gcuserDao.getUser(tempUser.getUp()); } } Gcuser quUser = gcuserDao.getGcuserByQu(qu); if(quUser!=null){ int addNum = (int)(0.01*jbCount); gcuserDao.updateQuPay(quUser.getUsername(),addNum); logService.addDlDate(quUser.getUsername(), addNum, quUser.getQupay()+addNum, ""+userName+""+jbCount); } Gcuser shiUser = gcuserDao.getGcuserByShi(shi); if(shiUser!=null){ int addNum = (int)(0.005*jbCount); gcuserDao.updateShiPay(shiUser.getUsername(),addNum); logService.addDlDate(shiUser.getUsername(), addNum, shiUser.getShipay()+addNum, ""+userName+""+jbCount); } Gcuser shengUser = gcuserDao.getGcuserBySheng(sheng); if(shengUser!=null){ int addNum = (int)(0.002*jbCount); gcuserDao.updateShengPay(shengUser.getUsername(), addNum); logService.addDlDate(shengUser.getUsername(), addNum, shengUser.getShengpay()+addNum, ""+userName+""+jbCount); } Gcuser dquUser = gcuserDao.getGcuserByDqu9(d9); if(dquUser!=null){ int addNum = (int)(0.001*jbCount); gcuserDao.update9QuPay(dquUser.getUsername(), addNum); logService.addDlDate(dquUser.getUsername(), addNum, dquUser.getDqupay()+addNum, ""+userName+""+jbCount); } // lkjlDao.updatelksl(userName, gmsl); batchGeneratorEjbk(userName,gmsl,mz); } private static final char[] RANDOMCHAR = new char[]{'0','1','2','3','4','9','a','b','c','d','e','f','g','5','6','7','8','h','j','k','x','y','z','i'}; private void batchGeneratorEjbk(String userName,int count,int value){ value = value/10; List<Ejbk> list = Lists.newArrayList(); for(int i=0;i<count;i++){ Ejbk ejbk = new Ejbk(); ejbk.setPdid(userName+""+RandomStringUtils.random(6,RANDOMCHAR)); ejbk.setUp(userName); ejbk.setGpa(1); ejbk.setBf2(value); ejbk.setGmdate(new Date()); list.add(ejbk); } ejbkDao.batchAdd(list); } private void updateUpJbAndYj(String upUserName,String desc,int count){ gcuserDao.addWhenOtherPersionBuyJbCard(upUserName, count); Gcuser gcuser = gcuserDao.getUser(upUserName); Datepay datePay = new Datepay(); datePay.setUsername(upUserName); datePay.setRegid(desc); datePay.setSyjz(count); datePay.setPay(gcuser.getPay()); datePay.setJydb(gcuser.getJydb()); datePay.setAbdate(new Date()); logService.addDatePay(datePay); } /** * * @param upUserName * @param pageIndex * @param pageSize * @return */ public IPage<Ejbk> getEjbkPageList(String upUserName,int pageIndex,int pageSize){ return ejbkDao.getPageList(upUserName, pageIndex, pageSize); } /** * * @param pdid * @return */ public Ejbk getEjbk(String pdid){ return ejbkDao.get(pdid); } /** * * @param pdid * @param pdpamd5 * @param fwidmd5 * @return */ public Ejbk updateEjbk(String pdid,String userName,String pdpa,String fwid){ Ejbk ejbk = ejbkDao.get(pdid); if(!ejbk.getUp().equals(userName)){ throw new ServiceException(3000, "~"); } String pdpamd5 = MD5Security.md5_16(pdpa).toUpperCase(); String fwidmd5 = MD5Security.md5_16(fwid).toUpperCase(); if(ejbkDao.update(pdid, pdpamd5, fwidmd5)){ return ejbkDao.get(pdid); } return null; } /** * * @param userName * @param pdid * @param pdpa * @param fwid * @param ip */ @Transactional public void activedGoldCard(String userName,String pdid,String pdpa,String fwid,String ip){ String pdpamd5 = MD5Security.md5_16(pdpa).toUpperCase(); String fwidmd5 = MD5Security.md5_16(fwid).toUpperCase(); Ejbk ejbk = ejbkDao.get(pdid); String gmuser = ""; Date gmdate= null; if(ejbk==null){ Jbk10 jbk10 = jdbDao.getJbk10(pdid); if(jbk10!=null){ if(!pdpamd5.equals(jbk10.getPdpamd5())){ throw new ServiceException(1, " "); } if(!fwidmd5.equals(jbk10.getFwidmd5())){ throw new ServiceException(2, " "); } int cjpay= 10; vipgwly(userName, pdid, pdpamd5, fwidmd5, gmuser, gmdate, cjpay, ip); if(!jdbDao.deleteJbk10(pdid)){ throw new ServiceException(3, " "); } }else{ Jbk50 jbk50 = jdbDao.getJbk50(pdid); if(jbk50!=null){ if(!pdpamd5.equals(jbk50.getPdpamd5())){ throw new ServiceException(1, " "); } if(!fwidmd5.equals(jbk50.getFwidmd5())){ throw new ServiceException(2, " "); } int cjpay= 50; vipgwly(userName, pdid, pdpamd5, fwidmd5, gmuser, gmdate, cjpay, ip); if(!jdbDao.deleteJbk50(pdid)){ throw new ServiceException(3, " "); } }else{ Jbk100 jbk100 = jdbDao.getJbk100(pdid); if(jbk100!=null){ if(!pdpamd5.equals(jbk100.getPdpamd5())){ throw new ServiceException(1, " "); } if(!fwidmd5.equals(jbk100.getFwidmd5())){ throw new ServiceException(2, " "); } int cjpay= 100; vipgwly(userName, pdid, pdpamd5, fwidmd5, gmuser, gmdate, cjpay, ip); if(!jdbDao.deleteJbk100(pdid)){ throw new ServiceException(3, " "); } }else{ Jbk300 jbk300 = jdbDao.getJbk300(pdid); if(jbk300!=null){ if(!pdpamd5.equals(jbk300.getPdpamd5())){ throw new ServiceException(1, " "); } if(!fwidmd5.equals(jbk300.getFwidmd5())){ throw new ServiceException(2, " "); } int cjpay= 300; vipgwly(userName, pdid, pdpamd5, fwidmd5, gmuser, gmdate, cjpay, ip); if(!jdbDao.deleteJbk300(pdid)){ throw new ServiceException(3, " "); } }else{ Jbk500 jbk500 = jdbDao.getJbk500(pdid); if(jbk500!=null){ if(!pdpamd5.equals(jbk500.getPdpamd5())){ throw new ServiceException(1, " "); } if(!fwidmd5.equals(jbk500.getFwidmd5())){ throw new ServiceException(2, " "); } int cjpay= 500; vipgwly(userName, pdid, pdpamd5, fwidmd5, gmuser, gmdate, cjpay, ip); if(!jdbDao.deleteJbk500(pdid)){ throw new ServiceException(3, " "); } }else{ throw new ServiceException(3, " "); } } } } } }else{ if(!pdpamd5.equals(ejbk.getPdpamd5())){ throw new ServiceException(1, " "); } if(!fwidmd5.equals(ejbk.getFwidmd5())){ throw new ServiceException(2, " "); } gmuser= ejbk.getUp(); gmdate= ejbk.getGmdate(); int cjpay= ejbk.getBf2()*10; vipgwly(userName, pdid, pdpamd5, fwidmd5, gmuser, gmdate, cjpay, ip); if(!ejbkDao.delete(pdid)){ throw new ServiceException(3, " "); } } } private void vipgwly(String userName,String pdid,String pdpa,String fwid,String gmuser,Date gmdate,int cjpay,String ip){ // double zjgc = 0; // if(cjpay<1000){ // zjgc=0; // }else if(cjpay>999 && cjpay<2000){ // zjgc=cjpay*0.01; // }else if(cjpay>1999 && cjpay<3000){ // zjgc=cjpay*0.02; // }else if(cjpay>2999 && cjpay<4000){ // zjgc=cjpay*0.03; // }else if(cjpay>3999 && cjpay<5000){ // zjgc=cjpay*0.04; // }else if(cjpay>4999 && cjpay<6000){ // zjgc=cjpay*0.05; // }else if(cjpay>5999 && cjpay<7000){ // zjgc=cjpay*0.06; // }else if(cjpay>6999 && cjpay<8000){ // zjgc=cjpay*0.07; // }else if(cjpay>7999 && cjpay<9000){ // zjgc=cjpay*0.08; // }else if(cjpay>8999 && cjpay<10000){ // zjgc=cjpay*0.09; // }else if(cjpay>9999){ // zjgc=cjpay*0.1; Datecj datecj = datecjDao.get(userName); int cjtj = 0; if(datecj!=null){ cjtj = datecj.getLjcj(); } Datecj datecjTemp = new Datecj(); datecjTemp.setCjuser(userName); datecjTemp.setDqcj(cjpay); datecjTemp.setLjcj(cjtj); datecjTemp.setCjfs(pdid); datecjTemp.setCjdate(gmdate); datecjTemp.setBz(gmuser); datecjTemp.setIp(ip); datecjDao.add(datecjTemp); Gcuser user = gcuserDao.getUser(userName); int count = (int)(cjpay*0.03); updateUpJbAndYj(user.getUp(), ""+userName+""+cjpay, count); gcuserDao.addOnlyJB(userName, cjpay); user = gcuserDao.getUser(userName); Datepay datePay = new Datepay(); datePay.setUsername(userName); datePay.setRegid(""+cjpay); datePay.setPay(user.getPay()); datePay.setJydb(user.getJydb()); datePay.setJyjz(cjpay); datePay.setAbdate(new Date()); logService.addDatePay(datePay); } /** * * @param userName * @param pageIndex * @param pageSize * @return */ public IPage<Gpjy> getGpjyPage(String userName,int pageIndex,int pageSize){ return gpjyDao.getPageList(userName, pageIndex, pageSize); } public Gpjy getGpjyByjyId(int jyid){ return gpjyDao.getByJyId(jyid); } public Gpjy getGpjyById(int id){ return gpjyDao.getById(id); } @Transactional public int jfQg(String userName,int goodsId){ checkJfIsOpen(); Gcuser user = gcuserDao.getUser(userName); int cost = 1; int buyNum = 1; if(user.getJyg()<10||user.getJyg()<cost){ throw new ServiceException(1, ""); } boolean result = jfcpDao.updateJf(goodsId, buyNum); if(!result){ throw new ServiceException(2,""); } Jfcp jfcp =jfcpDao.get(goodsId); if(!gcuserDao.updateJyg(userName, cost)){ throw new ServiceException(1, ""); } user = gcuserDao.getUser(userName); Gpjy gpjy = new Gpjy(); gpjy.setUsername(userName); gpjy.setMcsl(Double.valueOf(cost)); gpjy.setSysl(Double.valueOf(user.getJyg())); gpjy.setBz("-"+jfcp.getCpmq()); gpjy.setCgdate(new Date()); gpjy.setJy(1); gpjy.setAbdate(new Date()); gpjyDao.add(gpjy); if(jfcp.getDqjf()==10||jfcp.getDqjf()<21&&jfcp.getCglist()!=0){ if(!jfcpDao.updateDqjfAndCglist(goodsId, buyNum)){ throw new ServiceException(3000,""); } } jfcp =jfcpDao.get(goodsId); if(jfcp.getDqjf()==0||jfcp.getDqjf()<0&&jfcp.getCglist()==0){ Cpuser cpuser = new Cpuser(); cpuser.setCguser(userName); cpuser.setCpmq("jf-"+jfcp.getCpmq()); cpuser.setJydate(new Date()); cpuser.setJyjf(jfcp.getZjfsl()); cpuser.setJyname(user.getName()); cpuser.setJyqq(user.getQq()); cpuser.setJycall(user.getCall()); cpuserDao.add(cpuser); Gpjy gpjy2 = new Gpjy(); gpjy.setUsername(userName); gpjy.setSysl(Double.valueOf(user.getJyg())); gpjy.setBz("-"+jfcp.getCpmq()); gpjy.setCgdate(new Date()); gpjy.setJy(1); gpjyDao.add(gpjy2); if(!jfcpDao.updateDqjfOrCglistOrJysl(goodsId)){ throw new ServiceException(3000,""); } return -1; }else{ //throw new ServiceException(3,""+jfcp.getDqep()+""); return jfcp.getDqjf(); } } /** * * @param userName * @param buyNum */ @Transactional public void buyJf(String userName,int buyNum){ checkJfIsOpen(); Gcuser gcuser = gcuserDao.getUser(userName); if(gcuser.getJydb()>1500&&gpjyDao.get()!=null){ throw new ServiceException(1," [] "); } Fcxt fcxt = managerService.getFcxtById(2); int needJb = (int)(Math.ceil(fcxt.getJygj()*buyNum)); if(!gcuserDao.reduceOnlyJB(userName, needJb)){ throw new ServiceException(2,""); } Datepay datePay = new Datepay(); datePay.setUsername(userName); datePay.setRegid(""); datePay.setDbjc(needJb); datePay.setPay(gcuser.getPay()); datePay.setJydb(gcuser.getJydb()-needJb); datePay.setAbdate(new Date()); int id = logService.addDatePay(datePay); // int id = logService.getLasterInsertId(); Gpjy gpjy = new Gpjy(); gpjy.setUsername(userName); gpjy.setMysl(Double.valueOf(buyNum)); gpjy.setSysl(Double.valueOf(gcuser.getJyg())); gpjy.setPay(fcxt.getJygj()); gpjy.setBz(""); gpjy.setJypay(Double.valueOf(needJb)); gpjy.setJyid(id); gpjy.setAbdate(new Date()); gpjyDao.add(gpjy); } /** * * @param userName * @param orderId * @param pa3 */ @Transactional public void cancelBuyJf(String userName,int orderId,String pa3){ checkJfIsOpen(); Gcuser gcuser = gcuserDao.getUser(userName); if(!pa3.equals(gcuser.getPassword3())){ throw new ServiceException(1,""); } Gpjy gpjy1 = gpjyDao.getByJyId(orderId); if(!gpjy1.getUsername().equals(userName)){ throw new ServiceException(3000,""); } if(!gpjyDao.delete(orderId,gpjy1.getId())){ throw new ServiceException(2,""); } gpjyDao.deleteIndex(gpjy1.getId()); datePayDao.updateRegIdToCancel(orderId,""); Datepay datepay = datePayDao.getById(orderId); gcuserDao.addOnlyJB(userName, datepay.getDbjc()); gcuser = gcuserDao.getUser(userName); Datepay datePay = new Datepay(); datePay.setUsername(userName); datePay.setRegid(""); datePay.setJyjz(datepay.getDbjc()); datePay.setJydb(gcuser.getJydb()); datePay.setPay(gcuser.getPay()); datePay.setNewbz(0); datePay.setAbdate(new Date()); logService.addDatePay(datePay); } public IPage<Gpjy> getAllGpjyPageList(String userName,int pageIndex,int pageSize){ return gpjyDao.getAllPageList(userName, pageIndex, pageSize); } public IPage<Gpjy> getAllGpjyDetailsPageList(String userName,int pageIndex,int pageSize){ return gpjyDao.getUserPageDetailsList(userName, pageIndex, pageSize); } public List<Gpjy> getMrPageList(int pageSize){ return gpjyDao.getMrPage(pageSize); } public List<Gpjy> getMcPageList(int pageSize){ return gpjyDao.getMcPageList(pageSize); } /** * * @param userName * @param price * @param saleNum * @param passwrod3 */ @Transactional public void saleJf(String userName,double price,int saleNum,String passwrod3){ checkSaleJf(userName,price,saleNum,passwrod3); checkJfIsOpen(); if(!gcuserDao.updateJyg(userName, saleNum)){ throw new ServiceException(9," "); } // if(!gcuserDao.increaseStopjyg(userName,20)){ // throw new ServiceException(8,"20"); if(saleNum>3000){ throw new ServiceException(11,"1000"); } int needJb = (int)(Math.ceil(price*saleNum)); Gcuser gcuser = gcuserDao.getUser(userName); Gpjy gpjy = new Gpjy(); gpjy.setUsername(userName); gpjy.setMcsl(Double.valueOf(saleNum)); gpjy.setSysl(Double.valueOf(gcuser.getJyg())); gpjy.setPay(price); gpjy.setBz(""); gpjy.setJypay(Double.valueOf(needJb)); gpjy.setAbdate(new Date()); gpjyDao.add(gpjy); } /** * * @param userName * @param price * @param saleNum * @param passwrod3 */ public void checkSaleJf(String userName,double price,int saleNum,String passwrod3){ Gcuser gcuser = gcuserDao.getUser(userName); if(gcuser.getBddate()!=null&&gcuser.getJyg()<50000&&DateUtils.getIntervalDays( new Date(),gcuser.getBddate())<100){ throw new ServiceException(1,"100"); } Sgxt sgxt = sgxtDao.get(userName); if(sgxt!=null){ if(sgxt.getMqfh()>0&&sgxt.getMqfh()<sgxt.getZfh()&&sgxt.getXxnew()>0&&gcuser.getJyg()<50000){ throw new ServiceException(2,""); } if(DateUtils.getIntervalDays(sgxt.getBddate(), new Date())==0){ throw new ServiceException(3,""); } } if(!passwrod3.equals("-1")&&!passwrod3.equals(gcuser.getPassword3())){ throw new ServiceException(4,""); } Fcxt fcxt = managerService.getFcxtById(2); if(price<fcxt.getZdj()){ throw new ServiceException(5,""+fcxt.getZdj()+" "); } if(price > fcxt.getJygj()+0.03){ throw new ServiceException(6," "+(fcxt.getJygj()+0.03)+" "); } if(saleNum<=0){ throw new ServiceException(7,""); } // if(gcuser.getStopjyg()>19){ // throw new ServiceException(8,"20"); if(saleNum>gcuser.getJyg()){ throw new ServiceException(9," "+gcuser.getJyg()+" "); } if(gcuser.getJygt1()==0){ if(gpjyDao.get()!=null){ throw new ServiceException(10," [] "); } } } private void checkJfIsOpen(){ if(AdminService.isClose){ throw new ServiceException(1860,""); } } /** * * @param userName * @param orderId * @param pa3 */ @Transactional public void cancelSale(String userName,int orderId,String pa3){ Gcuser gcuser = gcuserDao.getUser(userName); checkJfIsOpen(); if(!pa3.equals(gcuser.getPassword3())){ throw new ServiceException(1,""); } Gpjy gpjy1 = gpjyDao.getById(orderId); double mcsl=gpjy1.getMcsl(); if(!gpjy1.getUsername().equals(userName)){ throw new ServiceException(3000,""); } if(!gcuserDao.updateJyg(userName, -(int)mcsl)){ throw new ServiceException(3000,""); } if(!gcuserDao.resetStopjyg(userName)){ throw new ServiceException(3000,""); } if(!gpjyDao.updateJy(1, orderId)){ throw new ServiceException(2,""); } if(!gpjyDao.updateBz(orderId, "")){ throw new ServiceException(3000,""); } if(!gpjyDao.updateCgdate(orderId)){ throw new ServiceException(3000,""); } if(!gpjyDao.updateDqdate(orderId)){ throw new ServiceException(3000,""); } gpjyDao.deleteIndex(orderId); gcuser = gcuserDao.getUser(userName); Gpjy gpjy = new Gpjy(); gpjy.setUsername(userName); gpjy.setMysl(mcsl); gpjy.setSysl(Double.valueOf(gcuser.getJyg())); gpjy.setBz(""); gpjy.setCgdate(new Date()); gpjy.setJy(1); gpjyDao.add(gpjy); } /** * * @param userName * @param id * @param price */ public void editGpjy(String userName,int id,double price,String pa3){ checkJfIsOpen(); Gcuser gcuser = gcuserDao.getUser(userName); if(!pa3.equals(gcuser.getPassword3())){ throw new ServiceException(1,""); } Gpjy gpjy1 = gpjyDao.getById(id); if(!gpjy1.getUsername().equals(userName)){ throw new ServiceException(3000,""); } if(price>gpjy1.getPay()){ throw new ServiceException(2,""); } if(!gpjyDao.updatePayAndJyPay(id, price,(int)(Math.ceil(price*gpjy1.getMcsl())))){ throw new ServiceException(3,""); } gpjyDao.updateIndexPay(id, price); } /** * * @param userName * @param id */ @Transactional public void mrJf(String userName,int id){ checkJfIsOpen(); Gcuser gcuser = gcuserDao.getUser(userName); Gpjy gpjy1 = gpjyDao.getById(id); if (gcuser.getJydb() < gpjy1.getJypay()) { throw new ServiceException(1, ""); } if (!gcuserDao.reduceOnlyJB(userName, gpjy1.getJypay().intValue())) { throw new ServiceException(1, ""); } if (!gcuserDao.updateJyg(userName, - gpjy1.getMcsl().intValue())) { throw new ServiceException(3000, ""); } if (!gpjyDao.updateSaleSuccess(id, userName, "")) { throw new ServiceException(2, ""); } gpjyDao.deleteIndex(id); gcuser = gcuserDao.getUser(userName); Gpjy gpjy = new Gpjy(); gpjy.setUsername(userName); gpjy.setMysl(gpjy1.getMcsl()); gpjy.setSysl(Double.valueOf(gcuser.getJyg())); gpjy.setPay(gpjy1.getPay()); gpjy.setJypay(gpjy1.getJypay()); gpjy.setBz(""); gpjy.setCgdate(new Date()); gpjy.setJy(1); gpjy.setDfuser(gpjy1.getUsername()); gpjyDao.add(gpjy); String mcdj = gpjy1.getPay() < 1 ? "0" + gpjy1.getPay() : "" + gpjy1.getPay(); Datepay datePay1 = new Datepay(); datePay1.setUsername(userName); datePay1.setDbjc(gpjy1.getJypay().intValue()); datePay1.setPay(gcuser.getPay()); datePay1.setJydb(gcuser.getJydb()); datePay1.setRegid("" + gpjy1.getUsername() + "-" + gpjy1.getMcsl() + "-" + mcdj); datePay1.setAbdate(new Date()); logService.addDatePay(datePay1); double dqpay92 = (0.9 * gpjy1.getJypay()); int dqpay = (int) (dqpay92 * 1 + 0.1); double mc70a = 0.7 * dqpay; int mc70 = (int) (mc70a * 1 + 0.1); double mc30a = 0.3 * dqpay; int mc30 = (int) (mc30a * 1 + 0.1); gcuserDao.addWhenOtherPersionBuyJbCard(gpjy1.getUsername(), mc70); gcuserDao.addOnlyJB(gpjy1.getUsername(), mc30); gcuserDao.reduceStopjyg(gpjy1.getUsername()); Gcuser gcuser2 = gcuserDao.getUser(gpjy1.getUsername()); Datepay datePay2 = new Datepay(); datePay2.setUsername(gpjy1.getUsername()); datePay2.setSyjz(mc70); datePay2.setPay(gcuser2.getPay()); datePay2.setJydb(gcuser2.getJydb()); datePay2.setJyjz(mc30); datePay2.setRegid("" + gpjy1.getMcsl() + "" + mcdj + "" + userName); datePay2.setAbdate(new Date()); logService.addDatePay(datePay2); fcxtDao.update(2,gpjy1.getMcsl().intValue()); } /** * * @param userName * @param id */ @Transactional public void mcJf(String userName,int id,String pa3){ checkJfIsOpen(); Gcuser gcuser = gcuserDao.getUser(userName); if(!gcuser.getName().equals("")&&!gcuser.getPassword3().equals(pa3)){ throw new ServiceException(4,""); } Gpjy gpjy1 = gpjyDao.getById(id); double dqpay92 = (0.9 * gpjy1.getJypay()); int dqpay = (int) (dqpay92 * 1 + 0.1); double mc70a = 0.7 * dqpay; int mc70 = (int) (mc70a * 1 + 0.1); double mc30a = 0.3 * dqpay; int mc30 = (int) (mc30a * 1 + 0.1); if (gcuser.getJyg() < gpjy1.getMysl()) { throw new ServiceException(1, " " + gcuser.getJyg() + " " + gpjy1.getMysl() + " "); } if (!gcuserDao.updateJyg(userName, gpjy1.getMysl().intValue())) { throw new ServiceException(1, " " + gcuser.getJyg() + " " + gpjy1.getMysl() + " "); } gcuserDao.addWhenOtherPersionBuyJbCard(userName, mc70); gcuserDao.addOnlyJB(userName, mc30); gcuserDao.updateJyg(gpjy1.getUsername(), -gpjy1.getMysl().intValue()); Gcuser dfuser = gcuserDao.getUser(gpjy1.getUsername()); if (!gpjyDao.updateBuySuccess(id, userName, "",dfuser.getJyg())) { throw new ServiceException(2, ""); } gpjyDao.deleteIndex(id); if(gcuser.getBddate()!=null&&gcuser.getJyg()<50000&&DateUtils.getIntervalDays( new Date(),gcuser.getBddate())<100){ throw new ServiceException(3,"100"); } gcuser = gcuserDao.getUser(userName); Gpjy gpjy = new Gpjy(); gpjy.setUsername(userName); gpjy.setMcsl(gpjy1.getMysl()); gpjy.setSysl(Double.valueOf(gcuser.getJyg())); gpjy.setPay(gpjy1.getPay()); gpjy.setJypay(gpjy1.getJypay()); gpjy.setAbdate(gpjy1.getAbdate()); gpjy.setBz(""); gpjy.setCgdate(new Date()); gpjy.setJy(1); gpjy.setDfuser(gpjy1.getUsername()); gpjyDao.add(gpjy); String mydj = gpjy1.getPay() < 1 ? "0" + gpjy1.getPay() : "" + gpjy1.getPay(); Datepay datePay1 = new Datepay(); datePay1.setUsername(userName); datePay1.setSyjz(mc70); datePay1.setPay(gcuser.getPay()); datePay1.setJydb(gcuser.getJydb()); datePay1.setJyjz(mc30); datePay1.setRegid("" + gpjy1.getMysl() + "" + mydj + "" + gpjy1.getUsername()); datePay1.setAbdate(new Date()); logService.addDatePay(datePay1); String d = DateUtils.DateToString(gpjy1.getCgdate(), DateStyle.YYYY_MM_DD_HH_MM_SS); String dStr = d==null?"":d; logService.updateRegId(gpjy1.getJyid(), dStr+"" + userName + "-" + gpjy1.getMysl() + "-" + mydj); fcxtDao.update(2, gpjy1.getMysl().intValue()); } // private String shpa; // private int sfpay; // private String pay10; // private int ybpay; // private String user; // private String pa01; // private String pa02; // private String sfcode; @Transactional public void transferYbToShop(String userName,String shpa,int sfpay,String pay10,int ybpay,String user,String pa01,String pa02,String sfcode){ Gcuser gcuser = gcuserDao.getUser(userName); if(gcuser.getJb()!=5){ // super.setErroCodeNum(1);//alert(''); // return SUCCESS; throw new ServiceException(1, ""); } if(Strings.isNullOrEmpty(shpa)||!shpa.equals(gcuser.getPassword3())){ // super.setErroCodeNum(2);//alert(''); // return SUCCESS; throw new ServiceException(2, ""); } if(ybpay<=0){ // super.setErroCodeNum(3);//alert(''); // return SUCCESS; throw new ServiceException(3, ""); } Gcuser beReduceUser = gcuserDao.getUser(user); if(beReduceUser==null){ // super.setErroCodeNum(4);//alert(''); // return SUCCESS; throw new ServiceException(4, ""); } if(Strings.isNullOrEmpty(pa01)||!MD5Security.md5_16(pa01).equals(beReduceUser.getPassword())){ // super.setErroCodeNum(5);//alert(''); // return SUCCESS; throw new ServiceException(5, ""); } if(Strings.isNullOrEmpty(pa02)||!pa02.equals(beReduceUser.getPassword3())){ // super.setErroCodeNum(6);//alert(''); // return SUCCESS; throw new ServiceException(6, ""); } if(beReduceUser.getPay()<ybpay){ // super.setErroCodeNum(7);//alert(''); // return SUCCESS; throw new ServiceException(7, ""); } if(!beReduceUser.getVipsq().equals(sfcode)){ // super.setErroCodeNum(8);//alert(''); // return SUCCESS; throw new ServiceException(8, ""); } gcuserDao.updateSmsCode(userName, INIT_SMS_CODE); if(!this.changeYb(user, -ybpay,gcuser.getName(),12,null)){ // super.setErroCodeNum(7);//alert(''); // return SUCCESS; throw new ServiceException(7, ""); } if(!this.changeYb(gcuser.getUsername(), ybpay,gcuser.getName()+"-"+beReduceUser.getName(),5,null)){ // super.setErroCodeNum(9);//alert(''); // return SUCCESS; throw new ServiceException(9, ""); } } private static final char[] chars = new char[]{'0','1','2','3','4','5','6','7','8','9'}; public void sendSmsMsg(String userName){ Gcuser gcuser = gcuserDao.getUser(userName); Map<String,String> param = new HashMap<String,String>(); String randomString = RandomStringUtils.random(6, chars); param.put("code", randomString); if(gcuserDao.updateSmsCode(userName, randomString)){ try { if(!SubMailSendUtils.sendMessage(gcuser.getCall(), "aGTtt3", param)){ throw new ServiceException(3000, ","); } } catch (Exception e) { LogSystem.error(e, "phone="+gcuser.getCall()+",userName="+gcuser.getUsername()+""); throw new ServiceException(3000, "phone="+gcuser.getCall()+",userName="+gcuser.getUsername()+","); } }else{ throw new ServiceException(3000, ","); } } private static final String[] smsCode = new String[]{"WKkt32","BlQ9X","R630D1"}; public void sendYbSaleSmsMsg(String userName,int code){ Gcuser gcuser = gcuserDao.getUser(userName); try { if(!SubMailSendUtils.sendMessage(gcuser.getCall(), smsCode[code], new HashMap<String,String>())){ throw new ServiceException(3000, ","); } } catch (Exception e) { LogSystem.error(e, "phone="+gcuser.getCall()+",userName="+gcuser.getUsername()+""); throw new ServiceException(3000, "phone="+gcuser.getCall()+",userName="+gcuser.getUsername()+","); } } /** * * @param userName * @param numStr */ public void sendBdSmsMsg(String userName,String numStr){ Gcuser gcuser = gcuserDao.getUser(userName); if(gcuser==null){ LogSystem.warn(",="+userName); return; } String name = ""; if(!Strings.isNullOrEmpty(gcuser.getName())){ name = gcuser.getName().substring(0, 1); } String date = DateUtils.DateToString(new Date(), DateStyle.YYYY_MM_DD_EN); Map<String,String> param = new HashMap<String,String>(); param.put("name", name); param.put("numStr", numStr); param.put("userName", userName); param.put("date", date); try { if(!SubMailSendUtils.sendMessage(gcuser.getCall(), "sUb981",param)){ throw new ServiceException(3000, ","); } } catch (Exception e) { LogSystem.error(e, "phone="+gcuser.getCall()+",userName="+gcuser.getUsername()+""); throw new ServiceException(3000, "phone="+gcuser.getCall()+",userName="+gcuser.getUsername()+","); } } /** * 2 * @param userName * @param op */ // 0 1 2 3 4 5 6 7 8 9 10 11 12 private String[] OP_STR = new String[]{"","","","","","","","","","","","",""}; public void sendSmsMsg(String userName,int op){ Gcuser gcuser = gcuserDao.getUser(userName); Map<String,String> param = new HashMap<String,String>(); String randomString = RandomStringUtils.random(6, chars); param.put("code", randomString); param.put("userName", userName); param.put("op", OP_STR.length>op?OP_STR[op]:""); if(gcuserDao.updateSmsCode(userName, randomString)){ try { if(!SubMailSendUtils.sendMessage(gcuser.getCall(), "NFgnN3", param)){ throw new ServiceException(3000, ","); } } catch (Exception e) { LogSystem.error(e, "phone="+gcuser.getCall()+",userName="+gcuser.getUsername()+""); throw new ServiceException(3000, "phone="+gcuser.getCall()+",userName="+gcuser.getUsername()+","); } }else{ throw new ServiceException(3000, ","); } } /** * * @param pageIndex * @param pageSize * @return */ public IPage<Gcuser> getUserPageList(int pageIndex,int pageSize){ return gcuserDao.getPageList(pageIndex, pageSize); } public IPage<Sgxt> getSgxtPageList(int pageIndex,int pageSize){ return sgxtDao.getPageList(pageIndex, pageSize); } public IPage<Vipcjgl> getVipcjbPageList(String userName,int pageIndex,int pageSize){ return vipcjglDao.getPageList(pageIndex, pageSize, "order by cjid desc", new SqlParamBean("vipuser", userName)); } /** * vip * @param fromUser * @param toUser * @param amount * @param password */ @Transactional public void vipCj(String fromUserName,String toUserName,int amount,String password){ if(zuoMingxiDao.get(fromUserName, toUserName)==null&&youMingXiDao.get(fromUserName, toUserName)==null){ throw new ServiceException(1, ""); } if(!password.equals("zjl888vip")){ throw new ServiceException(2, ""); } Gcuser toUser = gcuserDao.getUser(toUserName); if(toUser==null){ throw new ServiceException(3, ""); } if(toUser.getGmdate()!=null&&toUser.getGmdate().getTime()+2*60*1000>System.currentTimeMillis()){ throw new ServiceException(4, ""); } Gcuser fromUser = gcuserDao.getUser(fromUserName); if(fromUser.getVipcjcjb()<amount){ throw new ServiceException(5, ""+amount+""); } if(toUser.getPay()<9*amount){ throw new ServiceException(6, ""+amount+""+9*amount+""); } if(!gcuserDao.reduceVipcjcjb(fromUserName, amount)){ throw new ServiceException(5, ""+amount+""); } gcuserDao.updateCjtj(toUserName, amount); Vipcjgl vipcjgl = new Vipcjgl(); vipcjgl.setCjuser(toUserName); vipcjgl.setCjjo(amount); vipcjgl.setSycjb(fromUser.getVipcjcjb()-amount); vipcjgl.setVipuser(fromUserName); vipcjgl.setBz(""); vipcjgl.setCjdate(new Date()); vipcjglDao.add(vipcjgl); if(!this.changeYb(toUserName, -9*amount, "v", 0, null)){ throw new ServiceException(6, ""+amount+""+9*amount+""); } this.updateSybdb(toUserName, amount*10, ""+amount+""+9*amount+"v"); } /** * * @param userName * @param regId * @return */ public Datepay getHgybOrder(String userName,String regId){ return datePayDao.getDatepayByUserNameAndRegid(userName, regId); } /** * yb * @param userName * @param ybsl * @param fee * @param gwuser * @param hgcode * @param pa3 * @param gwno * @param gwid */ @Transactional public void hgybOk(String userName,int ybsl,int fee,String gwuser,String hgcode,String pa3,String gwno,String gwid){ if(!userName.equals(gwuser)){ throw new ServiceException(1, ""); } Gcuser gcuser = gcuserDao.getUser(userName); if(gcuser.getPay()<ybsl||ybsl<=0){ throw new ServiceException(2, ""); } Datepay datepay = getHgybOrder(userName, "-"+gwno); if(datepay!=null){ throw new ServiceException(3, " "); } if(!gcuser.getPassword3().equals(pa3)){ throw new ServiceException(4, ""); } if(!hgcode.equals(gcuser.getVipsq())){ throw new ServiceException(5, ""); } gcuserDao.updateSmsCode(userName, INIT_SMS_CODE); if(!this.changeYb(userName, -ybsl, "-"+gwno, 4, null)){ throw new ServiceException(2, ""); } } /** * * @param ybsl * @param fee * @param sjuser * @param gwno * @param gwid */ public void hgybSh(int ybsl,int fee,String sjuser,String gwno,String gwid){ ybsl = (int)(ybsl*0.98); if(ybsl<=0){ throw new ServiceException(6, ""); } Gcuser gcuser = gcuserDao.getUser(sjuser); if(gcuser==null){ throw new ServiceException(7, ""); } this.changeYb(sjuser, ybsl, "-"+gwno, 5, null); } /** * * @param gwpay * @param pa01 * @param pid * @param ybf * @param user * @param order * @param pa02 */ public void ybpay(double gwpay,String pa01,int pid,String ybf,String user,String order, String pa02,String hgcode){ int ybsl = (int)(gwpay*1.02); if(ybsl<=0){ throw new ServiceException(2, ""); } String paylb; if(pid==1){ paylb="-"+order; } else{ paylb="-"+order; } Gcuser gcuser = gcuserDao.getUser(user); if(gcuser==null){ throw new ServiceException(3, ""); } if(!MD5Security.md5_16(pa01).equals(gcuser.getPassword())){ throw new ServiceException(4, ""); } if(!gcuser.getPassword3().equals(pa02)){ throw new ServiceException(5, ""); } if(gcuser.getPay()<ybsl){ throw new ServiceException(6, ""); } if(!hgcode.equals(gcuser.getVipsq())){ throw new ServiceException(7, ""); } if(!this.changeYb(user, -ybsl, paylb, 10, null)){ throw new ServiceException(6, ""); } gcuserDao.updateSmsCode(user, INIT_SMS_CODE); } /** * * @param gwpay * @param pa01 * @param pid * @param ybf * @param user * @param order * @param pa02 */ @Transactional public int kypwe(double gwpay,String pa01,int pid,String ybf,String user,String order, String pa02,String hgcode){ int ybsl = (int)(gwpay*1.02); if(ybsl<=0){ throw new ServiceException(2, ""); } String paylb; if(pid==1){ paylb="-"+order; } else{ paylb="-"+order; } Gcuser gcuser = gcuserDao.getUser(user); if(gcuser==null){ throw new ServiceException(3, ""); } if(!MD5Security.md5_16(pa01).equals(gcuser.getPassword())){ throw new ServiceException(4, ""); } if(!gcuser.getPassword3().equals(pa02)){ throw new ServiceException(5, ""); } if(gcuser.getPay()<ybsl){ throw new ServiceException(6, ""); } if(!hgcode.equals(gcuser.getVipsq())){ throw new ServiceException(7, ""); } int day = 0; // if(gcuser.getPwdate()!=null&&gcuser.getPwdate().getTime()>new Date().getTime()){ // day = DateUtils.getIntervalDays(gcuser.getPwdate(), new Date()); // throw new ServiceException(8, "30"+day+""); int year = DateUtils.getYear(new Date()); int month = DateUtils.getMonth(new Date())+1; String date = year+"-"+month+"-01"; int amount = userDailyGainLogDao.getUserDailyGain(user, 1, date); if(amount+ybsl>10000){ throw new ServiceException(8, "1w"); } if(!this.changeYb(user, -ybsl, paylb, 11, null)){ throw new ServiceException(6, ""); } // Date date = gcuser.getPwdate(); // if(date==null){ // date = new Date(); // gcuserDao.updatePwdate(gcuser.getUserid(), gcuser.getName(), DateUtils.addDay(date, 30)); userDailyGainLogDao.addUserDailyGain(user, 1, ybsl, date); gcuserDao.updateSmsCode(user, INIT_SMS_CODE); return day; } public String ybts(String userName,String states){ Gcuser gcuser = gcuserDao.getUser(userName); if(gcuser!=null){ int txlb = 0; String result = ""; if(states.equals("0")){ txlb = 3; result = ""; }else if(states.equals("1")){ txlb = 0; result = ""; } gcuserDao.updateTxlb(userName, txlb); return result; } return "error,can not find username="+userName; } @Transactional public void telCharge(String userName,String call,String pa3,String smdCode,String ip){ int amount = 100; int yb = 110; Fcxt fcxt = fcxtDao.get(12); if(fcxt!=null&&fcxt.getPayadd()<1){ throw new ServiceException(1, ""); } Gcuser gcuser = gcuserDao.getUser(userName); if(gcuser!=null){ if(gcuser.getHfcjdate()!=null&&gcuser.getHfcjdate().getTime()>System.currentTimeMillis()){ throw new ServiceException(2, "30"+DateUtils.getIntervalDays(gcuser.getHfcjdate(), new Date())+""); } if(gcuser.getPay()<yb){ throw new ServiceException(3,"110"); } if(!gcuser.getPassword3().equals(pa3)){ throw new ServiceException(4,""); } if(!smdCode.equals(gcuser.getVipsq())){ throw new ServiceException(5,""); } }else{ throw new ServiceException(3000, ""); } if(callRemoteCharge(call,amount,ip,userName)){ // if(1==1){ this.changeYbCanFu(userName, -yb, "-"+call, 7, null); fcxtDao.updatePayAdd(); gcuserDao.updateUserHfCz(gcuser.getName(), gcuser.getUserid(), DateUtils.addDay(new Date(), 30)); }else{ throw new ServiceException(100, ""); } gcuserDao.updateSmsCode(userName, INIT_SMS_CODE); } public boolean callRemoteCharge(String call,int amount,String ip,String userName){ LogSystem.info(","+userName+""+""+call+""+","+amount+",ip"+ip+""); _99douInterface _99dou = new _99douInterface(); String out_trade_id = userName+"-"+DateUtils.DateToString(new Date(),DateStyle.YY_MM_EN); String account = call; String account_info = ""; int quantity=1; String value = amount+""; String client_ip = ip; int expired_mini = 5; Ref<String> msg = new Ref<String>(); int result = -1; try { result =_99dou.Huafei(out_trade_id, account, account_info, quantity, value, client_ip, expired_mini, msg); } catch (Exception e) { LogSystem.error(e, ""); throw new ServiceException(100, ""); } LogSystem.info(" :"+result+" :"+msg); if(result==0){ return true; } return false; } public void checkCxt(){ List<Txpay> listNoGiveMoney = txPayDao.getAllNoGiveMoneyRecord(); if(listNoGiveMoney!=null&&listNoGiveMoney.size()>0){ for(Txpay txpay:listNoGiveMoney){ // Gpjy gpjy = gpjyDao.get(txpay.getDfuser(), txpay.getPayid()+""); // if(gpjy!=null){ try { Gcuser user = gcuserDao.getUser(txpay.getDfuser()); if(user==null){ continue; } int addCxdateDay = getAddCxdateDay(user.getCxt()); gcuserDao.updateCxtAndCxtDate(user.getUsername(), 1, addCxdateDay); txPayDao.resetOrder(txpay.getPayid()); Datepay datePay = new Datepay(); datePay.setUsername(user.getUsername()); datePay.setPay(user.getPay()); datePay.setJydb(user.getJydb()); datePay.setRegid("--"+(user.getCxt()-1)+"-"+txpay.getPayid()+"-"+txpay.getPayusername()); datePay.setNewbz(20); datePay.setAbdate(new Date()); logService.addDatePay(datePay); sendYbSaleSmsMsg(txpay.getPayusername(), 2); // gpjyDao.updateGpjy(txpay.getDfuser(), txpay.getPayid()+"", "--"+(user.getCxt()-1), gpjy.getDfuser()+"-"+txpay.getPayusername(), new Date()); } catch (Exception e) { LogSystem.error(e, ""); } } } List<Txpay> listNoSureReceiveMoney = txPayDao.getAllNoSureReceiveMoneyRecord(); if(listNoSureReceiveMoney!=null&&listNoSureReceiveMoney.size()>0){ for(Txpay txpay:listNoSureReceiveMoney){ try { Gcuser user = gcuserDao.getUser(txpay.getPayusername()); if(user==null){ continue; } int addCxdateDay = getAddCxdateDay(user.getCxt()); gcuserDao.updateCxtAndCxtDate(user.getUsername(), 1, addCxdateDay); txPayDao.updateClip(txpay.getPayid()); Datepay datePay = new Datepay(); datePay.setUsername(user.getUsername()); datePay.setPay(user.getPay()); datePay.setJydb(user.getJydb()); datePay.setRegid("--"+(user.getCxt()-1)+"-"+txpay.getPayid()+"-"+txpay.getDfuser()); datePay.setNewbz(20); datePay.setAbdate(new Date()); logService.addDatePay(datePay); } catch (Exception e) { LogSystem.error(e, ""); } } } List<Txpay> listNoSureReceiveMoneyAfter5Days = txPayDao.getAllNoSureReceiveMoneyRecordAfter5Days(); if(listNoSureReceiveMoneyAfter5Days!=null&&listNoSureReceiveMoneyAfter5Days.size()>0){ for(Txpay txpay:listNoSureReceiveMoneyAfter5Days){ try { this.sureIReceivedMoneyBySystem(txpay.getPayid()); } catch (Exception e) { LogSystem.error(e, ""); } } } } private int getAddCxdateDay(int cxt){ int addCxdate = 0; if(cxt-1==3){ addCxdate=7; }else if(cxt-1==2){ addCxdate=14; }else if(cxt-1==1){ addCxdate = 21; }else if(cxt-1<1){ addCxdate = 60; } return addCxdate; } public void resetVip(String userName){ Sgxt sgxt = sgxtDao.get(userName); if(sgxt==null){ gcuserDao.updateVipName(userName, "xtgc001"); }else{ String vipName = findMyUpVipName(userName); gcuserDao.updateVipName(userName, vipName); sgxtDao.updateVipUser(userName, vipName); } } private String findMyUpVipName(String userName) { Sgxt sgxtBd = sgxtDao.getByAOrBuid(userName); if (sgxtBd != null) { if (sgxtBd.getVip() == 1) { return sgxtBd.getUsername(); } else { return findMyUpVipName(sgxtBd.getUsername()); } } return "xtgc001"; } @Transactional public void addBabyInfo(String userName,String babyName, int babyAge, String babySex, String dadyName, int dadyAge, String dadyCall, String momName, int momAge, String momCall, String address, String details,String pa3,String smsCode){ if(Strings.isNullOrEmpty(babyName)||Strings.isNullOrEmpty(babySex)||Strings.isNullOrEmpty(dadyName)||Strings.isNullOrEmpty(dadyCall)||Strings.isNullOrEmpty(momName)||Strings.isNullOrEmpty(momCall)||Strings.isNullOrEmpty(address)||Strings.isNullOrEmpty(details)){ throw new ServiceException(4, ""); } Gcuser gcuser = gcuserDao.getUser(userName); if(!gcuser.getPassword3().equals(pa3)){ throw new ServiceException(2, ""); } if(!gcuser.getVipsq().equals(smsCode)){ throw new ServiceException(3, ""); } gcuserDao.updateSmsCode(userName, INIT_SMS_CODE); if(!this.changeYb(userName, -23800, "", 0, null)){ throw new ServiceException(1, ""); } BabyInfo babyInfo = new BabyInfo(userName, gcuser.getName(), babyName, babyAge, babySex, dadyName, dadyAge, dadyCall, momName, momAge, momCall, address, details, 0, "", null, "", "", new Date()); if(!babyInfoDao.add(babyInfo)){ throw new ServiceException(3000, ""); } } public IPage<BabyInfo> getBabyInfoPage(String param,Integer status,String startTime,String endTime,int pageIndex,int pageSize){ return babyInfoDao.getPage(param, status,pageIndex, pageSize, startTime, endTime); } public List<BabyInfo> getBabyInfoList(String param,Integer status,String startTime,String endTime){ return babyInfoDao.getList(param, status, startTime, endTime); } public BabyInfo getOneBabyInfo(int id){ return babyInfoDao.getBabyInfo(id); } /** * * @param id * @param deleteName * @return */ public boolean deleteBabyInfo(int id,String deleteName){ BabyInfo baby = babyInfoDao.getBabyInfo(id); if(baby!=null&&baby.getStatus()==0){ baby.setStatus(1); baby.setDeleteName(deleteName); baby.setEditTime(new Date()); return babyInfoDao.update(baby); } return false; } /** * * @param id * @param recoverName * @return */ public boolean recoverBabyInfo(int id,String recoverName){ BabyInfo baby = babyInfoDao.getBabyInfo(id); if(baby!=null&&baby.getStatus()==1){ baby.setStatus(0); baby.setRecoverName(recoverName); baby.setEditTime(new Date()); return babyInfoDao.update(baby); } return false; } /** * * @param id * @param editName * @param babyName * @param babyAge * @param babySex * @param dadyName * @param dadyAge * @param dadyCall * @param momName * @param momAge * @param momCall * @param address * @param details * @return */ public boolean updateBabyInfo(int id,String editName,String babyName, int babyAge, String babySex, String dadyName, int dadyAge, String dadyCall, String momName, int momAge, String momCall, String address, String details){ if(Strings.isNullOrEmpty(babyName)||Strings.isNullOrEmpty(babySex)||Strings.isNullOrEmpty(dadyName)||Strings.isNullOrEmpty(dadyCall)||Strings.isNullOrEmpty(momName)||Strings.isNullOrEmpty(momCall)||Strings.isNullOrEmpty(address)||Strings.isNullOrEmpty(details)){ throw new ServiceException(1, ""); } BabyInfo baby = babyInfoDao.getBabyInfo(id); if(baby!=null){ baby.setEditName(editName); baby.setEditTime(new Date()); baby.setBabyName(babyName); baby.setBabyAge(babyAge); baby.setBabySex(babySex); baby.setDadyName(dadyName); baby.setDadyAge(dadyAge); baby.setDadyCall(dadyCall); baby.setMomAge(momAge); baby.setMomCall(momCall); baby.setMomName(momName); baby.setAddress(address); baby.setDetails(details); return babyInfoDao.update(baby); } return false; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controller.simulation; import controller.Controller; import controller.ExtraGraphEvent; import controller.Stats; import edu.uci.ics.jung.graph.MyGraph; import model.MyEdge; import model.MyVertex; import model.SimulationDynamics; import org.apache.commons.collections15.buffer.CircularFifoBuffer; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.XYDataItem; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import javax.swing.*; import java.awt.*; import java.util.*; /** * @author Miroslav Batchkarov */ public class Simulator { private Random rng; private SimModelThread thread; private volatile int stepNumber; private CircularFifoBuffer<Double> xValues; private CircularFifoBuffer<Integer> yValues; private boolean doOneStepOnly; private final int WINDOW_WIDTH = 50; private XYSeries infectedXYSeries; private XYPlot xyPlot; private MyGraph g; private Stats stats; private Controller controller; public Simulator(MyGraph g, Stats stats, Controller controller) { this.g = g; this.stats = stats; this.controller = controller; this.rng = new Random(); this.doOneStepOnly = false; this.infectedXYSeries = new SynchronisedXYSeries("Infected", false, false); this.xValues = new CircularFifoBuffer<Double>(WINDOW_WIDTH); this.yValues = new CircularFifoBuffer<Integer>(WINDOW_WIDTH); this.thread = new SimModelThread("sim-thread"); this.thread.pause(); this.thread.start(); } public void resetSimulation() { this.stepNumber = 0; this.xValues.clear(); this.yValues.clear(); this.updateChartUnderlyingData(); this.updateChartAxisParameters(); } private void doStep(MyGraph<MyVertex, MyEdge> g) { LinkedList<SimulationCommand> commands = new LinkedList<SimulationCommand>(); checkForTopologyChanges(g, commands); checkForInfection(g, commands); checkForRecovery(g, commands); //here the next state of each vertex should be known, updating for (SimulationCommand c : commands) { c.execute(); } //record changes in number of inf/sus/res nodes controller.updateCounts(); xValues.add(stepNumber * g.getDynamics().getTimeStep()); yValues.add(g.getNumInfected()); stats.recalculateAll(); } /** * Checks if any edge creations, deletions of rewirings should occur at this time step. * * NB: Multiple edge rewirings may occur in a single time step. These are executed in * order. The process has two independent step- removing the old edge and then * adding a new one. However, the second part may fail if the edge we are adding * exists already (as we don't want to be adding multiple edges between a pair of * vertices). This means sometimes an edge rewiring mey just turn into an edge * deletion. This is particularly problematic when the edge rewiring rate is high. * * @param g the graph * @param commands a list of changes that will be executed later. This methods appends to the * list */ public void checkForTopologyChanges(MyGraph<MyVertex, MyEdge> g, LinkedList<SimulationCommand> commands) { // check for edge breaking SimulationDynamics d = g.getDynamics(); for (MyEdge e : g.getEdges()) { double eventProba = 0d; MyVertex v1 = g.getEndpoints(e).getFirst(); MyVertex v2 = g.getEndpoints(e).getSecond(); if (v1.isInfected()) { if (v2.isSusceptible()) { eventProba = d.getSIEdgeBreakingProb(); } if (v2.isInfected()) { eventProba = d.getIIEdgeBreakingProb(); } } if (v1.isSusceptible()) { if (v2.isSusceptible()) { eventProba = d.getSSEdgeBreakingProb(); } if (v2.isInfected()) { eventProba = d.getSIEdgeBreakingProb(); } } if (rng.nextFloat() < eventProba) { commands.add(new EdgeBreakingCommand(g, e)); } } // check for edge creation for (MyVertex v1 : g.getVertices()) { for (MyVertex v2 : g.getVertices()) { if (g.isNeighbor(v1, v2) || v1 == v2) continue; double eventProba = 0d; if (v1.isInfected()) { if (v2.isSusceptible()) { eventProba = d.getSIEdgeCreationProb(); } if (v2.isInfected()) { eventProba = d.getIIEdgeCreationProb(); } } if (v1.isSusceptible()) { if (v2.isSusceptible()) { eventProba = d.getSSEdgeCreationProb(); } if (v2.isInfected()) { eventProba = d.getSIEdgeCreationProb(); } } if (rng.nextFloat() < eventProba) { commands.add(new EdgeCreationCommand(controller.getEdgeFactory(), g, v1, v2)); } } } // check for edge rewiring for (MyEdge e : g.getEdges()) { double eventProba = 0d; MyVertex v1 = g.getEndpoints(e).getFirst(); MyVertex v2 = g.getEndpoints(e).getSecond(); if (v1.isInfected()) { if (v2.isSusceptible()) { eventProba = d.getSIEdgeRewiringProb(); } if (v2.isInfected()) { eventProba = d.getIIEdgeRewiringProb(); } } if (v1.isSusceptible()) { if (v2.isSusceptible()) { eventProba = d.getSSEdgeRewiringProb(); } if (v2.isInfected()) { eventProba = d.getSIEdgeRewiringProb(); } } if (rng.nextFloat() < eventProba) { MyVertex newEndpoint = findSusceptibleVertex(g, v1.isInfected() ? v2 : v1, v1.isInfected() ? v1 : v2); if (newEndpoint != null) { commands.add(new EdgeBreakingCommand(g, e)); commands.add(new EdgeCreationCommand(controller.getEdgeFactory(), g, v1, newEndpoint)); } } } } private MyVertex findSusceptibleVertex(MyGraph<MyVertex, MyEdge> g, MyVertex origin, MyVertex oldEndoint) { //break current connection from origin to oldEndpoint and find another susceptible node // to connect origin to ArrayList<MyVertex> susceptibles = new ArrayList<MyVertex>(); for (MyVertex v : g.getVertices()) { if (v.isSusceptible() && v != origin && v != oldEndoint) { susceptibles.add(v); } } if (susceptibles.size() < 1) { // there aren't any susceptibles in the graph return null; } MyVertex[] candidates = new MyVertex[1]; candidates = susceptibles.toArray(candidates); while (true) { int i = rng.nextInt(susceptibles.size()); if (!g.isNeighbor(origin, candidates[i])) { //found a guy return candidates[i]; } } } /** * Once a chart has been created from an up-to-date data set, * set its range and ticks */ public void updateChartAxisParameters() { NumberAxis yAxis = (NumberAxis) xyPlot.getRangeAxis(); yAxis.setRange(0, g.getVertexCount()); yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); final NumberAxis domainAxis = (NumberAxis) xyPlot.getDomainAxis(); domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); } public void createInfectedCountGraph(JPanel statsPanel) { Dimension maxSize = statsPanel.getSize(); updateChartUnderlyingData(); XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(infectedXYSeries); // create the chart JFreeChart jfreechart = ChartFactory.createXYLineChart("", "", "Infected", dataset, PlotOrientation.VERTICAL, false, false, false); // save plot object so that we can update its axes if the graph changes xyPlot = (XYPlot) jfreechart.getPlot(); updateChartAxisParameters(); int maxHeight = (int) (0.6 * maxSize.getHeight()); //save vertical space int maxWidth = (int) maxSize.getWidth(); ChartPanel panel = new ChartPanel(jfreechart, maxWidth, maxHeight, maxWidth, maxHeight, maxWidth, maxHeight, true, true, false, false, false, false, true); statsPanel.setLayout(new FlowLayout()); statsPanel.removeAll(); statsPanel.add(panel); statsPanel.validate(); statsPanel.revalidate(); panel.repaint(); } /** * Updates the data that underlies the chart. This should fire an * event and force the chart to update */ public void updateChartUnderlyingData() { if (xValues.size() != yValues.size()) throw new IllegalStateException("X and Y data of chart has different length"); Double[] xarr = new Double[xValues.size()]; Integer[] yarr = new Integer[yValues.size()]; xarr = xValues.toArray(xarr); yarr = yValues.toArray(yarr); synchronized (infectedXYSeries){ infectedXYSeries.clear(); for (int i = 0; i < xarr.length; i++) { infectedXYSeries.add(xarr[i], yarr[i]); } } } public void pauseSim() { thread.pause(); } public void resumeSim() { thread.unpause(); } public void resumeSimForOneStep() { doOneStepOnly = true; thread.unpause(); } /** * Checks if a SUSCEPTIBLE node vertex second will get infected at this * time step. */ public void checkForInfection(MyGraph<MyVertex, MyEdge> g, LinkedList<SimulationCommand> commands) { for (MyEdge e : g.getEdges()) { MyVertex first = g.getEndpoints(e).getFirst(); MyVertex second = g.getEndpoints(e).getSecond(); if (first.isInfected() && second.isSusceptible()) { if (rng.nextFloat() < g.getDynamics().getInfectionProb()) //put on the waiting list to be infected at the next time step { commands.add(new ChangeSIRStateCommand (second, g.getDynamics().getNextState(second))); } } if (second.isInfected() && first.isSusceptible()) { if (rng.nextFloat() < g.getDynamics().getInfectionProb()) { commands.add(new ChangeSIRStateCommand(first, g.getDynamics().getNextState(first))); } } } } /** * Checks if the given vertex will recover at this step, it is assumed to be * infected, so make your own checks */ public void checkForRecovery(MyGraph<MyVertex, MyEdge> g, LinkedList<SimulationCommand> commands) { for (MyVertex vertex : g.getVertices()) if (vertex.isInfected()) if (rng.nextFloat() < g.getDynamics().getRecoveryProb()) { //put this vertex on the "waiting list" for recovery commands.add(new ChangeSIRStateCommand(vertex, g.getDynamics().getNextState(vertex))); } } class SimModelThread extends Thread { /** * Is the thread suspended? */ private volatile boolean suspended; /** * Is the thread alive? If this is set to false, the thread will die * gracefully */ private volatile boolean alive; /** * Starts the thread. */ public SimModelThread(String name) { super(name); alive = true; suspended = true; } /** * Suspends the thread. */ public synchronized void pause() { suspended = true; } /** * Resumes the thread. */ public synchronized void unpause() { suspended = false; notify(); } /** * Stops the thread. Invoked when the program exits. This method cannot * be named stop(). */ public synchronized void die() { alive = false; interrupt(); } /** * Returns true if the thread is not suspended and not dead */ public boolean isRunning() { return !suspended && alive; } /** * Invokes Model.doStep() and sleeps for sleepTime milliseconds */ public void run() { xValues = new CircularFifoBuffer<Double>(WINDOW_WIDTH); yValues = new CircularFifoBuffer<Integer>(WINDOW_WIDTH); while (alive) { try { sleep(g.getSleepTimeBetweenSteps()); synchronized (this) { while (suspended && alive && !doOneStepOnly) { wait(); } } doStepWithCurrentSettings(); //make sure if (doOneStepOnly) { doOneStepOnly = false; pause(); } } catch (InterruptedException e) { System.err.println("Interrupted"); e.printStackTrace(); } } } } public void doStepWithCurrentSettings() { doStep(g); stepNumber++; g.fireExtraEvent(new ExtraGraphEvent(g, ExtraGraphEvent.SIM_STEP_COMPLETE)); } private class SynchronisedXYSeries extends XYSeries{ public SynchronisedXYSeries(Comparable key, boolean autoSort, boolean allowDuplicateXValues) { super(key, autoSort, allowDuplicateXValues); } @Override public synchronized XYDataItem getDataItem(int index) { return super.getDataItem(index); } } }
package net.sf.cglib.reflect; import java.lang.reflect.*; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Type; abstract public class MulticastDelegate implements Cloneable { protected Object[] targets = {}; protected MulticastDelegate() { } public List getTargets() { return new ArrayList(Arrays.asList(targets)); } abstract public MulticastDelegate add(Object target); protected MulticastDelegate addHelper(Object target) { MulticastDelegate copy = newInstance(); copy.targets = new Object[targets.length + 1]; System.arraycopy(targets, 0, copy.targets, 0, targets.length); copy.targets[targets.length] = target; return copy; } public MulticastDelegate remove(Object target) { for (int i = targets.length - 1; i >= 0; i if (targets[i].equals(target)) { MulticastDelegate copy = newInstance(); copy.targets = new Object[targets.length - 1]; System.arraycopy(targets, 0, copy.targets, 0, i); System.arraycopy(targets, i + 1, copy.targets, i, targets.length - i - 1); return copy; } } return this; } abstract public MulticastDelegate newInstance(); public static MulticastDelegate create(Class iface) { Generator gen = new Generator(); gen.setInterface(iface); return gen.create(); } public static class Generator extends AbstractClassGenerator { private static final Source SOURCE = new Source(MulticastDelegate.class, true); private static final Signature NEW_INSTANCE = Signature.parse("net.sf.cglib.reflect.MulticastDelegate newInstance()"); private static final Signature ADD = Signature.parse("net.sf.cglib.reflect.MulticastDelegate add(Object)"); private static final Signature ADD_HELPER = Signature.parse("net.sf.cglib.reflect.MulticastDelegate addHelper(Object)"); private Class iface; public Generator() { super(SOURCE); } protected ClassLoader getDefaultClassLoader() { return iface.getClassLoader(); } public void setInterface(Class iface) { this.iface = iface; } public MulticastDelegate create() { return (MulticastDelegate)super.create(iface); } public void generateClass(ClassVisitor v) throws NoSuchFieldException { setNamePrefix(MulticastDelegate.class.getName()); final Method method = ReflectUtils.findInterfaceMethod(iface); final Emitter2 e = new Emitter2(v); Ops.begin_class(e, Modifier.PUBLIC, getClassName(), MulticastDelegate.class, new Class[]{ iface }, Constants.SOURCE_FILE); Ops.null_constructor(e); // generate proxied method Ops.begin_method(e, method); Type returnType = e.getReturnType(); final boolean returns = returnType != Type.VOID_TYPE; Local2 result = null; if (returns) { result = e.make_local(returnType); Ops.zero_or_null(e, returnType); e.store_local(result); } e.load_this(); e.super_getfield("targets", Types.OBJECT_ARRAY); final Local2 result2 = result; Ops.process_array(e, Types.OBJECT_ARRAY, new ProcessArrayCallback() { public void processElement(Type type) { e.checkcast(Type.getType(iface)); e.load_args(); Ops.invoke(e, method); if (returns) { e.store_local(result2); } } }); if (returns) { e.load_local(result); } e.return_value(); // newInstance e.begin_method(Constants.ACC_PUBLIC, NEW_INSTANCE, null); e.new_instance_this(); e.dup(); e.invoke_constructor_this(); e.return_value(); // add e.begin_method(Constants.ACC_PUBLIC, ADD, null); e.load_this(); e.load_arg(0); e.checkcast(Type.getType(iface)); e.invoke_virtual_this(ADD_HELPER); e.return_value(); e.end_class(); } protected Object firstInstance(Class type) { // make a new instance in case first object is used with a long list of targets return ((MulticastDelegate)ReflectUtils.newInstance(type)).newInstance(); } protected Object nextInstance(Object instance) { return ((MulticastDelegate)instance).newInstance(); } } }
package de.galan.commons.time; import static de.galan.commons.time.Instants.*; import static org.apache.commons.lang3.StringUtils.*; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.math.NumberUtils; import de.galan.commons.collection.SoftReferenceCache; /** * Utility class to handle human readable time durations. * * @author galan */ public class Durations { private static final Pattern PATTERN_HUMAN_TIME = Pattern .compile("^([0-9]+w)?[ ]*([0-9]+d)?[ ]*([0-9]+h)?[ ]*([0-9]+m[^s]{0})?[ ]*([0-9]+s)?[ ]*([0-9]+ms)?$"); public static final long MS_MILLISECOND = 1L; public static final long MS_SECOND = 1000L; public static final long MS_MINUTE = MS_SECOND * 60L; public static final long MS_HOUR = MS_MINUTE * 60L; public static final long MS_DAY = MS_HOUR * 24L; public static final long MS_WEEK = MS_DAY * 7L; /** Cache for calculated humantimes */ private static SoftReferenceCache<Long> humantimeCache; /** Prints how long the given date is in the future in the format "Xd Xh Xm Xs Xms" */ public static String timeLeft(Date date) { return timeLeft(date.toInstant()); } /** Prints how long the given date is in the future in the format "Xd Xh Xm Xs Xms" */ public static String timeLeft(Instant date) { return timeAgo(now(), date); } /** Prints how long the given date is ago in the format "Xd Xh Xm Xs Xms" */ public static String timeAgo(Date date) { return timeAgo(date.toInstant()); } /** Prints how long the given date is ago in the format "Xd Xh Xm Xs Xms" */ public static String timeAgo(Instant date) { return timeAgo(date, now()); } protected static String timeAgo(Instant date, Instant reference) { String result = ""; if ((date != null) && (reference != null)) { long time = reference.toEpochMilli() - date.toEpochMilli(); result = humanize(time, SPACE); } return result; } /** Converts a time in miliseconds to human readable duration in the format "Xd Xh Xm Xs Xms" */ public static String humanize(long time) { return humanize(time, EMPTY); } public static String humanize(long time, String separator) { StringBuilder result = new StringBuilder(); if (time == 0L) { result.append("0ms"); } else { long timeLeft = time; timeLeft = appendUnit(timeLeft, separator, MS_DAY, "d", result); timeLeft = appendUnit(timeLeft, separator, MS_HOUR, "h", result); timeLeft = appendUnit(timeLeft, separator, MS_MINUTE, "m", result); timeLeft = appendUnit(timeLeft, separator, MS_SECOND, "s", result); timeLeft = appendUnit(timeLeft, separator, MS_MILLISECOND, "ms", result); } return result.toString().trim(); } private static long appendUnit(long time, String separator, long unit, String text, StringBuilder buffer) { long result = time; if (time >= unit) { long hours = time / unit; buffer.append(hours); buffer.append(text); buffer.append(separator); result -= unit * hours; } return result; } private static SoftReferenceCache<Long> getHumantimeCache() { if (humantimeCache == null) { humantimeCache = new SoftReferenceCache<Long>(); } return humantimeCache; } /** Converts a human readable duration in the format "Xd Xh Xm Xs Xms" to miliseconds. */ public static Long dehumanize(String time) { Long result = getHumantimeCache().get(time); if (result == null) { if (isNotBlank(time)) { String input = time.trim(); if (NumberUtils.isDigits(input)) { result = NumberUtils.toLong(input); } else { Matcher matcher = PATTERN_HUMAN_TIME.matcher(input); if (matcher.matches()) { long sum = 0L; sum += dehumanizeUnit(matcher.group(1), MS_WEEK); sum += dehumanizeUnit(matcher.group(2), MS_DAY); sum += dehumanizeUnit(matcher.group(3), MS_HOUR); sum += dehumanizeUnit(matcher.group(4), MS_MINUTE); sum += dehumanizeUnit(matcher.group(5), MS_SECOND); sum += dehumanizeUnit(matcher.group(6), MS_MILLISECOND); result = sum; } } getHumantimeCache().put(time, result); } } return result; } private static long dehumanizeUnit(String group, long unit) { long result = 0L; if (isNotBlank(group)) { String longString = group.replaceAll("[a-z ]", ""); result = Long.valueOf(longString) * unit; } return result; } /** Converts a time in human readable format "Xd Xh Xm Xs Xms" to java.util.time.Duration (for interoperability). */ public static Duration toDuration(String time) { if (isBlank(time)) { return Duration.ZERO; } return Duration.of(dehumanize(time), ChronoUnit.MILLIS); } /** * Converts a time from java.util.time.Duration to human readable format "Xd Xh Xm Xs Xms" (for interoperability). */ public static String fromDuration(Duration duration) { if (duration == null) { return null; } return humanize(duration.get(ChronoUnit.MILLIS)); } }
package de.galan.commons.util; import static de.galan.commons.util.Sugar.*; import static org.apache.commons.lang3.StringUtils.*; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import de.galan.commons.logging.Say; import de.galan.commons.time.Durations; import de.galan.commons.time.Sleeper; /** * Invokes a Callable/ExceptionalRunnable until it runs without Exception the specified times of retries. */ public class Retryable { public static final String DEFAULT_WAIT_TIME = "1s"; public static final long INFINITE = -1; private long numberOfRetries; // total number of tries private long numberOfTriesLeft; // number left private String timeToWait; // wait interval private String message; // message to identify retry Retryable(long numberOfRetries) { retries(numberOfRetries); } public static Retryable retry(long numberOfRetries) { return new Retryable(numberOfRetries); } public static Retryable infinite() { return new Retryable(INFINITE); } public Retryable timeToWait(String timeToWaitBetween) { timeToWait = timeToWaitBetween; return this; } public Retryable timeToWait(long millis) { timeToWait = Durations.humanize(millis); return this; } public Retryable retries(long retries) { numberOfRetries = retries; numberOfTriesLeft = numberOfRetries + 1; return this; } public Retryable message(String msg) { message = msg; return this; } public <V> V call(Callable<V> callable) throws Exception { while(true) { try { return callable.call(); } catch (InterruptedException e) { throw e; } catch (CancellationException e) { throw e; } catch (Exception e) { numberOfTriesLeft if (numberOfRetries != INFINITE) { if (numberOfTriesLeft == 0) { throw new RetryException(numberOfRetries + " attempts to retry, failed at " + timeToWait + " interval for " + message, e, numberOfRetries, timeToWait, message); } if (isBlank(message)) { Say.info("Retrying {numberOfRetriesLeft}/{numberOfRetries} in {timeToWait}", numberOfRetries - numberOfTriesLeft + 1, numberOfRetries, timeToWait); } else { Say.info("Retrying {numberOfRetriesLeft}/{numberOfRetries} in {timeToWait} for {message}", numberOfRetries - numberOfTriesLeft + 1, numberOfRetries, timeToWait, message); } } else { if (isBlank(message)) { Say.info("Retrying {} in {}", Math.abs(numberOfTriesLeft + 1), timeToWait); } else { Say.info("Retrying {} in {} for {}", Math.abs(numberOfTriesLeft + 1), timeToWait, message); } } Sleeper.sleep(optional(timeToWait).orElse(DEFAULT_WAIT_TIME)); } } } public void run(ExceptionalRunnable runnable) throws Exception { call(() -> { runnable.run(); return null; }); } }
package models; import models.base.BaseModel; import play.db.jpa.JPA; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.ManyToOne; import javax.persistence.NoResultException; import java.util.Date; @Entity public class Token extends BaseModel { @ManyToOne public Client client; @ManyToOne public Account user; @Column(unique=true) public String accessToken; public Date expires; @Override public void create() { JPA.em().persist(this); } @Override public void update() { } @Override public void delete() { } public static Token findByAccesToken(String accessToken) { try{ return (Token) JPA.em() .createQuery("from Token a where a.accessToken = :accessToken") .setParameter("accessToken", accessToken).getSingleResult(); } catch (NoResultException exp) { return null; } } }
package de.htw_berlin.HoboOthello.KI; import de.htw_berlin.HoboOthello.Core.*; import java.util.ArrayList; import java.util.List; public class KI extends Player { private Color kiColor; private Level level; private Board board; private Field field; private GameRule gameRule; public KI(Color kiColor) { this.kiColor = kiColor; } /** * Method which will be used by the controller to let the KI pick a field * * @param board actual board, information for the KI to act upon * @return field with coordinates where the KI wants to put down a stone, * return field is null in case there is no possible move for the KI */ public Field setMove(Board board) { Field fieldToSetMove = null; if (level == level.LEVEL1) { fieldToSetMove = pickRandomFieldFromList(); return fieldToSetMove; } if (level == level.LEVEL2) { fieldToSetMove = pickCornerOrSideFieldFromList(); if (fieldToSetMove == null) { fieldToSetMove = pickRandomFieldFromList(); } return fieldToSetMove; } if (level == level.LEVEL3) { return fieldToSetMove; } else { throw new IllegalArgumentException("Level of KI is off...!"); } } /** * Method which lists all possible moves for the KI * * @return listOfPossibleMoves */ private List<Field> listPossibleMoves() { List<Field> listOfPossibleMoves = new ArrayList<Field>(); for (Field field : board.iterateThroughAllFields()) { if (gameRule.isMoveAllowed(field, kiColor)) { listOfPossibleMoves.add(field); } } return listOfPossibleMoves; } /** * Method which picks a random move from the list of all possible moves for the KI * * @return field which is randomly chosen by this method */ private Field pickRandomFieldFromList() { Field fieldToSet; List<Field> listOfPossibleMoves = listPossibleMoves(); int randomNumber = (int) (Math.random() * listOfPossibleMoves.size()); // picks random index of field in list fieldToSet = listOfPossibleMoves.get(randomNumber); return fieldToSet; } /** * Method which picks the first possible corner field or the first possible side field for a turn * If there are no corner or side fields possible for this turn, this method returns null * * @return cornerOrSideField a possible corner or side field, null field if both are impossible */ private Field pickCornerOrSideFieldFromList() { List<Field> listOfPossibleMoves = listPossibleMoves(); Field cornerOrSideField = null; int cornerFieldIndex = 0; while (cornerFieldIndex < listOfPossibleMoves.size()) { Field field = listOfPossibleMoves.get(cornerFieldIndex); if (board.isCornerField(field)) { cornerOrSideField = field; } else { cornerFieldIndex++; } } int sideFieldIndex = 0; while (sideFieldIndex < listOfPossibleMoves.size()) { Field field = listOfPossibleMoves.get(sideFieldIndex); if (board.isSideField(field)) { cornerOrSideField = field; } else { sideFieldIndex++; } } return cornerOrSideField; } private List<Field> listFieldsNotTooCloseToBorder() { List<Field> listOfPossibleMoves = listPossibleMoves(); List<Field> listOfFieldsNotCloseToBorder = null; int count = 0; while (count < listOfPossibleMoves.size()) { Field field = listOfPossibleMoves.get(count); if (board.isNotSideMinusOneField(field)) { listOfFieldsNotCloseToBorder.add(field); } else { count++; } } return listOfFieldsNotCloseToBorder; } private Field pickTacticalField() { List<Field> listOfFieldsNotTooCloseToBorder = listFieldsNotTooCloseToBorder(); List<Field> allPossibleMoves = listPossibleMoves(); Field tacticalField = null; int soManyFlipped; int mostFlipped = 0; for (int fieldIndex = 0; fieldIndex < listOfFieldsNotTooCloseToBorder.size(); fieldIndex++) { soManyFlipped = testHowManyStonesAreFlipped(listOfFieldsNotTooCloseToBorder.get(fieldIndex)); if (soManyFlipped > mostFlipped){ tacticalField = listOfFieldsNotTooCloseToBorder.get(soManyFlipped); mostFlipped = soManyFlipped; } } return tacticalField; } private int testHowManyStonesAreFlipped(Field field){ int actualNumberOfStones = board.getNumberOfFieldsOccupiedByStone(kiColor); gameRule.setMove(field, kiColor); int newNumberOfStones = board.getNumberOfFieldsOccupiedByStone(kiColor); int soManyStonesFlipped = (newNumberOfStones - actualNumberOfStones); return soManyStonesFlipped; } /* int randomNumber = (int) (Math.random() * listOfFieldsNotCloseToBorder.size()); // picks random index of field in list fieldToSet = listOfFieldsNotCloseToBorder.get(randomNumber); return fieldToSet; */ }
package de.is24.deadcode4j; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Map; /** * <code>AnalyzedCode</code> comprises the classes being analyzed as well as the code dependencies. * * @since 1.0.0 */ public class AnalyzedCode { private final Collection<String> analyzedClasses; private final Map<String, ? extends Iterable<String>> codeDependencies; public AnalyzedCode(@Nonnull Collection<String> analyzedClasses, @Nonnull Map<String, ? extends Iterable<String>> codeDependencies) { this.analyzedClasses = analyzedClasses; this.codeDependencies = codeDependencies; } @Nonnull public Collection<String> getAnalyzedClasses() { return analyzedClasses; } /** * Returns a map consisting of code artifacts (typically classes) pointing to their dependencies. */ @Nonnull public Map<String, ? extends Iterable<String>> getCodeDependencies() { return codeDependencies; } }
package de.prob2.ui.menu; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import de.be4.classicalb.core.parser.exceptions.BException; import de.codecentric.centerdevice.MenuToolkit; import de.prob.scripting.Api; import de.prob.statespace.AnimationSelector; import de.prob.statespace.StateSpace; import de.prob.statespace.Trace; import de.prob2.ui.consoles.b.BConsoleStage; import de.prob2.ui.consoles.groovy.GroovyConsoleStage; import de.prob2.ui.dotty.DottyStage; import de.prob2.ui.formula.FormulaGenerator; import de.prob2.ui.modelchecking.ModelcheckingController; import de.prob2.ui.preferences.PreferencesStage; import de.prob2.ui.prob2fx.CurrentStage; import de.prob2.ui.prob2fx.CurrentTrace; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.control.Alert; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.TextInputDialog; import javafx.scene.input.KeyCombination; import javafx.scene.layout.AnchorPane; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.stage.Window; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public final class MenuController extends MenuBar { private static final Logger logger = LoggerFactory.getLogger(MenuController.class); private final Injector injector; private final Api api; private final AnimationSelector animationSelector; private final CurrentStage currentStage; private final CurrentTrace currentTrace; private final FormulaGenerator formulaGenerator; private final RecentFiles recentFiles; private Window window; @FXML private Menu recentFilesMenu; @FXML private MenuItem recentFilesPlaceholder; @FXML private MenuItem clearRecentFiles; @FXML private Menu windowMenu; @FXML private MenuItem preferencesItem; @FXML private MenuItem enterFormulaForVisualization; @FXML private MenuItem aboutItem; @Inject private MenuController( final FXMLLoader loader, final Injector injector, final Api api, final AnimationSelector animationSelector, final CurrentStage currentStage, final CurrentTrace currentTrace, final FormulaGenerator formulaGenerator, final RecentFiles recentFiles ) { this.injector = injector; this.api = api; this.animationSelector = animationSelector; this.currentStage = currentStage; this.currentTrace = currentTrace; this.formulaGenerator = formulaGenerator; this.recentFiles = recentFiles; loader.setLocation(getClass().getResource("menu.fxml")); loader.setRoot(this); loader.setController(this); try { loader.load(); } catch (IOException e) { logger.error("loading fxml failed", e); } if (System.getProperty("os.name", "").toLowerCase().contains("mac")) { // Mac-specific menu stuff this.setUseSystemMenuBar(true); final MenuToolkit tk = MenuToolkit.toolkit(); // Remove About menu item from Help aboutItem.getParentMenu().getItems().remove(aboutItem); aboutItem.setText("About ProB 2"); // Remove Preferences menu item from Edit preferencesItem.getParentMenu().getItems().remove(preferencesItem); preferencesItem.setAccelerator(KeyCombination.valueOf("Shortcut+,")); // Create Mac-style application menu final Menu applicationMenu = tk.createDefaultApplicationMenu("ProB 2"); this.getMenus().add(0, applicationMenu); tk.setApplicationMenu(applicationMenu); applicationMenu.getItems().setAll(aboutItem, new SeparatorMenuItem(), preferencesItem, new SeparatorMenuItem(), tk.createHideMenuItem("ProB 2"), tk.createHideOthersMenuItem(), tk.createUnhideAllMenuItem(), new SeparatorMenuItem(), tk.createQuitMenuItem("ProB 2")); // Add Mac-style items to Window menu windowMenu.getItems().addAll(tk.createMinimizeMenuItem(), tk.createZoomMenuItem(), tk.createCycleWindowsItem(), new SeparatorMenuItem(), tk.createBringAllToFrontItem(), new SeparatorMenuItem()); tk.autoAddWindowMenuItems(windowMenu); // Make this the global menu bar tk.setGlobalMenuBar(this); } } @FXML public void initialize() { this.sceneProperty().addListener((observable, from, to) -> { if (to != null) { to.windowProperty().addListener((observable1, from1, to1) -> this.window = to1); } }); final ListChangeListener<String> recentFilesListener = change -> { final ObservableList<MenuItem> recentItems = this.recentFilesMenu.getItems(); final List<MenuItem> newItems = new ArrayList<>(); for (String s : this.recentFiles) { final MenuItem item = new MenuItem(new File(s).getName()); item.setOnAction(event -> this.open(s)); newItems.add(item); } // If there are no recent files, show a placeholder and disable clearing this.clearRecentFiles.setDisable(newItems.isEmpty()); if (newItems.isEmpty()) { newItems.add(this.recentFilesPlaceholder); } // Add a shortcut for reopening the most recent file newItems.get(0).setAccelerator(KeyCombination.valueOf("Shift+Shortcut+'O'")); // Keep the last two items (the separator and the "clear recent files" item) newItems.addAll(recentItems.subList(recentItems.size()-2, recentItems.size())); // Replace the old recents with the new ones this.recentFilesMenu.getItems().setAll(newItems); }; this.recentFiles.addListener(recentFilesListener); // Fire the listener once to populate the recent files menu recentFilesListener.onChanged(null); this.enterFormulaForVisualization.disableProperty().bind(currentTrace.currentStateProperty().initializedProperty().not()); } @FXML private void handleClearRecentFiles() { this.recentFiles.clear(); } @FXML private void handleLoadDefault() { loadPreset("../main.fxml"); } @FXML private void handleLoadDetached() { loadPreset("../detachedHistory.fxml"); } @FXML private void handleLoadDetached2() { loadPreset("../detachedHistoryAndStatistics.fxml"); } @FXML private void handleLoadStacked() { loadPreset("../stackedLists.fxml"); } @FXML private void handleLoadPerspective() { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open File"); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("FXML Files", "*.fxml")); File selectedFile = fileChooser.showOpenDialog(window); if (selectedFile != null) { try { FXMLLoader loader = injector.getInstance(FXMLLoader.class); loader.setLocation(selectedFile.toURI().toURL()); Parent root = loader.load(); window.getScene().setRoot(root); } catch (IOException e) { logger.error("loading fxml failed", e); Alert alert = new Alert(Alert.AlertType.ERROR, "Could not open file:\n" + e); alert.getDialogPane().getStylesheets().add("prob.css"); alert.showAndWait(); } } } private void open(String path) { final StateSpace newSpace; try { newSpace = this.api.b_load(path); } catch (IOException | BException e) { logger.error("loading file failed", e); Alert alert = new Alert(Alert.AlertType.ERROR, "Could not open file:\n" + e); alert.getDialogPane().getStylesheets().add("prob.css"); alert.showAndWait(); return; } this.animationSelector.addNewAnimation(new Trace(newSpace)); injector.getInstance(ModelcheckingController.class).resetView(); // Remove the path first to avoid listing the same file twice. this.recentFiles.remove(path); this.recentFiles.add(0, path); } @FXML private void handleOpen(ActionEvent event) { final FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open File"); fileChooser.getExtensionFilters().addAll( // new FileChooser.ExtensionFilter("All Files", "*.*"), new FileChooser.ExtensionFilter("Classical B Files", "*.mch", "*.ref", "*.imp") // new FileChooser.ExtensionFilter("EventB Files", "*.eventb", "*.bum", "*.buc"), // new FileChooser.ExtensionFilter("CSP Files", "*.cspm") ); final File selectedFile = fileChooser.showOpenDialog(this.window); if (selectedFile == null) { return; } switch (fileChooser.getSelectedExtensionFilter().getDescription()) { case "Classical B Files": this.open(selectedFile.getAbsolutePath()); break; default: throw new IllegalStateException( "Unknown file type selected: " + fileChooser.getSelectedExtensionFilter().getDescription()); } } @FXML private void handleClose(final ActionEvent event) { final Stage stage = this.currentStage.get(); if (stage != null) { stage.close(); } } @FXML private void handlePreferences(ActionEvent event) { final Stage preferencesStage = injector.getInstance(PreferencesStage.class); preferencesStage.show(); preferencesStage.toFront(); } @FXML private void handleFormulaInput(ActionEvent event) { TextInputDialog dialog = new TextInputDialog(); dialog.setTitle("Enter Formula for Visualization"); dialog.setHeaderText("Enter Formula for Visualization"); dialog.setContentText("Enter Formula: "); dialog.getDialogPane().getStylesheets().add("prob.css"); Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { formulaGenerator.parseAndShowFormula(result.get()); } } @FXML private void handleDotty(ActionEvent event) { injector.getInstance(DottyStage.class).showAndWait(); } @FXML public void handleGroovyConsole(ActionEvent event) { final Stage groovyConsoleStage = injector.getInstance(GroovyConsoleStage.class); groovyConsoleStage.show(); groovyConsoleStage.toFront(); } @FXML public void handleBConsole(ActionEvent event) { final Stage bConsoleStage = injector.getInstance(BConsoleStage.class); bConsoleStage.show(); bConsoleStage.toFront(); } private void loadPreset(String location) { FXMLLoader loader = injector.getInstance(FXMLLoader.class); loader.setLocation(getClass().getResource(location)); Parent root; try { root = loader.load(); } catch (IOException e) { logger.error("loading fxml failed", e); Alert alert = new Alert(Alert.AlertType.ERROR, "Could not open file:\n" + e); alert.getDialogPane().getStylesheets().add("prob.css"); alert.showAndWait(); return; } window.getScene().setRoot(root); animationSelector.changeCurrentAnimation(currentTrace.get()); if (System.getProperty("os.name", "").toLowerCase().contains("mac")) { final MenuToolkit tk = MenuToolkit.toolkit(); tk.setGlobalMenuBar(this); tk.setApplicationMenu(this.getMenus().get(0)); } } }
package entities.sub_entity; import com.fasterxml.jackson.annotation.JsonBackReference; import entities.super_entity.CoreEntity; import javax.persistence.*; import java.sql.Date; @Entity public class WeatherInfo extends CoreEntity { private double temp; private String date; private int airPressure; private byte humidity; private double windForce; private int cloudBase; private byte okta; private String cloudType; private String windDirection; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "weather_station_id") @JsonBackReference private WeatherStation weatherStation; public WeatherInfo(){} public WeatherInfo(String date , int airPressure , byte humidity , double windForce , int cloudBase , byte okta , String windDirection , String cloudType , double temp ){ this.date = date; this.airPressure = airPressure; this.humidity = humidity; this.windForce = windForce; this.cloudBase = cloudBase; this.okta = okta; this.windDirection = windDirection; this.cloudType = cloudType; this.temp = temp; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public int getAirPressure() { return airPressure; } public void setAirPressure(int airPressure) { this.airPressure = airPressure; } public byte getHumidity() { return humidity; } public void setHumidity(byte humidity) { this.humidity = humidity; } public double getWindForce() { return windForce; } public void setWindForce(double windForce) { this.windForce = windForce; } public int getCloudBase() { return cloudBase; } public void setCloudBase(int cloudBase) { this.cloudBase = cloudBase; } public byte getOkta() { return okta; } public void setOkta(byte okta) { this.okta = okta; } public String getCloudType() { return cloudType; } public void setCloudType(String cloudType) { this.cloudType = cloudType; } public String getWindDirection() { return windDirection; } public void setWindDirection(String windDirection) { this.windDirection = windDirection; } public WeatherStation getWeatherStation() { return weatherStation; } public void setWeatherStation(WeatherStation weatherStation) { this.weatherStation = weatherStation; } public double getTemp() { return temp; } public void setTemp(double temp) { this.temp = temp; } }
package fr.aumgn.tobenamed.region; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import fr.aumgn.tobenamed.util.Vector; public class Totem extends Region { public Totem(Vector pos) { super(pos.subtract(3, 1, 3), pos.add(3, 5, 3)); } public void create(World world) { int y = min.getY(); Vector fMin = min; Vector fMax = max; for (int x = fMin.getX(); x <= fMax.getX(); x++) { setEdge(world, x, y, fMin.getZ()); setEdge(world, x, y, fMax.getZ()); } fMin = fMin.add(0, 0, 1); fMax = fMax.subtract(0, 0, 1); for (int z = fMin.getZ(); z <= fMax.getZ(); z++) { setEdge(world, fMin.getX(), y, z); setEdge(world, fMax.getX(), y, z); } fMin = fMin.add(1, 0, 0); fMax = fMax.subtract(1, 0, 0); for (int x = fMin.getX(); x <= fMax.getX(); x++) { for (int z = fMin.getZ(); z <= fMax.getZ(); z++) { setInside(world, x, y, z); } } createTotem(world); } private void setEdge(World world, int x, int y, int z) { Block block = world.getBlockAt(x, y, z); block.setType(Material.SMOOTH_BRICK); block.setData((byte) 3); } private void setInside(World world, int x, int y, int z) { Block block = world.getBlockAt(x, y, z); block.setType(Material.SMOOTH_BRICK); } private void createTotem(World world) { Vector pos = min.getMiddle(max).setY(min.getY() + 1); for (int i = 1; i <= 3; i++) { setTotemBlock(world, pos.add(0, i, 0)); } setTotemBlock(world, pos.add( 1, 3, 0)); setTotemBlock(world, pos.add(-1, 3, 0)); setTorchBlock(world, pos.add(-1, 3, -1)); setTorchBlock(world, pos.add(-1, 3, 1)); } private void setTotemBlock(World world, Vector pos) { Block block = world.getBlockAt(pos.getX(), pos.getY(), pos.getZ()); block.setType(Material.OBSIDIAN); } private void setTorchBlock(World world, Vector pos) { Block block = world.getBlockAt(pos.getX(), pos.getY(), pos.getZ()); block.setType(Material.TORCH); } }
package hudson.plugins.git; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.model.*; import hudson.scm.AbstractScmTagAction; import hudson.security.Permission; import hudson.util.CopyOnWriteMap; import hudson.util.MultipartFormDataParser; import jenkins.model.*; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import org.kohsuke.stapler.interceptor.RequirePOST; import javax.servlet.ServletException; import java.io.File; import java.io.IOException; import java.util.*; /** * @author Nicolas de Loof */ @ExportedBean public class GitTagAction extends AbstractScmTagAction implements Describable<GitTagAction> { /** * Map is from the repository URL to the URLs of tags. * If a module is not tagged, the value will be empty list. * Never an empty map. */ private final Map<String, List<String>> tags = new CopyOnWriteMap.Tree<>(); private final String ws; private String lastTagName = null; private GitException lastTagException = null; protected GitTagAction(Run build, FilePath workspace, Revision revision) { super(build); this.ws = workspace.getRemote(); if (revision.getBranches() != null) { for (Branch b : revision.getBranches()) { tags.put(b.getName(), new ArrayList<>()); } } } public Descriptor<GitTagAction> getDescriptor() { Jenkins jenkins = Jenkins.get(); return jenkins.getDescriptorOrDie(getClass()); } @Override public boolean isTagged() { for (List<String> t : tags.values()) { if (!t.isEmpty()) return true; } return false; } @Override public String getIconFileName() { if (!isTagged() && !getACL().hasPermission(getPermission())) return null; return "save.gif"; } @Override public String getDisplayName() { int nonNullTag = 0; for (List<String> v : tags.values()) { if (!v.isEmpty()) { nonNullTag += v.size(); if (nonNullTag > 1) break; } } if (nonNullTag == 0) return "No Tags"; if (nonNullTag == 1) return "One tag"; else return "Multiple tags"; } /** * @see #tags * @return tag names and annotations for this repository */ public Map<String, List<String>> getTags() { return Collections.unmodifiableMap(tags); } @Exported(name = "tags") public List<TagInfo> getTagInfo() { List<TagInfo> data = new ArrayList<>(); for (Map.Entry<String, List<String>> e : tags.entrySet()) { String module = e.getKey(); for (String tag : e.getValue()) data.add(new TagInfo(module, tag)); } return data; } @ExportedBean public static class TagInfo { private final String module; private final String url; private TagInfo(String branch, String tag) { this.module = branch; this.url = tag; } @Exported public String getBranch() { return module; } @Exported public String getTag() { return url; } } @Override public String getTooltip() { String tag = null; for (List<String> v : tags.values()) { for (String s : v) { if (tag != null) return "Tagged"; // Multiple tags tag = s; } } if (tag != null) return "Tag: " + tag; else return null; } /** * Invoked to actually tag the workspace. * @param req request for submit * @param rsp response used to send result * @throws IOException on input or output error * @throws ServletException on servlet error */ @RequirePOST public synchronized void doSubmit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { getACL().checkPermission(getPermission()); try (MultipartFormDataParser parser = new MultipartFormDataParser(req)) { Map<String, String> newTags = new HashMap<>(); int i = -1; for (String e : tags.keySet()) { i++; if (tags.size() > 1 && parser.get("tag" + i) == null) continue; // when tags.size()==1, UI won't show the checkbox. newTags.put(e, parser.get("name" + i)); } scheduleTagCreation(newTags, parser.get("comment")); rsp.sendRedirect("."); } } /** * Schedule creation of a tag. For test purposes only, not to be called outside this package. * * @param newTags tags to be created * @param comment tag comment to be included with created tags * @throws IOException on IO error * @throws ServletException on servlet exception */ void scheduleTagCreation(Map<String, String> newTags, String comment) throws IOException, ServletException { new TagWorkerThread(newTags, comment).start(); } /** * The thread that performs tagging operation asynchronously. */ public final class TagWorkerThread extends TaskThread { private final Map<String, String> tagSet; public TagWorkerThread(Map<String, String> tagSet,String ignoredComment) { super(GitTagAction.this, ListenerAndText.forMemory(null)); this.tagSet = tagSet; } @Override protected void perform(final TaskListener listener) throws Exception { final EnvVars environment = getRun().getEnvironment(listener); final FilePath workspace = new FilePath(new File(ws)); final GitClient git = Git.with(listener, environment) .in(workspace) .getClient(); for (Map.Entry<String, String> entry : tagSet.entrySet()) { try { String buildNum = "jenkins-" + getRun().getParent().getName().replace(" ", "_") + "-" + entry.getValue(); git.tag(entry.getValue(), "Jenkins Build #" + buildNum); lastTagName = entry.getValue(); for (Map.Entry<String, String> e : tagSet.entrySet()) GitTagAction.this.tags.get(e.getKey()).add(e.getValue()); getRun().save(); workerThread = null; } catch (GitException ex) { lastTagException = ex; ex.printStackTrace(listener.error("Error tagging repo '%s' : %s", entry.getKey(), ex.getMessage())); // Failed. Try the next one listener.getLogger().println("Trying next branch"); } } } } @Override public Permission getPermission() { return GitSCM.TAG; } /** * Just for assisting form related stuff. */ @Extension public static class DescriptorImpl extends Descriptor<GitTagAction> { @Override public String getDisplayName() { return "Tag"; } } /* Package protected for use only by tests */ String getLastTagName() { return lastTagName; } /* Package protected for use only by tests */ GitException getLastTagException() { return lastTagException; } }
package id.ac.unpar.siamodels; import java.net.URL; import java.time.LocalDate; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeSet; public class Mahasiswa { protected final String npm; protected String nama; protected final List<Nilai> riwayatNilai; protected URL photoURL; protected List<JadwalKuliah> jadwalKuliahList; protected SortedMap<LocalDate, Integer> nilaiTOEFL; public Mahasiswa(String npm) throws NumberFormatException { super(); if (!npm.matches("[0-9]{10}")) { throw new NumberFormatException("NPM tidak valid: " + npm); } this.npm = npm; this.riwayatNilai = new ArrayList<Nilai>(); } public String getNama() { return nama; } public void setNama(String nama) { this.nama = nama; } public String getNpm() { return npm; } public URL getPhotoURL() { return photoURL; } public void setPhotoURL(URL photoURL) { this.photoURL = photoURL; } public List<JadwalKuliah> getJadwalKuliahList() { return jadwalKuliahList; } public void setJadwalKuliahList(List<JadwalKuliah> jadwalKuliahList) { this.jadwalKuliahList = jadwalKuliahList; } public String getEmailAddress() { return npm.substring(4, 6) + npm.substring(2, 4) + npm.substring(7, 10) + "@student.unpar.ac.id"; } public List<Nilai> getRiwayatNilai() { return riwayatNilai; } public SortedMap<LocalDate, Integer> getNilaiTOEFL(){ return nilaiTOEFL; } public void setNilaiTOEFL(SortedMap<LocalDate, Integer> nilaiTOEFL){ this.nilaiTOEFL = nilaiTOEFL; } /** * Menghitung IPK mahasiswa sampai saat ini, dengan aturan: * <ul> * <li>Kuliah yang tidak lulus tidak dihitung * <li>Jika pengambilan beberapa kali, diambil <em>nilai terbaik</em>. * </ul> * Sebelum memanggil method ini, {@link #getRiwayatNilai()} harus sudah mengandung nilai per mata kuliah! * @return IPK Lulus, atau {#link {@link Double#NaN}} jika belum mengambil satu kuliah pun. * @deprecated Gunakan {@link #calculateIPLulus()}, nama lebih konsisten dengan DPS. */ public double calculateIPKLulus() throws ArrayIndexOutOfBoundsException { return calculateIPTempuh(true); } /** * Menghitung IP mahasiswa sampai saat ini, dengan aturan: * <ul> * <li>Kuliah yang tidak lulus tidak dihitung * <li>Jika pengambilan beberapa kali, diambil <em>nilai terbaik</em>. * </ul> * Sebelum memanggil method ini, {@link #getRiwayatNilai()} harus sudah mengandung nilai per mata kuliah! * @return IPK Lulus, atau {#link {@link Double#NaN}} jika belum mengambil satu kuliah pun. */ public double calculateIPLulus() throws ArrayIndexOutOfBoundsException { return calculateIPTempuh(true); } /** * Menghitung IP mahasiswa sampai saat ini, dengan aturan: * <ul> * <li>Perhitungan kuliah yang tidak lulus ditentukan parameter * <li>Jika pengambilan beberapa kali, diambil <em>nilai terbaik</em>. * </ul> * @param lulusSaja set true jika ingin membuang mata kuliah tidak lulus, false jika ingin semua (sama dengan "IP N. Terbaik" di DPS) * Sebelum memanggil method ini, {@link #getRiwayatNilai()} harus sudah mengandung nilai per mata kuliah! * @return IPK Lulus, atau {#link {@link Double#NaN}} jika belum mengambil satu kuliah pun. */ public double calculateIPTempuh(boolean lulusSaja) throws ArrayIndexOutOfBoundsException { List<Nilai> riwayatNilai = getRiwayatNilai(); if (riwayatNilai.size() == 0) { return Double.NaN; } Map<String, Double> nilaiTerbaik = new HashMap<String, Double>(); int totalSKS = 0; // Cari nilai lulus terbaik setiap kuliah for (Nilai nilai: riwayatNilai) { if (nilai.getNilaiAkhir() == null) { continue; } if (lulusSaja && nilai.getNilaiAkhir().equals('E')) { continue; } String kodeMK = nilai.getMataKuliah().getKode(); Double angkaAkhir = nilai.getAngkaAkhir(); int sks = nilai.getMataKuliah().getSks(); if (!nilaiTerbaik.containsKey(kodeMK)) { totalSKS += sks; nilaiTerbaik.put(kodeMK, sks * angkaAkhir); } else if (sks * angkaAkhir > nilaiTerbaik.get(kodeMK)) { nilaiTerbaik.put(kodeMK, sks * angkaAkhir); } } // Hitung IPK dari nilai-nilai terbaik double totalNilai = 0.0; for (Double nilaiAkhir: nilaiTerbaik.values()) { totalNilai += nilaiAkhir; } return totalNilai / totalSKS; } /** * Menghitung IP Kumulatif mahasiswa sampai saat ini, dengan aturan: * <ul> * <li>Jika pengambilan beberapa kali, diambil semua. * </ul> * Sebelum memanggil method ini, {@link #getRiwayatNilai()} harus sudah mengandung nilai per mata kuliah! * @return IPK Lulus, atau {#link {@link Double#NaN}} jika belum mengambil satu kuliah pun. */ public double calculateIPKumulatif() throws ArrayIndexOutOfBoundsException { List<Nilai> riwayatNilai = getRiwayatNilai(); if (riwayatNilai.size() == 0) { return Double.NaN; } double totalNilai = 0.0; int totalSKS = 0; // Cari nilai setiap kuliah for (Nilai nilai: riwayatNilai) { if (nilai.getNilaiAkhir() == null) { continue; } Double angkaAkhir = nilai.getAngkaAkhir(); int sks = nilai.getMataKuliah().getSks(); totalSKS += sks; totalNilai += sks * angkaAkhir; } return totalNilai / totalSKS; } /** * Menghitung IPK mahasiswa sampai saat ini, dengan aturan: * <ul> * <li>Perhitungan kuliah yang tidak lulus ditentukan parameter * <li>Jika pengambilan beberapa kali, diambil <em>nilai terbaik</em>. * </ul> * @param lulusSaja set true jika ingin membuang mata kuliah tidak lulus * Sebelum memanggil method ini, {@link #getRiwayatNilai()} harus sudah mengandung nilai per mata kuliah! * @return IPK Lulus, atau {#link {@link Double#NaN}} jika belum mengambil satu kuliah pun. * @deprecated Gunakan {@link #calculateIPKTempuh(boolean)}, nama lebih konsisten dengan DPS. */ public double calculateIPKTempuh(boolean lulusSaja) throws ArrayIndexOutOfBoundsException { return calculateIPTempuh(lulusSaja); } /** * Menghitung IPS semester terakhir sampai saat ini, dengan aturan: * <ul> * <li>Kuliah yang tidak lulus <em>dihitung</em>. * </ul> * Sebelum memanggil method ini, {@link #getRiwayatNilai()} harus sudah mengandung nilai per mata kuliah! * @return nilai IPS sampai saat ini * @throws ArrayIndexOutOfBoundsException jika belum ada nilai satupun */ public double calculateIPS() throws ArrayIndexOutOfBoundsException { List<Nilai> riwayatNilai = getRiwayatNilai(); if (riwayatNilai.size() == 0) { throw new ArrayIndexOutOfBoundsException("Minimal harus ada satu nilai untuk menghitung IPS"); } int lastIndex = riwayatNilai.size() - 1; TahunSemester tahunSemester = riwayatNilai.get(lastIndex).getTahunSemester(); double totalNilai = 0; double totalSKS = 0; for (int i = lastIndex; i >= 0; i Nilai nilai = riwayatNilai.get(i); if (nilai.tahunSemester.equals(tahunSemester)) { if (nilai.getAngkaAkhir() != null) { totalNilai += nilai.getMataKuliah().getSks() * nilai.getAngkaAkhir(); totalSKS += nilai.getMataKuliah().getSks(); } } else { break; } } return totalNilai / totalSKS; } /** * Menghitung jumlah SKS lulus mahasiswa saat ini. * Sebelum memanggil method ini, {@link #getRiwayatNilai()} harus sudah mengandung nilai per mata kuliah! * @return SKS Lulus */ public int calculateSKSLulus() throws ArrayIndexOutOfBoundsException { return calculateSKSTempuh(true); } /** * Menghitung jumlah SKS tempuh mahasiswa saat ini. * Sebelum memanggil method ini, {@link #getRiwayatNilai()} harus sudah mengandung nilai per mata kuliah! * @param lulusSaja set true jika ingin membuang SKS tidak lulus * @return SKS tempuh */ public int calculateSKSTempuh(boolean lulusSaja) throws ArrayIndexOutOfBoundsException { List<Nilai> riwayatNilai = getRiwayatNilai(); Set<String> sksTerhitung = new HashSet<String>(); int totalSKS = 0; // Tambahkan SKS setiap kuliah for (Nilai nilai: riwayatNilai) { if (nilai.getNilaiAkhir() == null) { continue; } if (lulusSaja && nilai.getNilaiAkhir().equals('E')) { continue; } String kodeMK = nilai.getMataKuliah().getKode(); if (!sksTerhitung.contains(kodeMK)) { totalSKS += nilai.getMataKuliah().getSks(); sksTerhitung.add(kodeMK); } } return totalSKS; } /** * Mendapatkan seluruh tahun semester di mana mahasiswa ini tercatat * sebagai mahasiswa aktif, dengan strategi memeriksa riwayat nilainya. * Jika ada satu nilai saja pada sebuah tahun semester, maka dianggap * aktif pada semester tersebut. * @return kumpulan tahun semester di mana mahasiswa ini aktif */ public Set<TahunSemester> calculateTahunSemesterAktif() { Set<TahunSemester> tahunSemesterAktif = new TreeSet<TahunSemester>(); List<Nilai> riwayatNilai = getRiwayatNilai(); for (Nilai nilai: riwayatNilai) { tahunSemesterAktif.add(nilai.getTahunSemester()); } return tahunSemesterAktif; } /** * Memeriksa apakah mahasiswa ini sudah lulus mata kuliah tertentu. Kompleksitas O(n). * Sebelum memanggil method ini, {@link #getRiwayatNilai()} harus sudah mengandung nilai per mata kuliah! * Note: jika yang dimiliki adalah {@link MataKuliah}, gunakanlah {@link MataKuliah#getKode()}. * @param kodeMataKuliah kode mata kuliah yang ingin diperiksa kelulusannya. * @return true jika sudah pernah mengambil dan lulus, false jika belum */ public boolean hasLulusKuliah(String kodeMataKuliah) { for (Nilai nilai: riwayatNilai) { if (nilai.getMataKuliah().getKode().equals(kodeMataKuliah)) { Character na = nilai.getNilaiAkhir(); if (na != null && na >= 'A' && na <= 'D') { return true; } } } return false; } /** * Memeriksa apakah mahasiswa ini sudah pernah menempuh mata kuliah tertentu. Kompleksitas O(n). * Sebelum memanggil method ini, {@link #getRiwayatNilai()} harus sudah ada isinya! * Note: jika yang dimiliki adalah {@link MataKuliah}, gunakanlah {@link MataKuliah#getKode()}. * @param kodeMataKuliah kode mata kuliah yang ingin diperiksa. * @return true jika sudah pernah mengambil, false jika belum */ public boolean hasTempuhKuliah(String kodeMataKuliah) { for (Nilai nilai: riwayatNilai) { if (nilai.getMataKuliah().getKode().equals(kodeMataKuliah)) { return true; } } return false; } /** * Mendapatkan tahun angkatan mahasiswa ini, berdasarkan NPM nya * @return tahun angkatan */ public int getTahunAngkatan() { return Integer.parseInt(getNpm().substring(0, 4)); } @Override public String toString() { return "Mahasiswa [npm=" + npm + ", nama=" + nama + "]"; } /** * Merepresentasikan nilai yang ada di riwayat nilai mahasiswa * @author pascal * */ public static class Nilai { /** Tahun dan Semester kuliah ini diambil */ protected final TahunSemester tahunSemester; /** Mata kuliah yang diambil */ protected final MataKuliah mataKuliah; /** Kelas kuliah */ protected final Character kelas; /** Nilai ART */ protected final Double nilaiART; /** Nilai UTS */ protected final Double nilaiUTS; /** Nilai UAS */ protected final Double nilaiUAS; /** Nilai Akhir */ protected final Character nilaiAkhir; public Nilai(TahunSemester tahunSemester, MataKuliah mataKuliah, Character kelas, Double nilaiART, Double nilaiUTS, Double nilaiUAS, Character nilaiAkhir) { super(); this.tahunSemester = tahunSemester; this.mataKuliah = mataKuliah; this.kelas = kelas; this.nilaiART = nilaiART; this.nilaiUTS = nilaiUTS; this.nilaiUAS = nilaiUAS; this.nilaiAkhir = nilaiAkhir; } public MataKuliah getMataKuliah() { return mataKuliah; } public Character getKelas() { return kelas; } public Double getNilaiART() { return nilaiART; } public Double getNilaiUTS() { return nilaiUTS; } public Double getNilaiUAS() { return nilaiUAS; } /** * Mengembalikan nilai akhir dalam bentuk huruf (A, B, C, D, ..., atau K) * @return nilai akhir dalam huruf, atau null jika tidak ada. */ public Character getNilaiAkhir() { return nilaiAkhir; } /** * Mendapatkan nilai akhir dalam bentuk angka * @return nilai akhir dalam angka, atau null jika {@link #getNilaiAkhir() mengembalikan 'K' atau null} */ public Double getAngkaAkhir() { if (nilaiAkhir == null) { return null; } switch (nilaiAkhir) { case 'A': return 4.0; case 'B': return 3.0; case 'C': return 2.0; case 'D': return 1.0; case 'E': return 0.0; case 'K': return null; } return null; } public TahunSemester getTahunSemester() { return tahunSemester; } public int getTahunAjaran() { return tahunSemester.getTahun(); } public Semester getSemester() { return tahunSemester.getSemester(); } @Override public String toString() { return "Nilai [tahunSemester=" + tahunSemester + ", mataKuliah=" + mataKuliah + ", kelas=" + kelas + ", nilaiART=" + nilaiART + ", nilaiUTS=" + nilaiUTS + ", nilaiUAS=" + nilaiUAS + ", nilaiAkhir=" + nilaiAkhir + "]"; } /** * Pembanding antara satu nilai dengan nilai lainnya, secara * kronologis waktu pengambilan. * @author pascal * */ public static class ChronologicalComparator implements Comparator<Nilai> { @Override public int compare(Nilai o1, Nilai o2) { return o1.getTahunSemester().compareTo(o2.getTahunSemester()); } } } }
package imagej.patcher; import java.util.Set; /** * Assorted legacy patches / extension points for use in the legacy mode. * * <p> * The Fiji distribution of ImageJ accumulated patches and extensions to ImageJ * 1.x over the years. * </p> * * <p> * However, there was a lot of overlap with the ImageJ2 project, so it was * decided to focus Fiji more on the life-science specific part and move all the * parts that are of more general use into ImageJ2. That way, it is pretty * clear-cut what goes into Fiji and what goes into ImageJ2. * </p> * * <p> * This class contains the extension points (such as being able to override the * macro editor) ported from Fiji as well as the code for runtime patching * ImageJ 1.x needed both for the extension points and for more backwards * compatibility than ImageJ 1.x wanted to provide (e.g. when public methods or * classes that were used by Fiji plugins were removed all of a sudden, without * being deprecated first). * </p> * * <p> * The code in this class is only used in the legacy mode. * </p> * * @author Johannes Schindelin */ class LegacyExtensions { /* * Extension points */ /* * Runtime patches (using CodeHacker for patching) */ /** * Applies runtime patches to ImageJ 1.x for backwards-compatibility and extension points. * * <p> * These patches enable a patched ImageJ 1.x to call a different script editor or to override * the application icon. * </p> * * <p> * This method is called by {@link LegacyInjector#injectHooks(ClassLoader)}. * </p> * * @param hacker the {@link CodeHacker} instance */ public static void injectHooks(final CodeHacker hacker, boolean headless) { // Below are patches to make ImageJ 1.x more backwards-compatible // add back the (deprecated) killProcessor(), and overlay methods final String[] imagePlusMethods = { "public void killProcessor()", "{}", "public void setDisplayList(java.util.Vector list)", "getCanvas().setDisplayList(list);", "public java.util.Vector getDisplayList()", "return getCanvas().getDisplayList();", "public void setDisplayList(ij.gui.Roi roi, java.awt.Color strokeColor," + " int strokeWidth, java.awt.Color fillColor)", "setOverlay(roi, strokeColor, strokeWidth, fillColor);" }; for (int i = 0; i < imagePlusMethods.length; i++) try { hacker.insertNewMethod("ij.ImagePlus", imagePlusMethods[i], imagePlusMethods[++i]); } catch (Exception e) { /* ignore */ } // make sure that ImageJ has been initialized in batch mode hacker.insertAtTopOfMethod("ij.IJ", "public static java.lang.String runMacro(java.lang.String macro, java.lang.String arg)", "if (ij==null && ij.Menus.getCommands()==null) init();"); try { hacker.insertNewMethod("ij.CompositeImage", "public ij.ImagePlus[] splitChannels(boolean closeAfter)", "ij.ImagePlus[] result = ij.plugin.ChannelSplitter.split(this);" + "if (closeAfter) close();" + "return result;"); hacker.insertNewMethod("ij.plugin.filter.RGBStackSplitter", "public static ij.ImagePlus[] splitChannelsToArray(ij.ImagePlus imp, boolean closeAfter)", "if (!imp.isComposite()) {" + " ij.IJ.error(\"splitChannelsToArray was called on a non-composite image\");" + " return null;" + "}" + "ij.ImagePlus[] result = ij.plugin.ChannelSplitter.split(imp);" + "if (closeAfter)" + " imp.close();" + "return result;"); } catch (IllegalArgumentException e) { final Throwable cause = e.getCause(); if (cause != null && !cause.getClass().getName().endsWith("DuplicateMemberException")) { throw e; } } // handle mighty mouse (at least on old Linux, Java mistakes the horizontal wheel for a popup trigger) for (String fullClass : new String[] { "ij.gui.ImageCanvas", "ij.plugin.frame.RoiManager", "ij.text.TextPanel", "ij.gui.Toolbar" }) { hacker.handleMightyMousePressed(fullClass); } // tell IJ#runUserPlugIn to catch NoSuchMethodErrors final String runUserPlugInSig = "static java.lang.Object runUserPlugIn(java.lang.String commandName, java.lang.String className, java.lang.String arg, boolean createNewLoader)"; hacker.addCatch("ij.IJ", runUserPlugInSig, "java.lang.NoSuchMethodError", "if (ij.IJ._hooks.handleNoSuchMethodError($e))" + " throw new RuntimeException(ij.Macro.MACRO_CANCELED);" + "throw $e;"); // tell IJ#runUserPlugIn to be more careful about catching NoClassDefFoundError hacker.insertPrivateStaticField("ij.IJ", String.class, "originalClassName"); hacker.insertAtTopOfMethod("ij.IJ", runUserPlugInSig, "originalClassName = $2;"); hacker.insertAtTopOfExceptionHandlers("ij.IJ", runUserPlugInSig, "java.lang.NoClassDefFoundError", "java.lang.String realClassName = $1.getMessage();" + "int spaceParen = realClassName.indexOf(\" (\");" + "if (spaceParen > 0) realClassName = realClassName.substring(0, spaceParen);" + "if (!originalClassName.replace('.', '/').equals(realClassName)) {" + " if (realClassName.startsWith(\"javax/vecmath/\") || realClassName.startsWith(\"com/sun/j3d/\") || realClassName.startsWith(\"javax/media/j3d/\"))" + " ij.IJ.error(\"The class \" + originalClassName + \" did not find Java3D (\" + realClassName + \")\\nPlease call Plugins>3D Viewer to install\");" + " else" + " ij.IJ.handleException($1);" + " return null;" + "}"); // let the plugin class loader find stuff in $HOME/.plugins, too addExtraPlugins(hacker); // make sure that the GenericDialog is disposed in macro mode if (hacker.hasMethod("ij.gui.GenericDialog", "public void showDialog()")) { hacker.insertAtTopOfMethod("ij.gui.GenericDialog", "public void showDialog()", "if (macro) dispose();"); } // make sure NonBlockingGenericDialog does not wait in macro mode hacker.replaceCallInMethod("ij.gui.NonBlockingGenericDialog", "public void showDialog()", "java.lang.Object", "wait", "if (isShowing()) wait();"); // tell the showStatus() method to show the version() instead of empty status hacker.insertAtTopOfMethod("ij.ImageJ", "void showStatus(java.lang.String s)", "if ($1 == null || \"\".equals($1)) $1 = version();"); // make sure that the GenericDialog does not make a hidden main window visible if (!headless) { hacker.replaceCallInMethod("ij.gui.GenericDialog", "public <init>(java.lang.String title, java.awt.Frame f)", "java.awt.Dialog", "super", "$proceed($1 != null && $1.isVisible() ? $1 : null, $2, $3);"); } // handle custom icon (e.g. for Fiji) addIconHooks(hacker); // optionally disallow batch mode from calling System.exit() hacker.insertPrivateStaticField("ij.ImageJ", Boolean.TYPE, "batchModeMayExit"); hacker.insertAtTopOfMethod("ij.ImageJ", "public static void main(java.lang.String[] args)", "batchModeMayExit = true;" + "for (int i = 0; i < $1.length; i++) {" + " if (\"-batch-no-exit\".equals($1[i])) {" + " batchModeMayExit = false;" + " $1[i] = \"-batch\";" + " }" + "}"); hacker.replaceCallInMethod("ij.ImageJ", "public static void main(java.lang.String[] args)", "java.lang.System", "exit", "if (batchModeMayExit) System.exit($1);" + "if ($1 == 0) return;" + "throw new RuntimeException(\"Exit code: \" + $1);"); // do not use the current directory as IJ home on Windows String prefsDir = System.getenv("IJ_PREFS_DIR"); if (prefsDir == null && System.getProperty("os.name").startsWith("Windows")) { prefsDir = System.getenv("user.home"); } if (prefsDir != null) { hacker.overrideFieldWrite("ij.Prefs", "public java.lang.String load(java.lang.Object ij, java.applet.Applet applet)", "prefsDir", "$_ = \"" + prefsDir + "\";"); } // tool names can be prefixes of other tools, watch out for that! hacker.replaceCallInMethod("ij.gui.Toolbar", "public int getToolId(java.lang.String name)", "java.lang.String", "startsWith", "$_ = $0.equals($1) || $0.startsWith($1 + \"-\") || $0.startsWith($1 + \" -\");"); // make sure Rhino gets the correct class loader hacker.insertAtTopOfMethod("JavaScriptEvaluator", "public void run()", "Thread.currentThread().setContextClassLoader(ij.IJ.getClassLoader());"); // make sure that the check for Bio-Formats is correct hacker.addToClassInitializer("ij.io.Opener", "try {" + " ij.IJ.getClassLoader().loadClass(\"loci.plugins.LociImporter\");" + " bioformats = true;" + "} catch (ClassNotFoundException e) {" + " bioformats = false;" + "}"); // make sure that symbolic links are *not* resolved (because then the parent info in the FileInfo would be wrong) hacker.replaceCallInMethod("ij.plugin.DragAndDrop", "public void openFile(java.io.File f)", "java.io.File", "getCanonicalPath", "$_ = $0.getAbsolutePath();"); // make sure no dialog is opened in headless mode hacker.insertAtTopOfMethod("ij.macro.Interpreter", "void showError(java.lang.String title, java.lang.String msg, java.lang.String[] variables)", "if (ij.IJ.getInstance() == null) {" + " java.lang.System.err.println($1 + \": \" + $2);" + " return;" + "}"); // let IJ.handleException override the macro interpreter's call()'s exception handling hacker.insertAtTopOfExceptionHandlers("ij.macro.Functions", "java.lang.String call()", "java.lang.reflect.InvocationTargetException", "ij.IJ.handleException($1);" + "return null;"); // Add back the "Convert to 8-bit Grayscale" checkbox to Import>Image Sequence if (!hacker.hasField("ij.plugin.FolderOpener", "convertToGrayscale")) { hacker.insertPrivateStaticField("ij.plugin.FolderOpener", Boolean.TYPE, "convertToGrayscale"); hacker.replaceCallInMethod("ij.plugin.FolderOpener", "public void run(java.lang.String arg)", "ij.io.Opener", "openImage", "$_ = $0.openImage($1, $2);" + "if (convertToGrayscale) {" + " final String saved = ij.Macro.getOptions();" + " ij.IJ.run($_, \"8-bit\", \"\");" + " if (saved != null && !saved.equals(\"\")) ij.Macro.setOptions(saved);" + "}"); hacker.replaceCallInMethod("ij.plugin.FolderOpener", "boolean showDialog(ij.ImagePlus imp, java.lang.String[] list)", "ij.plugin.FolderOpener$FolderOpenerDialog", "addCheckbox", "$0.addCheckbox(\"Convert to 8-bit Grayscale\", convertToGrayscale);" + "$0.addCheckbox($1, $2);", 1); hacker.replaceCallInMethod("ij.plugin.FolderOpener", "boolean showDialog(ij.ImagePlus imp, java.lang.String[] list)", "ij.plugin.FolderOpener$FolderOpenerDialog", "getNextBoolean", "convertToGrayscale = $0.getNextBoolean();" + "$_ = $0.getNextBoolean();" + "if (convertToGrayscale && $_) {" + " ij.IJ.error(\"Cannot convert to grayscale and RGB at the same time.\");" + " return false;" + "}", 1); } // handle HTTPS in addition to HTTP hacker.handleHTTPS("ij.macro.Functions", "java.lang.String exec()"); hacker.handleHTTPS("ij.plugin.DragAndDrop", "public void drop(java.awt.dnd.DropTargetDropEvent dtde)"); hacker.handleHTTPS(hacker.existsClass("ij.plugin.PluginInstaller") ? "ij.plugin.PluginInstaller" : "ij.io.PluginInstaller", "public boolean install(java.lang.String path)"); hacker.handleHTTPS("ij.plugin.ListVirtualStack", "public void run(java.lang.String arg)"); hacker.handleHTTPS("ij.plugin.ListVirtualStack", "java.lang.String[] open(java.lang.String path)"); addEditorExtensionPoints(hacker); insertAppNameHooks(hacker); insertRefreshMenusHook(hacker); overrideStartupMacrosForFiji(hacker); handleMacAdapter(hacker); } /** * Install a hook to optionally run a Runnable at the end of Help>Refresh Menus. * * <p> * See {@link LegacyExtensions#runAfterRefreshMenus(Runnable)}. * </p> * * @param hacker the {@link CodeHacker} to use for patching */ private static void insertRefreshMenusHook(CodeHacker hacker) { hacker.insertAtBottomOfMethod("ij.Menus", "public static void updateImageJMenus()", "ij.IJ._hooks.runAfterRefreshMenus();"); } private static void addEditorExtensionPoints(final CodeHacker hacker) { hacker.insertAtTopOfMethod("ij.io.Opener", "public void open(java.lang.String path)", "if (isText($1) && ij.IJ._hooks.openInEditor($1)) return;"); hacker.dontReturnOnNull("ij.plugin.frame.Recorder", "void createMacro()"); hacker.replaceCallInMethod("ij.plugin.frame.Recorder", "void createMacro()", "ij.IJ", "runPlugIn", "$_ = null;"); hacker.replaceCallInMethod("ij.plugin.frame.Recorder", "void createMacro()", "ij.plugin.frame.Editor", "createMacro", "if ($1.endsWith(\".txt\")) {" + " $1 = $1.substring($1.length() - 3) + \"ijm\";" + "}" + "if (!ij.IJ._hooks.createInEditor($1, $2)) {" + " ((ij.plugin.frame.Editor)ij.IJ.runPlugIn(\"ij.plugin.frame.Editor\", \"\")).createMacro($1, $2);" + "}"); hacker.insertPublicStaticField("ij.plugin.frame.Recorder", String.class, "nameForEditor", null); hacker.insertAtTopOfMethod("ij.plugin.frame.Recorder", "void createPlugin(java.lang.String text, java.lang.String name)", "this.nameForEditor = $2;"); hacker.replaceCallInMethod("ij.plugin.frame.Recorder", "void createPlugin(java.lang.String text, java.lang.String name)", "ij.IJ", "runPlugIn", "$_ = null;" + "new ij.plugin.NewPlugin().createPlugin(this.nameForEditor, ij.plugin.NewPlugin.PLUGIN, $2);" + "return;"); hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createMacro(java.lang.String name)", "ij.plugin.frame.Editor", "<init>", "$_ = null;"); hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createMacro(java.lang.String name)", "ij.plugin.frame.Editor", "create", "if ($1.endsWith(\".txt\")) {" + " $1 = $1.substring(0, $1.length() - 3) + \"ijm\";" + "}" + "if ($1.endsWith(\".ijm\") && ij.IJ._hooks.createInEditor($1, $2)) return;" + "int options = (monospaced ? ij.plugin.frame.Editor.MONOSPACED : 0)" + " | (menuBar ? ij.plugin.frame.Editor.MENU_BAR : 0);" + "new ij.plugin.frame.Editor(rows, columns, 0, options).create($1, $2);"); hacker.dontReturnOnNull("ij.plugin.NewPlugin", "public void createPlugin(java.lang.String name, int type, java.lang.String methods)"); hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createPlugin(java.lang.String name, int type, java.lang.String methods)", "ij.IJ", "runPlugIn", "$_ = null;"); hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createPlugin(java.lang.String name, int type, java.lang.String methods)", "ij.plugin.frame.Editor", "create", "if (!ij.IJ._hooks.createInEditor($1, $2)) {" + " ((ij.plugin.frame.Editor)ij.IJ.runPlugIn(\"ij.plugin.frame.Editor\", \"\")).create($1, $2);" + "}"); } /** * Inserts hooks to replace the application name. */ private static void insertAppNameHooks(final CodeHacker hacker) { final String appName = "ij.IJ._hooks.getAppName()"; final String replace = ".replace(\"ImageJ\", " + appName + ")"; hacker.insertAtTopOfMethod("ij.IJ", "public void error(java.lang.String title, java.lang.String msg)", "if ($1 == null || $1.equals(\"ImageJ\")) $1 = " + appName + ";"); hacker.insertAtBottomOfMethod("ij.ImageJ", "public java.lang.String version()", "$_ = $_" + replace + ";"); hacker.replaceAppNameInCall("ij.ImageJ", "public <init>(java.applet.Applet applet, int mode)", "super", 1, appName); hacker.replaceAppNameInNew("ij.ImageJ", "public void run()", "ij.gui.GenericDialog", 1, appName); hacker.replaceAppNameInCall("ij.ImageJ", "public void run()", "addMessage", 1, appName); if (hacker.hasMethod("ij.plugin.CommandFinder", "public void export()")) { hacker.replaceAppNameInNew("ij.plugin.CommandFinder", "public void export()", "ij.text.TextWindow", 1, appName); } hacker.replaceAppNameInCall("ij.plugin.Hotkeys", "public void removeHotkey()", "addMessage", 1, appName); hacker.replaceAppNameInCall("ij.plugin.Hotkeys", "public void removeHotkey()", "showStatus", 1, appName); if (hacker.existsClass("ij.plugin.AppearanceOptions")) { hacker.replaceAppNameInCall("ij.plugin.AppearanceOptions", "void showDialog()", "showMessage", 2, appName); } else { hacker.replaceAppNameInCall("ij.plugin.Options", "public void appearance()", "showMessage", 2, appName); } hacker.replaceAppNameInCall("ij.gui.YesNoCancelDialog", "public <init>(java.awt.Frame parent, java.lang.String title, java.lang.String msg)", "super", 2, appName); hacker.replaceAppNameInCall("ij.gui.Toolbar", "private void showMessage(int toolId)", "showStatus", 1, appName); } private static void addIconHooks(final CodeHacker hacker) { final String icon = "ij.IJ._hooks.getIconURL()"; hacker.replaceCallInMethod("ij.ImageJ", "void setIcon()", "java.lang.Class", "getResource", "java.net.URL _iconURL = " + icon + ";\n" + "if (_iconURL == null) $_ = $0.getResource($1);" + "else $_ = _iconURL;"); hacker.insertAtTopOfMethod("ij.ImageJ", "public <init>(java.applet.Applet applet, int mode)", "if ($2 != 2 /* ij.ImageJ.NO_SHOW */) setIcon();"); hacker.insertAtTopOfMethod("ij.WindowManager", "public void addWindow(java.awt.Frame window)", "java.net.URL _iconURL = " + icon + ";\n" + "if (_iconURL != null && $1 != null) {" + " java.awt.Image img = $1.createImage((java.awt.image.ImageProducer)_iconURL.getContent());" + " if (img != null) {" + " $1.setIconImage(img);" + " }" + "}"); } /** * Makes sure that the legacy plugin class loader finds stuff in * {@code $HOME/.plugins/}. */ private static void addExtraPlugins(final CodeHacker hacker) { for (final String methodName : new String[] { "addJAR", "addJar" }) { if (hacker.hasMethod("ij.io.PluginClassLoader", "private void " + methodName + "(java.io.File file)")) { hacker.insertAtTopOfMethod("ij.io.PluginClassLoader", "void init(java.lang.String path)", extraPluginJarsHandler("if (file.isDirectory()) addDirectory(file);" + "else " + methodName + "(file);")); } } // avoid parsing ij.jar for plugins hacker.replaceCallInMethod("ij.Menus", "InputStream autoGenerateConfigFile(java.lang.String jar)", "java.util.zip.ZipEntry", "getName", "$_ = $proceed($$);" + "if (\"IJ_Props.txt\".equals($_)) return null;"); // make sure that extra directories added to the plugin class path work, too hacker.insertAtTopOfMethod("ij.Menus", "InputStream getConfigurationFile(java.lang.String jar)", "java.io.File isDir = new java.io.File($1);" + "if (!isDir.exists()) return null;" + "if (isDir.isDirectory()) {" + " java.io.File config = new java.io.File(isDir, \"plugins.config\");" + " if (config.exists()) return new java.io.FileInputStream(config);" + " return ij.IJ._hooks.autoGenerateConfigFile(isDir);" + "}"); // fix overzealous assumption that all plugins are in plugins.dir hacker.insertPrivateStaticField("ij.Menus", Set.class, "_extraJars"); hacker.insertAtTopOfMethod("ij.Menus", "java.lang.String getSubmenuName(java.lang.String jarPath)", "if (_extraJars.contains($1)) return null;"); // add the extra .jar files to the list of plugin .jar files to be processed. hacker.insertAtBottomOfMethod("ij.Menus", "public static synchronized java.lang.String[] getPlugins()", "if (_extraJars == null) _extraJars = new java.util.HashSet();" + extraPluginJarsHandler("if (jarFiles == null) jarFiles = new java.util.Vector();" + "jarFiles.addElement(file.getAbsolutePath());" + "_extraJars.add(file.getAbsolutePath());")); // exclude -sources.jar entries generated by Maven. hacker.insertAtBottomOfMethod("ij.Menus", "public static synchronized java.lang.String[] getPlugins()", "if (jarFiles != null) {" + " for (int i = jarFiles.size() - 1; i >= 0; i " String entry = (String) jarFiles.elementAt(i);" + " if (entry.endsWith(\"-sources.jar\")) {" + " jarFiles.remove(i);" + " }" + " }" + "}"); // force IJ.getClassLoader() to instantiate a PluginClassLoader hacker.replaceCallInMethod( "ij.IJ", "public static ClassLoader getClassLoader()", "java.lang.System", "getProperty", "$_ = System.getProperty($1);\n" + "if ($_ == null && $1.equals(\"plugins.dir\")) $_ = \"/non-existant/\";"); } private static String extraPluginJarsHandler(final String code) { return "for (java.util.Iterator iter = ij.IJ._hooks.handleExtraPluginJars().iterator();\n" + "iter.hasNext(); ) {\n" + "\tjava.io.File file = (java.io.File)iter.next();\n" + code + "\n" + "}\n"; } private static void overrideStartupMacrosForFiji(CodeHacker hacker) { hacker.replaceCallInMethod("ij.Menus", "void installStartupMacroSet()", "java.io.File", "<init>", "if ($1.endsWith(\"StartupMacros.txt\")) {" + " java.lang.String fijiPath = $1.substring(0, $1.length() - 3) + \"fiji.ijm\";" + " java.io.File fijiFile = new java.io.File(fijiPath);" + " $_ = fijiFile.exists() ? fijiFile : new java.io.File($1);" + "} else $_ = new java.io.File($1);"); hacker.replaceCallInMethod("ij.Menus", "void installStartupMacroSet()", "ij.plugin.MacroInstaller", "installFile", "if ($1.endsWith(\"StartupMacros.txt\")) {" + " java.lang.String fijiPath = $1.substring(0, $1.length() - 3) + \"fiji.ijm\";" + " java.io.File fijiFile = new java.io.File(fijiPath);" + " $0.installFile(fijiFile.exists() ? fijiFile.getPath() : $1);" + "} else $0.installFile($1);"); } private static void handleMacAdapter(final CodeHacker hacker) { // Without the ApplicationListener, MacAdapter cannot load, and hence CodeHacker would fail // to load it if we patched the class. if (!hacker.existsClass("com.apple.eawt.ApplicationListener")) return; hacker.insertAtTopOfMethod("MacAdapter", "public void run(java.lang.String arg)", "return;"); } }
package info.faceland.mint; import com.tealcube.minecraft.bukkit.TextUtils; import com.tealcube.minecraft.bukkit.bullion.GoldDropEvent; import com.tealcube.minecraft.bukkit.facecore.utilities.MessageUtils; import com.tealcube.minecraft.bukkit.hilt.HiltItemStack; import com.tealcube.minecraft.bukkit.shade.apache.commons.lang3.math.NumberUtils; import com.tealcube.minecraft.bukkit.shade.google.common.base.CharMatcher; import com.tealcubegames.minecraft.spigot.versions.actionbars.ActionBarMessager; import com.tealcubegames.minecraft.spigot.versions.api.actionbars.ActionBarMessage; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.World; import org.bukkit.entity.EntityType; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.ItemSpawnEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.CraftItemEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryPickupItemEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.potion.PotionEffectType; import org.nunnerycode.mint.MintPlugin; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.ThreadLocalRandom; public class MintListener implements Listener { private static final DecimalFormat DF = new DecimalFormat(" private final MintPlugin plugin; private final Set<UUID> dead; public MintListener(MintPlugin mintPlugin) { this.plugin = mintPlugin; this.dead = new HashSet<>(); } @EventHandler(priority = EventPriority.MONITOR) public void onMintEvent(MintEvent mintEvent) { if (mintEvent.getUuid().equals("")) { return; } UUID uuid; try { uuid = UUID.fromString(mintEvent.getUuid()); } catch (IllegalArgumentException e) { uuid = Bukkit.getPlayer(mintEvent.getUuid()).getUniqueId(); } Player player = Bukkit.getPlayer(uuid); if (player == null) { return; } PlayerInventory pi = player.getInventory(); HiltItemStack wallet = null; ItemStack[] contents = pi.getContents(); for (ItemStack is : contents) { if (is == null || is.getType() == Material.AIR) { continue; } HiltItemStack his = new HiltItemStack(is); if (his.getName().equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name", "")))) { wallet = his; } } if (wallet == null) { wallet = new HiltItemStack(Material.PAPER); } pi.removeItem(wallet); player.updateInventory(); double b = plugin.getEconomy().getBalance(player); wallet.setName(TextUtils.color(plugin.getSettings().getString("config.wallet.name", ""))); wallet.setLore(TextUtils.args( TextUtils.color(plugin.getSettings().getStringList("config.wallet.lore")), new String[][]{{"%amount%", DF.format(b)}, {"%currency%", b == 1.00D ? plugin.getEconomy().currencyNameSingular() : plugin.getEconomy().currencyNamePlural()}})); if (pi.getItem(17) != null && pi.getItem(17).getType() != Material.AIR) { ItemStack old = new HiltItemStack(pi.getItem(17)); pi.setItem(17, wallet); pi.addItem(old); } else { pi.setItem(17, wallet); } player.updateInventory(); } @EventHandler(priority = EventPriority.HIGHEST) public void onEntityDeathEvent(final EntityDeathEvent event) { if (event instanceof PlayerDeathEvent) { return; } if (event.getEntity().getKiller() == null) { return; } if (!plugin.getSettings().getBoolean("config.money-drop-worlds." + event.getEntity().getWorld().getName() + ".enabled", false)) { return; } EntityType entityType = event.getEntityType(); double reward = plugin.getSettings().getDouble("rewards." + entityType.name(), 0D); Location worldSpawn = event.getEntity().getWorld().getSpawnLocation(); Location entityLoc = event.getEntity().getLocation(); double distance = worldSpawn.distance(entityLoc); double blockInterval = plugin.getSettings().getDouble("config.money-drop-worlds." + event.getEntity() .getWorld().getName() + ".mult-distance", 0.0); double intervalMult = plugin.getSettings().getDouble("config.money-drop-worlds." + event.getEntity() .getWorld().getName() + ".mult-amount", 0.0); double distMult = (distance / blockInterval) * intervalMult; reward *= 1 + distMult; if (reward == 0D) { return; } GoldDropEvent gde = new GoldDropEvent(event.getEntity().getKiller(), event.getEntity(), reward); Bukkit.getPluginManager().callEvent(gde); HiltItemStack his = new HiltItemStack(Material.GOLD_NUGGET); his.setName(ChatColor.GOLD + "REWARD!"); String rewardString = DF.format(gde.getAmount()); int numberOfDrops = 1; double bombChance = 0.0001; if (event.getEntity().getKiller().hasPotionEffect(PotionEffectType.LUCK)) { bombChance = 0.001; } if (ThreadLocalRandom.current().nextDouble(0, 1) <= bombChance) { numberOfDrops = ThreadLocalRandom.current().nextInt(100, 150); } while (numberOfDrops > 0) { his.setLore(Arrays.asList(rewardString)); event.getDrops().add(his); numberOfDrops } } @EventHandler(priority = EventPriority.LOWEST) public void onItemPickupEvent(PlayerPickupItemEvent event) { if (event.isCancelled()) { return; } if (event.getItem() == null || event.getItem().getItemStack() == null) { return; } Item item = event.getItem(); HiltItemStack hiltItemStack = new HiltItemStack(item.getItemStack()); int stacksize = hiltItemStack.getAmount(); if (hiltItemStack.getType() != Material.GOLD_NUGGET) { return; } if (!hiltItemStack.getName().equals(ChatColor.GOLD + "REWARD!")) { return; } String name = item.getCustomName(); if (name == null) { return; } event.getPlayer().getWorld().playSound(event.getPlayer().getLocation(), Sound.ENTITY_CHICKEN_EGG, 0.8F, 2); String stripped = ChatColor.stripColor(name); String replaced = CharMatcher.JAVA_LETTER.removeFrom(stripped).trim(); double amount = stacksize * NumberUtils.toDouble(replaced); plugin.getEconomy().depositPlayer(event.getPlayer(), amount); event.getItem().remove(); event.setCancelled(true); String message = "<dark green>Wallet: <white>" + plugin.getEconomy().format(plugin.getEconomy().getBalance( event.getPlayer())); ActionBarMessage econMsg = ActionBarMessager.createActionBarMessage(message); econMsg.send(event.getPlayer()); } @EventHandler(priority = EventPriority.HIGH) public void onPlayerDeathEvent(final PlayerDeathEvent event) { if (plugin.getSettings().getStringList("config.no-drop-worlds").contains(event.getEntity().getWorld() .getName())) { return; } if (dead.contains(event.getEntity().getUniqueId())) { return; } dead.add(event.getEntity().getUniqueId()); Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { @Override public void run() { dead.remove(event.getEntity().getUniqueId()); } }, 20L * 5); Player player = event.getEntity(); World world = player.getWorld(); int maximumKeptBits; if (event.getEntity().hasPermission("mint.keep")) { maximumKeptBits = 1000; } else { maximumKeptBits = 100; } double amount = plugin.getEconomy().getBalance(event.getEntity()) - maximumKeptBits; if (amount > 0) { HiltItemStack his = new HiltItemStack(Material.GOLD_NUGGET); his.setName(ChatColor.GOLD + "REWARD!"); his.setLore(Arrays.asList(DF.format(amount))); world.dropItemNaturally(player.getLocation(), his); plugin.getEconomy().setBalance(event.getEntity(), maximumKeptBits); } } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerRespawnEvent(PlayerRespawnEvent event) { Player player = event.getPlayer(); plugin.getEconomy().withdrawPlayer(player, 1); plugin.getEconomy().depositPlayer(player, 1); } @EventHandler(priority = EventPriority.LOWEST) public void onItemSpawnEvent(ItemSpawnEvent event) { if (event.getEntity().getItemStack().getType() == Material.GOLD_NUGGET) { HiltItemStack nuggetStack = new HiltItemStack(event.getEntity().getItemStack()); if (!nuggetStack.getName().equals(ChatColor.GOLD + "REWARD!") || nuggetStack.getLore().isEmpty()) { return; } String s = nuggetStack.getLore().get(0); String stripped = ChatColor.stripColor(s); double amount = NumberUtils.toDouble(stripped); if (amount <= 0.00D) { event.setCancelled(true); return; } int antiStackSerial = ThreadLocalRandom.current().nextInt(0, 999999); HiltItemStack nugget = new HiltItemStack(Material.GOLD_NUGGET); nugget.setName(ChatColor.GOLD + "REWARD!"); nugget.setLore(Arrays.asList(DF.format(amount), "S:" + antiStackSerial)); event.getEntity().setItemStack(nugget); event.getEntity().setCustomName(ChatColor.YELLOW + plugin.getEconomy().format(amount)); event.getEntity().setCustomNameVisible(true); } if (event.getEntity().getItemStack().getType() == Material.PAPER) { HiltItemStack iS = new HiltItemStack(event.getEntity().getItemStack()); if (iS.getName().equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name")))) { event.getEntity().remove(); } } } @EventHandler(priority = EventPriority.LOWEST) public void onCraftItem(CraftItemEvent event) { for (ItemStack is : event.getInventory().getMatrix()) { if (is == null || is.getType() != Material.PAPER) { continue; } HiltItemStack his = new HiltItemStack(is); if (his.getName().equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name")))) { event.setCancelled(true); return; } } } @EventHandler public void onInventoryClickEvent(InventoryClickEvent event) { ItemStack is = event.getCurrentItem(); if (is == null || is.getType() == Material.AIR) { return; } HiltItemStack his = new HiltItemStack(is); if (his.getLore().size() < 1) { return; } if (his.getName().equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name", "")))) { event.setCancelled(true); } } @EventHandler public void onInventoryClose(InventoryCloseEvent event) { if (!event.getInventory().getName() .equals(TextUtils.color(plugin.getSettings().getString("language.pawn-shop-name")))) { return; } double value = 0D; int amountSold = 0; for (ItemStack itemStack : event.getInventory().getContents()) { if (itemStack == null || itemStack.getType() == Material.AIR) { continue; } HiltItemStack hiltItemStack = new HiltItemStack(itemStack); if (hiltItemStack.getName() .equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name", "")))) { continue; } List<String> lore = hiltItemStack.getLore(); double amount = plugin.getSettings().getDouble("prices.materials." + hiltItemStack.getType().name(), 0D); if (!lore.isEmpty()) { amount += plugin.getSettings().getDouble("prices.options.lore.base-price", 3D); amount += plugin.getSettings().getDouble("prices.options.lore.per-line", 1D) * lore.size(); } String strippedName = ChatColor.stripColor(hiltItemStack.getName()); if (strippedName.startsWith("Socket Gem")) { value += plugin.getSettings().getDouble("prices.special.gems") * hiltItemStack.getAmount(); } else if (plugin.getSettings().isSet("prices.names." + strippedName)) { value += plugin.getSettings().getDouble("prices.names." + strippedName, 0D) * hiltItemStack.getAmount(); } else { value += amount * hiltItemStack.getAmount(); } } for (HumanEntity entity : event.getViewers()) { if (!(entity instanceof Player)) { continue; } if (value > 0) { plugin.getEconomy().depositPlayer((Player) entity, value); MessageUtils.sendMessage(entity, plugin.getSettings().getString("language.pawn-success"), new String[][]{{"%amount%", "" + amountSold}, {"%currency%", plugin.getEconomy().format(value)}}); } } } @EventHandler public void onInventoryPickupItem(InventoryPickupItemEvent event) { HiltItemStack his = new HiltItemStack(event.getItem().getItemStack()); if (his.getName().equals(TextUtils.color(plugin.getSettings().getString("config.wallet.name", ""))) || his.getName().equals( ChatColor.GOLD + "REWARD!")) { event.setCancelled(true); } } }
package com.amos.project4.models; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; public abstract class AbstractViewModel { protected PropertyChangeSupport propertyChangeSupport; public AbstractViewModel() { propertyChangeSupport = new PropertyChangeSupport(this); } public void addPropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.removePropertyChangeListener(listener); } protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { propertyChangeSupport.firePropertyChange(propertyName, oldValue, newValue); } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.util.Optional; import javax.swing.*; import javax.swing.table.DefaultTableModel; public final class MainPanel extends JPanel { private final String[] columnNames = {"String", "Integer", "Boolean"}; private final Object[][] data = { {"aaa", 12, true}, {"bbb", 5, false}, {"CCC", 92, true}, {"DDD", 0, false} }; private final DefaultTableModel model = new DefaultTableModel(data, columnNames) { @Override public Class<?> getColumnClass(int column) { return getValueAt(0, column).getClass(); } }; private final JTable table = new JTable(model) { private int prevHeight = -1; private int prevCount = -1; private void updateRowsHeight(JViewport vport) { int height = vport.getExtentSize().height; int rowCount = getModel().getRowCount(); int defaultRowHeight = height / rowCount; if ((height != prevHeight || rowCount != prevCount) && defaultRowHeight > 0) { int over = height - rowCount * defaultRowHeight; for (int i = 0; i < rowCount; i++) { int a = over > 0 ? i == rowCount - 1 ? over : 1 : 0; setRowHeight(i, defaultRowHeight + a); over } } prevHeight = height; prevCount = rowCount; } @Override public void doLayout() { super.doLayout(); Class<JViewport> clz = JViewport.class; Optional.ofNullable(SwingUtilities.getAncestorOfClass(clz, this)) .filter(clz::isInstance).map(clz::cast) .ifPresent(this::updateRowsHeight); } }; private MainPanel() { super(new BorderLayout()); JScrollPane scroll = new JScrollPane(table); scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scroll.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { Component c = e.getComponent(); if (c instanceof JScrollPane) { ((JScrollPane) c).getViewport().getView().revalidate(); } } }); JButton button = new JButton("add"); button.addActionListener(e -> model.addRow(new Object[] {"", 0, false})); add(scroll); add(button, BorderLayout.SOUTH); setPreferredSize(new Dimension(320, 240)); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGui(); } }); } public static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
package istc.bigdawg.monitoring; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import istc.bigdawg.BDConstants; import istc.bigdawg.exceptions.MigrationException; import istc.bigdawg.exceptions.NotSupportIslandException; import istc.bigdawg.executor.Executor; import istc.bigdawg.executor.plan.QueryExecutionPlan; import istc.bigdawg.migration.MigrationStatistics; import istc.bigdawg.packages.CrossIslandQueryNode; import istc.bigdawg.packages.CrossIslandQueryPlan; import istc.bigdawg.parsers.UserQueryParser; import istc.bigdawg.postgresql.PostgreSQLHandler; import istc.bigdawg.query.ConnectionInfo; import istc.bigdawg.query.ConnectionInfoParser; import istc.bigdawg.signature.Signature; import org.apache.log4j.Logger; import org.mortbay.log.Log; public class Monitor { private static Logger logger = Logger.getLogger(Monitor.class.getName()); public static final String stringSeparator = "****"; private static final String INSERT = "INSERT INTO monitoring (signature, index, lastRan, duration) SELECT '%s', '%d', -1, -1 WHERE NOT EXISTS (SELECT 1 FROM monitoring WHERE signature='%s' AND index='%d)"; private static final String DELETE = "DELETE FROM monitoring WHERE signature='%s'"; private static final String UPDATE = "UPDATE monitoring SET lastRan=%d, duration=%d WHERE signature='%s' AND index='%d"; private static final String RETRIEVE = "SELECT duration FROM monitoring WHERE signature='%s' ORDER BY index"; private static final String SIGS = "SELECT DISTINCT(signature) FROM monitoring"; private static final String MINDURATION = "SELECT min(duration) FROM monitoring"; private static final String MIGRATE = "INSERT INTO migrationstats(fromLoc, toLoc, objectFrom, objectTo, startTime, endTime, countExtracted, countLoaded, message) VALUES ('%s', '%s', '%s', '%s', %d, %d, %d, %d, '%s')"; private static final String RETRIEVEMIGRATE = "SELECT objectFrom, objectTo, startTime, endTime, countExtracted, countLoaded, message FROM migrationstats WHERE fromLoc='%s' AND toLoc='%s'"; public static boolean addBenchmarks(Signature signature, boolean lean) throws Exception { BDConstants.Shim[] shims = BDConstants.Shim.values(); return addBenchmarks(signature, lean, shims); } public static boolean addBenchmarks(Signature signature, boolean lean, BDConstants.Shim[] shims) throws Exception { LinkedHashMap<String, String> crossIslandQuery = UserQueryParser.getUnwrappedQueriesByIslands(signature.getQuery()); logger.debug("Query for signature: " + signature.getQuery()); CrossIslandQueryPlan ciqp = new CrossIslandQueryPlan(crossIslandQuery); CrossIslandQueryNode ciqn = ciqp.getRoot(); List<QueryExecutionPlan> qeps = ciqn.getAllQEPs(true); for (int i = 0; i < qeps.size(); i++){ try { if (!insert(signature, i)) { return false; } } catch (NotSupportIslandException e) { e.printStackTrace(); } } if (!lean) { try { runBenchmarks(qeps, signature); } catch (Exception e) { e.printStackTrace(); } } return true; } public static boolean removeBenchmarks(Signature signature) { return delete(signature); } public static boolean allQueriesDone() { PostgreSQLHandler handler = new PostgreSQLHandler(); try { PostgreSQLHandler.QueryResult qresult = handler.executeQueryPostgreSQL(MINDURATION); List<List<String>> rows = qresult.getRows(); long minDuration = Long.MAX_VALUE; for (List<String> row: rows){ long currentDuration = Long.parseLong(row.get(0)); if (currentDuration < minDuration){ minDuration = currentDuration; } } if (minDuration < 0){ return false; } } catch (SQLException e) { e.printStackTrace(); } return true; } public static List<Long> getBenchmarkPerformance(Signature signature) throws NotSupportIslandException, SQLException { List<Long> perfInfo = new ArrayList<>(); String escapedSignature = signature.toRecoverableString().replace("'", stringSeparator); PostgreSQLHandler handler = new PostgreSQLHandler(); PostgreSQLHandler.QueryResult qresult = handler.executeQueryPostgreSQL(String.format(RETRIEVE, escapedSignature)); List<List<String>> rows = qresult.getRows(); for (List<String> row: rows){ long currentDuration = Long.parseLong(row.get(0)); if (currentDuration >= 0){ perfInfo.add(currentDuration); } else { perfInfo.add(Long.MAX_VALUE); } } System.out.printf("[BigDAWG] MONITOR: Performance information generated.\n"); return perfInfo; } public static List<Signature> getAllSignatures() { List<Signature> signatures = new ArrayList<>(); PostgreSQLHandler handler = new PostgreSQLHandler(); try { PostgreSQLHandler.QueryResult qresult = handler.executeQueryPostgreSQL(SIGS); List<List<String>> rows = qresult.getRows();for (List<String> row: rows){ String signature = row.get(0).replace(stringSeparator, "'"); signatures.add(new Signature(signature)); } } catch (Exception e) { Log.debug(e.getMessage()); e.printStackTrace(); } return signatures; } public static Signature getClosestSignature(Signature signature) { // TODO This needs to be changed to be much more efficient. // We need a way to do similarity in postgres (likely indexing on signature) // based on the dimensions we care about List<Signature> signatures = getAllSignatures(); Signature closest = null; double distance = Double.MAX_VALUE; for (Signature current: signatures){ // compare them and pick the closest Signature double curDist = signature.compare(current); if (curDist < distance){ distance = curDist; closest = current; } } return closest; } private static boolean insert(Signature signature, int index) throws NotSupportIslandException { PostgreSQLHandler handler = new PostgreSQLHandler(); try { String escapedSignature = signature.toRecoverableString().replace("'", stringSeparator); handler.executeStatementPostgreSQL(String.format(INSERT, escapedSignature, index, escapedSignature, index)); return true; } catch (SQLException e) { return false; } } private static boolean delete(Signature signature) { PostgreSQLHandler handler = new PostgreSQLHandler(); try { String escapedSignature = signature.toRecoverableString().replace("'", stringSeparator); handler.executeStatementPostgreSQL(String.format(DELETE, escapedSignature)); return true; } catch (SQLException e) { return false; } } public static void runBenchmarks(List<QueryExecutionPlan> qeps, Signature signature) throws SQLException, MigrationException { for (int i = 0; i < qeps.size(); i++){ Executor.executePlan(qeps.get(i), signature, i); } } public void finishedBenchmark(Signature signature, int index, long startTime, long endTime) throws SQLException { PostgreSQLHandler handler = new PostgreSQLHandler(); String escapedSignature = signature.toRecoverableString().replace("'", stringSeparator); handler.executeStatementPostgreSQL(String.format(UPDATE, endTime, endTime-startTime, escapedSignature, index)); // Only for testing purposes.Uncomment when necessary. /* try { File temp = File.createTempFile("queries", ".tmp"); BufferedWriter bw = new BufferedWriter(new FileWriter(temp,true)); bw.write(String.format("%d %s %s\n", endTime-startTime, qep.getIsland(), qepString)); bw.close(); } catch (IOException e) { e.printStackTrace(); }*/ } public static void addMigrationStats(MigrationStatistics stats) throws SQLException { PostgreSQLHandler handler = new PostgreSQLHandler(); String fromLoc = ConnectionInfoParser.connectionInfoToString(stats.getConnectionFrom()); String toLoc = ConnectionInfoParser.connectionInfoToString(stats.getConnectionTo()); long countExtracted = -1; long countLoaded = -1; if (stats.getCountExtractedElements() != null){ countExtracted = stats.getCountExtractedElements(); } if (stats.getCountLoadedElements() != null){ countLoaded = stats.getCountLoadedElements(); } handler.executeStatementPostgreSQL(String.format(MIGRATE, fromLoc, toLoc, stats.getObjectFrom(), stats.getObjectTo(), stats.getStartTimeMigration(), stats.getEndTimeMigration(), countExtracted, countLoaded, stats.getMessage())); } public List<MigrationStatistics> getMigrationStats(ConnectionInfo from, ConnectionInfo to) throws SQLException { String fromLoc = ConnectionInfoParser.connectionInfoToString(from); String toLoc = ConnectionInfoParser.connectionInfoToString(to); PostgreSQLHandler handler = new PostgreSQLHandler(); PostgreSQLHandler.QueryResult qresult = handler.executeQueryPostgreSQL(String.format(RETRIEVEMIGRATE, fromLoc, toLoc)); List<MigrationStatistics> results = new ArrayList<>(); List<List<String>> rows = qresult.getRows(); for (List<String> row: rows){ String objectFrom = row.get(0); String objectTo = row.get(1); long startTime = Long.parseLong(row.get(2)); long endTime = Long.parseLong(row.get(3)); long countExtracted = Long.parseLong(row.get(4)); Long countExtractedElements = null; if (countExtracted >= 0) { countExtractedElements = countExtracted; } long countLoaded = Long.parseLong(row.get(5)); Long countLoadedElements = null; if (countLoaded >= 0) { countLoadedElements = countLoaded; } String message = row.get(6); results.add(new MigrationStatistics(from, to, objectFrom, objectTo, startTime, endTime, countExtractedElements, countLoadedElements, message)); } return results; } }
package yuku.alkitab.base.dialog; import android.app.*; import android.content.*; import android.view.*; import android.view.ViewGroup.LayoutParams; import android.widget.*; import java.util.*; import yuku.alkitab.*; import yuku.alkitab.base.*; import yuku.alkitab.base.model.*; import yuku.alkitab.base.storage.*; public class JenisCatatanDialog { final Context context; final AlertDialog dialog; final RefreshCallback refreshCallback; final Kitab kitab; final int pasal_1; final int ayat_1; EditText tCatatan; int ari; String alamat; Bukmak2 bukmak; public interface RefreshCallback { void udahan(); } public JenisCatatanDialog(Context context, Kitab kitab, int pasal_1, int ayat_1, RefreshCallback refreshCallback) { this.kitab = kitab; this.pasal_1 = pasal_1; this.ayat_1 = ayat_1; this.ari = Ari.encode(kitab.pos, pasal_1, ayat_1); this.alamat = S.alamat(kitab, pasal_1, ayat_1); this.context = context; this.refreshCallback = refreshCallback; View dialogLayout = LayoutInflater.from(context).inflate(R.layout.dialog_catatan_ubah, null); this.dialog = new AlertDialog.Builder(context) .setView(dialogLayout) .setIcon(R.drawable.jenis_catatan) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { bOk_click(); } }) .setNegativeButton(R.string.delete, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { bHapus_click(); } }) .create(); tCatatan = (EditText) dialogLayout.findViewById(R.id.tCatatan); tCatatan.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { if (tCatatan.length() == 0) { dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } } }); } private void setCatatan(CharSequence catatan) { tCatatan.setText(catatan); } public void bukaDialog() { this.dialog.setTitle(context.getString(R.string.catatan_alamat, alamat)); this.bukmak = S.getDb().getBukmakByAri(ari, Db.Bukmak2.jenis_catatan); if (bukmak != null) { tCatatan.setText(bukmak.tulisan); } dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); dialog.show(); } protected void bOk_click() { String tulisan = tCatatan.getText().toString(); Date kini = new Date(); if (bukmak != null) { if (tulisan.length() == 0) { S.getDb().hapusBukmakByAri(ari, Db.Bukmak2.jenis_catatan); } else { bukmak.tulisan = tulisan; bukmak.waktuUbah = kini; S.getDb().updateBukmak(bukmak); } } else { // bukmak == null; belum ada sebelumnya, maka hanya insert kalo ada tulisan. if (tulisan.length() > 0) { bukmak = S.getDb().insertBukmak(ari, Db.Bukmak2.jenis_catatan, tulisan, kini, kini); } } if (refreshCallback != null) refreshCallback.udahan(); } protected void bHapus_click() { // kalo emang ga ada, cek apakah udah ada teks, kalau udah ada, tanya dulu if (bukmak != null || (bukmak == null && tCatatan.length() > 0)) { new AlertDialog.Builder(context) .setTitle(R.string.hapus_catatan) .setMessage(R.string.anda_yakin_mau_menghapus_catatan_ini) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (bukmak != null) { // beneran hapus dari db S.getDb().hapusBukmakByAri(ari, Db.Bukmak2.jenis_catatan); } else { // ga ngapa2in, karena emang ga ada di db, cuma di editor buffer } if (refreshCallback != null) refreshCallback.udahan(); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface _unused_, int which) { JenisCatatanDialog dialog = new JenisCatatanDialog(context, kitab, pasal_1, ayat_1, refreshCallback); dialog.setCatatan(tCatatan.getText()); dialog.bukaDialog(); } }) .show(); } } }