id
int64
22
34.9k
comment_id
int64
0
328
comment
stringlengths
2
2.55k
code
stringlengths
31
107k
classification
stringclasses
6 values
isFinished
bool
1 class
code_context_2
stringlengths
21
27.3k
code_context_10
stringlengths
29
27.3k
code_context_20
stringlengths
29
27.3k
31,217
2
// TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
TEST
true
// TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs =
} // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress();
31,217
3
// metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi";
Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() {
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } }
31,217
4
// We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() {
// avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace();
// TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer);
31,217
5
// Create a KeyStore containing our trusted CAs
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType);
server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS");
} else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) {
31,217
6
// Create a TrustManager that trusts the CAs in our KeyStore
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace();
} catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try {
31,217
7
// Create an SSLContext that uses our TrustManager
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null);
} // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace();
if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput);
31,217
8
// Create a KeyStore containing our trusted CAs
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType);
server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS");
} else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) {
31,217
9
// Create a TrustManager that trusts the CAs in our KeyStore
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace();
} catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try {
31,217
10
// Create an SSLContext that uses our TrustManager
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null);
} // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace();
if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput);
31,217
11
// Extract data that was sent by previous activity. In our case, list of // apps, server and timing
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false;
} catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone
// Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); }
31,217
12
// generate or retrieve an id for this phone
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
"path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) {
// apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); }
e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit();
31,217
13
// to get historyCount
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone
SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else {
analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000);
31,217
14
// generate or retrieve an historyCount for this phone
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
// to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) {
editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); }
results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace();
31,217
15
// check if retrieve historyCount succeeded
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException();
boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait
31,217
16
// make sure server is initialized!
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try {
editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", "");
a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) {
31,217
17
// Find a way to switch to no wait
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
} }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try {
} } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) {
// check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null;
31,217
18
// Set the app to run test for
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app
try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) {
Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
31,217
19
// Run the test on this.app
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
NONSATD
true
// Set the app to run test for this.app = app; // Run the test on this.app runTest(); }
} catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults();
Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
31,217
20
// Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking
@Override protected Void doInBackground(String... args) { if (isCancelled()) { return null; } // TODO subscribe to network events instead of using this if (!networkAvailable) { Toast.makeText( context, getString(R.string.toast_nonetwork), Toast.LENGTH_LONG).show(); } else { // TODO remove this but with caution updateUIBean = new UpdateUIBean(); // TODO to test different configs change the files poiting by CONFIG_FILE // avoid changing the code directly Config.readConfigFile(ReplayConstants.CONFIG_FILE, context); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { // metadata here is user's network type device used geolocation if permitted etc // Google storage forbids to store user related data // So we send that data to a private server server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi"); metadataServer = "wehe-metadata.meddle.mobi"; // We first resolve the IP of the server and then communicate with the server // Using IP only, because we have multiple server under same domain and we want // the client not to switch server during a test run // TODO come up with a better way to handle Inet related queries, since this // introduced inefficiency final InetAddress[] address = {null, null}; new Thread() { public void run() { while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) { try { server = InetAddress.getByName(server).getHostAddress(); address[0] = InetAddress.getByName(server); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); new Thread() { public void run() { while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { metadataServer = InetAddress.getByName(metadataServer).getHostAddress(); address[1] = InetAddress.getByName(metadataServer); } catch (UnknownHostException e) { Log.w("GetReplayServerIP", "get IP of replay server failed!"); e.printStackTrace(); } } } }.start(); int maxWaitTime = 5000; int currentWaitTime = 500; while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address) && !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) { try { if (currentWaitTime <= maxWaitTime) { Thread.sleep(currentWaitTime); currentWaitTime += 500; } else { Toast.makeText(context, R.string.server_unavailable, Toast.LENGTH_LONG).show(); return null; } } catch (InterruptedException e) { e.printStackTrace(); } } if (address[0] instanceof Inet6Address) server = "[" + server + "]"; if (address[1] instanceof Inet6Address) metadataServer = "[" + metadataServer + "]"; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.main)) { ca = cf.generateCertificate(caInput); System.out.println("main=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("main", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); sslSocketFactory = context.getSocketFactory(); hostnameVerifier = (hostname, session) -> true; } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) { ca = cf.generateCertificate(caInput); System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN()); } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("metadata", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); metadataSocketFactory = context.getSocketFactory(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("GetReplayServerIP", "Server IP: " + server); } catch (NullPointerException e) { e.printStackTrace(); Log.w("GetReplayServerIP", "Invalid IP address!"); } // Extract data that was sent by previous activity. In our case, list of // apps, server and timing enableTiming = "true"; doTest = false; int port = Integer.valueOf(Config.get("result_port")); analyzerServerUrl = ("https://" + server + ":" + port + "/Results"); date = new Date(); results = new JSONArray(); Log.d("Result Channel", "path: " + server + " port: " + port); confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true); // generate or retrieve an id for this phone boolean hasID = sharedPrefs.getBoolean("hasID", false); if (!hasID) { randomID = new RandomString(10).nextString(); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putBoolean("hasID", true); editor.putString("ID", randomID); editor.apply(); } else { randomID = sharedPrefs.getString("ID", null); } a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10"))); ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5"))); confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true); // to get historyCount settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE); // generate or retrieve an historyCount for this phone boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false); if (!hasHistoryCount) { historyCount = 0; SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("hasHistoryCount", true); editor.putInt("historyCount", historyCount); editor.apply(); } else { historyCount = settings.getInt("historyCount", -1); } // check if retrieve historyCount succeeded if (historyCount == -1) throw new RuntimeException(); Config.set("timing", enableTiming); // make sure server is initialized! while (server == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Config.set("server", server); Config.set("jitter", "true"); Config.set("publicIP", ""); new Thread(new Runnable() { public void run() { Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
DESIGN
true
runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null;
} Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; }
Config.set("publicIP", getPublicIP("80")); } }).start(); // Find a way to switch to no wait while (Config.get("publicIP").equals("")) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d("Replay", "public IP: " + Config.get("publicIP")); } for (ApplicationBean app : selectedApps) { rerun = false; // Set the app to run test for this.app = app; // Run the test on this.app runTest(); } // Keep checking if the user exited from ReplayActivity or not // TODO find a better way stop the tests immediately without continues checking if (isCancelled()) { return null; } if (results.length() > 0) { Log.d("Result Channel", "Storing results"); saveResults(); } if (isCancelled()) { return null; } showFinishDialog(); Log.d("Result Channel", "Exiting normally"); return null; }
31,226
0
// TODO: alternatively we can just take a json string here and pass that directly to the ffi for librgb
@ReactMethod public void issue( // TODO: alternatively we can just take a json string here and pass that directly to the ffi for librgb int alloc_coins, String alloc_outpoint, String network, String ticker, String name, String description, int precision, Promise promise) { try { final Runtime runtime = ((MainApplication) getCurrentActivity().getApplication()).getRuntime(); final OutpointCoins allocation = new OutpointCoins((long) alloc_coins, alloc_outpoint); runtime.issue(network, ticker, name, description, precision, Arrays.asList(allocation), new HashSet<OutpointCoins>(), null, null); WritableMap map = Arguments.createMap(); promise.resolve(map); } catch (Exception e) { promise.reject(e); } }
DESIGN
true
@ReactMethod public void issue( // TODO: alternatively we can just take a json string here and pass that directly to the ffi for librgb int alloc_coins, String alloc_outpoint,
@ReactMethod public void issue( // TODO: alternatively we can just take a json string here and pass that directly to the ffi for librgb int alloc_coins, String alloc_outpoint, String network, String ticker, String name, String description, int precision, Promise promise) { try { final Runtime runtime = ((MainApplication) getCurrentActivity().getApplication()).getRuntime();
@ReactMethod public void issue( // TODO: alternatively we can just take a json string here and pass that directly to the ffi for librgb int alloc_coins, String alloc_outpoint, String network, String ticker, String name, String description, int precision, Promise promise) { try { final Runtime runtime = ((MainApplication) getCurrentActivity().getApplication()).getRuntime(); final OutpointCoins allocation = new OutpointCoins((long) alloc_coins, alloc_outpoint); runtime.issue(network, ticker, name, description, precision, Arrays.asList(allocation), new HashSet<OutpointCoins>(), null, null); WritableMap map = Arguments.createMap(); promise.resolve(map); } catch (Exception e) { promise.reject(e); } }
23,034
0
//Confused? Copy the URL and paste it in your browser.
private static boolean isOnline(){ try{ new URL("http://74.125.230.174").openConnection().connect(); //Confused? Copy the URL and paste it in your browser. return true; }catch (IOException e) { return false; } }
DESIGN
true
private static boolean isOnline(){ try{ new URL("http://74.125.230.174").openConnection().connect(); //Confused? Copy the URL and paste it in your browser. return true; }catch (IOException e) {
private static boolean isOnline(){ try{ new URL("http://74.125.230.174").openConnection().connect(); //Confused? Copy the URL and paste it in your browser. return true; }catch (IOException e) { return false; } }
private static boolean isOnline(){ try{ new URL("http://74.125.230.174").openConnection().connect(); //Confused? Copy the URL and paste it in your browser. return true; }catch (IOException e) { return false; } }
23,038
0
// we have more space than necessary; resize to give each at least // preferred size
@Override public void resetToPreferredSizes() { Insets i = getInsets(); if (getOrientation() == VERTICAL_SPLIT) { int h = getHeight() - i.top - i.bottom - getDividerSize(); int topH = getTopComponent().getPreferredSize().height; int bottomH = getBottomComponent().getPreferredSize().height; int extraSpace = h - topH - bottomH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.top + topH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } else { int w = getWidth() - i.left - i.right - getDividerSize(); int leftH = getLeftComponent().getPreferredSize().width; int rightH = getRightComponent().getPreferredSize().width; int extraSpace = w - leftH - rightH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.left + leftH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } }
NONSATD
true
int bottomH = getBottomComponent().getPreferredSize().height; int extraSpace = h - topH - bottomH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.top + topH
@Override public void resetToPreferredSizes() { Insets i = getInsets(); if (getOrientation() == VERTICAL_SPLIT) { int h = getHeight() - i.top - i.bottom - getDividerSize(); int topH = getTopComponent().getPreferredSize().height; int bottomH = getBottomComponent().getPreferredSize().height; int extraSpace = h - topH - bottomH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.top + topH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } else { int w = getWidth() - i.left - i.right - getDividerSize(); int leftH = getLeftComponent().getPreferredSize().width; int rightH = getRightComponent().getPreferredSize().width;
@Override public void resetToPreferredSizes() { Insets i = getInsets(); if (getOrientation() == VERTICAL_SPLIT) { int h = getHeight() - i.top - i.bottom - getDividerSize(); int topH = getTopComponent().getPreferredSize().height; int bottomH = getBottomComponent().getPreferredSize().height; int extraSpace = h - topH - bottomH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.top + topH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } else { int w = getWidth() - i.left - i.right - getDividerSize(); int leftH = getLeftComponent().getPreferredSize().width; int rightH = getRightComponent().getPreferredSize().width; int extraSpace = w - leftH - rightH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.left + leftH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more }
23,038
1
// TODO implement shrinking excess space to ensure that one has // preferred and nothing more
@Override public void resetToPreferredSizes() { Insets i = getInsets(); if (getOrientation() == VERTICAL_SPLIT) { int h = getHeight() - i.top - i.bottom - getDividerSize(); int topH = getTopComponent().getPreferredSize().height; int bottomH = getBottomComponent().getPreferredSize().height; int extraSpace = h - topH - bottomH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.top + topH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } else { int w = getWidth() - i.left - i.right - getDividerSize(); int leftH = getLeftComponent().getPreferredSize().width; int rightH = getRightComponent().getPreferredSize().width; int extraSpace = w - leftH - rightH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.left + leftH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } }
IMPLEMENTATION
true
+ ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } else { int w = getWidth() - i.left - i.right - getDividerSize();
int h = getHeight() - i.top - i.bottom - getDividerSize(); int topH = getTopComponent().getPreferredSize().height; int bottomH = getBottomComponent().getPreferredSize().height; int extraSpace = h - topH - bottomH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.top + topH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } else { int w = getWidth() - i.left - i.right - getDividerSize(); int leftH = getLeftComponent().getPreferredSize().width; int rightH = getRightComponent().getPreferredSize().width; int extraSpace = w - leftH - rightH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.left + leftH + ((int) (extraSpace * getResizeWeight() + .5)));
@Override public void resetToPreferredSizes() { Insets i = getInsets(); if (getOrientation() == VERTICAL_SPLIT) { int h = getHeight() - i.top - i.bottom - getDividerSize(); int topH = getTopComponent().getPreferredSize().height; int bottomH = getBottomComponent().getPreferredSize().height; int extraSpace = h - topH - bottomH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.top + topH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } else { int w = getWidth() - i.left - i.right - getDividerSize(); int leftH = getLeftComponent().getPreferredSize().width; int rightH = getRightComponent().getPreferredSize().width; int extraSpace = w - leftH - rightH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.left + leftH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } }
23,038
2
// we have more space than necessary; resize to give each at least // preferred size
@Override public void resetToPreferredSizes() { Insets i = getInsets(); if (getOrientation() == VERTICAL_SPLIT) { int h = getHeight() - i.top - i.bottom - getDividerSize(); int topH = getTopComponent().getPreferredSize().height; int bottomH = getBottomComponent().getPreferredSize().height; int extraSpace = h - topH - bottomH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.top + topH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } else { int w = getWidth() - i.left - i.right - getDividerSize(); int leftH = getLeftComponent().getPreferredSize().width; int rightH = getRightComponent().getPreferredSize().width; int extraSpace = w - leftH - rightH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.left + leftH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } }
NONSATD
true
int bottomH = getBottomComponent().getPreferredSize().height; int extraSpace = h - topH - bottomH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.top + topH
@Override public void resetToPreferredSizes() { Insets i = getInsets(); if (getOrientation() == VERTICAL_SPLIT) { int h = getHeight() - i.top - i.bottom - getDividerSize(); int topH = getTopComponent().getPreferredSize().height; int bottomH = getBottomComponent().getPreferredSize().height; int extraSpace = h - topH - bottomH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.top + topH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } else { int w = getWidth() - i.left - i.right - getDividerSize(); int leftH = getLeftComponent().getPreferredSize().width; int rightH = getRightComponent().getPreferredSize().width;
@Override public void resetToPreferredSizes() { Insets i = getInsets(); if (getOrientation() == VERTICAL_SPLIT) { int h = getHeight() - i.top - i.bottom - getDividerSize(); int topH = getTopComponent().getPreferredSize().height; int bottomH = getBottomComponent().getPreferredSize().height; int extraSpace = h - topH - bottomH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.top + topH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } else { int w = getWidth() - i.left - i.right - getDividerSize(); int leftH = getLeftComponent().getPreferredSize().width; int rightH = getRightComponent().getPreferredSize().width; int extraSpace = w - leftH - rightH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.left + leftH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more }
23,038
3
// TODO implement shrinking excess space to ensure that one has // preferred and nothing more
@Override public void resetToPreferredSizes() { Insets i = getInsets(); if (getOrientation() == VERTICAL_SPLIT) { int h = getHeight() - i.top - i.bottom - getDividerSize(); int topH = getTopComponent().getPreferredSize().height; int bottomH = getBottomComponent().getPreferredSize().height; int extraSpace = h - topH - bottomH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.top + topH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } else { int w = getWidth() - i.left - i.right - getDividerSize(); int leftH = getLeftComponent().getPreferredSize().width; int rightH = getRightComponent().getPreferredSize().width; int extraSpace = w - leftH - rightH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.left + leftH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } }
IMPLEMENTATION
true
+ ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } else { int w = getWidth() - i.left - i.right - getDividerSize();
int h = getHeight() - i.top - i.bottom - getDividerSize(); int topH = getTopComponent().getPreferredSize().height; int bottomH = getBottomComponent().getPreferredSize().height; int extraSpace = h - topH - bottomH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.top + topH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } else { int w = getWidth() - i.left - i.right - getDividerSize(); int leftH = getLeftComponent().getPreferredSize().width; int rightH = getRightComponent().getPreferredSize().width; int extraSpace = w - leftH - rightH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.left + leftH + ((int) (extraSpace * getResizeWeight() + .5)));
@Override public void resetToPreferredSizes() { Insets i = getInsets(); if (getOrientation() == VERTICAL_SPLIT) { int h = getHeight() - i.top - i.bottom - getDividerSize(); int topH = getTopComponent().getPreferredSize().height; int bottomH = getBottomComponent().getPreferredSize().height; int extraSpace = h - topH - bottomH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.top + topH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } else { int w = getWidth() - i.left - i.right - getDividerSize(); int leftH = getLeftComponent().getPreferredSize().width; int rightH = getRightComponent().getPreferredSize().width; int extraSpace = w - leftH - rightH; // we have more space than necessary; resize to give each at least // preferred size if (extraSpace >= 0) { setDividerLocation(i.left + leftH + ((int) (extraSpace * getResizeWeight() + .5))); } // TODO implement shrinking excess space to ensure that one has // preferred and nothing more } }
23,039
0
//FIXME use Auth header with basic auth
@GetMapping("/sign-in") Mono<JwtToken> signIn(@RequestParam("login") String login,//FIXME use Auth header with basic auth @RequestParam("password") String password) { return userRepository.findByEmailOrMobile(login, login) .filter(u -> u.validatePassword(password)) .map(this::createToken) .map(Mono::just) .orElseThrow(() -> new IllegalArgumentException("Invalid login or password")); }
DEFECT
true
@GetMapping("/sign-in") Mono<JwtToken> signIn(@RequestParam("login") String login,//FIXME use Auth header with basic auth @RequestParam("password") String password) { return userRepository.findByEmailOrMobile(login, login)
@GetMapping("/sign-in") Mono<JwtToken> signIn(@RequestParam("login") String login,//FIXME use Auth header with basic auth @RequestParam("password") String password) { return userRepository.findByEmailOrMobile(login, login) .filter(u -> u.validatePassword(password)) .map(this::createToken) .map(Mono::just) .orElseThrow(() -> new IllegalArgumentException("Invalid login or password")); }
@GetMapping("/sign-in") Mono<JwtToken> signIn(@RequestParam("login") String login,//FIXME use Auth header with basic auth @RequestParam("password") String password) { return userRepository.findByEmailOrMobile(login, login) .filter(u -> u.validatePassword(password)) .map(this::createToken) .map(Mono::just) .orElseThrow(() -> new IllegalArgumentException("Invalid login or password")); }
23,040
0
// Update each of the widgets with the remote adapter
@Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // Update each of the widgets with the remote adapter for (int i = 0; i < appWidgetIds.length; ++i) { RemoteViews layout = buildLayout(context, appWidgetIds[i]); appWidgetManager.updateAppWidget(appWidgetIds[i], layout); } super.onUpdate(context, appWidgetManager, appWidgetIds); // wtf another google bug? this.onEnabled(context); }
NONSATD
true
@Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // Update each of the widgets with the remote adapter for (int i = 0; i < appWidgetIds.length; ++i) { RemoteViews layout = buildLayout(context, appWidgetIds[i]);
@Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // Update each of the widgets with the remote adapter for (int i = 0; i < appWidgetIds.length; ++i) { RemoteViews layout = buildLayout(context, appWidgetIds[i]); appWidgetManager.updateAppWidget(appWidgetIds[i], layout); } super.onUpdate(context, appWidgetManager, appWidgetIds); // wtf another google bug? this.onEnabled(context); }
@Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // Update each of the widgets with the remote adapter for (int i = 0; i < appWidgetIds.length; ++i) { RemoteViews layout = buildLayout(context, appWidgetIds[i]); appWidgetManager.updateAppWidget(appWidgetIds[i], layout); } super.onUpdate(context, appWidgetManager, appWidgetIds); // wtf another google bug? this.onEnabled(context); }
23,040
1
// wtf another google bug?
@Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // Update each of the widgets with the remote adapter for (int i = 0; i < appWidgetIds.length; ++i) { RemoteViews layout = buildLayout(context, appWidgetIds[i]); appWidgetManager.updateAppWidget(appWidgetIds[i], layout); } super.onUpdate(context, appWidgetManager, appWidgetIds); // wtf another google bug? this.onEnabled(context); }
DEFECT
true
} super.onUpdate(context, appWidgetManager, appWidgetIds); // wtf another google bug? this.onEnabled(context); }
@Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // Update each of the widgets with the remote adapter for (int i = 0; i < appWidgetIds.length; ++i) { RemoteViews layout = buildLayout(context, appWidgetIds[i]); appWidgetManager.updateAppWidget(appWidgetIds[i], layout); } super.onUpdate(context, appWidgetManager, appWidgetIds); // wtf another google bug? this.onEnabled(context); }
@Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // Update each of the widgets with the remote adapter for (int i = 0; i < appWidgetIds.length; ++i) { RemoteViews layout = buildLayout(context, appWidgetIds[i]); appWidgetManager.updateAppWidget(appWidgetIds[i], layout); } super.onUpdate(context, appWidgetManager, appWidgetIds); // wtf another google bug? this.onEnabled(context); }
23,051
0
// TODO: Update this logic to also handle the user logged in by email.
@Override protected void updateConnectButtonState() { // TODO: Update this logic to also handle the user logged in by email. boolean connected = getPlusClient().isConnected(); mSignOutButtons.setVisibility(connected ? View.VISIBLE : View.GONE); mPlusSignInButton.setVisibility(connected ? View.GONE : View.VISIBLE); }
IMPLEMENTATION
true
@Override protected void updateConnectButtonState() { // TODO: Update this logic to also handle the user logged in by email. boolean connected = getPlusClient().isConnected(); mSignOutButtons.setVisibility(connected ? View.VISIBLE : View.GONE);
@Override protected void updateConnectButtonState() { // TODO: Update this logic to also handle the user logged in by email. boolean connected = getPlusClient().isConnected(); mSignOutButtons.setVisibility(connected ? View.VISIBLE : View.GONE); mPlusSignInButton.setVisibility(connected ? View.GONE : View.VISIBLE); }
@Override protected void updateConnectButtonState() { // TODO: Update this logic to also handle the user logged in by email. boolean connected = getPlusClient().isConnected(); mSignOutButtons.setVisibility(connected ? View.VISIBLE : View.GONE); mPlusSignInButton.setVisibility(connected ? View.GONE : View.VISIBLE); }
31,251
0
/* Write a program to add a score of 100 to the the array scores. */
public static void main(String[] args){ /* Write a program to add a score of 100 to the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
NONSATD
true
public static void main(String[] args){ /* Write a program to add a score of 100 to the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores));
public static void main(String[] args){ /* Write a program to add a score of 100 to the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line
public static void main(String[] args){ /* Write a program to add a score of 100 to the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores);
31,251
1
//TODO 1: Write code to make a new array that can hold a new score
public static void main(String[] args){ /* Write a program to add a score of 100 to the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
IMPLEMENTATION
true
int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){
public static void main(String[] args){ /* Write a program to add a score of 100 to the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1];
public static void main(String[] args){ /* Write a program to add a score of 100 to the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
31,251
2
// ... code to add should stay above this line
public static void main(String[] args){ /* Write a program to add a score of 100 to the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
NONSATD
true
temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores
*/ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores);
public static void main(String[] args){ /* Write a program to add a score of 100 to the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
31,251
3
//TODO 2: Next, write code to remove the first value from the scores
public static void main(String[] args){ /* Write a program to add a score of 100 to the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
IMPLEMENTATION
true
// ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){
System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
public static void main(String[] args){ /* Write a program to add a score of 100 to the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
31,251
4
// ... code to remove should stay above this line
public static void main(String[] args){ /* Write a program to add a score of 100 to the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
NONSATD
true
temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below
} temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
/* Write a program to add a score of 100 to the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
31,251
5
//TODO 3: Implement the methods below
public static void main(String[] args){ /* Write a program to add a score of 100 to the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
IMPLEMENTATION
true
// ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores);
scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
31,251
6
//System.out.println("Copy of scores looks like: " + scores);
public static void main(String[] args){ /* Write a program to add a score of 100 to the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
NONSATD
true
//TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
31,253
0
/** * Verifies semantics of all component definitions: * + check root component has no generics * + check all identifiers used are declared * + check all expressions in declarations use generics or constants * + check types for all expressions are valid * Future: * + check width for all expressions - recurse through all instances (would need to do fancy stuff to check using only component definition) */
private void verifyAllComponents() { // check root component has no generics if (!this.components.get(this.topname).getGenerics().isEmpty()) genericError(String.format("top component %s cannot contain generics", this.topname)); // verify all components for (Component component : this.components.values()) { this.currentComponent = component.name; this.verifyPortArch(component.ast); this.verifyIdentifiers(component.ast); this.verifyConstantExpressions(component.ast); this.verifyTypes(component.ast); } }
IMPLEMENTATION
true
private void verifyAllComponents() { // check root component has no generics if (!this.components.get(this.topname).getGenerics().isEmpty()) genericError(String.format("top component %s cannot contain generics", this.topname)); // verify all components for (Component component : this.components.values()) { this.currentComponent = component.name; this.verifyPortArch(component.ast); this.verifyIdentifiers(component.ast); this.verifyConstantExpressions(component.ast); this.verifyTypes(component.ast); } }
private void verifyAllComponents() { // check root component has no generics if (!this.components.get(this.topname).getGenerics().isEmpty()) genericError(String.format("top component %s cannot contain generics", this.topname)); // verify all components for (Component component : this.components.values()) { this.currentComponent = component.name; this.verifyPortArch(component.ast); this.verifyIdentifiers(component.ast); this.verifyConstantExpressions(component.ast); this.verifyTypes(component.ast); } }
private void verifyAllComponents() { // check root component has no generics if (!this.components.get(this.topname).getGenerics().isEmpty()) genericError(String.format("top component %s cannot contain generics", this.topname)); // verify all components for (Component component : this.components.values()) { this.currentComponent = component.name; this.verifyPortArch(component.ast); this.verifyIdentifiers(component.ast); this.verifyConstantExpressions(component.ast); this.verifyTypes(component.ast); } }
31,253
1
// check root component has no generics
private void verifyAllComponents() { // check root component has no generics if (!this.components.get(this.topname).getGenerics().isEmpty()) genericError(String.format("top component %s cannot contain generics", this.topname)); // verify all components for (Component component : this.components.values()) { this.currentComponent = component.name; this.verifyPortArch(component.ast); this.verifyIdentifiers(component.ast); this.verifyConstantExpressions(component.ast); this.verifyTypes(component.ast); } }
NONSATD
true
private void verifyAllComponents() { // check root component has no generics if (!this.components.get(this.topname).getGenerics().isEmpty()) genericError(String.format("top component %s cannot contain generics", this.topname));
private void verifyAllComponents() { // check root component has no generics if (!this.components.get(this.topname).getGenerics().isEmpty()) genericError(String.format("top component %s cannot contain generics", this.topname)); // verify all components for (Component component : this.components.values()) { this.currentComponent = component.name; this.verifyPortArch(component.ast); this.verifyIdentifiers(component.ast); this.verifyConstantExpressions(component.ast); this.verifyTypes(component.ast);
private void verifyAllComponents() { // check root component has no generics if (!this.components.get(this.topname).getGenerics().isEmpty()) genericError(String.format("top component %s cannot contain generics", this.topname)); // verify all components for (Component component : this.components.values()) { this.currentComponent = component.name; this.verifyPortArch(component.ast); this.verifyIdentifiers(component.ast); this.verifyConstantExpressions(component.ast); this.verifyTypes(component.ast); } }
31,253
2
// verify all components
private void verifyAllComponents() { // check root component has no generics if (!this.components.get(this.topname).getGenerics().isEmpty()) genericError(String.format("top component %s cannot contain generics", this.topname)); // verify all components for (Component component : this.components.values()) { this.currentComponent = component.name; this.verifyPortArch(component.ast); this.verifyIdentifiers(component.ast); this.verifyConstantExpressions(component.ast); this.verifyTypes(component.ast); } }
NONSATD
true
if (!this.components.get(this.topname).getGenerics().isEmpty()) genericError(String.format("top component %s cannot contain generics", this.topname)); // verify all components for (Component component : this.components.values()) {
private void verifyAllComponents() { // check root component has no generics if (!this.components.get(this.topname).getGenerics().isEmpty()) genericError(String.format("top component %s cannot contain generics", this.topname)); // verify all components for (Component component : this.components.values()) { this.currentComponent = component.name; this.verifyPortArch(component.ast); this.verifyIdentifiers(component.ast); this.verifyConstantExpressions(component.ast); this.verifyTypes(component.ast); } }
private void verifyAllComponents() { // check root component has no generics if (!this.components.get(this.topname).getGenerics().isEmpty()) genericError(String.format("top component %s cannot contain generics", this.topname)); // verify all components for (Component component : this.components.values()) { this.currentComponent = component.name; this.verifyPortArch(component.ast); this.verifyIdentifiers(component.ast); this.verifyConstantExpressions(component.ast); this.verifyTypes(component.ast); } }
14,870
0
/** * Handles changes to the APN database. */
private void onApnChanged() { DctConstants.State overallState = getOverallState(); boolean isDisconnected = (overallState == DctConstants.State.IDLE || overallState == DctConstants.State.FAILED); if (mPhone instanceof GSMPhone) { // The "current" may no longer be valid. MMS depends on this to send properly. TBD ((GSMPhone)mPhone).updateCurrentCarrierInProvider(); } // TODO: It'd be nice to only do this if the changed entrie(s) // match the current operator. if (DBG) log("onApnChanged: createAllApnList and cleanUpAllConnections"); createAllApnList(); setInitialAttachApn(); cleanUpAllConnections(!isDisconnected, Phone.REASON_APN_CHANGED); if (isDisconnected) { setupDataOnConnectableApns(Phone.REASON_APN_CHANGED); } }
NONSATD
true
private void onApnChanged() { DctConstants.State overallState = getOverallState(); boolean isDisconnected = (overallState == DctConstants.State.IDLE || overallState == DctConstants.State.FAILED); if (mPhone instanceof GSMPhone) { // The "current" may no longer be valid. MMS depends on this to send properly. TBD ((GSMPhone)mPhone).updateCurrentCarrierInProvider(); } // TODO: It'd be nice to only do this if the changed entrie(s) // match the current operator. if (DBG) log("onApnChanged: createAllApnList and cleanUpAllConnections"); createAllApnList(); setInitialAttachApn(); cleanUpAllConnections(!isDisconnected, Phone.REASON_APN_CHANGED); if (isDisconnected) { setupDataOnConnectableApns(Phone.REASON_APN_CHANGED); } }
private void onApnChanged() { DctConstants.State overallState = getOverallState(); boolean isDisconnected = (overallState == DctConstants.State.IDLE || overallState == DctConstants.State.FAILED); if (mPhone instanceof GSMPhone) { // The "current" may no longer be valid. MMS depends on this to send properly. TBD ((GSMPhone)mPhone).updateCurrentCarrierInProvider(); } // TODO: It'd be nice to only do this if the changed entrie(s) // match the current operator. if (DBG) log("onApnChanged: createAllApnList and cleanUpAllConnections"); createAllApnList(); setInitialAttachApn(); cleanUpAllConnections(!isDisconnected, Phone.REASON_APN_CHANGED); if (isDisconnected) { setupDataOnConnectableApns(Phone.REASON_APN_CHANGED); } }
private void onApnChanged() { DctConstants.State overallState = getOverallState(); boolean isDisconnected = (overallState == DctConstants.State.IDLE || overallState == DctConstants.State.FAILED); if (mPhone instanceof GSMPhone) { // The "current" may no longer be valid. MMS depends on this to send properly. TBD ((GSMPhone)mPhone).updateCurrentCarrierInProvider(); } // TODO: It'd be nice to only do this if the changed entrie(s) // match the current operator. if (DBG) log("onApnChanged: createAllApnList and cleanUpAllConnections"); createAllApnList(); setInitialAttachApn(); cleanUpAllConnections(!isDisconnected, Phone.REASON_APN_CHANGED); if (isDisconnected) { setupDataOnConnectableApns(Phone.REASON_APN_CHANGED); } }
14,870
1
// The "current" may no longer be valid. MMS depends on this to send properly. TBD
private void onApnChanged() { DctConstants.State overallState = getOverallState(); boolean isDisconnected = (overallState == DctConstants.State.IDLE || overallState == DctConstants.State.FAILED); if (mPhone instanceof GSMPhone) { // The "current" may no longer be valid. MMS depends on this to send properly. TBD ((GSMPhone)mPhone).updateCurrentCarrierInProvider(); } // TODO: It'd be nice to only do this if the changed entrie(s) // match the current operator. if (DBG) log("onApnChanged: createAllApnList and cleanUpAllConnections"); createAllApnList(); setInitialAttachApn(); cleanUpAllConnections(!isDisconnected, Phone.REASON_APN_CHANGED); if (isDisconnected) { setupDataOnConnectableApns(Phone.REASON_APN_CHANGED); } }
NONSATD
true
overallState == DctConstants.State.FAILED); if (mPhone instanceof GSMPhone) { // The "current" may no longer be valid. MMS depends on this to send properly. TBD ((GSMPhone)mPhone).updateCurrentCarrierInProvider(); }
private void onApnChanged() { DctConstants.State overallState = getOverallState(); boolean isDisconnected = (overallState == DctConstants.State.IDLE || overallState == DctConstants.State.FAILED); if (mPhone instanceof GSMPhone) { // The "current" may no longer be valid. MMS depends on this to send properly. TBD ((GSMPhone)mPhone).updateCurrentCarrierInProvider(); } // TODO: It'd be nice to only do this if the changed entrie(s) // match the current operator. if (DBG) log("onApnChanged: createAllApnList and cleanUpAllConnections"); createAllApnList(); setInitialAttachApn(); cleanUpAllConnections(!isDisconnected, Phone.REASON_APN_CHANGED); if (isDisconnected) { setupDataOnConnectableApns(Phone.REASON_APN_CHANGED);
private void onApnChanged() { DctConstants.State overallState = getOverallState(); boolean isDisconnected = (overallState == DctConstants.State.IDLE || overallState == DctConstants.State.FAILED); if (mPhone instanceof GSMPhone) { // The "current" may no longer be valid. MMS depends on this to send properly. TBD ((GSMPhone)mPhone).updateCurrentCarrierInProvider(); } // TODO: It'd be nice to only do this if the changed entrie(s) // match the current operator. if (DBG) log("onApnChanged: createAllApnList and cleanUpAllConnections"); createAllApnList(); setInitialAttachApn(); cleanUpAllConnections(!isDisconnected, Phone.REASON_APN_CHANGED); if (isDisconnected) { setupDataOnConnectableApns(Phone.REASON_APN_CHANGED); } }
14,870
2
// TODO: It'd be nice to only do this if the changed entrie(s) // match the current operator.
private void onApnChanged() { DctConstants.State overallState = getOverallState(); boolean isDisconnected = (overallState == DctConstants.State.IDLE || overallState == DctConstants.State.FAILED); if (mPhone instanceof GSMPhone) { // The "current" may no longer be valid. MMS depends on this to send properly. TBD ((GSMPhone)mPhone).updateCurrentCarrierInProvider(); } // TODO: It'd be nice to only do this if the changed entrie(s) // match the current operator. if (DBG) log("onApnChanged: createAllApnList and cleanUpAllConnections"); createAllApnList(); setInitialAttachApn(); cleanUpAllConnections(!isDisconnected, Phone.REASON_APN_CHANGED); if (isDisconnected) { setupDataOnConnectableApns(Phone.REASON_APN_CHANGED); } }
DESIGN
true
((GSMPhone)mPhone).updateCurrentCarrierInProvider(); } // TODO: It'd be nice to only do this if the changed entrie(s) // match the current operator. if (DBG) log("onApnChanged: createAllApnList and cleanUpAllConnections"); createAllApnList();
private void onApnChanged() { DctConstants.State overallState = getOverallState(); boolean isDisconnected = (overallState == DctConstants.State.IDLE || overallState == DctConstants.State.FAILED); if (mPhone instanceof GSMPhone) { // The "current" may no longer be valid. MMS depends on this to send properly. TBD ((GSMPhone)mPhone).updateCurrentCarrierInProvider(); } // TODO: It'd be nice to only do this if the changed entrie(s) // match the current operator. if (DBG) log("onApnChanged: createAllApnList and cleanUpAllConnections"); createAllApnList(); setInitialAttachApn(); cleanUpAllConnections(!isDisconnected, Phone.REASON_APN_CHANGED); if (isDisconnected) { setupDataOnConnectableApns(Phone.REASON_APN_CHANGED); } }
private void onApnChanged() { DctConstants.State overallState = getOverallState(); boolean isDisconnected = (overallState == DctConstants.State.IDLE || overallState == DctConstants.State.FAILED); if (mPhone instanceof GSMPhone) { // The "current" may no longer be valid. MMS depends on this to send properly. TBD ((GSMPhone)mPhone).updateCurrentCarrierInProvider(); } // TODO: It'd be nice to only do this if the changed entrie(s) // match the current operator. if (DBG) log("onApnChanged: createAllApnList and cleanUpAllConnections"); createAllApnList(); setInitialAttachApn(); cleanUpAllConnections(!isDisconnected, Phone.REASON_APN_CHANGED); if (isDisconnected) { setupDataOnConnectableApns(Phone.REASON_APN_CHANGED); } }
23,061
0
// FIXME Test failures
@Override void testBaseLib() {}
TEST
true
@Override void testBaseLib() {}
@Override void testBaseLib() {}
@Override void testBaseLib() {}
23,062
0
// FIXME Test failures
@Override void testCoroutineLib() {}
TEST
true
@Override void testCoroutineLib() {}
@Override void testCoroutineLib() {}
@Override void testCoroutineLib() {}
23,063
0
// FIXME Test failures
@Override void testIoLib() {}
TEST
true
@Override void testIoLib() {}
@Override void testIoLib() {}
@Override void testIoLib() {}
23,064
0
// FIXME Test failures
@Override void testMetatags() {}
TEST
true
@Override void testMetatags() {}
@Override void testMetatags() {}
@Override void testMetatags() {}
23,065
0
// FIXME Test failures
@Override void testOsLib() {}
TEST
true
@Override void testOsLib() {}
@Override void testOsLib() {}
@Override void testOsLib() {}
23,066
0
// FIXME Test failures
@Override void testStringLib() {}
TEST
true
@Override void testStringLib() {}
@Override void testStringLib() {}
@Override void testStringLib() {}
23,074
0
// TODO: Need to work on layout algorithm... believe we can do better, but don't have // a decision on the best speculative results yet. // @Test
public void testJ5_32_speculative() throws Exception { CppCompositeType J5_struct = createJ5_struct32(vbtManager32); J5_struct.createLayout(classLayoutChoice, vbtManager32, TaskMonitor.DUMMY); Composite composite = J5_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ5_32(), composite, true); }
DESIGN
true
public void testJ5_32_speculative() throws Exception { CppCompositeType J5_struct = createJ5_struct32(vbtManager32); J5_struct.createLayout(classLayoutChoice, vbtManager32, TaskMonitor.DUMMY); Composite composite = J5_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ5_32(), composite, true); }
public void testJ5_32_speculative() throws Exception { CppCompositeType J5_struct = createJ5_struct32(vbtManager32); J5_struct.createLayout(classLayoutChoice, vbtManager32, TaskMonitor.DUMMY); Composite composite = J5_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ5_32(), composite, true); }
public void testJ5_32_speculative() throws Exception { CppCompositeType J5_struct = createJ5_struct32(vbtManager32); J5_struct.createLayout(classLayoutChoice, vbtManager32, TaskMonitor.DUMMY); Composite composite = J5_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ5_32(), composite, true); }
23,075
0
// TODO: Need to work on layout algorithm... believe we can do better, but don't have // a decision on the best speculative results yet. // @Test
public void testJ5_64_speculative() throws Exception { CppCompositeType J5_struct = createJ5_struct64(vbtManager64); J5_struct.createLayout(classLayoutChoice, vbtManager64, TaskMonitor.DUMMY); Composite composite = J5_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ5_64(), composite, true); }
DESIGN
true
public void testJ5_64_speculative() throws Exception { CppCompositeType J5_struct = createJ5_struct64(vbtManager64); J5_struct.createLayout(classLayoutChoice, vbtManager64, TaskMonitor.DUMMY); Composite composite = J5_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ5_64(), composite, true); }
public void testJ5_64_speculative() throws Exception { CppCompositeType J5_struct = createJ5_struct64(vbtManager64); J5_struct.createLayout(classLayoutChoice, vbtManager64, TaskMonitor.DUMMY); Composite composite = J5_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ5_64(), composite, true); }
public void testJ5_64_speculative() throws Exception { CppCompositeType J5_struct = createJ5_struct64(vbtManager64); J5_struct.createLayout(classLayoutChoice, vbtManager64, TaskMonitor.DUMMY); Composite composite = J5_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ5_64(), composite, true); }
23,076
0
// TODO: Need to work on layout algorithm... believe we can do better, but don't have // a decision on the best speculative results yet. // @Test
public void testJ6_32_speculative() throws Exception { CppCompositeType J6_struct = createJ6_struct32(vbtManager32); J6_struct.createLayout(classLayoutChoice, vbtManager32, TaskMonitor.DUMMY); Composite composite = J6_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ6_32(), composite, true); }
DESIGN
true
public void testJ6_32_speculative() throws Exception { CppCompositeType J6_struct = createJ6_struct32(vbtManager32); J6_struct.createLayout(classLayoutChoice, vbtManager32, TaskMonitor.DUMMY); Composite composite = J6_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ6_32(), composite, true); }
public void testJ6_32_speculative() throws Exception { CppCompositeType J6_struct = createJ6_struct32(vbtManager32); J6_struct.createLayout(classLayoutChoice, vbtManager32, TaskMonitor.DUMMY); Composite composite = J6_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ6_32(), composite, true); }
public void testJ6_32_speculative() throws Exception { CppCompositeType J6_struct = createJ6_struct32(vbtManager32); J6_struct.createLayout(classLayoutChoice, vbtManager32, TaskMonitor.DUMMY); Composite composite = J6_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ6_32(), composite, true); }
23,077
0
// TODO: Need to work on layout algorithm... believe we can do better, but don't have // a decision on the best speculative results yet. // @Test
public void testJ6_64_speculative() throws Exception { CppCompositeType J6_struct = createJ6_struct64(vbtManager64); J6_struct.createLayout(classLayoutChoice, vbtManager64, TaskMonitor.DUMMY); Composite composite = J6_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ6_64(), composite, true); }
DESIGN
true
public void testJ6_64_speculative() throws Exception { CppCompositeType J6_struct = createJ6_struct64(vbtManager64); J6_struct.createLayout(classLayoutChoice, vbtManager64, TaskMonitor.DUMMY); Composite composite = J6_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ6_64(), composite, true); }
public void testJ6_64_speculative() throws Exception { CppCompositeType J6_struct = createJ6_struct64(vbtManager64); J6_struct.createLayout(classLayoutChoice, vbtManager64, TaskMonitor.DUMMY); Composite composite = J6_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ6_64(), composite, true); }
public void testJ6_64_speculative() throws Exception { CppCompositeType J6_struct = createJ6_struct64(vbtManager64); J6_struct.createLayout(classLayoutChoice, vbtManager64, TaskMonitor.DUMMY); Composite composite = J6_struct.getComposite(); CompositeTestUtils.assertExpectedComposite(this, getSpeculatedJ6_64(), composite, true); }
14,893
0
/** * Create new block. * * @param nodes Nodes from which Block should be created; if the set of nodes contains inner * function calls, the called function body should NOT be included. * @param blockHead Entry point for the block. */
public void addBlock(Set<CFANode> nodes, CFANode blockHead) { Set<ReferencedVariable> referencedVariables = collectReferencedVariables(nodes); Set<CFANode> callNodes = collectCallNodes(nodes); Set<CFANode> returnNodes = collectReturnNodes(nodes); Set<FunctionEntryNode> innerFunctionCalls = collectInnerFunctionCalls(nodes); if (callNodes.isEmpty()) { /* What shall we do with function, which is not called from anywhere? * There are problems with them at partitioning building stage */ return; } CFANode registerNode = null; for (CFANode node : callNodes) { registerNode = node; if (node instanceof FunctionEntryNode) { break; } } if (registerNode == null) { //It means, that there is no entry in this block. Don't add it return; } referencedVariablesMap.put(registerNode, referencedVariables); callNodesMap.put(registerNode, callNodes); returnNodesMap.put(registerNode, returnNodes); innerFunctionCallsMap.put(registerNode, innerFunctionCalls); blockNodesMap.put(registerNode, nodes); }
NONSATD
true
public void addBlock(Set<CFANode> nodes, CFANode blockHead) { Set<ReferencedVariable> referencedVariables = collectReferencedVariables(nodes); Set<CFANode> callNodes = collectCallNodes(nodes); Set<CFANode> returnNodes = collectReturnNodes(nodes); Set<FunctionEntryNode> innerFunctionCalls = collectInnerFunctionCalls(nodes); if (callNodes.isEmpty()) { /* What shall we do with function, which is not called from anywhere? * There are problems with them at partitioning building stage */ return; } CFANode registerNode = null; for (CFANode node : callNodes) { registerNode = node; if (node instanceof FunctionEntryNode) { break; } } if (registerNode == null) { //It means, that there is no entry in this block. Don't add it return; } referencedVariablesMap.put(registerNode, referencedVariables); callNodesMap.put(registerNode, callNodes); returnNodesMap.put(registerNode, returnNodes); innerFunctionCallsMap.put(registerNode, innerFunctionCalls); blockNodesMap.put(registerNode, nodes); }
public void addBlock(Set<CFANode> nodes, CFANode blockHead) { Set<ReferencedVariable> referencedVariables = collectReferencedVariables(nodes); Set<CFANode> callNodes = collectCallNodes(nodes); Set<CFANode> returnNodes = collectReturnNodes(nodes); Set<FunctionEntryNode> innerFunctionCalls = collectInnerFunctionCalls(nodes); if (callNodes.isEmpty()) { /* What shall we do with function, which is not called from anywhere? * There are problems with them at partitioning building stage */ return; } CFANode registerNode = null; for (CFANode node : callNodes) { registerNode = node; if (node instanceof FunctionEntryNode) { break; } } if (registerNode == null) { //It means, that there is no entry in this block. Don't add it return; } referencedVariablesMap.put(registerNode, referencedVariables); callNodesMap.put(registerNode, callNodes); returnNodesMap.put(registerNode, returnNodes); innerFunctionCallsMap.put(registerNode, innerFunctionCalls); blockNodesMap.put(registerNode, nodes); }
public void addBlock(Set<CFANode> nodes, CFANode blockHead) { Set<ReferencedVariable> referencedVariables = collectReferencedVariables(nodes); Set<CFANode> callNodes = collectCallNodes(nodes); Set<CFANode> returnNodes = collectReturnNodes(nodes); Set<FunctionEntryNode> innerFunctionCalls = collectInnerFunctionCalls(nodes); if (callNodes.isEmpty()) { /* What shall we do with function, which is not called from anywhere? * There are problems with them at partitioning building stage */ return; } CFANode registerNode = null; for (CFANode node : callNodes) { registerNode = node; if (node instanceof FunctionEntryNode) { break; } } if (registerNode == null) { //It means, that there is no entry in this block. Don't add it return; } referencedVariablesMap.put(registerNode, referencedVariables); callNodesMap.put(registerNode, callNodes); returnNodesMap.put(registerNode, returnNodes); innerFunctionCallsMap.put(registerNode, innerFunctionCalls); blockNodesMap.put(registerNode, nodes); }
14,893
1
/* What shall we do with function, which is not called from anywhere? * There are problems with them at partitioning building stage */
public void addBlock(Set<CFANode> nodes, CFANode blockHead) { Set<ReferencedVariable> referencedVariables = collectReferencedVariables(nodes); Set<CFANode> callNodes = collectCallNodes(nodes); Set<CFANode> returnNodes = collectReturnNodes(nodes); Set<FunctionEntryNode> innerFunctionCalls = collectInnerFunctionCalls(nodes); if (callNodes.isEmpty()) { /* What shall we do with function, which is not called from anywhere? * There are problems with them at partitioning building stage */ return; } CFANode registerNode = null; for (CFANode node : callNodes) { registerNode = node; if (node instanceof FunctionEntryNode) { break; } } if (registerNode == null) { //It means, that there is no entry in this block. Don't add it return; } referencedVariablesMap.put(registerNode, referencedVariables); callNodesMap.put(registerNode, callNodes); returnNodesMap.put(registerNode, returnNodes); innerFunctionCallsMap.put(registerNode, innerFunctionCalls); blockNodesMap.put(registerNode, nodes); }
IMPLEMENTATION
true
Set<FunctionEntryNode> innerFunctionCalls = collectInnerFunctionCalls(nodes); if (callNodes.isEmpty()) { /* What shall we do with function, which is not called from anywhere? * There are problems with them at partitioning building stage */ return; }
public void addBlock(Set<CFANode> nodes, CFANode blockHead) { Set<ReferencedVariable> referencedVariables = collectReferencedVariables(nodes); Set<CFANode> callNodes = collectCallNodes(nodes); Set<CFANode> returnNodes = collectReturnNodes(nodes); Set<FunctionEntryNode> innerFunctionCalls = collectInnerFunctionCalls(nodes); if (callNodes.isEmpty()) { /* What shall we do with function, which is not called from anywhere? * There are problems with them at partitioning building stage */ return; } CFANode registerNode = null; for (CFANode node : callNodes) { registerNode = node; if (node instanceof FunctionEntryNode) { break; } } if (registerNode == null) {
public void addBlock(Set<CFANode> nodes, CFANode blockHead) { Set<ReferencedVariable> referencedVariables = collectReferencedVariables(nodes); Set<CFANode> callNodes = collectCallNodes(nodes); Set<CFANode> returnNodes = collectReturnNodes(nodes); Set<FunctionEntryNode> innerFunctionCalls = collectInnerFunctionCalls(nodes); if (callNodes.isEmpty()) { /* What shall we do with function, which is not called from anywhere? * There are problems with them at partitioning building stage */ return; } CFANode registerNode = null; for (CFANode node : callNodes) { registerNode = node; if (node instanceof FunctionEntryNode) { break; } } if (registerNode == null) { //It means, that there is no entry in this block. Don't add it return; } referencedVariablesMap.put(registerNode, referencedVariables); callNodesMap.put(registerNode, callNodes); returnNodesMap.put(registerNode, returnNodes); innerFunctionCallsMap.put(registerNode, innerFunctionCalls); blockNodesMap.put(registerNode, nodes); }
14,893
2
//It means, that there is no entry in this block. Don't add it
public void addBlock(Set<CFANode> nodes, CFANode blockHead) { Set<ReferencedVariable> referencedVariables = collectReferencedVariables(nodes); Set<CFANode> callNodes = collectCallNodes(nodes); Set<CFANode> returnNodes = collectReturnNodes(nodes); Set<FunctionEntryNode> innerFunctionCalls = collectInnerFunctionCalls(nodes); if (callNodes.isEmpty()) { /* What shall we do with function, which is not called from anywhere? * There are problems with them at partitioning building stage */ return; } CFANode registerNode = null; for (CFANode node : callNodes) { registerNode = node; if (node instanceof FunctionEntryNode) { break; } } if (registerNode == null) { //It means, that there is no entry in this block. Don't add it return; } referencedVariablesMap.put(registerNode, referencedVariables); callNodesMap.put(registerNode, callNodes); returnNodesMap.put(registerNode, returnNodes); innerFunctionCallsMap.put(registerNode, innerFunctionCalls); blockNodesMap.put(registerNode, nodes); }
NONSATD
true
} if (registerNode == null) { //It means, that there is no entry in this block. Don't add it return; }
return; } CFANode registerNode = null; for (CFANode node : callNodes) { registerNode = node; if (node instanceof FunctionEntryNode) { break; } } if (registerNode == null) { //It means, that there is no entry in this block. Don't add it return; } referencedVariablesMap.put(registerNode, referencedVariables); callNodesMap.put(registerNode, callNodes); returnNodesMap.put(registerNode, returnNodes); innerFunctionCallsMap.put(registerNode, innerFunctionCalls); blockNodesMap.put(registerNode, nodes); }
public void addBlock(Set<CFANode> nodes, CFANode blockHead) { Set<ReferencedVariable> referencedVariables = collectReferencedVariables(nodes); Set<CFANode> callNodes = collectCallNodes(nodes); Set<CFANode> returnNodes = collectReturnNodes(nodes); Set<FunctionEntryNode> innerFunctionCalls = collectInnerFunctionCalls(nodes); if (callNodes.isEmpty()) { /* What shall we do with function, which is not called from anywhere? * There are problems with them at partitioning building stage */ return; } CFANode registerNode = null; for (CFANode node : callNodes) { registerNode = node; if (node instanceof FunctionEntryNode) { break; } } if (registerNode == null) { //It means, that there is no entry in this block. Don't add it return; } referencedVariablesMap.put(registerNode, referencedVariables); callNodesMap.put(registerNode, callNodes); returnNodesMap.put(registerNode, returnNodes); innerFunctionCallsMap.put(registerNode, innerFunctionCalls); blockNodesMap.put(registerNode, nodes); }
14,914
0
// type is a normal class.
public static Class<?> getRawType(Type type) { if (type instanceof Class<?>) { // type is a normal class. return (Class<?>)type; } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)type; // I'm not exactly sure why getRawType() returns Type instead of Class. // Neal isn't either but suspects some pathological case related // to nested classes exists. Type rawType = parameterizedType.getRawType(); Asserts.isTrue(rawType instanceof Class); return (Class<?>)rawType; } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType)type).getGenericComponentType(); return Array.newInstance(getRawType(componentType), 0).getClass(); } else if (type instanceof TypeVariable) { // we could use the variable's bounds, but that won't work if there are multiple. // having a raw type that's more general than necessary is okay return Object.class; } else if (type instanceof WildcardType) { return getRawType(((WildcardType)type).getUpperBounds()[0]); } else { String className = type == null ? "null" : type.getClass().getName(); throw new IllegalArgumentException("Expected a Class, ParameterizedType, or " + "GenericArrayType, but <" + type + "> is of type " + className); } }
NONSATD
true
public static Class<?> getRawType(Type type) { if (type instanceof Class<?>) { // type is a normal class. return (Class<?>)type; }
public static Class<?> getRawType(Type type) { if (type instanceof Class<?>) { // type is a normal class. return (Class<?>)type; } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)type; // I'm not exactly sure why getRawType() returns Type instead of Class. // Neal isn't either but suspects some pathological case related // to nested classes exists. Type rawType = parameterizedType.getRawType(); Asserts.isTrue(rawType instanceof Class); return (Class<?>)rawType;
public static Class<?> getRawType(Type type) { if (type instanceof Class<?>) { // type is a normal class. return (Class<?>)type; } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)type; // I'm not exactly sure why getRawType() returns Type instead of Class. // Neal isn't either but suspects some pathological case related // to nested classes exists. Type rawType = parameterizedType.getRawType(); Asserts.isTrue(rawType instanceof Class); return (Class<?>)rawType; } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType)type).getGenericComponentType(); return Array.newInstance(getRawType(componentType), 0).getClass(); } else if (type instanceof TypeVariable) { // we could use the variable's bounds, but that won't work if there are multiple. // having a raw type that's more general than necessary is okay return Object.class; }
14,914
1
// I'm not exactly sure why getRawType() returns Type instead of Class. // Neal isn't either but suspects some pathological case related // to nested classes exists.
public static Class<?> getRawType(Type type) { if (type instanceof Class<?>) { // type is a normal class. return (Class<?>)type; } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)type; // I'm not exactly sure why getRawType() returns Type instead of Class. // Neal isn't either but suspects some pathological case related // to nested classes exists. Type rawType = parameterizedType.getRawType(); Asserts.isTrue(rawType instanceof Class); return (Class<?>)rawType; } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType)type).getGenericComponentType(); return Array.newInstance(getRawType(componentType), 0).getClass(); } else if (type instanceof TypeVariable) { // we could use the variable's bounds, but that won't work if there are multiple. // having a raw type that's more general than necessary is okay return Object.class; } else if (type instanceof WildcardType) { return getRawType(((WildcardType)type).getUpperBounds()[0]); } else { String className = type == null ? "null" : type.getClass().getName(); throw new IllegalArgumentException("Expected a Class, ParameterizedType, or " + "GenericArrayType, but <" + type + "> is of type " + className); } }
NONSATD
true
else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)type; // I'm not exactly sure why getRawType() returns Type instead of Class. // Neal isn't either but suspects some pathological case related // to nested classes exists. Type rawType = parameterizedType.getRawType(); Asserts.isTrue(rawType instanceof Class);
public static Class<?> getRawType(Type type) { if (type instanceof Class<?>) { // type is a normal class. return (Class<?>)type; } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)type; // I'm not exactly sure why getRawType() returns Type instead of Class. // Neal isn't either but suspects some pathological case related // to nested classes exists. Type rawType = parameterizedType.getRawType(); Asserts.isTrue(rawType instanceof Class); return (Class<?>)rawType; } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType)type).getGenericComponentType(); return Array.newInstance(getRawType(componentType), 0).getClass(); } else if (type instanceof TypeVariable) { // we could use the variable's bounds, but that won't work if there are multiple.
public static Class<?> getRawType(Type type) { if (type instanceof Class<?>) { // type is a normal class. return (Class<?>)type; } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)type; // I'm not exactly sure why getRawType() returns Type instead of Class. // Neal isn't either but suspects some pathological case related // to nested classes exists. Type rawType = parameterizedType.getRawType(); Asserts.isTrue(rawType instanceof Class); return (Class<?>)rawType; } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType)type).getGenericComponentType(); return Array.newInstance(getRawType(componentType), 0).getClass(); } else if (type instanceof TypeVariable) { // we could use the variable's bounds, but that won't work if there are multiple. // having a raw type that's more general than necessary is okay return Object.class; } else if (type instanceof WildcardType) { return getRawType(((WildcardType)type).getUpperBounds()[0]); } else { String className = type == null ? "null" : type.getClass().getName(); throw new IllegalArgumentException("Expected a Class, ParameterizedType, or " + "GenericArrayType, but <" + type + "> is of type " + className);
14,914
2
// we could use the variable's bounds, but that won't work if there are multiple. // having a raw type that's more general than necessary is okay
public static Class<?> getRawType(Type type) { if (type instanceof Class<?>) { // type is a normal class. return (Class<?>)type; } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)type; // I'm not exactly sure why getRawType() returns Type instead of Class. // Neal isn't either but suspects some pathological case related // to nested classes exists. Type rawType = parameterizedType.getRawType(); Asserts.isTrue(rawType instanceof Class); return (Class<?>)rawType; } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType)type).getGenericComponentType(); return Array.newInstance(getRawType(componentType), 0).getClass(); } else if (type instanceof TypeVariable) { // we could use the variable's bounds, but that won't work if there are multiple. // having a raw type that's more general than necessary is okay return Object.class; } else if (type instanceof WildcardType) { return getRawType(((WildcardType)type).getUpperBounds()[0]); } else { String className = type == null ? "null" : type.getClass().getName(); throw new IllegalArgumentException("Expected a Class, ParameterizedType, or " + "GenericArrayType, but <" + type + "> is of type " + className); } }
DESIGN
true
} else if (type instanceof TypeVariable) { // we could use the variable's bounds, but that won't work if there are multiple. // having a raw type that's more general than necessary is okay return Object.class; }
// to nested classes exists. Type rawType = parameterizedType.getRawType(); Asserts.isTrue(rawType instanceof Class); return (Class<?>)rawType; } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType)type).getGenericComponentType(); return Array.newInstance(getRawType(componentType), 0).getClass(); } else if (type instanceof TypeVariable) { // we could use the variable's bounds, but that won't work if there are multiple. // having a raw type that's more general than necessary is okay return Object.class; } else if (type instanceof WildcardType) { return getRawType(((WildcardType)type).getUpperBounds()[0]); } else { String className = type == null ? "null" : type.getClass().getName(); throw new IllegalArgumentException("Expected a Class, ParameterizedType, or " + "GenericArrayType, but <" + type + "> is of type " + className); }
public static Class<?> getRawType(Type type) { if (type instanceof Class<?>) { // type is a normal class. return (Class<?>)type; } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)type; // I'm not exactly sure why getRawType() returns Type instead of Class. // Neal isn't either but suspects some pathological case related // to nested classes exists. Type rawType = parameterizedType.getRawType(); Asserts.isTrue(rawType instanceof Class); return (Class<?>)rawType; } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType)type).getGenericComponentType(); return Array.newInstance(getRawType(componentType), 0).getClass(); } else if (type instanceof TypeVariable) { // we could use the variable's bounds, but that won't work if there are multiple. // having a raw type that's more general than necessary is okay return Object.class; } else if (type instanceof WildcardType) { return getRawType(((WildcardType)type).getUpperBounds()[0]); } else { String className = type == null ? "null" : type.getClass().getName(); throw new IllegalArgumentException("Expected a Class, ParameterizedType, or " + "GenericArrayType, but <" + type + "> is of type " + className); } }
23,121
0
// Not work, maybe only in Android JUnit test.
@Test public void isJson_shouldReturnTrue_whenStringIsJsonArray() throws JSONException { assertTrue(validateTor.isJSON("[]")); assertTrue(validateTor.isJSON("[{\"id\":1}]")); }
DEFECT
true
@Test public void isJson_shouldReturnTrue_whenStringIsJsonArray() throws JSONException { assertTrue(validateTor.isJSON("[]")); assertTrue(validateTor.isJSON("[{\"id\":1}]")); }
@Test public void isJson_shouldReturnTrue_whenStringIsJsonArray() throws JSONException { assertTrue(validateTor.isJSON("[]")); assertTrue(validateTor.isJSON("[{\"id\":1}]")); }
@Test public void isJson_shouldReturnTrue_whenStringIsJsonArray() throws JSONException { assertTrue(validateTor.isJSON("[]")); assertTrue(validateTor.isJSON("[{\"id\":1}]")); }
23,126
0
/** * Replaces the tokens within the format String with the content of the groups found within the userAgentString. * <p> * Tokens within the format string are formatted as #{$i} where i is the index of the group in the pattern. * <p> * TODO: I would expect that there is an easier way to do this. * * @param pattern The regexp pattern to search for groups within the userAgentString * @param userAgentString * @param format The string to replace the tokens within * @return The format string with the tokens replaced with the groups found in the userAgentString */
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
DESIGN
true
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
23,126
1
// System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format);
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
NONSATD
true
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s);
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format;
23,126
2
// Move the group content into an array
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
NONSATD
true
// System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount());
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
23,126
3
// System.out.println("Group Count: "+m.groupCount());
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
NONSATD
true
// Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++)
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) {
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
23,126
4
// System.out.println("--"+s);
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
NONSATD
true
{ String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); }
// System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format);
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
23,126
5
// Replace the tokens in the pattern
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
NONSATD
true
groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) {
// Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
23,126
6
// System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]");
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
NONSATD
true
{ String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); }
for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
23,126
7
// System.out.println("Response: "+format);
public String replaceTokens(Pattern pattern, String userAgentString, String format) { // System.out.println("UserAgent: " + userAgentString); // System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
NONSATD
true
format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
// System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
// System.out.println("Regexp: " + pattern.toString()); // System.out.println("Replacement: " + format); Matcher m = pattern.matcher(userAgentString); // Move the group content into an array List<String> groupContent = new ArrayList<String>(); // System.out.println("Group Count: "+m.groupCount()); m.find(); for(int i=0; i<=m.groupCount(); i++) { String s = m.group(i); // System.out.println("--"+s); groupContent.add(s); } // Replace the tokens in the pattern for(int i=0; i<groupContent.size(); i++) { String token = "#\\{\\$"+i+"\\}"; // System.out.println("Replacing ["+token+"] with ["+groupContent.get(i)+"]"); format = format.replaceAll(token, groupContent.get(i)); } // System.out.println("Response: "+format); return format; }
31,319
0
// TODO convert into model that contains electricity info also
public List<HeatConsumption> findHeatConsumptions() throws IOException { // TODO convert into model that contains electricity info also return heatRepository.findAll(); }
IMPLEMENTATION
true
public List<HeatConsumption> findHeatConsumptions() throws IOException { // TODO convert into model that contains electricity info also return heatRepository.findAll(); }
public List<HeatConsumption> findHeatConsumptions() throws IOException { // TODO convert into model that contains electricity info also return heatRepository.findAll(); }
public List<HeatConsumption> findHeatConsumptions() throws IOException { // TODO convert into model that contains electricity info also return heatRepository.findAll(); }
31,329
0
/** * Create a document from the given text. * TODO: explain the parsing process * * @param text * @param window * @return */
public static Document parse(String text, int windowSize, JSONArray spacyEntities, JSONArray dbpediaEntities) { Document result = new Document(); result._originaltext = text; result._sentences = new java.util.ArrayList<Sentence>(); List<String> splitSentences = StanfordNLP.splitSentences(text); int lastFoundPosition = -1; int lastSentenceLength = 1; int sentenceCount = 0; int runningSentinmentScore = 0; // perform the window parsing - used to do coreref, plus get initial named entities, sentiment, and tokens for (int sentenceIndex = 0; sentenceIndex < splitSentences.size(); sentenceIndex++) { SplitResult sr = getTextWindow(splitSentences, sentenceIndex,windowSize); Annotation sentenceDoc = StanfordNLP.annotateText(sr.text); List<CoreMap> sentences = sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class); CoreMap sentence = sentences.get(sr.sentencePositionToUse); sentenceCount++; String sentenceText = sentence.get(CoreAnnotations.TextAnnotation.class); int documentPosition = text.indexOf(sentenceText,lastFoundPosition); if (documentPosition == -1) { documentPosition = lastFoundPosition + lastSentenceLength; } java.util.List<Token> sentenceTokens = Token.extractTokens(sentence, sentenceCount); Sentence s = new Sentence(sentenceText, documentPosition, sentenceCount, sentenceTokens); Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class); int sentiment = RNNCoreAnnotations.getPredictedClass(tree); s.setSentiment(sentiment); runningSentinmentScore += sentiment; List<String> resolvedSentences = Coreference.resolveCoreferences(sentenceDoc); s.setCorefText(resolvedSentences.get(sr.sentencePositionToUse)); result._sentences.add(s); lastFoundPosition = documentPosition; lastSentenceLength = sentenceText.length(); } result._sentimentScore = ((double) runningSentinmentScore) / sentenceCount; // reparse to get openIE / relations items int baseSentenceIndex = -1; for (Sentence s: result._sentences) { Annotation sentenceDoc = StanfordNLP.annotateText(s.getCorefText()); baseSentenceIndex++; java.util.List<Token> sentenceTokens = Token.extractTokens(sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class).get(0), baseSentenceIndex); java.util.List<TripleRelation> triples = TripleRelation.extractTriples(sentenceDoc, baseSentenceIndex); triples = TripleRelation.valiadateTriples(triples, sentenceTokens); List<AnnotatedProposition> minieTriplesAP = StanfordNLP.extractMinIETriples(s.getCorefText()); java.util.List<TripleRelation> minetriples = TripleRelation.extractTriples(minieTriplesAP, baseSentenceIndex); minetriples = TripleRelation.valiadateTriples(minetriples, sentenceTokens); java.util.List<TripleRelation> combinedTriples = TripleRelation.combine(triples, minetriples); combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MAXIMIZE_SUBJ_OBJ_MINIMIZE_RELATION); //combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MINIMIZE_TERMS); TripleRelation.augmentSubjectObjectWithStanfordNER(combinedTriples,s.getNamedEntities()); TripleRelation.augmentSubjectObjectWithSpacyNER(combinedTriples, spacyEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); TripleRelation.augmentSubjectObjectWithDBPedia(combinedTriples, dbpediaEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); s.setTripleRelations(combinedTriples); } return result; }
DOCUMENTATION
true
public static Document parse(String text, int windowSize, JSONArray spacyEntities, JSONArray dbpediaEntities) { Document result = new Document(); result._originaltext = text; result._sentences = new java.util.ArrayList<Sentence>(); List<String> splitSentences = StanfordNLP.splitSentences(text); int lastFoundPosition = -1; int lastSentenceLength = 1; int sentenceCount = 0; int runningSentinmentScore = 0; // perform the window parsing - used to do coreref, plus get initial named entities, sentiment, and tokens for (int sentenceIndex = 0; sentenceIndex < splitSentences.size(); sentenceIndex++) { SplitResult sr = getTextWindow(splitSentences, sentenceIndex,windowSize); Annotation sentenceDoc = StanfordNLP.annotateText(sr.text); List<CoreMap> sentences = sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class); CoreMap sentence = sentences.get(sr.sentencePositionToUse); sentenceCount++; String sentenceText = sentence.get(CoreAnnotations.TextAnnotation.class); int documentPosition = text.indexOf(sentenceText,lastFoundPosition); if (documentPosition == -1) { documentPosition = lastFoundPosition + lastSentenceLength; } java.util.List<Token> sentenceTokens = Token.extractTokens(sentence, sentenceCount); Sentence s = new Sentence(sentenceText, documentPosition, sentenceCount, sentenceTokens); Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class); int sentiment = RNNCoreAnnotations.getPredictedClass(tree); s.setSentiment(sentiment); runningSentinmentScore += sentiment; List<String> resolvedSentences = Coreference.resolveCoreferences(sentenceDoc); s.setCorefText(resolvedSentences.get(sr.sentencePositionToUse)); result._sentences.add(s); lastFoundPosition = documentPosition; lastSentenceLength = sentenceText.length(); } result._sentimentScore = ((double) runningSentinmentScore) / sentenceCount; // reparse to get openIE / relations items int baseSentenceIndex = -1; for (Sentence s: result._sentences) { Annotation sentenceDoc = StanfordNLP.annotateText(s.getCorefText()); baseSentenceIndex++; java.util.List<Token> sentenceTokens = Token.extractTokens(sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class).get(0), baseSentenceIndex); java.util.List<TripleRelation> triples = TripleRelation.extractTriples(sentenceDoc, baseSentenceIndex); triples = TripleRelation.valiadateTriples(triples, sentenceTokens); List<AnnotatedProposition> minieTriplesAP = StanfordNLP.extractMinIETriples(s.getCorefText()); java.util.List<TripleRelation> minetriples = TripleRelation.extractTriples(minieTriplesAP, baseSentenceIndex); minetriples = TripleRelation.valiadateTriples(minetriples, sentenceTokens); java.util.List<TripleRelation> combinedTriples = TripleRelation.combine(triples, minetriples); combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MAXIMIZE_SUBJ_OBJ_MINIMIZE_RELATION); //combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MINIMIZE_TERMS); TripleRelation.augmentSubjectObjectWithStanfordNER(combinedTriples,s.getNamedEntities()); TripleRelation.augmentSubjectObjectWithSpacyNER(combinedTriples, spacyEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); TripleRelation.augmentSubjectObjectWithDBPedia(combinedTriples, dbpediaEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); s.setTripleRelations(combinedTriples); } return result; }
public static Document parse(String text, int windowSize, JSONArray spacyEntities, JSONArray dbpediaEntities) { Document result = new Document(); result._originaltext = text; result._sentences = new java.util.ArrayList<Sentence>(); List<String> splitSentences = StanfordNLP.splitSentences(text); int lastFoundPosition = -1; int lastSentenceLength = 1; int sentenceCount = 0; int runningSentinmentScore = 0; // perform the window parsing - used to do coreref, plus get initial named entities, sentiment, and tokens for (int sentenceIndex = 0; sentenceIndex < splitSentences.size(); sentenceIndex++) { SplitResult sr = getTextWindow(splitSentences, sentenceIndex,windowSize); Annotation sentenceDoc = StanfordNLP.annotateText(sr.text); List<CoreMap> sentences = sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class); CoreMap sentence = sentences.get(sr.sentencePositionToUse); sentenceCount++; String sentenceText = sentence.get(CoreAnnotations.TextAnnotation.class); int documentPosition = text.indexOf(sentenceText,lastFoundPosition); if (documentPosition == -1) { documentPosition = lastFoundPosition + lastSentenceLength; } java.util.List<Token> sentenceTokens = Token.extractTokens(sentence, sentenceCount); Sentence s = new Sentence(sentenceText, documentPosition, sentenceCount, sentenceTokens); Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class); int sentiment = RNNCoreAnnotations.getPredictedClass(tree); s.setSentiment(sentiment); runningSentinmentScore += sentiment; List<String> resolvedSentences = Coreference.resolveCoreferences(sentenceDoc); s.setCorefText(resolvedSentences.get(sr.sentencePositionToUse)); result._sentences.add(s); lastFoundPosition = documentPosition; lastSentenceLength = sentenceText.length(); } result._sentimentScore = ((double) runningSentinmentScore) / sentenceCount; // reparse to get openIE / relations items int baseSentenceIndex = -1; for (Sentence s: result._sentences) { Annotation sentenceDoc = StanfordNLP.annotateText(s.getCorefText()); baseSentenceIndex++; java.util.List<Token> sentenceTokens = Token.extractTokens(sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class).get(0), baseSentenceIndex); java.util.List<TripleRelation> triples = TripleRelation.extractTriples(sentenceDoc, baseSentenceIndex); triples = TripleRelation.valiadateTriples(triples, sentenceTokens); List<AnnotatedProposition> minieTriplesAP = StanfordNLP.extractMinIETriples(s.getCorefText()); java.util.List<TripleRelation> minetriples = TripleRelation.extractTriples(minieTriplesAP, baseSentenceIndex); minetriples = TripleRelation.valiadateTriples(minetriples, sentenceTokens); java.util.List<TripleRelation> combinedTriples = TripleRelation.combine(triples, minetriples); combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MAXIMIZE_SUBJ_OBJ_MINIMIZE_RELATION); //combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MINIMIZE_TERMS); TripleRelation.augmentSubjectObjectWithStanfordNER(combinedTriples,s.getNamedEntities()); TripleRelation.augmentSubjectObjectWithSpacyNER(combinedTriples, spacyEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); TripleRelation.augmentSubjectObjectWithDBPedia(combinedTriples, dbpediaEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); s.setTripleRelations(combinedTriples); } return result; }
public static Document parse(String text, int windowSize, JSONArray spacyEntities, JSONArray dbpediaEntities) { Document result = new Document(); result._originaltext = text; result._sentences = new java.util.ArrayList<Sentence>(); List<String> splitSentences = StanfordNLP.splitSentences(text); int lastFoundPosition = -1; int lastSentenceLength = 1; int sentenceCount = 0; int runningSentinmentScore = 0; // perform the window parsing - used to do coreref, plus get initial named entities, sentiment, and tokens for (int sentenceIndex = 0; sentenceIndex < splitSentences.size(); sentenceIndex++) { SplitResult sr = getTextWindow(splitSentences, sentenceIndex,windowSize); Annotation sentenceDoc = StanfordNLP.annotateText(sr.text); List<CoreMap> sentences = sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class); CoreMap sentence = sentences.get(sr.sentencePositionToUse); sentenceCount++; String sentenceText = sentence.get(CoreAnnotations.TextAnnotation.class); int documentPosition = text.indexOf(sentenceText,lastFoundPosition); if (documentPosition == -1) { documentPosition = lastFoundPosition + lastSentenceLength; } java.util.List<Token> sentenceTokens = Token.extractTokens(sentence, sentenceCount); Sentence s = new Sentence(sentenceText, documentPosition, sentenceCount, sentenceTokens); Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class); int sentiment = RNNCoreAnnotations.getPredictedClass(tree); s.setSentiment(sentiment); runningSentinmentScore += sentiment; List<String> resolvedSentences = Coreference.resolveCoreferences(sentenceDoc); s.setCorefText(resolvedSentences.get(sr.sentencePositionToUse)); result._sentences.add(s); lastFoundPosition = documentPosition; lastSentenceLength = sentenceText.length(); } result._sentimentScore = ((double) runningSentinmentScore) / sentenceCount; // reparse to get openIE / relations items int baseSentenceIndex = -1; for (Sentence s: result._sentences) { Annotation sentenceDoc = StanfordNLP.annotateText(s.getCorefText()); baseSentenceIndex++; java.util.List<Token> sentenceTokens = Token.extractTokens(sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class).get(0), baseSentenceIndex); java.util.List<TripleRelation> triples = TripleRelation.extractTriples(sentenceDoc, baseSentenceIndex); triples = TripleRelation.valiadateTriples(triples, sentenceTokens); List<AnnotatedProposition> minieTriplesAP = StanfordNLP.extractMinIETriples(s.getCorefText()); java.util.List<TripleRelation> minetriples = TripleRelation.extractTriples(minieTriplesAP, baseSentenceIndex); minetriples = TripleRelation.valiadateTriples(minetriples, sentenceTokens); java.util.List<TripleRelation> combinedTriples = TripleRelation.combine(triples, minetriples); combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MAXIMIZE_SUBJ_OBJ_MINIMIZE_RELATION); //combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MINIMIZE_TERMS); TripleRelation.augmentSubjectObjectWithStanfordNER(combinedTriples,s.getNamedEntities()); TripleRelation.augmentSubjectObjectWithSpacyNER(combinedTriples, spacyEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); TripleRelation.augmentSubjectObjectWithDBPedia(combinedTriples, dbpediaEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); s.setTripleRelations(combinedTriples); } return result; }
31,329
1
// perform the window parsing - used to do coreref, plus get initial named entities, sentiment, and tokens
public static Document parse(String text, int windowSize, JSONArray spacyEntities, JSONArray dbpediaEntities) { Document result = new Document(); result._originaltext = text; result._sentences = new java.util.ArrayList<Sentence>(); List<String> splitSentences = StanfordNLP.splitSentences(text); int lastFoundPosition = -1; int lastSentenceLength = 1; int sentenceCount = 0; int runningSentinmentScore = 0; // perform the window parsing - used to do coreref, plus get initial named entities, sentiment, and tokens for (int sentenceIndex = 0; sentenceIndex < splitSentences.size(); sentenceIndex++) { SplitResult sr = getTextWindow(splitSentences, sentenceIndex,windowSize); Annotation sentenceDoc = StanfordNLP.annotateText(sr.text); List<CoreMap> sentences = sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class); CoreMap sentence = sentences.get(sr.sentencePositionToUse); sentenceCount++; String sentenceText = sentence.get(CoreAnnotations.TextAnnotation.class); int documentPosition = text.indexOf(sentenceText,lastFoundPosition); if (documentPosition == -1) { documentPosition = lastFoundPosition + lastSentenceLength; } java.util.List<Token> sentenceTokens = Token.extractTokens(sentence, sentenceCount); Sentence s = new Sentence(sentenceText, documentPosition, sentenceCount, sentenceTokens); Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class); int sentiment = RNNCoreAnnotations.getPredictedClass(tree); s.setSentiment(sentiment); runningSentinmentScore += sentiment; List<String> resolvedSentences = Coreference.resolveCoreferences(sentenceDoc); s.setCorefText(resolvedSentences.get(sr.sentencePositionToUse)); result._sentences.add(s); lastFoundPosition = documentPosition; lastSentenceLength = sentenceText.length(); } result._sentimentScore = ((double) runningSentinmentScore) / sentenceCount; // reparse to get openIE / relations items int baseSentenceIndex = -1; for (Sentence s: result._sentences) { Annotation sentenceDoc = StanfordNLP.annotateText(s.getCorefText()); baseSentenceIndex++; java.util.List<Token> sentenceTokens = Token.extractTokens(sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class).get(0), baseSentenceIndex); java.util.List<TripleRelation> triples = TripleRelation.extractTriples(sentenceDoc, baseSentenceIndex); triples = TripleRelation.valiadateTriples(triples, sentenceTokens); List<AnnotatedProposition> minieTriplesAP = StanfordNLP.extractMinIETriples(s.getCorefText()); java.util.List<TripleRelation> minetriples = TripleRelation.extractTriples(minieTriplesAP, baseSentenceIndex); minetriples = TripleRelation.valiadateTriples(minetriples, sentenceTokens); java.util.List<TripleRelation> combinedTriples = TripleRelation.combine(triples, minetriples); combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MAXIMIZE_SUBJ_OBJ_MINIMIZE_RELATION); //combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MINIMIZE_TERMS); TripleRelation.augmentSubjectObjectWithStanfordNER(combinedTriples,s.getNamedEntities()); TripleRelation.augmentSubjectObjectWithSpacyNER(combinedTriples, spacyEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); TripleRelation.augmentSubjectObjectWithDBPedia(combinedTriples, dbpediaEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); s.setTripleRelations(combinedTriples); } return result; }
NONSATD
true
int sentenceCount = 0; int runningSentinmentScore = 0; // perform the window parsing - used to do coreref, plus get initial named entities, sentiment, and tokens for (int sentenceIndex = 0; sentenceIndex < splitSentences.size(); sentenceIndex++) { SplitResult sr = getTextWindow(splitSentences, sentenceIndex,windowSize);
public static Document parse(String text, int windowSize, JSONArray spacyEntities, JSONArray dbpediaEntities) { Document result = new Document(); result._originaltext = text; result._sentences = new java.util.ArrayList<Sentence>(); List<String> splitSentences = StanfordNLP.splitSentences(text); int lastFoundPosition = -1; int lastSentenceLength = 1; int sentenceCount = 0; int runningSentinmentScore = 0; // perform the window parsing - used to do coreref, plus get initial named entities, sentiment, and tokens for (int sentenceIndex = 0; sentenceIndex < splitSentences.size(); sentenceIndex++) { SplitResult sr = getTextWindow(splitSentences, sentenceIndex,windowSize); Annotation sentenceDoc = StanfordNLP.annotateText(sr.text); List<CoreMap> sentences = sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class); CoreMap sentence = sentences.get(sr.sentencePositionToUse); sentenceCount++; String sentenceText = sentence.get(CoreAnnotations.TextAnnotation.class); int documentPosition = text.indexOf(sentenceText,lastFoundPosition); if (documentPosition == -1) { documentPosition = lastFoundPosition + lastSentenceLength;
public static Document parse(String text, int windowSize, JSONArray spacyEntities, JSONArray dbpediaEntities) { Document result = new Document(); result._originaltext = text; result._sentences = new java.util.ArrayList<Sentence>(); List<String> splitSentences = StanfordNLP.splitSentences(text); int lastFoundPosition = -1; int lastSentenceLength = 1; int sentenceCount = 0; int runningSentinmentScore = 0; // perform the window parsing - used to do coreref, plus get initial named entities, sentiment, and tokens for (int sentenceIndex = 0; sentenceIndex < splitSentences.size(); sentenceIndex++) { SplitResult sr = getTextWindow(splitSentences, sentenceIndex,windowSize); Annotation sentenceDoc = StanfordNLP.annotateText(sr.text); List<CoreMap> sentences = sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class); CoreMap sentence = sentences.get(sr.sentencePositionToUse); sentenceCount++; String sentenceText = sentence.get(CoreAnnotations.TextAnnotation.class); int documentPosition = text.indexOf(sentenceText,lastFoundPosition); if (documentPosition == -1) { documentPosition = lastFoundPosition + lastSentenceLength; } java.util.List<Token> sentenceTokens = Token.extractTokens(sentence, sentenceCount); Sentence s = new Sentence(sentenceText, documentPosition, sentenceCount, sentenceTokens); Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class); int sentiment = RNNCoreAnnotations.getPredictedClass(tree); s.setSentiment(sentiment); runningSentinmentScore += sentiment; List<String> resolvedSentences = Coreference.resolveCoreferences(sentenceDoc); s.setCorefText(resolvedSentences.get(sr.sentencePositionToUse)); result._sentences.add(s);
31,329
2
// reparse to get openIE / relations items
public static Document parse(String text, int windowSize, JSONArray spacyEntities, JSONArray dbpediaEntities) { Document result = new Document(); result._originaltext = text; result._sentences = new java.util.ArrayList<Sentence>(); List<String> splitSentences = StanfordNLP.splitSentences(text); int lastFoundPosition = -1; int lastSentenceLength = 1; int sentenceCount = 0; int runningSentinmentScore = 0; // perform the window parsing - used to do coreref, plus get initial named entities, sentiment, and tokens for (int sentenceIndex = 0; sentenceIndex < splitSentences.size(); sentenceIndex++) { SplitResult sr = getTextWindow(splitSentences, sentenceIndex,windowSize); Annotation sentenceDoc = StanfordNLP.annotateText(sr.text); List<CoreMap> sentences = sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class); CoreMap sentence = sentences.get(sr.sentencePositionToUse); sentenceCount++; String sentenceText = sentence.get(CoreAnnotations.TextAnnotation.class); int documentPosition = text.indexOf(sentenceText,lastFoundPosition); if (documentPosition == -1) { documentPosition = lastFoundPosition + lastSentenceLength; } java.util.List<Token> sentenceTokens = Token.extractTokens(sentence, sentenceCount); Sentence s = new Sentence(sentenceText, documentPosition, sentenceCount, sentenceTokens); Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class); int sentiment = RNNCoreAnnotations.getPredictedClass(tree); s.setSentiment(sentiment); runningSentinmentScore += sentiment; List<String> resolvedSentences = Coreference.resolveCoreferences(sentenceDoc); s.setCorefText(resolvedSentences.get(sr.sentencePositionToUse)); result._sentences.add(s); lastFoundPosition = documentPosition; lastSentenceLength = sentenceText.length(); } result._sentimentScore = ((double) runningSentinmentScore) / sentenceCount; // reparse to get openIE / relations items int baseSentenceIndex = -1; for (Sentence s: result._sentences) { Annotation sentenceDoc = StanfordNLP.annotateText(s.getCorefText()); baseSentenceIndex++; java.util.List<Token> sentenceTokens = Token.extractTokens(sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class).get(0), baseSentenceIndex); java.util.List<TripleRelation> triples = TripleRelation.extractTriples(sentenceDoc, baseSentenceIndex); triples = TripleRelation.valiadateTriples(triples, sentenceTokens); List<AnnotatedProposition> minieTriplesAP = StanfordNLP.extractMinIETriples(s.getCorefText()); java.util.List<TripleRelation> minetriples = TripleRelation.extractTriples(minieTriplesAP, baseSentenceIndex); minetriples = TripleRelation.valiadateTriples(minetriples, sentenceTokens); java.util.List<TripleRelation> combinedTriples = TripleRelation.combine(triples, minetriples); combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MAXIMIZE_SUBJ_OBJ_MINIMIZE_RELATION); //combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MINIMIZE_TERMS); TripleRelation.augmentSubjectObjectWithStanfordNER(combinedTriples,s.getNamedEntities()); TripleRelation.augmentSubjectObjectWithSpacyNER(combinedTriples, spacyEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); TripleRelation.augmentSubjectObjectWithDBPedia(combinedTriples, dbpediaEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); s.setTripleRelations(combinedTriples); } return result; }
NONSATD
true
} result._sentimentScore = ((double) runningSentinmentScore) / sentenceCount; // reparse to get openIE / relations items int baseSentenceIndex = -1; for (Sentence s: result._sentences) {
int sentiment = RNNCoreAnnotations.getPredictedClass(tree); s.setSentiment(sentiment); runningSentinmentScore += sentiment; List<String> resolvedSentences = Coreference.resolveCoreferences(sentenceDoc); s.setCorefText(resolvedSentences.get(sr.sentencePositionToUse)); result._sentences.add(s); lastFoundPosition = documentPosition; lastSentenceLength = sentenceText.length(); } result._sentimentScore = ((double) runningSentinmentScore) / sentenceCount; // reparse to get openIE / relations items int baseSentenceIndex = -1; for (Sentence s: result._sentences) { Annotation sentenceDoc = StanfordNLP.annotateText(s.getCorefText()); baseSentenceIndex++; java.util.List<Token> sentenceTokens = Token.extractTokens(sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class).get(0), baseSentenceIndex); java.util.List<TripleRelation> triples = TripleRelation.extractTriples(sentenceDoc, baseSentenceIndex); triples = TripleRelation.valiadateTriples(triples, sentenceTokens); List<AnnotatedProposition> minieTriplesAP = StanfordNLP.extractMinIETriples(s.getCorefText()); java.util.List<TripleRelation> minetriples = TripleRelation.extractTriples(minieTriplesAP, baseSentenceIndex); minetriples = TripleRelation.valiadateTriples(minetriples, sentenceTokens);
CoreMap sentence = sentences.get(sr.sentencePositionToUse); sentenceCount++; String sentenceText = sentence.get(CoreAnnotations.TextAnnotation.class); int documentPosition = text.indexOf(sentenceText,lastFoundPosition); if (documentPosition == -1) { documentPosition = lastFoundPosition + lastSentenceLength; } java.util.List<Token> sentenceTokens = Token.extractTokens(sentence, sentenceCount); Sentence s = new Sentence(sentenceText, documentPosition, sentenceCount, sentenceTokens); Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class); int sentiment = RNNCoreAnnotations.getPredictedClass(tree); s.setSentiment(sentiment); runningSentinmentScore += sentiment; List<String> resolvedSentences = Coreference.resolveCoreferences(sentenceDoc); s.setCorefText(resolvedSentences.get(sr.sentencePositionToUse)); result._sentences.add(s); lastFoundPosition = documentPosition; lastSentenceLength = sentenceText.length(); } result._sentimentScore = ((double) runningSentinmentScore) / sentenceCount; // reparse to get openIE / relations items int baseSentenceIndex = -1; for (Sentence s: result._sentences) { Annotation sentenceDoc = StanfordNLP.annotateText(s.getCorefText()); baseSentenceIndex++; java.util.List<Token> sentenceTokens = Token.extractTokens(sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class).get(0), baseSentenceIndex); java.util.List<TripleRelation> triples = TripleRelation.extractTriples(sentenceDoc, baseSentenceIndex); triples = TripleRelation.valiadateTriples(triples, sentenceTokens); List<AnnotatedProposition> minieTriplesAP = StanfordNLP.extractMinIETriples(s.getCorefText()); java.util.List<TripleRelation> minetriples = TripleRelation.extractTriples(minieTriplesAP, baseSentenceIndex); minetriples = TripleRelation.valiadateTriples(minetriples, sentenceTokens); java.util.List<TripleRelation> combinedTriples = TripleRelation.combine(triples, minetriples); combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MAXIMIZE_SUBJ_OBJ_MINIMIZE_RELATION); //combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MINIMIZE_TERMS); TripleRelation.augmentSubjectObjectWithStanfordNER(combinedTriples,s.getNamedEntities()); TripleRelation.augmentSubjectObjectWithSpacyNER(combinedTriples, spacyEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); TripleRelation.augmentSubjectObjectWithDBPedia(combinedTriples, dbpediaEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); s.setTripleRelations(combinedTriples); } return result; }
31,329
3
//combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MINIMIZE_TERMS);
public static Document parse(String text, int windowSize, JSONArray spacyEntities, JSONArray dbpediaEntities) { Document result = new Document(); result._originaltext = text; result._sentences = new java.util.ArrayList<Sentence>(); List<String> splitSentences = StanfordNLP.splitSentences(text); int lastFoundPosition = -1; int lastSentenceLength = 1; int sentenceCount = 0; int runningSentinmentScore = 0; // perform the window parsing - used to do coreref, plus get initial named entities, sentiment, and tokens for (int sentenceIndex = 0; sentenceIndex < splitSentences.size(); sentenceIndex++) { SplitResult sr = getTextWindow(splitSentences, sentenceIndex,windowSize); Annotation sentenceDoc = StanfordNLP.annotateText(sr.text); List<CoreMap> sentences = sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class); CoreMap sentence = sentences.get(sr.sentencePositionToUse); sentenceCount++; String sentenceText = sentence.get(CoreAnnotations.TextAnnotation.class); int documentPosition = text.indexOf(sentenceText,lastFoundPosition); if (documentPosition == -1) { documentPosition = lastFoundPosition + lastSentenceLength; } java.util.List<Token> sentenceTokens = Token.extractTokens(sentence, sentenceCount); Sentence s = new Sentence(sentenceText, documentPosition, sentenceCount, sentenceTokens); Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class); int sentiment = RNNCoreAnnotations.getPredictedClass(tree); s.setSentiment(sentiment); runningSentinmentScore += sentiment; List<String> resolvedSentences = Coreference.resolveCoreferences(sentenceDoc); s.setCorefText(resolvedSentences.get(sr.sentencePositionToUse)); result._sentences.add(s); lastFoundPosition = documentPosition; lastSentenceLength = sentenceText.length(); } result._sentimentScore = ((double) runningSentinmentScore) / sentenceCount; // reparse to get openIE / relations items int baseSentenceIndex = -1; for (Sentence s: result._sentences) { Annotation sentenceDoc = StanfordNLP.annotateText(s.getCorefText()); baseSentenceIndex++; java.util.List<Token> sentenceTokens = Token.extractTokens(sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class).get(0), baseSentenceIndex); java.util.List<TripleRelation> triples = TripleRelation.extractTriples(sentenceDoc, baseSentenceIndex); triples = TripleRelation.valiadateTriples(triples, sentenceTokens); List<AnnotatedProposition> minieTriplesAP = StanfordNLP.extractMinIETriples(s.getCorefText()); java.util.List<TripleRelation> minetriples = TripleRelation.extractTriples(minieTriplesAP, baseSentenceIndex); minetriples = TripleRelation.valiadateTriples(minetriples, sentenceTokens); java.util.List<TripleRelation> combinedTriples = TripleRelation.combine(triples, minetriples); combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MAXIMIZE_SUBJ_OBJ_MINIMIZE_RELATION); //combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MINIMIZE_TERMS); TripleRelation.augmentSubjectObjectWithStanfordNER(combinedTriples,s.getNamedEntities()); TripleRelation.augmentSubjectObjectWithSpacyNER(combinedTriples, spacyEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); TripleRelation.augmentSubjectObjectWithDBPedia(combinedTriples, dbpediaEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); s.setTripleRelations(combinedTriples); } return result; }
NONSATD
true
java.util.List<TripleRelation> combinedTriples = TripleRelation.combine(triples, minetriples); combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MAXIMIZE_SUBJ_OBJ_MINIMIZE_RELATION); //combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MINIMIZE_TERMS); TripleRelation.augmentSubjectObjectWithStanfordNER(combinedTriples,s.getNamedEntities()); TripleRelation.augmentSubjectObjectWithSpacyNER(combinedTriples, spacyEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length());
Annotation sentenceDoc = StanfordNLP.annotateText(s.getCorefText()); baseSentenceIndex++; java.util.List<Token> sentenceTokens = Token.extractTokens(sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class).get(0), baseSentenceIndex); java.util.List<TripleRelation> triples = TripleRelation.extractTriples(sentenceDoc, baseSentenceIndex); triples = TripleRelation.valiadateTriples(triples, sentenceTokens); List<AnnotatedProposition> minieTriplesAP = StanfordNLP.extractMinIETriples(s.getCorefText()); java.util.List<TripleRelation> minetriples = TripleRelation.extractTriples(minieTriplesAP, baseSentenceIndex); minetriples = TripleRelation.valiadateTriples(minetriples, sentenceTokens); java.util.List<TripleRelation> combinedTriples = TripleRelation.combine(triples, minetriples); combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MAXIMIZE_SUBJ_OBJ_MINIMIZE_RELATION); //combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MINIMIZE_TERMS); TripleRelation.augmentSubjectObjectWithStanfordNER(combinedTriples,s.getNamedEntities()); TripleRelation.augmentSubjectObjectWithSpacyNER(combinedTriples, spacyEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); TripleRelation.augmentSubjectObjectWithDBPedia(combinedTriples, dbpediaEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); s.setTripleRelations(combinedTriples); } return result; }
List<String> resolvedSentences = Coreference.resolveCoreferences(sentenceDoc); s.setCorefText(resolvedSentences.get(sr.sentencePositionToUse)); result._sentences.add(s); lastFoundPosition = documentPosition; lastSentenceLength = sentenceText.length(); } result._sentimentScore = ((double) runningSentinmentScore) / sentenceCount; // reparse to get openIE / relations items int baseSentenceIndex = -1; for (Sentence s: result._sentences) { Annotation sentenceDoc = StanfordNLP.annotateText(s.getCorefText()); baseSentenceIndex++; java.util.List<Token> sentenceTokens = Token.extractTokens(sentenceDoc.get(CoreAnnotations.SentencesAnnotation.class).get(0), baseSentenceIndex); java.util.List<TripleRelation> triples = TripleRelation.extractTriples(sentenceDoc, baseSentenceIndex); triples = TripleRelation.valiadateTriples(triples, sentenceTokens); List<AnnotatedProposition> minieTriplesAP = StanfordNLP.extractMinIETriples(s.getCorefText()); java.util.List<TripleRelation> minetriples = TripleRelation.extractTriples(minieTriplesAP, baseSentenceIndex); minetriples = TripleRelation.valiadateTriples(minetriples, sentenceTokens); java.util.List<TripleRelation> combinedTriples = TripleRelation.combine(triples, minetriples); combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MAXIMIZE_SUBJ_OBJ_MINIMIZE_RELATION); //combinedTriples = TripleRelation.reduceTriples(combinedTriples, FilterStyle.FILTER_TO_MINIMIZE_TERMS); TripleRelation.augmentSubjectObjectWithStanfordNER(combinedTriples,s.getNamedEntities()); TripleRelation.augmentSubjectObjectWithSpacyNER(combinedTriples, spacyEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); TripleRelation.augmentSubjectObjectWithDBPedia(combinedTriples, dbpediaEntities, s.getStartPosition(), s.getStartPosition() + s.getOriginalText().length()); s.setTripleRelations(combinedTriples); } return result; }
23,144
0
/** * Make point obs from a single timestep of a grid * * @param timeStep the grid * @param dt the timestep for the grid * * @return a Field of PointObs * * @throws RemoteException Java RMI problem * @throws VisADException VisAD problem */
private static FieldImpl makePointObs(FlatField timeStep, DateTime dt) throws VisADException, RemoteException { if (timeStep == null) { return null; } SampledSet domain = getSpatialDomain(timeStep); int numPoints = domain.getLength(); Integer1DSet points = new Integer1DSet(RealType.getRealType("index"), numPoints); TupleType tt = getParamType(timeStep); TupleType rangeType = new TupleType(new MathType[] { RealTupleType.LatitudeLongitudeAltitude, RealType.Time, tt }); FieldImpl ff = new FieldImpl( new FunctionType( ((SetType) points.getType()).getDomain(), rangeType), points); float[][] samples = timeStep.getFloats(false); float[][] geoVals = getEarthLocationPoints((GriddedSet) domain); boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } EarthLocation el = new EarthLocationLite(lat, lon, alt); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el, dt, timeStep.getSample(i), rangeType); ff.setSample(i, pot, false, false); } } return ff; }
NONSATD
true
private static FieldImpl makePointObs(FlatField timeStep, DateTime dt) throws VisADException, RemoteException { if (timeStep == null) { return null; } SampledSet domain = getSpatialDomain(timeStep); int numPoints = domain.getLength(); Integer1DSet points = new Integer1DSet(RealType.getRealType("index"), numPoints); TupleType tt = getParamType(timeStep); TupleType rangeType = new TupleType(new MathType[] { RealTupleType.LatitudeLongitudeAltitude, RealType.Time, tt }); FieldImpl ff = new FieldImpl( new FunctionType( ((SetType) points.getType()).getDomain(), rangeType), points); float[][] samples = timeStep.getFloats(false); float[][] geoVals = getEarthLocationPoints((GriddedSet) domain); boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } EarthLocation el = new EarthLocationLite(lat, lon, alt); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el, dt, timeStep.getSample(i), rangeType); ff.setSample(i, pot, false, false); } } return ff; }
private static FieldImpl makePointObs(FlatField timeStep, DateTime dt) throws VisADException, RemoteException { if (timeStep == null) { return null; } SampledSet domain = getSpatialDomain(timeStep); int numPoints = domain.getLength(); Integer1DSet points = new Integer1DSet(RealType.getRealType("index"), numPoints); TupleType tt = getParamType(timeStep); TupleType rangeType = new TupleType(new MathType[] { RealTupleType.LatitudeLongitudeAltitude, RealType.Time, tt }); FieldImpl ff = new FieldImpl( new FunctionType( ((SetType) points.getType()).getDomain(), rangeType), points); float[][] samples = timeStep.getFloats(false); float[][] geoVals = getEarthLocationPoints((GriddedSet) domain); boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } EarthLocation el = new EarthLocationLite(lat, lon, alt); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el, dt, timeStep.getSample(i), rangeType); ff.setSample(i, pot, false, false); } } return ff; }
private static FieldImpl makePointObs(FlatField timeStep, DateTime dt) throws VisADException, RemoteException { if (timeStep == null) { return null; } SampledSet domain = getSpatialDomain(timeStep); int numPoints = domain.getLength(); Integer1DSet points = new Integer1DSet(RealType.getRealType("index"), numPoints); TupleType tt = getParamType(timeStep); TupleType rangeType = new TupleType(new MathType[] { RealTupleType.LatitudeLongitudeAltitude, RealType.Time, tt }); FieldImpl ff = new FieldImpl( new FunctionType( ((SetType) points.getType()).getDomain(), rangeType), points); float[][] samples = timeStep.getFloats(false); float[][] geoVals = getEarthLocationPoints((GriddedSet) domain); boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } EarthLocation el = new EarthLocationLite(lat, lon, alt); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el, dt, timeStep.getSample(i), rangeType); ff.setSample(i, pot, false, false); } } return ff; }
23,144
1
// TODO: make this more efficient
private static FieldImpl makePointObs(FlatField timeStep, DateTime dt) throws VisADException, RemoteException { if (timeStep == null) { return null; } SampledSet domain = getSpatialDomain(timeStep); int numPoints = domain.getLength(); Integer1DSet points = new Integer1DSet(RealType.getRealType("index"), numPoints); TupleType tt = getParamType(timeStep); TupleType rangeType = new TupleType(new MathType[] { RealTupleType.LatitudeLongitudeAltitude, RealType.Time, tt }); FieldImpl ff = new FieldImpl( new FunctionType( ((SetType) points.getType()).getDomain(), rangeType), points); float[][] samples = timeStep.getFloats(false); float[][] geoVals = getEarthLocationPoints((GriddedSet) domain); boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } EarthLocation el = new EarthLocationLite(lat, lon, alt); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el, dt, timeStep.getSample(i), rangeType); ff.setSample(i, pot, false, false); } } return ff; }
DESIGN
true
} EarthLocation el = new EarthLocationLite(lat, lon, alt); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el, dt, timeStep.getSample(i), rangeType);
float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } EarthLocation el = new EarthLocationLite(lat, lon, alt); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el, dt, timeStep.getSample(i), rangeType); ff.setSample(i, pot, false, false); } } return ff; }
float[][] geoVals = getEarthLocationPoints((GriddedSet) domain); boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } EarthLocation el = new EarthLocationLite(lat, lon, alt); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el, dt, timeStep.getSample(i), rangeType); ff.setSample(i, pot, false, false); } } return ff; }
23,145
0
/** * Make point obs from a single timestep of a grid * * @param timeStep the grid * @param dt the timestep for the grid * * @return a Field of PointObs * * @throws RemoteException Java RMI problem * @throws VisADException VisAD problem */
private static FieldImpl makePointObs(FlatField timeStep, DateTime dt, String function) throws VisADException, RemoteException { final boolean doMax = function.equals(FUNC_MAX); final boolean doMin = function.equals(FUNC_MIN); if (timeStep == null) { return null; } SampledSet domain = getSpatialDomain(timeStep); int numPoints = domain.getLength(); Integer1DSet points = new Integer1DSet(RealType.getRealType("index"), numPoints); TupleType tt = getParamType(timeStep); TupleType rangeType = new TupleType(new MathType[] { RealTupleType.LatitudeLongitudeAltitude, RealType.Time, tt }); FieldImpl ff = new FieldImpl( new FunctionType( ((SetType) points.getType()).getDomain(), rangeType), points); float[][] samples = timeStep.getFloats(false); float[][] geoVals = getEarthLocationPoints((GriddedSet) domain); boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; float pMin = Float.POSITIVE_INFINITY; float pMax = Float.NEGATIVE_INFINITY; int index = 0; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } if(doMax && (float)timeStep.getValues(i)[0] >= pMax){ pMax = (float)timeStep.getValues(i)[0]; index = i; } else if(doMin && (float)timeStep.getValues(i)[0] < pMin){ pMin = (float)timeStep.getValues(i)[0]; index = i; } } } float alt0 = haveAlt ? geoVals[2][index] : 0; EarthLocation el0 = new EarthLocationLite(geoVals[latIndex][index], geoVals[lonIndex][index], alt0); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el0, dt, timeStep.getSample(index), rangeType); ff.setSample(0, pot, false, false); return ff; }
NONSATD
true
private static FieldImpl makePointObs(FlatField timeStep, DateTime dt, String function) throws VisADException, RemoteException { final boolean doMax = function.equals(FUNC_MAX); final boolean doMin = function.equals(FUNC_MIN); if (timeStep == null) { return null; } SampledSet domain = getSpatialDomain(timeStep); int numPoints = domain.getLength(); Integer1DSet points = new Integer1DSet(RealType.getRealType("index"), numPoints); TupleType tt = getParamType(timeStep); TupleType rangeType = new TupleType(new MathType[] { RealTupleType.LatitudeLongitudeAltitude, RealType.Time, tt }); FieldImpl ff = new FieldImpl( new FunctionType( ((SetType) points.getType()).getDomain(), rangeType), points); float[][] samples = timeStep.getFloats(false); float[][] geoVals = getEarthLocationPoints((GriddedSet) domain); boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; float pMin = Float.POSITIVE_INFINITY; float pMax = Float.NEGATIVE_INFINITY; int index = 0; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } if(doMax && (float)timeStep.getValues(i)[0] >= pMax){ pMax = (float)timeStep.getValues(i)[0]; index = i; } else if(doMin && (float)timeStep.getValues(i)[0] < pMin){ pMin = (float)timeStep.getValues(i)[0]; index = i; } } } float alt0 = haveAlt ? geoVals[2][index] : 0; EarthLocation el0 = new EarthLocationLite(geoVals[latIndex][index], geoVals[lonIndex][index], alt0); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el0, dt, timeStep.getSample(index), rangeType); ff.setSample(0, pot, false, false); return ff; }
private static FieldImpl makePointObs(FlatField timeStep, DateTime dt, String function) throws VisADException, RemoteException { final boolean doMax = function.equals(FUNC_MAX); final boolean doMin = function.equals(FUNC_MIN); if (timeStep == null) { return null; } SampledSet domain = getSpatialDomain(timeStep); int numPoints = domain.getLength(); Integer1DSet points = new Integer1DSet(RealType.getRealType("index"), numPoints); TupleType tt = getParamType(timeStep); TupleType rangeType = new TupleType(new MathType[] { RealTupleType.LatitudeLongitudeAltitude, RealType.Time, tt }); FieldImpl ff = new FieldImpl( new FunctionType( ((SetType) points.getType()).getDomain(), rangeType), points); float[][] samples = timeStep.getFloats(false); float[][] geoVals = getEarthLocationPoints((GriddedSet) domain); boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; float pMin = Float.POSITIVE_INFINITY; float pMax = Float.NEGATIVE_INFINITY; int index = 0; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } if(doMax && (float)timeStep.getValues(i)[0] >= pMax){ pMax = (float)timeStep.getValues(i)[0]; index = i; } else if(doMin && (float)timeStep.getValues(i)[0] < pMin){ pMin = (float)timeStep.getValues(i)[0]; index = i; } } } float alt0 = haveAlt ? geoVals[2][index] : 0; EarthLocation el0 = new EarthLocationLite(geoVals[latIndex][index], geoVals[lonIndex][index], alt0); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el0, dt, timeStep.getSample(index), rangeType); ff.setSample(0, pot, false, false); return ff; }
private static FieldImpl makePointObs(FlatField timeStep, DateTime dt, String function) throws VisADException, RemoteException { final boolean doMax = function.equals(FUNC_MAX); final boolean doMin = function.equals(FUNC_MIN); if (timeStep == null) { return null; } SampledSet domain = getSpatialDomain(timeStep); int numPoints = domain.getLength(); Integer1DSet points = new Integer1DSet(RealType.getRealType("index"), numPoints); TupleType tt = getParamType(timeStep); TupleType rangeType = new TupleType(new MathType[] { RealTupleType.LatitudeLongitudeAltitude, RealType.Time, tt }); FieldImpl ff = new FieldImpl( new FunctionType( ((SetType) points.getType()).getDomain(), rangeType), points); float[][] samples = timeStep.getFloats(false); float[][] geoVals = getEarthLocationPoints((GriddedSet) domain); boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; float pMin = Float.POSITIVE_INFINITY; float pMax = Float.NEGATIVE_INFINITY; int index = 0; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } if(doMax && (float)timeStep.getValues(i)[0] >= pMax){ pMax = (float)timeStep.getValues(i)[0]; index = i; } else if(doMin && (float)timeStep.getValues(i)[0] < pMin){ pMin = (float)timeStep.getValues(i)[0]; index = i; } } } float alt0 = haveAlt ? geoVals[2][index] : 0; EarthLocation el0 = new EarthLocationLite(geoVals[latIndex][index], geoVals[lonIndex][index], alt0); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el0, dt, timeStep.getSample(index), rangeType); ff.setSample(0, pot, false, false); return ff; }
23,145
1
// TODO: make this more efficient
private static FieldImpl makePointObs(FlatField timeStep, DateTime dt, String function) throws VisADException, RemoteException { final boolean doMax = function.equals(FUNC_MAX); final boolean doMin = function.equals(FUNC_MIN); if (timeStep == null) { return null; } SampledSet domain = getSpatialDomain(timeStep); int numPoints = domain.getLength(); Integer1DSet points = new Integer1DSet(RealType.getRealType("index"), numPoints); TupleType tt = getParamType(timeStep); TupleType rangeType = new TupleType(new MathType[] { RealTupleType.LatitudeLongitudeAltitude, RealType.Time, tt }); FieldImpl ff = new FieldImpl( new FunctionType( ((SetType) points.getType()).getDomain(), rangeType), points); float[][] samples = timeStep.getFloats(false); float[][] geoVals = getEarthLocationPoints((GriddedSet) domain); boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; float pMin = Float.POSITIVE_INFINITY; float pMax = Float.NEGATIVE_INFINITY; int index = 0; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } if(doMax && (float)timeStep.getValues(i)[0] >= pMax){ pMax = (float)timeStep.getValues(i)[0]; index = i; } else if(doMin && (float)timeStep.getValues(i)[0] < pMin){ pMin = (float)timeStep.getValues(i)[0]; index = i; } } } float alt0 = haveAlt ? geoVals[2][index] : 0; EarthLocation el0 = new EarthLocationLite(geoVals[latIndex][index], geoVals[lonIndex][index], alt0); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el0, dt, timeStep.getSample(index), rangeType); ff.setSample(0, pot, false, false); return ff; }
DESIGN
true
: 0; EarthLocation el0 = new EarthLocationLite(geoVals[latIndex][index], geoVals[lonIndex][index], alt0); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el0, dt, timeStep.getSample(index), rangeType);
} else if(doMin && (float)timeStep.getValues(i)[0] < pMin){ pMin = (float)timeStep.getValues(i)[0]; index = i; } } } float alt0 = haveAlt ? geoVals[2][index] : 0; EarthLocation el0 = new EarthLocationLite(geoVals[latIndex][index], geoVals[lonIndex][index], alt0); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el0, dt, timeStep.getSample(index), rangeType); ff.setSample(0, pot, false, false); return ff; }
float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } if(doMax && (float)timeStep.getValues(i)[0] >= pMax){ pMax = (float)timeStep.getValues(i)[0]; index = i; } else if(doMin && (float)timeStep.getValues(i)[0] < pMin){ pMin = (float)timeStep.getValues(i)[0]; index = i; } } } float alt0 = haveAlt ? geoVals[2][index] : 0; EarthLocation el0 = new EarthLocationLite(geoVals[latIndex][index], geoVals[lonIndex][index], alt0); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el0, dt, timeStep.getSample(index), rangeType); ff.setSample(0, pot, false, false); return ff; }
23,146
0
/** * Make point obs from a single timestep of a grid * * @param timeStep the grid * @param dt the timestep for the grid * * @return a Field of PointObs * * @throws RemoteException Java RMI problem * @throws VisADException VisAD problem */
private static FieldImpl makePointObs(FlatField timeStep, DateTime dt, double min, double max) throws VisADException, RemoteException { if (timeStep == null) { return null; } SampledSet domain = getSpatialDomain(timeStep); int numPoints = domain.getLength(); Integer1DSet points = new Integer1DSet(RealType.getRealType("index"), numPoints); TupleType tt = getParamType(timeStep); TupleType rangeType = new TupleType(new MathType[] { RealTupleType.LatitudeLongitudeAltitude, RealType.Time, tt }); FieldImpl ff = new FieldImpl( new FunctionType( ((SetType) points.getType()).getDomain(), rangeType), points); float[][] samples = timeStep.getFloats(false); float[][] geoVals = getEarthLocationPoints((GriddedSet) domain); boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } if(timeStep.getValues(i)[0] >= min && timeStep.getValues(i)[0] < max) { EarthLocation el = new EarthLocationLite(lat, lon, alt); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el, dt, timeStep.getSample(i), rangeType); ff.setSample(i, pot, false, false); } } } return ff; }
NONSATD
true
private static FieldImpl makePointObs(FlatField timeStep, DateTime dt, double min, double max) throws VisADException, RemoteException { if (timeStep == null) { return null; } SampledSet domain = getSpatialDomain(timeStep); int numPoints = domain.getLength(); Integer1DSet points = new Integer1DSet(RealType.getRealType("index"), numPoints); TupleType tt = getParamType(timeStep); TupleType rangeType = new TupleType(new MathType[] { RealTupleType.LatitudeLongitudeAltitude, RealType.Time, tt }); FieldImpl ff = new FieldImpl( new FunctionType( ((SetType) points.getType()).getDomain(), rangeType), points); float[][] samples = timeStep.getFloats(false); float[][] geoVals = getEarthLocationPoints((GriddedSet) domain); boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } if(timeStep.getValues(i)[0] >= min && timeStep.getValues(i)[0] < max) { EarthLocation el = new EarthLocationLite(lat, lon, alt); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el, dt, timeStep.getSample(i), rangeType); ff.setSample(i, pot, false, false); } } } return ff; }
private static FieldImpl makePointObs(FlatField timeStep, DateTime dt, double min, double max) throws VisADException, RemoteException { if (timeStep == null) { return null; } SampledSet domain = getSpatialDomain(timeStep); int numPoints = domain.getLength(); Integer1DSet points = new Integer1DSet(RealType.getRealType("index"), numPoints); TupleType tt = getParamType(timeStep); TupleType rangeType = new TupleType(new MathType[] { RealTupleType.LatitudeLongitudeAltitude, RealType.Time, tt }); FieldImpl ff = new FieldImpl( new FunctionType( ((SetType) points.getType()).getDomain(), rangeType), points); float[][] samples = timeStep.getFloats(false); float[][] geoVals = getEarthLocationPoints((GriddedSet) domain); boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } if(timeStep.getValues(i)[0] >= min && timeStep.getValues(i)[0] < max) { EarthLocation el = new EarthLocationLite(lat, lon, alt); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el, dt, timeStep.getSample(i), rangeType); ff.setSample(i, pot, false, false); } } } return ff; }
private static FieldImpl makePointObs(FlatField timeStep, DateTime dt, double min, double max) throws VisADException, RemoteException { if (timeStep == null) { return null; } SampledSet domain = getSpatialDomain(timeStep); int numPoints = domain.getLength(); Integer1DSet points = new Integer1DSet(RealType.getRealType("index"), numPoints); TupleType tt = getParamType(timeStep); TupleType rangeType = new TupleType(new MathType[] { RealTupleType.LatitudeLongitudeAltitude, RealType.Time, tt }); FieldImpl ff = new FieldImpl( new FunctionType( ((SetType) points.getType()).getDomain(), rangeType), points); float[][] samples = timeStep.getFloats(false); float[][] geoVals = getEarthLocationPoints((GriddedSet) domain); boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } if(timeStep.getValues(i)[0] >= min && timeStep.getValues(i)[0] < max) { EarthLocation el = new EarthLocationLite(lat, lon, alt); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el, dt, timeStep.getSample(i), rangeType); ff.setSample(i, pot, false, false); } } } return ff; }
23,146
1
// TODO: make this more efficient
private static FieldImpl makePointObs(FlatField timeStep, DateTime dt, double min, double max) throws VisADException, RemoteException { if (timeStep == null) { return null; } SampledSet domain = getSpatialDomain(timeStep); int numPoints = domain.getLength(); Integer1DSet points = new Integer1DSet(RealType.getRealType("index"), numPoints); TupleType tt = getParamType(timeStep); TupleType rangeType = new TupleType(new MathType[] { RealTupleType.LatitudeLongitudeAltitude, RealType.Time, tt }); FieldImpl ff = new FieldImpl( new FunctionType( ((SetType) points.getType()).getDomain(), rangeType), points); float[][] samples = timeStep.getFloats(false); float[][] geoVals = getEarthLocationPoints((GriddedSet) domain); boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } if(timeStep.getValues(i)[0] >= min && timeStep.getValues(i)[0] < max) { EarthLocation el = new EarthLocationLite(lat, lon, alt); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el, dt, timeStep.getSample(i), rangeType); ff.setSample(i, pot, false, false); } } } return ff; }
DESIGN
true
if(timeStep.getValues(i)[0] >= min && timeStep.getValues(i)[0] < max) { EarthLocation el = new EarthLocationLite(lat, lon, alt); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el, dt, timeStep.getSample(i), rangeType);
float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } if(timeStep.getValues(i)[0] >= min && timeStep.getValues(i)[0] < max) { EarthLocation el = new EarthLocationLite(lat, lon, alt); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el, dt, timeStep.getSample(i), rangeType); ff.setSample(i, pot, false, false); } } } return ff; }
boolean isLatLon = isLatLonOrder(domain); int latIndex = isLatLon ? 0 : 1; int lonIndex = isLatLon ? 1 : 0; boolean haveAlt = geoVals.length > 2; for (int i = 0; i < numPoints; i++) { float lat = geoVals[latIndex][i]; float lon = geoVals[lonIndex][i]; float alt = haveAlt ? geoVals[2][i] : 0; if ((lat == lat) && (lon == lon)) { if ( !(alt == alt)) { alt = 0; } if(timeStep.getValues(i)[0] >= min && timeStep.getValues(i)[0] < max) { EarthLocation el = new EarthLocationLite(lat, lon, alt); // TODO: make this more efficient PointObTuple pot = new PointObTuple(el, dt, timeStep.getSample(i), rangeType); ff.setSample(i, pot, false, false); } } } return ff; }
14,968
0
//This concept name is value so do special processing
@Override public String explainIncompleteness() { String result = null; if (isValueDomain()) { //This concept name is value so do special processing result = explainIfNotAllTokensProcessed(""); if (this.instanceName == null) { result = appendReason(result, "No instance name was identified"); } else { //TODO: Eventually remove this test if (this.instanceName.equals(TOKEN_NAMED)) { result = appendReason(result, "Instance name of 'named' was detected"); } } } else { //Do normal processing result = super.explainIncompleteness(); } return result; }
NONSATD
true
String result = null; if (isValueDomain()) { //This concept name is value so do special processing result = explainIfNotAllTokensProcessed(""); if (this.instanceName == null) {
@Override public String explainIncompleteness() { String result = null; if (isValueDomain()) { //This concept name is value so do special processing result = explainIfNotAllTokensProcessed(""); if (this.instanceName == null) { result = appendReason(result, "No instance name was identified"); } else { //TODO: Eventually remove this test if (this.instanceName.equals(TOKEN_NAMED)) { result = appendReason(result, "Instance name of 'named' was detected"); } } } else {
@Override public String explainIncompleteness() { String result = null; if (isValueDomain()) { //This concept name is value so do special processing result = explainIfNotAllTokensProcessed(""); if (this.instanceName == null) { result = appendReason(result, "No instance name was identified"); } else { //TODO: Eventually remove this test if (this.instanceName.equals(TOKEN_NAMED)) { result = appendReason(result, "Instance name of 'named' was detected"); } } } else { //Do normal processing result = super.explainIncompleteness(); } return result; }
14,968
1
//TODO: Eventually remove this test
@Override public String explainIncompleteness() { String result = null; if (isValueDomain()) { //This concept name is value so do special processing result = explainIfNotAllTokensProcessed(""); if (this.instanceName == null) { result = appendReason(result, "No instance name was identified"); } else { //TODO: Eventually remove this test if (this.instanceName.equals(TOKEN_NAMED)) { result = appendReason(result, "Instance name of 'named' was detected"); } } } else { //Do normal processing result = super.explainIncompleteness(); } return result; }
DESIGN
true
result = appendReason(result, "No instance name was identified"); } else { //TODO: Eventually remove this test if (this.instanceName.equals(TOKEN_NAMED)) { result = appendReason(result, "Instance name of 'named' was detected");
@Override public String explainIncompleteness() { String result = null; if (isValueDomain()) { //This concept name is value so do special processing result = explainIfNotAllTokensProcessed(""); if (this.instanceName == null) { result = appendReason(result, "No instance name was identified"); } else { //TODO: Eventually remove this test if (this.instanceName.equals(TOKEN_NAMED)) { result = appendReason(result, "Instance name of 'named' was detected"); } } } else { //Do normal processing result = super.explainIncompleteness(); } return result; }
@Override public String explainIncompleteness() { String result = null; if (isValueDomain()) { //This concept name is value so do special processing result = explainIfNotAllTokensProcessed(""); if (this.instanceName == null) { result = appendReason(result, "No instance name was identified"); } else { //TODO: Eventually remove this test if (this.instanceName.equals(TOKEN_NAMED)) { result = appendReason(result, "Instance name of 'named' was detected"); } } } else { //Do normal processing result = super.explainIncompleteness(); } return result; }
14,968
2
//Do normal processing
@Override public String explainIncompleteness() { String result = null; if (isValueDomain()) { //This concept name is value so do special processing result = explainIfNotAllTokensProcessed(""); if (this.instanceName == null) { result = appendReason(result, "No instance name was identified"); } else { //TODO: Eventually remove this test if (this.instanceName.equals(TOKEN_NAMED)) { result = appendReason(result, "Instance name of 'named' was detected"); } } } else { //Do normal processing result = super.explainIncompleteness(); } return result; }
NONSATD
true
} } else { //Do normal processing result = super.explainIncompleteness(); }
result = explainIfNotAllTokensProcessed(""); if (this.instanceName == null) { result = appendReason(result, "No instance name was identified"); } else { //TODO: Eventually remove this test if (this.instanceName.equals(TOKEN_NAMED)) { result = appendReason(result, "Instance name of 'named' was detected"); } } } else { //Do normal processing result = super.explainIncompleteness(); } return result; }
@Override public String explainIncompleteness() { String result = null; if (isValueDomain()) { //This concept name is value so do special processing result = explainIfNotAllTokensProcessed(""); if (this.instanceName == null) { result = appendReason(result, "No instance name was identified"); } else { //TODO: Eventually remove this test if (this.instanceName.equals(TOKEN_NAMED)) { result = appendReason(result, "Instance name of 'named' was detected"); } } } else { //Do normal processing result = super.explainIncompleteness(); } return result; }
14,974
0
/** * Returns the largest character or `null` if there are no characters. * * @deprecated Please use maxOrNull instead */
@Nullable @Deprecated public static Character max(@Nullable CharSequence charSequence) { return maxOrNull(charSequence); }
NONSATD
true
@Nullable @Deprecated public static Character max(@Nullable CharSequence charSequence) { return maxOrNull(charSequence); }
@Nullable @Deprecated public static Character max(@Nullable CharSequence charSequence) { return maxOrNull(charSequence); }
@Nullable @Deprecated public static Character max(@Nullable CharSequence charSequence) { return maxOrNull(charSequence); }
14,975
0
/** * Returns the first character yielding the largest value of the given function or `null` if there are no characters. * * @deprecated Please use maxByOrNull instead */
@Nullable @Deprecated public static <R extends Comparable<R>> Character maxBy(@Nullable CharSequence charSequence, @NotNull Transformer<Character, R> selector) { return maxByOrNull(charSequence, selector); }
NONSATD
true
@Nullable @Deprecated public static <R extends Comparable<R>> Character maxBy(@Nullable CharSequence charSequence, @NotNull Transformer<Character, R> selector) { return maxByOrNull(charSequence, selector); }
@Nullable @Deprecated public static <R extends Comparable<R>> Character maxBy(@Nullable CharSequence charSequence, @NotNull Transformer<Character, R> selector) { return maxByOrNull(charSequence, selector); }
@Nullable @Deprecated public static <R extends Comparable<R>> Character maxBy(@Nullable CharSequence charSequence, @NotNull Transformer<Character, R> selector) { return maxByOrNull(charSequence, selector); }
14,976
0
/** * Returns the smallest character or `null` if there are no characters. * * @deprecated Please use minOrNull instead */
@Nullable @Deprecated public static Character min(@Nullable CharSequence charSequence) { return minOrNull(charSequence); }
NONSATD
true
@Nullable @Deprecated public static Character min(@Nullable CharSequence charSequence) { return minOrNull(charSequence); }
@Nullable @Deprecated public static Character min(@Nullable CharSequence charSequence) { return minOrNull(charSequence); }
@Nullable @Deprecated public static Character min(@Nullable CharSequence charSequence) { return minOrNull(charSequence); }
14,977
0
/** * Returns the first character yielding the smallest value of the given function or `null` if there are no characters. * * @deprecated Please use minByOrNull instead */
@Nullable @Deprecated public static <R extends Comparable<R>> Character minBy(@Nullable CharSequence charSequence, @NotNull Transformer<Character, R> selector) { return minByOrNull(charSequence, selector); }
NONSATD
true
@Nullable @Deprecated public static <R extends Comparable<R>> Character minBy(@Nullable CharSequence charSequence, @NotNull Transformer<Character, R> selector) { return minByOrNull(charSequence, selector); }
@Nullable @Deprecated public static <R extends Comparable<R>> Character minBy(@Nullable CharSequence charSequence, @NotNull Transformer<Character, R> selector) { return minByOrNull(charSequence, selector); }
@Nullable @Deprecated public static <R extends Comparable<R>> Character minBy(@Nullable CharSequence charSequence, @NotNull Transformer<Character, R> selector) { return minByOrNull(charSequence, selector); }
23,182
0
/** * @param args the command line arguments */
public static void main(String[] args) { // TODO code application logic her // Hola Onasis int num = 0; // Holaaaaa // QQUE ONDASS switch(num){ case 1: case 2: default: } // }
NONSATD
true
public static void main(String[] args) { // TODO code application logic her // Hola Onasis int num = 0; // Holaaaaa // QQUE ONDASS switch(num){ case 1: case 2: default: } // }
public static void main(String[] args) { // TODO code application logic her // Hola Onasis int num = 0; // Holaaaaa // QQUE ONDASS switch(num){ case 1: case 2: default: } // }
public static void main(String[] args) { // TODO code application logic her // Hola Onasis int num = 0; // Holaaaaa // QQUE ONDASS switch(num){ case 1: case 2: default: } // }
23,182
1
// TODO code application logic her // Hola Onasis
public static void main(String[] args) { // TODO code application logic her // Hola Onasis int num = 0; // Holaaaaa // QQUE ONDASS switch(num){ case 1: case 2: default: } // }
IMPLEMENTATION
true
public static void main(String[] args) { // TODO code application logic her // Hola Onasis int num = 0; // Holaaaaa
public static void main(String[] args) { // TODO code application logic her // Hola Onasis int num = 0; // Holaaaaa // QQUE ONDASS switch(num){ case 1: case 2: default: } // }
public static void main(String[] args) { // TODO code application logic her // Hola Onasis int num = 0; // Holaaaaa // QQUE ONDASS switch(num){ case 1: case 2: default: } // }
23,182
2
// Holaaaaa // QQUE ONDASS
public static void main(String[] args) { // TODO code application logic her // Hola Onasis int num = 0; // Holaaaaa // QQUE ONDASS switch(num){ case 1: case 2: default: } // }
NONSATD
true
// Hola Onasis int num = 0; // Holaaaaa // QQUE ONDASS switch(num){ case 1:
public static void main(String[] args) { // TODO code application logic her // Hola Onasis int num = 0; // Holaaaaa // QQUE ONDASS switch(num){ case 1: case 2: default: } // }
public static void main(String[] args) { // TODO code application logic her // Hola Onasis int num = 0; // Holaaaaa // QQUE ONDASS switch(num){ case 1: case 2: default: } // }
23,182
3
//
public static void main(String[] args) { // TODO code application logic her // Hola Onasis int num = 0; // Holaaaaa // QQUE ONDASS switch(num){ case 1: case 2: default: } // }
NONSATD
true
public static void main(String[] args) { // TODO code application logic her // Hola Onasis int num = 0;
public static void main(String[] args) { // TODO code application logic her // Hola Onasis int num = 0; // Holaaaaa // QQUE ONDASS switch(num){ case 1: case 2: default: } //
public static void main(String[] args) { // TODO code application logic her // Hola Onasis int num = 0; // Holaaaaa // QQUE ONDASS switch(num){ case 1: case 2: default: } // }
15,012
0
// KIRK: this test fails intermittently with bug 37482
private void doTestServerEventsInSystemClient() throws Exception { // KIRK: this test fails intermittently with bug 37482 final boolean[] firedSystem = new boolean[3]; final DistributedMember[] memberSystem = new DistributedMember[3]; final String[] memberIdSystem = new String[3]; final boolean[] isClientSystem = new boolean[3]; final boolean[] firedAdapter = new boolean[3]; final DistributedMember[] memberAdapter = new DistributedMember[3]; final String[] memberIdAdapter = new String[3]; final boolean[] isClientAdapter = new boolean[3]; final boolean[] firedBridge = new boolean[3]; final DistributedMember[] memberBridge = new DistributedMember[3]; final String[] memberIdBridge = new String[3]; final boolean[] isClientBridge = new boolean[3]; final boolean[] firedSystemDuplicate = new boolean[3]; final boolean[] firedAdapterDuplicate = new boolean[3]; final boolean[] firedBridgeDuplicate = new boolean[3]; SystemMembershipListener systemListener = new SystemMembershipListener() { public synchronized void memberJoined(SystemMembershipEvent event) { firedSystemDuplicate[JOINED] = firedSystem[JOINED]; firedSystem[JOINED] = true; memberSystem[JOINED] = event.getDistributedMember(); memberIdSystem[JOINED] = event.getMemberId(); notify(); } public synchronized void memberLeft(SystemMembershipEvent event) { firedSystemDuplicate[LEFT] = firedSystem[LEFT]; firedSystem[LEFT] = true; memberSystem[LEFT] = event.getDistributedMember(); memberIdSystem[LEFT] = event.getMemberId(); notify(); } public synchronized void memberCrashed(SystemMembershipEvent event) { firedSystemDuplicate[CRASHED] = firedSystem[CRASHED]; firedSystem[CRASHED] = true; memberSystem[CRASHED] = event.getDistributedMember(); memberIdSystem[CRASHED] = event.getMemberId(); notify(); } }; UniversalMembershipListenerAdapter adapter = new UniversalMembershipListenerAdapter() { @Override public synchronized void memberJoined(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberJoined >" + event.getMemberId() + "<"); firedAdapterDuplicate[JOINED] = firedAdapter[JOINED]; firedAdapter[JOINED] = true; memberAdapter[JOINED] = event.getDistributedMember(); memberIdAdapter[JOINED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[JOINED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberLeft(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberLeft >" + event.getMemberId() + "<"); firedAdapterDuplicate[LEFT] = firedAdapter[LEFT]; firedAdapter[LEFT] = true; memberAdapter[LEFT] = event.getDistributedMember(); memberIdAdapter[LEFT] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[LEFT] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberCrashed(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberCrashed >" + event.getMemberId() + "<"); firedAdapterDuplicate[CRASHED] = firedAdapter[CRASHED]; firedAdapter[CRASHED] = true; memberAdapter[CRASHED] = event.getDistributedMember(); memberIdAdapter[CRASHED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[CRASHED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } }; BridgeMembershipListener bridgeListener = new BridgeMembershipListener() { public synchronized void memberJoined(BridgeMembershipEvent event) { firedBridgeDuplicate[JOINED] = firedBridge[JOINED]; firedBridge[JOINED] = true; memberBridge[JOINED] = event.getMember(); memberIdBridge[JOINED] = event.getMemberId(); isClientBridge[JOINED] = event.isClient(); notify(); } public synchronized void memberLeft(BridgeMembershipEvent event) { firedBridgeDuplicate[LEFT] = firedBridge[LEFT]; firedBridge[LEFT] = true; memberBridge[LEFT] = event.getMember(); memberIdBridge[LEFT] = event.getMemberId(); isClientBridge[LEFT] = event.isClient(); notify(); } public synchronized void memberCrashed(BridgeMembershipEvent event) { firedBridgeDuplicate[CRASHED] = firedBridge[CRASHED]; firedBridge[CRASHED] = true; memberBridge[CRASHED] = event.getMember(); memberIdBridge[CRASHED] = event.getMemberId(); isClientBridge[CRASHED] = event.isClient(); notify(); } }; final Host host = Host.getHost(0); final VM vm0 = host.getVM(0); final String name = this.getUniqueName(); final int[] ports = new int[] { AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) }; assertTrue(ports[0] != 0); // getLogWriter().info("[testServerEventsInSystemClient] create bridge client"); // Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); Region region = createRegion(name, factory.create()); assertNotNull(region); assertNotNull(getRootRegion().getSubregion(name)); try { testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e); fail(e.getMessage()); } } }; vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); String serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); DistributedMember serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); // create region which connects to bridge server AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); createRegion(name, factory.create()); assertNotNull(getRootRegion().getSubregion(name)); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); getLogWriter().info("[testServerEventsInSystemClient] wait for client to fully connect"); final String pl = getRootRegion().getSubregion(name).getAttributes().getPoolName(); PoolImpl pi = (PoolImpl)PoolManager.find(pl); waitForClientToFullyConnect(pi); LogWriter bgexecLogger = new LocalLogWriter(LogWriterImpl.ALL_LEVEL, System.out); bgexecLogger.info("<ExpectedException action=add>" + "java.io.IOException" + "</ExpectedException>"); final ExpectedException ex = addExpectedException( ServerConnectivityException.class.getName()); try { vm0.invoke(new SerializableRunnable("Disconnect bridge server") { public void run() { getLogWriter().info("[testServerEventsInSystemClient] disconnect bridge server"); closeCache(); disconnectFromDS(); } }); synchronized(systemListener) { if (!firedSystem[LEFT]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[LEFT]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); // KIRK: did increasing this solve problem on balrog? } } synchronized(bridgeListener) { if (!firedBridge[LEFT]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } } finally { bgexecLogger.info("<ExpectedException action=remove>" + "java.io.IOException" + "</ExpectedException>"); ex.remove(); } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server crashed"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertFalse(firedBridge[JOINED]); assertNull(memberIdBridge[JOINED]); assertNull(memberBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse("Please update testServerEventsInSystemClient to handle memberLeft for BridgeServer.", firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertTrue(firedBridge[CRASHED]); assertNotNull(memberBridge[CRASHED]); assertNotNull(memberIdBridge[CRASHED]); assertEquals(serverMemberId, memberIdBridge[CRASHED]); assertEquals(serverMember, memberBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertFalse(firedSystem[JOINED]); assertNull(memberSystem[JOINED]); assertNull(memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertTrue(firedSystem[LEFT]); assertEquals(serverMember, memberSystem[LEFT]); assertEquals(serverMemberId, memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertFalse("this intermittently fails", firedAdapter[JOINED]); // KIRK --> this fails on balrog occasionally assertNull(memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); // LEFT fired by System listener assertTrue(firedAdapter[LEFT]); assertEquals(serverMember, memberAdapter[LEFT]); assertEquals(serverMemberId, memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); // There won't be an adapter crashed event because since the two VMs // are in the same distributed system, and the server's real member // id is used now. In this case, two events are sent - one from // jgroups (memberDeparted), and one from the server (a memberCrshed). // The memberCrashed event is deemed a duplicate and not sent - see // UniversalMembershipListenerAdapter.SystemMembershipListener.isDuplicate assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); // reconnect bridge client to test for crashed event vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server re-join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); }
TEST
true
private void doTestServerEventsInSystemClient() throws Exception { // KIRK: this test fails intermittently with bug 37482 final boolean[] firedSystem = new boolean[3]; final DistributedMember[] memberSystem = new DistributedMember[3];
private void doTestServerEventsInSystemClient() throws Exception { // KIRK: this test fails intermittently with bug 37482 final boolean[] firedSystem = new boolean[3]; final DistributedMember[] memberSystem = new DistributedMember[3]; final String[] memberIdSystem = new String[3]; final boolean[] isClientSystem = new boolean[3]; final boolean[] firedAdapter = new boolean[3]; final DistributedMember[] memberAdapter = new DistributedMember[3]; final String[] memberIdAdapter = new String[3]; final boolean[] isClientAdapter = new boolean[3]; final boolean[] firedBridge = new boolean[3]; final DistributedMember[] memberBridge = new DistributedMember[3];
private void doTestServerEventsInSystemClient() throws Exception { // KIRK: this test fails intermittently with bug 37482 final boolean[] firedSystem = new boolean[3]; final DistributedMember[] memberSystem = new DistributedMember[3]; final String[] memberIdSystem = new String[3]; final boolean[] isClientSystem = new boolean[3]; final boolean[] firedAdapter = new boolean[3]; final DistributedMember[] memberAdapter = new DistributedMember[3]; final String[] memberIdAdapter = new String[3]; final boolean[] isClientAdapter = new boolean[3]; final boolean[] firedBridge = new boolean[3]; final DistributedMember[] memberBridge = new DistributedMember[3]; final String[] memberIdBridge = new String[3]; final boolean[] isClientBridge = new boolean[3]; final boolean[] firedSystemDuplicate = new boolean[3]; final boolean[] firedAdapterDuplicate = new boolean[3]; final boolean[] firedBridgeDuplicate = new boolean[3]; SystemMembershipListener systemListener = new SystemMembershipListener() { public synchronized void memberJoined(SystemMembershipEvent event) { firedSystemDuplicate[JOINED] = firedSystem[JOINED]; firedSystem[JOINED] = true; memberSystem[JOINED] = event.getDistributedMember();
15,012
1
// getLogWriter().info("[testServerEventsInSystemClient] create bridge client"); // Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name));
private void doTestServerEventsInSystemClient() throws Exception { // KIRK: this test fails intermittently with bug 37482 final boolean[] firedSystem = new boolean[3]; final DistributedMember[] memberSystem = new DistributedMember[3]; final String[] memberIdSystem = new String[3]; final boolean[] isClientSystem = new boolean[3]; final boolean[] firedAdapter = new boolean[3]; final DistributedMember[] memberAdapter = new DistributedMember[3]; final String[] memberIdAdapter = new String[3]; final boolean[] isClientAdapter = new boolean[3]; final boolean[] firedBridge = new boolean[3]; final DistributedMember[] memberBridge = new DistributedMember[3]; final String[] memberIdBridge = new String[3]; final boolean[] isClientBridge = new boolean[3]; final boolean[] firedSystemDuplicate = new boolean[3]; final boolean[] firedAdapterDuplicate = new boolean[3]; final boolean[] firedBridgeDuplicate = new boolean[3]; SystemMembershipListener systemListener = new SystemMembershipListener() { public synchronized void memberJoined(SystemMembershipEvent event) { firedSystemDuplicate[JOINED] = firedSystem[JOINED]; firedSystem[JOINED] = true; memberSystem[JOINED] = event.getDistributedMember(); memberIdSystem[JOINED] = event.getMemberId(); notify(); } public synchronized void memberLeft(SystemMembershipEvent event) { firedSystemDuplicate[LEFT] = firedSystem[LEFT]; firedSystem[LEFT] = true; memberSystem[LEFT] = event.getDistributedMember(); memberIdSystem[LEFT] = event.getMemberId(); notify(); } public synchronized void memberCrashed(SystemMembershipEvent event) { firedSystemDuplicate[CRASHED] = firedSystem[CRASHED]; firedSystem[CRASHED] = true; memberSystem[CRASHED] = event.getDistributedMember(); memberIdSystem[CRASHED] = event.getMemberId(); notify(); } }; UniversalMembershipListenerAdapter adapter = new UniversalMembershipListenerAdapter() { @Override public synchronized void memberJoined(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberJoined >" + event.getMemberId() + "<"); firedAdapterDuplicate[JOINED] = firedAdapter[JOINED]; firedAdapter[JOINED] = true; memberAdapter[JOINED] = event.getDistributedMember(); memberIdAdapter[JOINED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[JOINED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberLeft(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberLeft >" + event.getMemberId() + "<"); firedAdapterDuplicate[LEFT] = firedAdapter[LEFT]; firedAdapter[LEFT] = true; memberAdapter[LEFT] = event.getDistributedMember(); memberIdAdapter[LEFT] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[LEFT] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberCrashed(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberCrashed >" + event.getMemberId() + "<"); firedAdapterDuplicate[CRASHED] = firedAdapter[CRASHED]; firedAdapter[CRASHED] = true; memberAdapter[CRASHED] = event.getDistributedMember(); memberIdAdapter[CRASHED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[CRASHED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } }; BridgeMembershipListener bridgeListener = new BridgeMembershipListener() { public synchronized void memberJoined(BridgeMembershipEvent event) { firedBridgeDuplicate[JOINED] = firedBridge[JOINED]; firedBridge[JOINED] = true; memberBridge[JOINED] = event.getMember(); memberIdBridge[JOINED] = event.getMemberId(); isClientBridge[JOINED] = event.isClient(); notify(); } public synchronized void memberLeft(BridgeMembershipEvent event) { firedBridgeDuplicate[LEFT] = firedBridge[LEFT]; firedBridge[LEFT] = true; memberBridge[LEFT] = event.getMember(); memberIdBridge[LEFT] = event.getMemberId(); isClientBridge[LEFT] = event.isClient(); notify(); } public synchronized void memberCrashed(BridgeMembershipEvent event) { firedBridgeDuplicate[CRASHED] = firedBridge[CRASHED]; firedBridge[CRASHED] = true; memberBridge[CRASHED] = event.getMember(); memberIdBridge[CRASHED] = event.getMemberId(); isClientBridge[CRASHED] = event.isClient(); notify(); } }; final Host host = Host.getHost(0); final VM vm0 = host.getVM(0); final String name = this.getUniqueName(); final int[] ports = new int[] { AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) }; assertTrue(ports[0] != 0); // getLogWriter().info("[testServerEventsInSystemClient] create bridge client"); // Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); Region region = createRegion(name, factory.create()); assertNotNull(region); assertNotNull(getRootRegion().getSubregion(name)); try { testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e); fail(e.getMessage()); } } }; vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); String serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); DistributedMember serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); // create region which connects to bridge server AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); createRegion(name, factory.create()); assertNotNull(getRootRegion().getSubregion(name)); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); getLogWriter().info("[testServerEventsInSystemClient] wait for client to fully connect"); final String pl = getRootRegion().getSubregion(name).getAttributes().getPoolName(); PoolImpl pi = (PoolImpl)PoolManager.find(pl); waitForClientToFullyConnect(pi); LogWriter bgexecLogger = new LocalLogWriter(LogWriterImpl.ALL_LEVEL, System.out); bgexecLogger.info("<ExpectedException action=add>" + "java.io.IOException" + "</ExpectedException>"); final ExpectedException ex = addExpectedException( ServerConnectivityException.class.getName()); try { vm0.invoke(new SerializableRunnable("Disconnect bridge server") { public void run() { getLogWriter().info("[testServerEventsInSystemClient] disconnect bridge server"); closeCache(); disconnectFromDS(); } }); synchronized(systemListener) { if (!firedSystem[LEFT]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[LEFT]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); // KIRK: did increasing this solve problem on balrog? } } synchronized(bridgeListener) { if (!firedBridge[LEFT]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } } finally { bgexecLogger.info("<ExpectedException action=remove>" + "java.io.IOException" + "</ExpectedException>"); ex.remove(); } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server crashed"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertFalse(firedBridge[JOINED]); assertNull(memberIdBridge[JOINED]); assertNull(memberBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse("Please update testServerEventsInSystemClient to handle memberLeft for BridgeServer.", firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertTrue(firedBridge[CRASHED]); assertNotNull(memberBridge[CRASHED]); assertNotNull(memberIdBridge[CRASHED]); assertEquals(serverMemberId, memberIdBridge[CRASHED]); assertEquals(serverMember, memberBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertFalse(firedSystem[JOINED]); assertNull(memberSystem[JOINED]); assertNull(memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertTrue(firedSystem[LEFT]); assertEquals(serverMember, memberSystem[LEFT]); assertEquals(serverMemberId, memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertFalse("this intermittently fails", firedAdapter[JOINED]); // KIRK --> this fails on balrog occasionally assertNull(memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); // LEFT fired by System listener assertTrue(firedAdapter[LEFT]); assertEquals(serverMember, memberAdapter[LEFT]); assertEquals(serverMemberId, memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); // There won't be an adapter crashed event because since the two VMs // are in the same distributed system, and the server's real member // id is used now. In this case, two events are sent - one from // jgroups (memberDeparted), and one from the server (a memberCrshed). // The memberCrashed event is deemed a duplicate and not sent - see // UniversalMembershipListenerAdapter.SystemMembershipListener.isDuplicate assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); // reconnect bridge client to test for crashed event vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server re-join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); }
NONSATD
true
{ AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) }; assertTrue(ports[0] != 0); // getLogWriter().info("[testServerEventsInSystemClient] create bridge client"); // Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem();
isClientBridge[CRASHED] = event.isClient(); notify(); } }; final Host host = Host.getHost(0); final VM vm0 = host.getVM(0); final String name = this.getUniqueName(); final int[] ports = new int[] { AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) }; assertTrue(ports[0] != 0); // getLogWriter().info("[testServerEventsInSystemClient] create bridge client"); // Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect();
memberBridge[LEFT] = event.getMember(); memberIdBridge[LEFT] = event.getMemberId(); isClientBridge[LEFT] = event.isClient(); notify(); } public synchronized void memberCrashed(BridgeMembershipEvent event) { firedBridgeDuplicate[CRASHED] = firedBridge[CRASHED]; firedBridge[CRASHED] = true; memberBridge[CRASHED] = event.getMember(); memberIdBridge[CRASHED] = event.getMemberId(); isClientBridge[CRASHED] = event.isClient(); notify(); } }; final Host host = Host.getHost(0); final VM vm0 = host.getVM(0); final String name = this.getUniqueName(); final int[] ports = new int[] { AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) }; assertTrue(ports[0] != 0); // getLogWriter().info("[testServerEventsInSystemClient] create bridge client"); // Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException {
15,012
2
// register the bridge listener
private void doTestServerEventsInSystemClient() throws Exception { // KIRK: this test fails intermittently with bug 37482 final boolean[] firedSystem = new boolean[3]; final DistributedMember[] memberSystem = new DistributedMember[3]; final String[] memberIdSystem = new String[3]; final boolean[] isClientSystem = new boolean[3]; final boolean[] firedAdapter = new boolean[3]; final DistributedMember[] memberAdapter = new DistributedMember[3]; final String[] memberIdAdapter = new String[3]; final boolean[] isClientAdapter = new boolean[3]; final boolean[] firedBridge = new boolean[3]; final DistributedMember[] memberBridge = new DistributedMember[3]; final String[] memberIdBridge = new String[3]; final boolean[] isClientBridge = new boolean[3]; final boolean[] firedSystemDuplicate = new boolean[3]; final boolean[] firedAdapterDuplicate = new boolean[3]; final boolean[] firedBridgeDuplicate = new boolean[3]; SystemMembershipListener systemListener = new SystemMembershipListener() { public synchronized void memberJoined(SystemMembershipEvent event) { firedSystemDuplicate[JOINED] = firedSystem[JOINED]; firedSystem[JOINED] = true; memberSystem[JOINED] = event.getDistributedMember(); memberIdSystem[JOINED] = event.getMemberId(); notify(); } public synchronized void memberLeft(SystemMembershipEvent event) { firedSystemDuplicate[LEFT] = firedSystem[LEFT]; firedSystem[LEFT] = true; memberSystem[LEFT] = event.getDistributedMember(); memberIdSystem[LEFT] = event.getMemberId(); notify(); } public synchronized void memberCrashed(SystemMembershipEvent event) { firedSystemDuplicate[CRASHED] = firedSystem[CRASHED]; firedSystem[CRASHED] = true; memberSystem[CRASHED] = event.getDistributedMember(); memberIdSystem[CRASHED] = event.getMemberId(); notify(); } }; UniversalMembershipListenerAdapter adapter = new UniversalMembershipListenerAdapter() { @Override public synchronized void memberJoined(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberJoined >" + event.getMemberId() + "<"); firedAdapterDuplicate[JOINED] = firedAdapter[JOINED]; firedAdapter[JOINED] = true; memberAdapter[JOINED] = event.getDistributedMember(); memberIdAdapter[JOINED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[JOINED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberLeft(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberLeft >" + event.getMemberId() + "<"); firedAdapterDuplicate[LEFT] = firedAdapter[LEFT]; firedAdapter[LEFT] = true; memberAdapter[LEFT] = event.getDistributedMember(); memberIdAdapter[LEFT] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[LEFT] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberCrashed(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberCrashed >" + event.getMemberId() + "<"); firedAdapterDuplicate[CRASHED] = firedAdapter[CRASHED]; firedAdapter[CRASHED] = true; memberAdapter[CRASHED] = event.getDistributedMember(); memberIdAdapter[CRASHED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[CRASHED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } }; BridgeMembershipListener bridgeListener = new BridgeMembershipListener() { public synchronized void memberJoined(BridgeMembershipEvent event) { firedBridgeDuplicate[JOINED] = firedBridge[JOINED]; firedBridge[JOINED] = true; memberBridge[JOINED] = event.getMember(); memberIdBridge[JOINED] = event.getMemberId(); isClientBridge[JOINED] = event.isClient(); notify(); } public synchronized void memberLeft(BridgeMembershipEvent event) { firedBridgeDuplicate[LEFT] = firedBridge[LEFT]; firedBridge[LEFT] = true; memberBridge[LEFT] = event.getMember(); memberIdBridge[LEFT] = event.getMemberId(); isClientBridge[LEFT] = event.isClient(); notify(); } public synchronized void memberCrashed(BridgeMembershipEvent event) { firedBridgeDuplicate[CRASHED] = firedBridge[CRASHED]; firedBridge[CRASHED] = true; memberBridge[CRASHED] = event.getMember(); memberIdBridge[CRASHED] = event.getMemberId(); isClientBridge[CRASHED] = event.isClient(); notify(); } }; final Host host = Host.getHost(0); final VM vm0 = host.getVM(0); final String name = this.getUniqueName(); final int[] ports = new int[] { AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) }; assertTrue(ports[0] != 0); // getLogWriter().info("[testServerEventsInSystemClient] create bridge client"); // Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); Region region = createRegion(name, factory.create()); assertNotNull(region); assertNotNull(getRootRegion().getSubregion(name)); try { testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e); fail(e.getMessage()); } } }; vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); String serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); DistributedMember serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); // create region which connects to bridge server AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); createRegion(name, factory.create()); assertNotNull(getRootRegion().getSubregion(name)); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); getLogWriter().info("[testServerEventsInSystemClient] wait for client to fully connect"); final String pl = getRootRegion().getSubregion(name).getAttributes().getPoolName(); PoolImpl pi = (PoolImpl)PoolManager.find(pl); waitForClientToFullyConnect(pi); LogWriter bgexecLogger = new LocalLogWriter(LogWriterImpl.ALL_LEVEL, System.out); bgexecLogger.info("<ExpectedException action=add>" + "java.io.IOException" + "</ExpectedException>"); final ExpectedException ex = addExpectedException( ServerConnectivityException.class.getName()); try { vm0.invoke(new SerializableRunnable("Disconnect bridge server") { public void run() { getLogWriter().info("[testServerEventsInSystemClient] disconnect bridge server"); closeCache(); disconnectFromDS(); } }); synchronized(systemListener) { if (!firedSystem[LEFT]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[LEFT]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); // KIRK: did increasing this solve problem on balrog? } } synchronized(bridgeListener) { if (!firedBridge[LEFT]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } } finally { bgexecLogger.info("<ExpectedException action=remove>" + "java.io.IOException" + "</ExpectedException>"); ex.remove(); } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server crashed"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertFalse(firedBridge[JOINED]); assertNull(memberIdBridge[JOINED]); assertNull(memberBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse("Please update testServerEventsInSystemClient to handle memberLeft for BridgeServer.", firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertTrue(firedBridge[CRASHED]); assertNotNull(memberBridge[CRASHED]); assertNotNull(memberIdBridge[CRASHED]); assertEquals(serverMemberId, memberIdBridge[CRASHED]); assertEquals(serverMember, memberBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertFalse(firedSystem[JOINED]); assertNull(memberSystem[JOINED]); assertNull(memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertTrue(firedSystem[LEFT]); assertEquals(serverMember, memberSystem[LEFT]); assertEquals(serverMemberId, memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertFalse("this intermittently fails", firedAdapter[JOINED]); // KIRK --> this fails on balrog occasionally assertNull(memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); // LEFT fired by System listener assertTrue(firedAdapter[LEFT]); assertEquals(serverMember, memberAdapter[LEFT]); assertEquals(serverMemberId, memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); // There won't be an adapter crashed event because since the two VMs // are in the same distributed system, and the server's real member // id is used now. In this case, two events are sent - one from // jgroups (memberDeparted), and one from the server (a memberCrshed). // The memberCrashed event is deemed a duplicate and not sent - see // UniversalMembershipListenerAdapter.SystemMembershipListener.isDuplicate assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); // reconnect bridge client to test for crashed event vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server re-join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); }
NONSATD
true
getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config =
// config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter
}; final Host host = Host.getHost(0); final VM vm0 = host.getVM(0); final String name = this.getUniqueName(); final int[] ports = new int[] { AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) }; assertTrue(ports[0] != 0); // getLogWriter().info("[testServerEventsInSystemClient] create bridge client"); // Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL);
15,012
3
// register the system listener
private void doTestServerEventsInSystemClient() throws Exception { // KIRK: this test fails intermittently with bug 37482 final boolean[] firedSystem = new boolean[3]; final DistributedMember[] memberSystem = new DistributedMember[3]; final String[] memberIdSystem = new String[3]; final boolean[] isClientSystem = new boolean[3]; final boolean[] firedAdapter = new boolean[3]; final DistributedMember[] memberAdapter = new DistributedMember[3]; final String[] memberIdAdapter = new String[3]; final boolean[] isClientAdapter = new boolean[3]; final boolean[] firedBridge = new boolean[3]; final DistributedMember[] memberBridge = new DistributedMember[3]; final String[] memberIdBridge = new String[3]; final boolean[] isClientBridge = new boolean[3]; final boolean[] firedSystemDuplicate = new boolean[3]; final boolean[] firedAdapterDuplicate = new boolean[3]; final boolean[] firedBridgeDuplicate = new boolean[3]; SystemMembershipListener systemListener = new SystemMembershipListener() { public synchronized void memberJoined(SystemMembershipEvent event) { firedSystemDuplicate[JOINED] = firedSystem[JOINED]; firedSystem[JOINED] = true; memberSystem[JOINED] = event.getDistributedMember(); memberIdSystem[JOINED] = event.getMemberId(); notify(); } public synchronized void memberLeft(SystemMembershipEvent event) { firedSystemDuplicate[LEFT] = firedSystem[LEFT]; firedSystem[LEFT] = true; memberSystem[LEFT] = event.getDistributedMember(); memberIdSystem[LEFT] = event.getMemberId(); notify(); } public synchronized void memberCrashed(SystemMembershipEvent event) { firedSystemDuplicate[CRASHED] = firedSystem[CRASHED]; firedSystem[CRASHED] = true; memberSystem[CRASHED] = event.getDistributedMember(); memberIdSystem[CRASHED] = event.getMemberId(); notify(); } }; UniversalMembershipListenerAdapter adapter = new UniversalMembershipListenerAdapter() { @Override public synchronized void memberJoined(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberJoined >" + event.getMemberId() + "<"); firedAdapterDuplicate[JOINED] = firedAdapter[JOINED]; firedAdapter[JOINED] = true; memberAdapter[JOINED] = event.getDistributedMember(); memberIdAdapter[JOINED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[JOINED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberLeft(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberLeft >" + event.getMemberId() + "<"); firedAdapterDuplicate[LEFT] = firedAdapter[LEFT]; firedAdapter[LEFT] = true; memberAdapter[LEFT] = event.getDistributedMember(); memberIdAdapter[LEFT] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[LEFT] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberCrashed(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberCrashed >" + event.getMemberId() + "<"); firedAdapterDuplicate[CRASHED] = firedAdapter[CRASHED]; firedAdapter[CRASHED] = true; memberAdapter[CRASHED] = event.getDistributedMember(); memberIdAdapter[CRASHED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[CRASHED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } }; BridgeMembershipListener bridgeListener = new BridgeMembershipListener() { public synchronized void memberJoined(BridgeMembershipEvent event) { firedBridgeDuplicate[JOINED] = firedBridge[JOINED]; firedBridge[JOINED] = true; memberBridge[JOINED] = event.getMember(); memberIdBridge[JOINED] = event.getMemberId(); isClientBridge[JOINED] = event.isClient(); notify(); } public synchronized void memberLeft(BridgeMembershipEvent event) { firedBridgeDuplicate[LEFT] = firedBridge[LEFT]; firedBridge[LEFT] = true; memberBridge[LEFT] = event.getMember(); memberIdBridge[LEFT] = event.getMemberId(); isClientBridge[LEFT] = event.isClient(); notify(); } public synchronized void memberCrashed(BridgeMembershipEvent event) { firedBridgeDuplicate[CRASHED] = firedBridge[CRASHED]; firedBridge[CRASHED] = true; memberBridge[CRASHED] = event.getMember(); memberIdBridge[CRASHED] = event.getMemberId(); isClientBridge[CRASHED] = event.isClient(); notify(); } }; final Host host = Host.getHost(0); final VM vm0 = host.getVM(0); final String name = this.getUniqueName(); final int[] ports = new int[] { AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) }; assertTrue(ports[0] != 0); // getLogWriter().info("[testServerEventsInSystemClient] create bridge client"); // Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); Region region = createRegion(name, factory.create()); assertNotNull(region); assertNotNull(getRootRegion().getSubregion(name)); try { testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e); fail(e.getMessage()); } } }; vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); String serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); DistributedMember serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); // create region which connects to bridge server AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); createRegion(name, factory.create()); assertNotNull(getRootRegion().getSubregion(name)); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); getLogWriter().info("[testServerEventsInSystemClient] wait for client to fully connect"); final String pl = getRootRegion().getSubregion(name).getAttributes().getPoolName(); PoolImpl pi = (PoolImpl)PoolManager.find(pl); waitForClientToFullyConnect(pi); LogWriter bgexecLogger = new LocalLogWriter(LogWriterImpl.ALL_LEVEL, System.out); bgexecLogger.info("<ExpectedException action=add>" + "java.io.IOException" + "</ExpectedException>"); final ExpectedException ex = addExpectedException( ServerConnectivityException.class.getName()); try { vm0.invoke(new SerializableRunnable("Disconnect bridge server") { public void run() { getLogWriter().info("[testServerEventsInSystemClient] disconnect bridge server"); closeCache(); disconnectFromDS(); } }); synchronized(systemListener) { if (!firedSystem[LEFT]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[LEFT]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); // KIRK: did increasing this solve problem on balrog? } } synchronized(bridgeListener) { if (!firedBridge[LEFT]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } } finally { bgexecLogger.info("<ExpectedException action=remove>" + "java.io.IOException" + "</ExpectedException>"); ex.remove(); } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server crashed"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertFalse(firedBridge[JOINED]); assertNull(memberIdBridge[JOINED]); assertNull(memberBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse("Please update testServerEventsInSystemClient to handle memberLeft for BridgeServer.", firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertTrue(firedBridge[CRASHED]); assertNotNull(memberBridge[CRASHED]); assertNotNull(memberIdBridge[CRASHED]); assertEquals(serverMemberId, memberIdBridge[CRASHED]); assertEquals(serverMember, memberBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertFalse(firedSystem[JOINED]); assertNull(memberSystem[JOINED]); assertNull(memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertTrue(firedSystem[LEFT]); assertEquals(serverMember, memberSystem[LEFT]); assertEquals(serverMemberId, memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertFalse("this intermittently fails", firedAdapter[JOINED]); // KIRK --> this fails on balrog occasionally assertNull(memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); // LEFT fired by System listener assertTrue(firedAdapter[LEFT]); assertEquals(serverMember, memberAdapter[LEFT]); assertEquals(serverMemberId, memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); // There won't be an adapter crashed event because since the two VMs // are in the same distributed system, and the server's real member // id is used now. In this case, two events are sent - one from // jgroups (memberDeparted), and one from the server (a memberCrshed). // The memberCrashed event is deemed a duplicate and not sent - see // UniversalMembershipListenerAdapter.SystemMembershipListener.isDuplicate assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); // reconnect bridge client to test for crashed event vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server re-join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); }
NONSATD
true
adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter
getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties);
// Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); Region region = createRegion(name, factory.create()); assertNotNull(region); assertNotNull(getRootRegion().getSubregion(name)); try { testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e);
15,012
4
// register the universal adapter
private void doTestServerEventsInSystemClient() throws Exception { // KIRK: this test fails intermittently with bug 37482 final boolean[] firedSystem = new boolean[3]; final DistributedMember[] memberSystem = new DistributedMember[3]; final String[] memberIdSystem = new String[3]; final boolean[] isClientSystem = new boolean[3]; final boolean[] firedAdapter = new boolean[3]; final DistributedMember[] memberAdapter = new DistributedMember[3]; final String[] memberIdAdapter = new String[3]; final boolean[] isClientAdapter = new boolean[3]; final boolean[] firedBridge = new boolean[3]; final DistributedMember[] memberBridge = new DistributedMember[3]; final String[] memberIdBridge = new String[3]; final boolean[] isClientBridge = new boolean[3]; final boolean[] firedSystemDuplicate = new boolean[3]; final boolean[] firedAdapterDuplicate = new boolean[3]; final boolean[] firedBridgeDuplicate = new boolean[3]; SystemMembershipListener systemListener = new SystemMembershipListener() { public synchronized void memberJoined(SystemMembershipEvent event) { firedSystemDuplicate[JOINED] = firedSystem[JOINED]; firedSystem[JOINED] = true; memberSystem[JOINED] = event.getDistributedMember(); memberIdSystem[JOINED] = event.getMemberId(); notify(); } public synchronized void memberLeft(SystemMembershipEvent event) { firedSystemDuplicate[LEFT] = firedSystem[LEFT]; firedSystem[LEFT] = true; memberSystem[LEFT] = event.getDistributedMember(); memberIdSystem[LEFT] = event.getMemberId(); notify(); } public synchronized void memberCrashed(SystemMembershipEvent event) { firedSystemDuplicate[CRASHED] = firedSystem[CRASHED]; firedSystem[CRASHED] = true; memberSystem[CRASHED] = event.getDistributedMember(); memberIdSystem[CRASHED] = event.getMemberId(); notify(); } }; UniversalMembershipListenerAdapter adapter = new UniversalMembershipListenerAdapter() { @Override public synchronized void memberJoined(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberJoined >" + event.getMemberId() + "<"); firedAdapterDuplicate[JOINED] = firedAdapter[JOINED]; firedAdapter[JOINED] = true; memberAdapter[JOINED] = event.getDistributedMember(); memberIdAdapter[JOINED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[JOINED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberLeft(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberLeft >" + event.getMemberId() + "<"); firedAdapterDuplicate[LEFT] = firedAdapter[LEFT]; firedAdapter[LEFT] = true; memberAdapter[LEFT] = event.getDistributedMember(); memberIdAdapter[LEFT] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[LEFT] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberCrashed(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberCrashed >" + event.getMemberId() + "<"); firedAdapterDuplicate[CRASHED] = firedAdapter[CRASHED]; firedAdapter[CRASHED] = true; memberAdapter[CRASHED] = event.getDistributedMember(); memberIdAdapter[CRASHED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[CRASHED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } }; BridgeMembershipListener bridgeListener = new BridgeMembershipListener() { public synchronized void memberJoined(BridgeMembershipEvent event) { firedBridgeDuplicate[JOINED] = firedBridge[JOINED]; firedBridge[JOINED] = true; memberBridge[JOINED] = event.getMember(); memberIdBridge[JOINED] = event.getMemberId(); isClientBridge[JOINED] = event.isClient(); notify(); } public synchronized void memberLeft(BridgeMembershipEvent event) { firedBridgeDuplicate[LEFT] = firedBridge[LEFT]; firedBridge[LEFT] = true; memberBridge[LEFT] = event.getMember(); memberIdBridge[LEFT] = event.getMemberId(); isClientBridge[LEFT] = event.isClient(); notify(); } public synchronized void memberCrashed(BridgeMembershipEvent event) { firedBridgeDuplicate[CRASHED] = firedBridge[CRASHED]; firedBridge[CRASHED] = true; memberBridge[CRASHED] = event.getMember(); memberIdBridge[CRASHED] = event.getMemberId(); isClientBridge[CRASHED] = event.isClient(); notify(); } }; final Host host = Host.getHost(0); final VM vm0 = host.getVM(0); final String name = this.getUniqueName(); final int[] ports = new int[] { AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) }; assertTrue(ports[0] != 0); // getLogWriter().info("[testServerEventsInSystemClient] create bridge client"); // Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); Region region = createRegion(name, factory.create()); assertNotNull(region); assertNotNull(getRootRegion().getSubregion(name)); try { testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e); fail(e.getMessage()); } } }; vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); String serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); DistributedMember serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); // create region which connects to bridge server AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); createRegion(name, factory.create()); assertNotNull(getRootRegion().getSubregion(name)); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); getLogWriter().info("[testServerEventsInSystemClient] wait for client to fully connect"); final String pl = getRootRegion().getSubregion(name).getAttributes().getPoolName(); PoolImpl pi = (PoolImpl)PoolManager.find(pl); waitForClientToFullyConnect(pi); LogWriter bgexecLogger = new LocalLogWriter(LogWriterImpl.ALL_LEVEL, System.out); bgexecLogger.info("<ExpectedException action=add>" + "java.io.IOException" + "</ExpectedException>"); final ExpectedException ex = addExpectedException( ServerConnectivityException.class.getName()); try { vm0.invoke(new SerializableRunnable("Disconnect bridge server") { public void run() { getLogWriter().info("[testServerEventsInSystemClient] disconnect bridge server"); closeCache(); disconnectFromDS(); } }); synchronized(systemListener) { if (!firedSystem[LEFT]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[LEFT]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); // KIRK: did increasing this solve problem on balrog? } } synchronized(bridgeListener) { if (!firedBridge[LEFT]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } } finally { bgexecLogger.info("<ExpectedException action=remove>" + "java.io.IOException" + "</ExpectedException>"); ex.remove(); } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server crashed"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertFalse(firedBridge[JOINED]); assertNull(memberIdBridge[JOINED]); assertNull(memberBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse("Please update testServerEventsInSystemClient to handle memberLeft for BridgeServer.", firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertTrue(firedBridge[CRASHED]); assertNotNull(memberBridge[CRASHED]); assertNotNull(memberIdBridge[CRASHED]); assertEquals(serverMemberId, memberIdBridge[CRASHED]); assertEquals(serverMember, memberBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertFalse(firedSystem[JOINED]); assertNull(memberSystem[JOINED]); assertNull(memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertTrue(firedSystem[LEFT]); assertEquals(serverMember, memberSystem[LEFT]); assertEquals(serverMemberId, memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertFalse("this intermittently fails", firedAdapter[JOINED]); // KIRK --> this fails on balrog occasionally assertNull(memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); // LEFT fired by System listener assertTrue(firedAdapter[LEFT]); assertEquals(serverMember, memberAdapter[LEFT]); assertEquals(serverMemberId, memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); // There won't be an adapter crashed event because since the two VMs // are in the same distributed system, and the server's real member // id is used now. In this case, two events are sent - one from // jgroups (memberDeparted), and one from the server (a memberCrshed). // The memberCrashed event is deemed a duplicate and not sent - see // UniversalMembershipListenerAdapter.SystemMembershipListener.isDuplicate assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); // reconnect bridge client to test for crashed event vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server re-join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); }
NONSATD
true
// register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0...
// register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL);
// config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); Region region = createRegion(name, factory.create()); assertNotNull(region); assertNotNull(getRootRegion().getSubregion(name)); try { testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e); fail(e.getMessage()); }
15,012
5
// create BridgeServer in vm0...
private void doTestServerEventsInSystemClient() throws Exception { // KIRK: this test fails intermittently with bug 37482 final boolean[] firedSystem = new boolean[3]; final DistributedMember[] memberSystem = new DistributedMember[3]; final String[] memberIdSystem = new String[3]; final boolean[] isClientSystem = new boolean[3]; final boolean[] firedAdapter = new boolean[3]; final DistributedMember[] memberAdapter = new DistributedMember[3]; final String[] memberIdAdapter = new String[3]; final boolean[] isClientAdapter = new boolean[3]; final boolean[] firedBridge = new boolean[3]; final DistributedMember[] memberBridge = new DistributedMember[3]; final String[] memberIdBridge = new String[3]; final boolean[] isClientBridge = new boolean[3]; final boolean[] firedSystemDuplicate = new boolean[3]; final boolean[] firedAdapterDuplicate = new boolean[3]; final boolean[] firedBridgeDuplicate = new boolean[3]; SystemMembershipListener systemListener = new SystemMembershipListener() { public synchronized void memberJoined(SystemMembershipEvent event) { firedSystemDuplicate[JOINED] = firedSystem[JOINED]; firedSystem[JOINED] = true; memberSystem[JOINED] = event.getDistributedMember(); memberIdSystem[JOINED] = event.getMemberId(); notify(); } public synchronized void memberLeft(SystemMembershipEvent event) { firedSystemDuplicate[LEFT] = firedSystem[LEFT]; firedSystem[LEFT] = true; memberSystem[LEFT] = event.getDistributedMember(); memberIdSystem[LEFT] = event.getMemberId(); notify(); } public synchronized void memberCrashed(SystemMembershipEvent event) { firedSystemDuplicate[CRASHED] = firedSystem[CRASHED]; firedSystem[CRASHED] = true; memberSystem[CRASHED] = event.getDistributedMember(); memberIdSystem[CRASHED] = event.getMemberId(); notify(); } }; UniversalMembershipListenerAdapter adapter = new UniversalMembershipListenerAdapter() { @Override public synchronized void memberJoined(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberJoined >" + event.getMemberId() + "<"); firedAdapterDuplicate[JOINED] = firedAdapter[JOINED]; firedAdapter[JOINED] = true; memberAdapter[JOINED] = event.getDistributedMember(); memberIdAdapter[JOINED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[JOINED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberLeft(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberLeft >" + event.getMemberId() + "<"); firedAdapterDuplicate[LEFT] = firedAdapter[LEFT]; firedAdapter[LEFT] = true; memberAdapter[LEFT] = event.getDistributedMember(); memberIdAdapter[LEFT] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[LEFT] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberCrashed(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberCrashed >" + event.getMemberId() + "<"); firedAdapterDuplicate[CRASHED] = firedAdapter[CRASHED]; firedAdapter[CRASHED] = true; memberAdapter[CRASHED] = event.getDistributedMember(); memberIdAdapter[CRASHED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[CRASHED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } }; BridgeMembershipListener bridgeListener = new BridgeMembershipListener() { public synchronized void memberJoined(BridgeMembershipEvent event) { firedBridgeDuplicate[JOINED] = firedBridge[JOINED]; firedBridge[JOINED] = true; memberBridge[JOINED] = event.getMember(); memberIdBridge[JOINED] = event.getMemberId(); isClientBridge[JOINED] = event.isClient(); notify(); } public synchronized void memberLeft(BridgeMembershipEvent event) { firedBridgeDuplicate[LEFT] = firedBridge[LEFT]; firedBridge[LEFT] = true; memberBridge[LEFT] = event.getMember(); memberIdBridge[LEFT] = event.getMemberId(); isClientBridge[LEFT] = event.isClient(); notify(); } public synchronized void memberCrashed(BridgeMembershipEvent event) { firedBridgeDuplicate[CRASHED] = firedBridge[CRASHED]; firedBridge[CRASHED] = true; memberBridge[CRASHED] = event.getMember(); memberIdBridge[CRASHED] = event.getMemberId(); isClientBridge[CRASHED] = event.isClient(); notify(); } }; final Host host = Host.getHost(0); final VM vm0 = host.getVM(0); final String name = this.getUniqueName(); final int[] ports = new int[] { AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) }; assertTrue(ports[0] != 0); // getLogWriter().info("[testServerEventsInSystemClient] create bridge client"); // Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); Region region = createRegion(name, factory.create()); assertNotNull(region); assertNotNull(getRootRegion().getSubregion(name)); try { testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e); fail(e.getMessage()); } } }; vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); String serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); DistributedMember serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); // create region which connects to bridge server AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); createRegion(name, factory.create()); assertNotNull(getRootRegion().getSubregion(name)); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); getLogWriter().info("[testServerEventsInSystemClient] wait for client to fully connect"); final String pl = getRootRegion().getSubregion(name).getAttributes().getPoolName(); PoolImpl pi = (PoolImpl)PoolManager.find(pl); waitForClientToFullyConnect(pi); LogWriter bgexecLogger = new LocalLogWriter(LogWriterImpl.ALL_LEVEL, System.out); bgexecLogger.info("<ExpectedException action=add>" + "java.io.IOException" + "</ExpectedException>"); final ExpectedException ex = addExpectedException( ServerConnectivityException.class.getName()); try { vm0.invoke(new SerializableRunnable("Disconnect bridge server") { public void run() { getLogWriter().info("[testServerEventsInSystemClient] disconnect bridge server"); closeCache(); disconnectFromDS(); } }); synchronized(systemListener) { if (!firedSystem[LEFT]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[LEFT]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); // KIRK: did increasing this solve problem on balrog? } } synchronized(bridgeListener) { if (!firedBridge[LEFT]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } } finally { bgexecLogger.info("<ExpectedException action=remove>" + "java.io.IOException" + "</ExpectedException>"); ex.remove(); } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server crashed"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertFalse(firedBridge[JOINED]); assertNull(memberIdBridge[JOINED]); assertNull(memberBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse("Please update testServerEventsInSystemClient to handle memberLeft for BridgeServer.", firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertTrue(firedBridge[CRASHED]); assertNotNull(memberBridge[CRASHED]); assertNotNull(memberIdBridge[CRASHED]); assertEquals(serverMemberId, memberIdBridge[CRASHED]); assertEquals(serverMember, memberBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertFalse(firedSystem[JOINED]); assertNull(memberSystem[JOINED]); assertNull(memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertTrue(firedSystem[LEFT]); assertEquals(serverMember, memberSystem[LEFT]); assertEquals(serverMemberId, memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertFalse("this intermittently fails", firedAdapter[JOINED]); // KIRK --> this fails on balrog occasionally assertNull(memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); // LEFT fired by System listener assertTrue(firedAdapter[LEFT]); assertEquals(serverMember, memberAdapter[LEFT]); assertEquals(serverMemberId, memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); // There won't be an adapter crashed event because since the two VMs // are in the same distributed system, and the server's real member // id is used now. In this case, two events are sent - one from // jgroups (memberDeparted), and one from the server (a memberCrshed). // The memberCrashed event is deemed a duplicate and not sent - see // UniversalMembershipListenerAdapter.SystemMembershipListener.isDuplicate assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); // reconnect bridge client to test for crashed event vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server re-join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); }
NONSATD
true
// register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") {
DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); Region region = createRegion(name, factory.create()); assertNotNull(region);
// AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); Region region = createRegion(name, factory.create()); assertNotNull(region); assertNotNull(getRootRegion().getSubregion(name)); try { testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e); fail(e.getMessage()); } } };
15,012
6
// gather details for later creation of BridgeLoader...
private void doTestServerEventsInSystemClient() throws Exception { // KIRK: this test fails intermittently with bug 37482 final boolean[] firedSystem = new boolean[3]; final DistributedMember[] memberSystem = new DistributedMember[3]; final String[] memberIdSystem = new String[3]; final boolean[] isClientSystem = new boolean[3]; final boolean[] firedAdapter = new boolean[3]; final DistributedMember[] memberAdapter = new DistributedMember[3]; final String[] memberIdAdapter = new String[3]; final boolean[] isClientAdapter = new boolean[3]; final boolean[] firedBridge = new boolean[3]; final DistributedMember[] memberBridge = new DistributedMember[3]; final String[] memberIdBridge = new String[3]; final boolean[] isClientBridge = new boolean[3]; final boolean[] firedSystemDuplicate = new boolean[3]; final boolean[] firedAdapterDuplicate = new boolean[3]; final boolean[] firedBridgeDuplicate = new boolean[3]; SystemMembershipListener systemListener = new SystemMembershipListener() { public synchronized void memberJoined(SystemMembershipEvent event) { firedSystemDuplicate[JOINED] = firedSystem[JOINED]; firedSystem[JOINED] = true; memberSystem[JOINED] = event.getDistributedMember(); memberIdSystem[JOINED] = event.getMemberId(); notify(); } public synchronized void memberLeft(SystemMembershipEvent event) { firedSystemDuplicate[LEFT] = firedSystem[LEFT]; firedSystem[LEFT] = true; memberSystem[LEFT] = event.getDistributedMember(); memberIdSystem[LEFT] = event.getMemberId(); notify(); } public synchronized void memberCrashed(SystemMembershipEvent event) { firedSystemDuplicate[CRASHED] = firedSystem[CRASHED]; firedSystem[CRASHED] = true; memberSystem[CRASHED] = event.getDistributedMember(); memberIdSystem[CRASHED] = event.getMemberId(); notify(); } }; UniversalMembershipListenerAdapter adapter = new UniversalMembershipListenerAdapter() { @Override public synchronized void memberJoined(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberJoined >" + event.getMemberId() + "<"); firedAdapterDuplicate[JOINED] = firedAdapter[JOINED]; firedAdapter[JOINED] = true; memberAdapter[JOINED] = event.getDistributedMember(); memberIdAdapter[JOINED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[JOINED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberLeft(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberLeft >" + event.getMemberId() + "<"); firedAdapterDuplicate[LEFT] = firedAdapter[LEFT]; firedAdapter[LEFT] = true; memberAdapter[LEFT] = event.getDistributedMember(); memberIdAdapter[LEFT] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[LEFT] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberCrashed(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberCrashed >" + event.getMemberId() + "<"); firedAdapterDuplicate[CRASHED] = firedAdapter[CRASHED]; firedAdapter[CRASHED] = true; memberAdapter[CRASHED] = event.getDistributedMember(); memberIdAdapter[CRASHED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[CRASHED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } }; BridgeMembershipListener bridgeListener = new BridgeMembershipListener() { public synchronized void memberJoined(BridgeMembershipEvent event) { firedBridgeDuplicate[JOINED] = firedBridge[JOINED]; firedBridge[JOINED] = true; memberBridge[JOINED] = event.getMember(); memberIdBridge[JOINED] = event.getMemberId(); isClientBridge[JOINED] = event.isClient(); notify(); } public synchronized void memberLeft(BridgeMembershipEvent event) { firedBridgeDuplicate[LEFT] = firedBridge[LEFT]; firedBridge[LEFT] = true; memberBridge[LEFT] = event.getMember(); memberIdBridge[LEFT] = event.getMemberId(); isClientBridge[LEFT] = event.isClient(); notify(); } public synchronized void memberCrashed(BridgeMembershipEvent event) { firedBridgeDuplicate[CRASHED] = firedBridge[CRASHED]; firedBridge[CRASHED] = true; memberBridge[CRASHED] = event.getMember(); memberIdBridge[CRASHED] = event.getMemberId(); isClientBridge[CRASHED] = event.isClient(); notify(); } }; final Host host = Host.getHost(0); final VM vm0 = host.getVM(0); final String name = this.getUniqueName(); final int[] ports = new int[] { AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) }; assertTrue(ports[0] != 0); // getLogWriter().info("[testServerEventsInSystemClient] create bridge client"); // Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); Region region = createRegion(name, factory.create()); assertNotNull(region); assertNotNull(getRootRegion().getSubregion(name)); try { testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e); fail(e.getMessage()); } } }; vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); String serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); DistributedMember serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); // create region which connects to bridge server AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); createRegion(name, factory.create()); assertNotNull(getRootRegion().getSubregion(name)); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); getLogWriter().info("[testServerEventsInSystemClient] wait for client to fully connect"); final String pl = getRootRegion().getSubregion(name).getAttributes().getPoolName(); PoolImpl pi = (PoolImpl)PoolManager.find(pl); waitForClientToFullyConnect(pi); LogWriter bgexecLogger = new LocalLogWriter(LogWriterImpl.ALL_LEVEL, System.out); bgexecLogger.info("<ExpectedException action=add>" + "java.io.IOException" + "</ExpectedException>"); final ExpectedException ex = addExpectedException( ServerConnectivityException.class.getName()); try { vm0.invoke(new SerializableRunnable("Disconnect bridge server") { public void run() { getLogWriter().info("[testServerEventsInSystemClient] disconnect bridge server"); closeCache(); disconnectFromDS(); } }); synchronized(systemListener) { if (!firedSystem[LEFT]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[LEFT]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); // KIRK: did increasing this solve problem on balrog? } } synchronized(bridgeListener) { if (!firedBridge[LEFT]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } } finally { bgexecLogger.info("<ExpectedException action=remove>" + "java.io.IOException" + "</ExpectedException>"); ex.remove(); } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server crashed"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertFalse(firedBridge[JOINED]); assertNull(memberIdBridge[JOINED]); assertNull(memberBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse("Please update testServerEventsInSystemClient to handle memberLeft for BridgeServer.", firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertTrue(firedBridge[CRASHED]); assertNotNull(memberBridge[CRASHED]); assertNotNull(memberIdBridge[CRASHED]); assertEquals(serverMemberId, memberIdBridge[CRASHED]); assertEquals(serverMember, memberBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertFalse(firedSystem[JOINED]); assertNull(memberSystem[JOINED]); assertNull(memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertTrue(firedSystem[LEFT]); assertEquals(serverMember, memberSystem[LEFT]); assertEquals(serverMemberId, memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertFalse("this intermittently fails", firedAdapter[JOINED]); // KIRK --> this fails on balrog occasionally assertNull(memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); // LEFT fired by System listener assertTrue(firedAdapter[LEFT]); assertEquals(serverMember, memberAdapter[LEFT]); assertEquals(serverMemberId, memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); // There won't be an adapter crashed event because since the two VMs // are in the same distributed system, and the server's real member // id is used now. In this case, two events are sent - one from // jgroups (memberDeparted), and one from the server (a memberCrshed). // The memberCrashed event is deemed a duplicate and not sent - see // UniversalMembershipListenerAdapter.SystemMembershipListener.isDuplicate assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); // reconnect bridge client to test for crashed event vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server re-join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); }
NONSATD
true
}; vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class,
try { testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e); fail(e.getMessage()); } } }; vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); String serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); DistributedMember serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember);
new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); Region region = createRegion(name, factory.create()); assertNotNull(region); assertNotNull(getRootRegion().getSubregion(name)); try { testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e); fail(e.getMessage()); } } }; vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); String serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); DistributedMember serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); // create region which connects to bridge server AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); createRegion(name, factory.create()); assertNotNull(getRootRegion().getSubregion(name)); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); }
15,012
7
// create region which connects to bridge server
private void doTestServerEventsInSystemClient() throws Exception { // KIRK: this test fails intermittently with bug 37482 final boolean[] firedSystem = new boolean[3]; final DistributedMember[] memberSystem = new DistributedMember[3]; final String[] memberIdSystem = new String[3]; final boolean[] isClientSystem = new boolean[3]; final boolean[] firedAdapter = new boolean[3]; final DistributedMember[] memberAdapter = new DistributedMember[3]; final String[] memberIdAdapter = new String[3]; final boolean[] isClientAdapter = new boolean[3]; final boolean[] firedBridge = new boolean[3]; final DistributedMember[] memberBridge = new DistributedMember[3]; final String[] memberIdBridge = new String[3]; final boolean[] isClientBridge = new boolean[3]; final boolean[] firedSystemDuplicate = new boolean[3]; final boolean[] firedAdapterDuplicate = new boolean[3]; final boolean[] firedBridgeDuplicate = new boolean[3]; SystemMembershipListener systemListener = new SystemMembershipListener() { public synchronized void memberJoined(SystemMembershipEvent event) { firedSystemDuplicate[JOINED] = firedSystem[JOINED]; firedSystem[JOINED] = true; memberSystem[JOINED] = event.getDistributedMember(); memberIdSystem[JOINED] = event.getMemberId(); notify(); } public synchronized void memberLeft(SystemMembershipEvent event) { firedSystemDuplicate[LEFT] = firedSystem[LEFT]; firedSystem[LEFT] = true; memberSystem[LEFT] = event.getDistributedMember(); memberIdSystem[LEFT] = event.getMemberId(); notify(); } public synchronized void memberCrashed(SystemMembershipEvent event) { firedSystemDuplicate[CRASHED] = firedSystem[CRASHED]; firedSystem[CRASHED] = true; memberSystem[CRASHED] = event.getDistributedMember(); memberIdSystem[CRASHED] = event.getMemberId(); notify(); } }; UniversalMembershipListenerAdapter adapter = new UniversalMembershipListenerAdapter() { @Override public synchronized void memberJoined(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberJoined >" + event.getMemberId() + "<"); firedAdapterDuplicate[JOINED] = firedAdapter[JOINED]; firedAdapter[JOINED] = true; memberAdapter[JOINED] = event.getDistributedMember(); memberIdAdapter[JOINED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[JOINED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberLeft(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberLeft >" + event.getMemberId() + "<"); firedAdapterDuplicate[LEFT] = firedAdapter[LEFT]; firedAdapter[LEFT] = true; memberAdapter[LEFT] = event.getDistributedMember(); memberIdAdapter[LEFT] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[LEFT] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberCrashed(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberCrashed >" + event.getMemberId() + "<"); firedAdapterDuplicate[CRASHED] = firedAdapter[CRASHED]; firedAdapter[CRASHED] = true; memberAdapter[CRASHED] = event.getDistributedMember(); memberIdAdapter[CRASHED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[CRASHED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } }; BridgeMembershipListener bridgeListener = new BridgeMembershipListener() { public synchronized void memberJoined(BridgeMembershipEvent event) { firedBridgeDuplicate[JOINED] = firedBridge[JOINED]; firedBridge[JOINED] = true; memberBridge[JOINED] = event.getMember(); memberIdBridge[JOINED] = event.getMemberId(); isClientBridge[JOINED] = event.isClient(); notify(); } public synchronized void memberLeft(BridgeMembershipEvent event) { firedBridgeDuplicate[LEFT] = firedBridge[LEFT]; firedBridge[LEFT] = true; memberBridge[LEFT] = event.getMember(); memberIdBridge[LEFT] = event.getMemberId(); isClientBridge[LEFT] = event.isClient(); notify(); } public synchronized void memberCrashed(BridgeMembershipEvent event) { firedBridgeDuplicate[CRASHED] = firedBridge[CRASHED]; firedBridge[CRASHED] = true; memberBridge[CRASHED] = event.getMember(); memberIdBridge[CRASHED] = event.getMemberId(); isClientBridge[CRASHED] = event.isClient(); notify(); } }; final Host host = Host.getHost(0); final VM vm0 = host.getVM(0); final String name = this.getUniqueName(); final int[] ports = new int[] { AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) }; assertTrue(ports[0] != 0); // getLogWriter().info("[testServerEventsInSystemClient] create bridge client"); // Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); Region region = createRegion(name, factory.create()); assertNotNull(region); assertNotNull(getRootRegion().getSubregion(name)); try { testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e); fail(e.getMessage()); } } }; vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); String serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); DistributedMember serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); // create region which connects to bridge server AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); createRegion(name, factory.create()); assertNotNull(getRootRegion().getSubregion(name)); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); getLogWriter().info("[testServerEventsInSystemClient] wait for client to fully connect"); final String pl = getRootRegion().getSubregion(name).getAttributes().getPoolName(); PoolImpl pi = (PoolImpl)PoolManager.find(pl); waitForClientToFullyConnect(pi); LogWriter bgexecLogger = new LocalLogWriter(LogWriterImpl.ALL_LEVEL, System.out); bgexecLogger.info("<ExpectedException action=add>" + "java.io.IOException" + "</ExpectedException>"); final ExpectedException ex = addExpectedException( ServerConnectivityException.class.getName()); try { vm0.invoke(new SerializableRunnable("Disconnect bridge server") { public void run() { getLogWriter().info("[testServerEventsInSystemClient] disconnect bridge server"); closeCache(); disconnectFromDS(); } }); synchronized(systemListener) { if (!firedSystem[LEFT]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[LEFT]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); // KIRK: did increasing this solve problem on balrog? } } synchronized(bridgeListener) { if (!firedBridge[LEFT]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } } finally { bgexecLogger.info("<ExpectedException action=remove>" + "java.io.IOException" + "</ExpectedException>"); ex.remove(); } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server crashed"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertFalse(firedBridge[JOINED]); assertNull(memberIdBridge[JOINED]); assertNull(memberBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse("Please update testServerEventsInSystemClient to handle memberLeft for BridgeServer.", firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertTrue(firedBridge[CRASHED]); assertNotNull(memberBridge[CRASHED]); assertNotNull(memberIdBridge[CRASHED]); assertEquals(serverMemberId, memberIdBridge[CRASHED]); assertEquals(serverMember, memberBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertFalse(firedSystem[JOINED]); assertNull(memberSystem[JOINED]); assertNull(memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertTrue(firedSystem[LEFT]); assertEquals(serverMember, memberSystem[LEFT]); assertEquals(serverMemberId, memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertFalse("this intermittently fails", firedAdapter[JOINED]); // KIRK --> this fails on balrog occasionally assertNull(memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); // LEFT fired by System listener assertTrue(firedAdapter[LEFT]); assertEquals(serverMember, memberAdapter[LEFT]); assertEquals(serverMemberId, memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); // There won't be an adapter crashed event because since the two VMs // are in the same distributed system, and the server's real member // id is used now. In this case, two events are sent - one from // jgroups (memberDeparted), and one from the server (a memberCrshed). // The memberCrashed event is deemed a duplicate and not sent - see // UniversalMembershipListenerAdapter.SystemMembershipListener.isDuplicate assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); // reconnect bridge client to test for crashed event vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server re-join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); }
NONSATD
true
getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); // create region which connects to bridge server AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL);
assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); String serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); DistributedMember serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); // create region which connects to bridge server AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); createRegion(name, factory.create()); assertNotNull(getRootRegion().getSubregion(name)); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } }
testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e); fail(e.getMessage()); } } }; vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); String serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); DistributedMember serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); // create region which connects to bridge server AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); createRegion(name, factory.create()); assertNotNull(getRootRegion().getSubregion(name)); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } }
15,012
8
// TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate);
private void doTestServerEventsInSystemClient() throws Exception { // KIRK: this test fails intermittently with bug 37482 final boolean[] firedSystem = new boolean[3]; final DistributedMember[] memberSystem = new DistributedMember[3]; final String[] memberIdSystem = new String[3]; final boolean[] isClientSystem = new boolean[3]; final boolean[] firedAdapter = new boolean[3]; final DistributedMember[] memberAdapter = new DistributedMember[3]; final String[] memberIdAdapter = new String[3]; final boolean[] isClientAdapter = new boolean[3]; final boolean[] firedBridge = new boolean[3]; final DistributedMember[] memberBridge = new DistributedMember[3]; final String[] memberIdBridge = new String[3]; final boolean[] isClientBridge = new boolean[3]; final boolean[] firedSystemDuplicate = new boolean[3]; final boolean[] firedAdapterDuplicate = new boolean[3]; final boolean[] firedBridgeDuplicate = new boolean[3]; SystemMembershipListener systemListener = new SystemMembershipListener() { public synchronized void memberJoined(SystemMembershipEvent event) { firedSystemDuplicate[JOINED] = firedSystem[JOINED]; firedSystem[JOINED] = true; memberSystem[JOINED] = event.getDistributedMember(); memberIdSystem[JOINED] = event.getMemberId(); notify(); } public synchronized void memberLeft(SystemMembershipEvent event) { firedSystemDuplicate[LEFT] = firedSystem[LEFT]; firedSystem[LEFT] = true; memberSystem[LEFT] = event.getDistributedMember(); memberIdSystem[LEFT] = event.getMemberId(); notify(); } public synchronized void memberCrashed(SystemMembershipEvent event) { firedSystemDuplicate[CRASHED] = firedSystem[CRASHED]; firedSystem[CRASHED] = true; memberSystem[CRASHED] = event.getDistributedMember(); memberIdSystem[CRASHED] = event.getMemberId(); notify(); } }; UniversalMembershipListenerAdapter adapter = new UniversalMembershipListenerAdapter() { @Override public synchronized void memberJoined(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberJoined >" + event.getMemberId() + "<"); firedAdapterDuplicate[JOINED] = firedAdapter[JOINED]; firedAdapter[JOINED] = true; memberAdapter[JOINED] = event.getDistributedMember(); memberIdAdapter[JOINED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[JOINED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberLeft(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberLeft >" + event.getMemberId() + "<"); firedAdapterDuplicate[LEFT] = firedAdapter[LEFT]; firedAdapter[LEFT] = true; memberAdapter[LEFT] = event.getDistributedMember(); memberIdAdapter[LEFT] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[LEFT] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberCrashed(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberCrashed >" + event.getMemberId() + "<"); firedAdapterDuplicate[CRASHED] = firedAdapter[CRASHED]; firedAdapter[CRASHED] = true; memberAdapter[CRASHED] = event.getDistributedMember(); memberIdAdapter[CRASHED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[CRASHED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } }; BridgeMembershipListener bridgeListener = new BridgeMembershipListener() { public synchronized void memberJoined(BridgeMembershipEvent event) { firedBridgeDuplicate[JOINED] = firedBridge[JOINED]; firedBridge[JOINED] = true; memberBridge[JOINED] = event.getMember(); memberIdBridge[JOINED] = event.getMemberId(); isClientBridge[JOINED] = event.isClient(); notify(); } public synchronized void memberLeft(BridgeMembershipEvent event) { firedBridgeDuplicate[LEFT] = firedBridge[LEFT]; firedBridge[LEFT] = true; memberBridge[LEFT] = event.getMember(); memberIdBridge[LEFT] = event.getMemberId(); isClientBridge[LEFT] = event.isClient(); notify(); } public synchronized void memberCrashed(BridgeMembershipEvent event) { firedBridgeDuplicate[CRASHED] = firedBridge[CRASHED]; firedBridge[CRASHED] = true; memberBridge[CRASHED] = event.getMember(); memberIdBridge[CRASHED] = event.getMemberId(); isClientBridge[CRASHED] = event.isClient(); notify(); } }; final Host host = Host.getHost(0); final VM vm0 = host.getVM(0); final String name = this.getUniqueName(); final int[] ports = new int[] { AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) }; assertTrue(ports[0] != 0); // getLogWriter().info("[testServerEventsInSystemClient] create bridge client"); // Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); Region region = createRegion(name, factory.create()); assertNotNull(region); assertNotNull(getRootRegion().getSubregion(name)); try { testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e); fail(e.getMessage()); } } }; vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); String serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); DistributedMember serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); // create region which connects to bridge server AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); createRegion(name, factory.create()); assertNotNull(getRootRegion().getSubregion(name)); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); getLogWriter().info("[testServerEventsInSystemClient] wait for client to fully connect"); final String pl = getRootRegion().getSubregion(name).getAttributes().getPoolName(); PoolImpl pi = (PoolImpl)PoolManager.find(pl); waitForClientToFullyConnect(pi); LogWriter bgexecLogger = new LocalLogWriter(LogWriterImpl.ALL_LEVEL, System.out); bgexecLogger.info("<ExpectedException action=add>" + "java.io.IOException" + "</ExpectedException>"); final ExpectedException ex = addExpectedException( ServerConnectivityException.class.getName()); try { vm0.invoke(new SerializableRunnable("Disconnect bridge server") { public void run() { getLogWriter().info("[testServerEventsInSystemClient] disconnect bridge server"); closeCache(); disconnectFromDS(); } }); synchronized(systemListener) { if (!firedSystem[LEFT]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[LEFT]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); // KIRK: did increasing this solve problem on balrog? } } synchronized(bridgeListener) { if (!firedBridge[LEFT]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } } finally { bgexecLogger.info("<ExpectedException action=remove>" + "java.io.IOException" + "</ExpectedException>"); ex.remove(); } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server crashed"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertFalse(firedBridge[JOINED]); assertNull(memberIdBridge[JOINED]); assertNull(memberBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse("Please update testServerEventsInSystemClient to handle memberLeft for BridgeServer.", firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertTrue(firedBridge[CRASHED]); assertNotNull(memberBridge[CRASHED]); assertNotNull(memberIdBridge[CRASHED]); assertEquals(serverMemberId, memberIdBridge[CRASHED]); assertEquals(serverMember, memberBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertFalse(firedSystem[JOINED]); assertNull(memberSystem[JOINED]); assertNull(memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertTrue(firedSystem[LEFT]); assertEquals(serverMember, memberSystem[LEFT]); assertEquals(serverMemberId, memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertFalse("this intermittently fails", firedAdapter[JOINED]); // KIRK --> this fails on balrog occasionally assertNull(memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); // LEFT fired by System listener assertTrue(firedAdapter[LEFT]); assertEquals(serverMember, memberAdapter[LEFT]); assertEquals(serverMemberId, memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); // There won't be an adapter crashed event because since the two VMs // are in the same distributed system, and the server's real member // id is used now. In this case, two events are sent - one from // jgroups (memberDeparted), and one from the server (a memberCrshed). // The memberCrashed event is deemed a duplicate and not sent - see // UniversalMembershipListenerAdapter.SystemMembershipListener.isDuplicate assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); // reconnect bridge client to test for crashed event vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server re-join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); }
DESIGN
true
getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]);
adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]);
BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); createRegion(name, factory.create()); assertNotNull(getRootRegion().getSubregion(name)); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]);
15,012
9
// KIRK: did increasing this solve problem on balrog?
private void doTestServerEventsInSystemClient() throws Exception { // KIRK: this test fails intermittently with bug 37482 final boolean[] firedSystem = new boolean[3]; final DistributedMember[] memberSystem = new DistributedMember[3]; final String[] memberIdSystem = new String[3]; final boolean[] isClientSystem = new boolean[3]; final boolean[] firedAdapter = new boolean[3]; final DistributedMember[] memberAdapter = new DistributedMember[3]; final String[] memberIdAdapter = new String[3]; final boolean[] isClientAdapter = new boolean[3]; final boolean[] firedBridge = new boolean[3]; final DistributedMember[] memberBridge = new DistributedMember[3]; final String[] memberIdBridge = new String[3]; final boolean[] isClientBridge = new boolean[3]; final boolean[] firedSystemDuplicate = new boolean[3]; final boolean[] firedAdapterDuplicate = new boolean[3]; final boolean[] firedBridgeDuplicate = new boolean[3]; SystemMembershipListener systemListener = new SystemMembershipListener() { public synchronized void memberJoined(SystemMembershipEvent event) { firedSystemDuplicate[JOINED] = firedSystem[JOINED]; firedSystem[JOINED] = true; memberSystem[JOINED] = event.getDistributedMember(); memberIdSystem[JOINED] = event.getMemberId(); notify(); } public synchronized void memberLeft(SystemMembershipEvent event) { firedSystemDuplicate[LEFT] = firedSystem[LEFT]; firedSystem[LEFT] = true; memberSystem[LEFT] = event.getDistributedMember(); memberIdSystem[LEFT] = event.getMemberId(); notify(); } public synchronized void memberCrashed(SystemMembershipEvent event) { firedSystemDuplicate[CRASHED] = firedSystem[CRASHED]; firedSystem[CRASHED] = true; memberSystem[CRASHED] = event.getDistributedMember(); memberIdSystem[CRASHED] = event.getMemberId(); notify(); } }; UniversalMembershipListenerAdapter adapter = new UniversalMembershipListenerAdapter() { @Override public synchronized void memberJoined(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberJoined >" + event.getMemberId() + "<"); firedAdapterDuplicate[JOINED] = firedAdapter[JOINED]; firedAdapter[JOINED] = true; memberAdapter[JOINED] = event.getDistributedMember(); memberIdAdapter[JOINED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[JOINED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberLeft(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberLeft >" + event.getMemberId() + "<"); firedAdapterDuplicate[LEFT] = firedAdapter[LEFT]; firedAdapter[LEFT] = true; memberAdapter[LEFT] = event.getDistributedMember(); memberIdAdapter[LEFT] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[LEFT] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberCrashed(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberCrashed >" + event.getMemberId() + "<"); firedAdapterDuplicate[CRASHED] = firedAdapter[CRASHED]; firedAdapter[CRASHED] = true; memberAdapter[CRASHED] = event.getDistributedMember(); memberIdAdapter[CRASHED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[CRASHED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } }; BridgeMembershipListener bridgeListener = new BridgeMembershipListener() { public synchronized void memberJoined(BridgeMembershipEvent event) { firedBridgeDuplicate[JOINED] = firedBridge[JOINED]; firedBridge[JOINED] = true; memberBridge[JOINED] = event.getMember(); memberIdBridge[JOINED] = event.getMemberId(); isClientBridge[JOINED] = event.isClient(); notify(); } public synchronized void memberLeft(BridgeMembershipEvent event) { firedBridgeDuplicate[LEFT] = firedBridge[LEFT]; firedBridge[LEFT] = true; memberBridge[LEFT] = event.getMember(); memberIdBridge[LEFT] = event.getMemberId(); isClientBridge[LEFT] = event.isClient(); notify(); } public synchronized void memberCrashed(BridgeMembershipEvent event) { firedBridgeDuplicate[CRASHED] = firedBridge[CRASHED]; firedBridge[CRASHED] = true; memberBridge[CRASHED] = event.getMember(); memberIdBridge[CRASHED] = event.getMemberId(); isClientBridge[CRASHED] = event.isClient(); notify(); } }; final Host host = Host.getHost(0); final VM vm0 = host.getVM(0); final String name = this.getUniqueName(); final int[] ports = new int[] { AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) }; assertTrue(ports[0] != 0); // getLogWriter().info("[testServerEventsInSystemClient] create bridge client"); // Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); Region region = createRegion(name, factory.create()); assertNotNull(region); assertNotNull(getRootRegion().getSubregion(name)); try { testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e); fail(e.getMessage()); } } }; vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); String serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); DistributedMember serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); // create region which connects to bridge server AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); createRegion(name, factory.create()); assertNotNull(getRootRegion().getSubregion(name)); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); getLogWriter().info("[testServerEventsInSystemClient] wait for client to fully connect"); final String pl = getRootRegion().getSubregion(name).getAttributes().getPoolName(); PoolImpl pi = (PoolImpl)PoolManager.find(pl); waitForClientToFullyConnect(pi); LogWriter bgexecLogger = new LocalLogWriter(LogWriterImpl.ALL_LEVEL, System.out); bgexecLogger.info("<ExpectedException action=add>" + "java.io.IOException" + "</ExpectedException>"); final ExpectedException ex = addExpectedException( ServerConnectivityException.class.getName()); try { vm0.invoke(new SerializableRunnable("Disconnect bridge server") { public void run() { getLogWriter().info("[testServerEventsInSystemClient] disconnect bridge server"); closeCache(); disconnectFromDS(); } }); synchronized(systemListener) { if (!firedSystem[LEFT]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[LEFT]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); // KIRK: did increasing this solve problem on balrog? } } synchronized(bridgeListener) { if (!firedBridge[LEFT]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } } finally { bgexecLogger.info("<ExpectedException action=remove>" + "java.io.IOException" + "</ExpectedException>"); ex.remove(); } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server crashed"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertFalse(firedBridge[JOINED]); assertNull(memberIdBridge[JOINED]); assertNull(memberBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse("Please update testServerEventsInSystemClient to handle memberLeft for BridgeServer.", firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertTrue(firedBridge[CRASHED]); assertNotNull(memberBridge[CRASHED]); assertNotNull(memberIdBridge[CRASHED]); assertEquals(serverMemberId, memberIdBridge[CRASHED]); assertEquals(serverMember, memberBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertFalse(firedSystem[JOINED]); assertNull(memberSystem[JOINED]); assertNull(memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertTrue(firedSystem[LEFT]); assertEquals(serverMember, memberSystem[LEFT]); assertEquals(serverMemberId, memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertFalse("this intermittently fails", firedAdapter[JOINED]); // KIRK --> this fails on balrog occasionally assertNull(memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); // LEFT fired by System listener assertTrue(firedAdapter[LEFT]); assertEquals(serverMember, memberAdapter[LEFT]); assertEquals(serverMemberId, memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); // There won't be an adapter crashed event because since the two VMs // are in the same distributed system, and the server's real member // id is used now. In this case, two events are sent - one from // jgroups (memberDeparted), and one from the server (a memberCrshed). // The memberCrashed event is deemed a duplicate and not sent - see // UniversalMembershipListenerAdapter.SystemMembershipListener.isDuplicate assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); // reconnect bridge client to test for crashed event vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server re-join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); }
DESIGN
true
synchronized(adapter) { if (!firedAdapter[LEFT]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); // KIRK: did increasing this solve problem on balrog? } }
disconnectFromDS(); } }); synchronized(systemListener) { if (!firedSystem[LEFT]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[LEFT]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); // KIRK: did increasing this solve problem on balrog? } } synchronized(bridgeListener) { if (!firedBridge[LEFT]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } } finally { bgexecLogger.info("<ExpectedException action=remove>" +
new LocalLogWriter(LogWriterImpl.ALL_LEVEL, System.out); bgexecLogger.info("<ExpectedException action=add>" + "java.io.IOException" + "</ExpectedException>"); final ExpectedException ex = addExpectedException( ServerConnectivityException.class.getName()); try { vm0.invoke(new SerializableRunnable("Disconnect bridge server") { public void run() { getLogWriter().info("[testServerEventsInSystemClient] disconnect bridge server"); closeCache(); disconnectFromDS(); } }); synchronized(systemListener) { if (!firedSystem[LEFT]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[LEFT]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); // KIRK: did increasing this solve problem on balrog? } } synchronized(bridgeListener) { if (!firedBridge[LEFT]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } } finally { bgexecLogger.info("<ExpectedException action=remove>" + "java.io.IOException" + "</ExpectedException>"); ex.remove(); } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server crashed"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate);
15,012
10
// TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate);
private void doTestServerEventsInSystemClient() throws Exception { // KIRK: this test fails intermittently with bug 37482 final boolean[] firedSystem = new boolean[3]; final DistributedMember[] memberSystem = new DistributedMember[3]; final String[] memberIdSystem = new String[3]; final boolean[] isClientSystem = new boolean[3]; final boolean[] firedAdapter = new boolean[3]; final DistributedMember[] memberAdapter = new DistributedMember[3]; final String[] memberIdAdapter = new String[3]; final boolean[] isClientAdapter = new boolean[3]; final boolean[] firedBridge = new boolean[3]; final DistributedMember[] memberBridge = new DistributedMember[3]; final String[] memberIdBridge = new String[3]; final boolean[] isClientBridge = new boolean[3]; final boolean[] firedSystemDuplicate = new boolean[3]; final boolean[] firedAdapterDuplicate = new boolean[3]; final boolean[] firedBridgeDuplicate = new boolean[3]; SystemMembershipListener systemListener = new SystemMembershipListener() { public synchronized void memberJoined(SystemMembershipEvent event) { firedSystemDuplicate[JOINED] = firedSystem[JOINED]; firedSystem[JOINED] = true; memberSystem[JOINED] = event.getDistributedMember(); memberIdSystem[JOINED] = event.getMemberId(); notify(); } public synchronized void memberLeft(SystemMembershipEvent event) { firedSystemDuplicate[LEFT] = firedSystem[LEFT]; firedSystem[LEFT] = true; memberSystem[LEFT] = event.getDistributedMember(); memberIdSystem[LEFT] = event.getMemberId(); notify(); } public synchronized void memberCrashed(SystemMembershipEvent event) { firedSystemDuplicate[CRASHED] = firedSystem[CRASHED]; firedSystem[CRASHED] = true; memberSystem[CRASHED] = event.getDistributedMember(); memberIdSystem[CRASHED] = event.getMemberId(); notify(); } }; UniversalMembershipListenerAdapter adapter = new UniversalMembershipListenerAdapter() { @Override public synchronized void memberJoined(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberJoined >" + event.getMemberId() + "<"); firedAdapterDuplicate[JOINED] = firedAdapter[JOINED]; firedAdapter[JOINED] = true; memberAdapter[JOINED] = event.getDistributedMember(); memberIdAdapter[JOINED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[JOINED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberLeft(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberLeft >" + event.getMemberId() + "<"); firedAdapterDuplicate[LEFT] = firedAdapter[LEFT]; firedAdapter[LEFT] = true; memberAdapter[LEFT] = event.getDistributedMember(); memberIdAdapter[LEFT] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[LEFT] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } @Override public synchronized void memberCrashed(SystemMembershipEvent event) { getLogWriter().info("[testServerEventsInSystemClient] memberCrashed >" + event.getMemberId() + "<"); firedAdapterDuplicate[CRASHED] = firedAdapter[CRASHED]; firedAdapter[CRASHED] = true; memberAdapter[CRASHED] = event.getDistributedMember(); memberIdAdapter[CRASHED] = event.getMemberId(); if (event instanceof UniversalMembershipListenerAdapter.AdaptedMembershipEvent) { isClientAdapter[CRASHED] = ((UniversalMembershipListenerAdapter.AdaptedMembershipEvent)event).isClient(); } notify(); } }; BridgeMembershipListener bridgeListener = new BridgeMembershipListener() { public synchronized void memberJoined(BridgeMembershipEvent event) { firedBridgeDuplicate[JOINED] = firedBridge[JOINED]; firedBridge[JOINED] = true; memberBridge[JOINED] = event.getMember(); memberIdBridge[JOINED] = event.getMemberId(); isClientBridge[JOINED] = event.isClient(); notify(); } public synchronized void memberLeft(BridgeMembershipEvent event) { firedBridgeDuplicate[LEFT] = firedBridge[LEFT]; firedBridge[LEFT] = true; memberBridge[LEFT] = event.getMember(); memberIdBridge[LEFT] = event.getMemberId(); isClientBridge[LEFT] = event.isClient(); notify(); } public synchronized void memberCrashed(BridgeMembershipEvent event) { firedBridgeDuplicate[CRASHED] = firedBridge[CRASHED]; firedBridge[CRASHED] = true; memberBridge[CRASHED] = event.getMember(); memberIdBridge[CRASHED] = event.getMemberId(); isClientBridge[CRASHED] = event.isClient(); notify(); } }; final Host host = Host.getHost(0); final VM vm0 = host.getVM(0); final String name = this.getUniqueName(); final int[] ports = new int[] { AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET) }; assertTrue(ports[0] != 0); // getLogWriter().info("[testServerEventsInSystemClient] create bridge client"); // Properties config = new Properties(); // config.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); // config.setProperty(DistributionConfig.LOCATORS_NAME, ""); // getSystem(config); // AttributesFactory factory = new AttributesFactory(); // factory.setScope(Scope.LOCAL); // BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); // createRegion(name, factory.create()); // assertNotNull(getRootRegion().getSubregion(name)); getLogWriter().info("[testServerEventsInSystemClient] create system bridge client"); getSystem(); final Properties clientProperties = getSystemProperties(); // register the bridge listener BridgeMembership.registerBridgeMembershipListener(bridgeListener); DistributedSystemConfig config = AdminDistributedSystemFactory.defineDistributedSystem(getSystem(), null); AdminDistributedSystem adminDS = AdminDistributedSystemFactory.getDistributedSystem(config); adminDS.connect(); assertTrue(adminDS.waitToBeConnected(5 * 1000)); // register the system listener adminDS.addMembershipListener(systemListener); // register the universal adapter adapter.registerMembershipListener(adminDS); // create BridgeServer in vm0... SerializableRunnable createBridgeServer = new CacheSerializableRunnable("Create BridgeServer") { @Override public void run2() throws CacheException { getLogWriter().info("[testServerEventsInSystemClient] Create BridgeServer"); getSystem(clientProperties); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); Region region = createRegion(name, factory.create()); assertNotNull(region); assertNotNull(getRootRegion().getSubregion(name)); try { testServerEventsInSystemClient_port = startBridgeServer(ports[0]); } catch (IOException e) { getLogWriter().error(e); fail(e.getMessage()); } } }; vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); String serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); DistributedMember serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); // create region which connects to bridge server AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); createRegion(name, factory.create()); assertNotNull(getRootRegion().getSubregion(name)); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); getLogWriter().info("[testServerEventsInSystemClient] wait for client to fully connect"); final String pl = getRootRegion().getSubregion(name).getAttributes().getPoolName(); PoolImpl pi = (PoolImpl)PoolManager.find(pl); waitForClientToFullyConnect(pi); LogWriter bgexecLogger = new LocalLogWriter(LogWriterImpl.ALL_LEVEL, System.out); bgexecLogger.info("<ExpectedException action=add>" + "java.io.IOException" + "</ExpectedException>"); final ExpectedException ex = addExpectedException( ServerConnectivityException.class.getName()); try { vm0.invoke(new SerializableRunnable("Disconnect bridge server") { public void run() { getLogWriter().info("[testServerEventsInSystemClient] disconnect bridge server"); closeCache(); disconnectFromDS(); } }); synchronized(systemListener) { if (!firedSystem[LEFT]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[LEFT]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); // KIRK: did increasing this solve problem on balrog? } } synchronized(bridgeListener) { if (!firedBridge[LEFT]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } } finally { bgexecLogger.info("<ExpectedException action=remove>" + "java.io.IOException" + "</ExpectedException>"); ex.remove(); } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server crashed"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertFalse(firedBridge[JOINED]); assertNull(memberIdBridge[JOINED]); assertNull(memberBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse("Please update testServerEventsInSystemClient to handle memberLeft for BridgeServer.", firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertTrue(firedBridge[CRASHED]); assertNotNull(memberBridge[CRASHED]); assertNotNull(memberIdBridge[CRASHED]); assertEquals(serverMemberId, memberIdBridge[CRASHED]); assertEquals(serverMember, memberBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertFalse(firedSystem[JOINED]); assertNull(memberSystem[JOINED]); assertNull(memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertTrue(firedSystem[LEFT]); assertEquals(serverMember, memberSystem[LEFT]); assertEquals(serverMemberId, memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertFalse("this intermittently fails", firedAdapter[JOINED]); // KIRK --> this fails on balrog occasionally assertNull(memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); // LEFT fired by System listener assertTrue(firedAdapter[LEFT]); assertEquals(serverMember, memberAdapter[LEFT]); assertEquals(serverMemberId, memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); // There won't be an adapter crashed event because since the two VMs // are in the same distributed system, and the server's real member // id is used now. In this case, two events are sent - one from // jgroups (memberDeparted), and one from the server (a memberCrshed). // The memberCrashed event is deemed a duplicate and not sent - see // UniversalMembershipListenerAdapter.SystemMembershipListener.isDuplicate assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); // reconnect bridge client to test for crashed event vm0.invoke(createBridgeServer); // gather details for later creation of BridgeLoader... assertEquals(ports[0], vm0.invokeInt(UniversalMembershipListenerAdapterDUnitTest.class, "getTestServerEventsInSystemClient_port")); serverMemberId = (String) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getMemberId"); serverMember = (DistributedMember) vm0.invoke( UniversalMembershipListenerAdapterDUnitTest.class, "getDistributedMember"); getLogWriter().info("[testServerEventsInSystemClient] ports[0]=" + ports[0]); getLogWriter().info("[testServerEventsInSystemClient] serverMemberId=" + serverMemberId); getLogWriter().info("[testServerEventsInSystemClient] serverMember=" + serverMember); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server re-join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]); assertFalse(firedSystem[LEFT]); assertNull(memberSystem[LEFT]); assertNull(memberIdSystem[LEFT]); assertFalse(isClientSystem[LEFT]); assertFalse(firedSystem[CRASHED]); assertNull(memberSystem[CRASHED]); assertNull(memberIdSystem[CRASHED]); assertFalse(isClientSystem[CRASHED]); resetArraysForTesting(firedSystem, memberSystem, memberIdSystem, isClientSystem); assertTrue(firedAdapter[JOINED]); assertNotNull(memberAdapter[JOINED]); assertNotNull(memberIdAdapter[JOINED]); assertEquals(serverMember, memberAdapter[JOINED]); assertEquals(serverMemberId, memberIdAdapter[JOINED]); assertFalse(isClientAdapter[JOINED]); assertFalse(firedAdapter[LEFT]); assertNull(memberAdapter[LEFT]); assertNull(memberIdAdapter[LEFT]); assertFalse(isClientAdapter[LEFT]); assertFalse(firedAdapter[CRASHED]); assertNull(memberAdapter[CRASHED]); assertNull(memberIdAdapter[CRASHED]); assertFalse(isClientAdapter[CRASHED]); resetArraysForTesting(firedAdapter, memberAdapter, memberIdAdapter, isClientAdapter); }
DESIGN
true
getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]);
adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]);
BridgeTestCase.configureConnectionPool(factory, getServerHostName(host), ports, false, -1, -1, null); createRegion(name, factory.create()); assertNotNull(getRootRegion().getSubregion(name)); synchronized(systemListener) { if (!firedSystem[JOINED]) { systemListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(adapter) { if (!firedAdapter[JOINED]) { adapter.wait(ASYNC_EVENT_WAIT_MILLIS); } } synchronized(bridgeListener) { if (!firedBridge[JOINED]) { bridgeListener.wait(ASYNC_EVENT_WAIT_MILLIS); } } getLogWriter().info("[testServerEventsInSystemClient] assert client detected server join"); assertFalse(firedSystemDuplicate); // TODO: sometimes get adapter duplicate since memberId isn't endpoint // initial impl uses Endpoint.toString() for memberId of server; final // impl should have server send its real memberId to client via HandShake //assertFalse("Please update testBridgeMembershipEventsInClient to use BridgeServer memberId.", // firedAdapterDuplicate); assertFalse(firedBridgeDuplicate); assertTrue(firedBridge[JOINED]); assertEquals(serverMember, memberBridge[JOINED]); assertEquals(serverMemberId, memberIdBridge[JOINED]); assertNotNull(memberBridge[JOINED]); assertNotNull(memberIdBridge[JOINED]); assertFalse(isClientBridge[JOINED]); assertFalse(firedBridge[LEFT]); assertNull(memberBridge[LEFT]); assertNull(memberIdBridge[LEFT]); assertFalse(isClientBridge[LEFT]); assertFalse(firedBridge[CRASHED]); assertNull(memberBridge[CRASHED]); assertNull(memberIdBridge[CRASHED]); assertFalse(isClientBridge[CRASHED]); resetArraysForTesting(firedBridge, memberBridge, memberIdBridge, isClientBridge); assertTrue(firedSystem[JOINED]); assertEquals(serverMember, memberSystem[JOINED]); assertEquals(serverMemberId, memberIdSystem[JOINED]); assertFalse(isClientSystem[JOINED]);