List of usage examples for java.lang String wait
public final native void wait(long timeoutMillis) throws InterruptedException;
From source file:org.alfresco.bm.tools.BMTestRunner.java
/** * Execute the default test against the given MongoDB or an in-memory instance * // ww w .ja v a 2s. c o m * @param mongoConfigHost the MongoDB host to connect to for configuraton data or <tt>null</tt> to use an in-memory version * @param mongoTestHost the MongoDB host to connect to for test data data or <tt>null</tt> to use the same database as the config * @param testProperties any properties to specifically set for the test or <tt>null</tt> if there are none */ public void run(String mongoConfigHost, String mongoTestHost, Properties testProperties) throws Exception { // Secure the listeners against modification List<BMTestRunnerListener> listeners = new ArrayList<BMTestRunnerListener>(this.listeners); // If no MongoDB URL is provided, then we have to start one MongoDBForTestsFactory mongoDBForTestsFactory = null; ClassPathXmlApplicationContext ctx = null; try { // Ensure that required system properties are present System.setProperty(PROP_APP_CONTEXT_PATH, System.getProperty("user.dir")); System.setProperty(PROP_APP_DIR, System.getProperty("user.dir")); // Create a MongoDB for use if one has not been specified if (mongoConfigHost == null) { mongoDBForTestsFactory = new MongoDBForTestsFactory(); String uriWithoutDB = mongoDBForTestsFactory.getMongoURIWithoutDB(); mongoConfigHost = new MongoClientURI(uriWithoutDB).getHosts().get(0); } // Fill in the URI for the test MongoDB if (mongoTestHost == null) { mongoTestHost = mongoConfigHost; } // Fill in the properties required for the test Properties mongoProps = new Properties(); mongoProps.put(PROP_MONGO_CONFIG_HOST, mongoConfigHost); // Construct the application context ctx = new ClassPathXmlApplicationContext(new String[] { PATH_APP_CONTEXT }, false); // Push cluster properties into the context (must be done AFTER setting parent context) ConfigurableEnvironment ctxEnv = ctx.getEnvironment(); // Mongo properties come first ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("mongo-props", mongoProps)); // Finally, system properties overrule them all ctxEnv.getPropertySources() .addFirst(new PropertiesPropertySource("system-props", System.getProperties())); // Kick it all off try { ctx.refresh(); } catch (Exception e) { Throwable root = ExceptionUtils.getRootCause(e); if (root != null && (root instanceof MongoSocketException || root instanceof UnknownHostException)) { // We deal with this specifically as it's a simple case of not finding the MongoDB logger.error("Set the configuration property '" + PROP_MONGO_CONFIG_HOST + "' (<server>:<port>) as required."); } else { // Log application start failure because test frameworks might not do so nicely logger.error("Failed to start application.", e); } throw new RuntimeException("Failed to start application.", e); } // Get the test Test test = ctx.getBean(Test.class); String release = test.getRelease(); Integer schema = test.getSchema(); TestRestAPI api = ctx.getBean(TestRestAPI.class); // Create a new test TestDetails testDetails = new TestDetails(); String testName = "BMTestRunner_" + System.currentTimeMillis(); testDetails.setName(testName); testDetails.setDescription("Test created by BMTestRunner on " + new Date()); testDetails.setRelease(release); testDetails.setSchema(schema); api.createTest(testDetails); // We need to tell the test which MongoDB to write data to PropSetBean propSet = new PropSetBean(); propSet.setValue(mongoTestHost); propSet.setVersion(0); api.setTestProperty(testName, PROP_MONGO_TEST_HOST, propSet); // Now set any properties that have been explicitly passed in for the test if (testProperties != null) { for (Map.Entry<Object, Object> entry : testProperties.entrySet()) { String propKey = (String) entry.getKey(); String propVal = (String) entry.getValue(); propSet.setValue(propVal); propSet.setVersion(0); api.setTestProperty(testName, propKey, propSet); } } // Call listeners: the test has been created for (BMTestRunnerListener listener : listeners) { listener.testReady(ctx, testName); } // Create a new test run TestRunDetails testRunDetails = new TestRunDetails(); String testRunName = "BMTestRunner_" + System.currentTimeMillis(); testRunDetails.setName(testRunName); testRunDetails.setDescription("Test run created by BMTestRunner on " + new Date()); api.createTestRun(testDetails.getName(), testRunDetails); // Call listeners: the test run has been created for (BMTestRunnerListener listener : listeners) { listener.testRunReady(ctx, testName, testRunName); } // Get all the test run properties for logging String jsonTestRun = api.getTestRun(testName, testRunName); // Start the test run logger.info("Starting test run: " + testRunName + "\n" + jsonTestRun); TestRunSchedule testRunSchedule = new TestRunSchedule(); testRunSchedule.setScheduled(System.currentTimeMillis()); api.scheduleTestRun(testName, testRunName, testRunSchedule); // Call listeners: the test run has started for (BMTestRunnerListener listener : listeners) { listener.testRunStarted(ctx, testName, testRunName); } // Wait for the test run to complete long timeInit = System.currentTimeMillis(); long timeLastChange = -1L; String jsonLastChange = null; String testRunStateStr = api.getTestRunState(testName, testRunName); // Keep looking until the test run completes while (!TestRunState.COMPLETED.toString().equals(testRunStateStr)) { long now = System.currentTimeMillis(); // Check that we have not exceeded the maximum time if (now - timeInit > maxTestTime) { throw new RuntimeException("Test run failed to complete in " + (int) maxTestTime / 1000 + "s."); } testRunStateStr = api.getTestRunState(testName, testRunName); if (TestRunState.SCHEDULED.toString().equals(testRunStateStr) && (now - timeInit) > 10000L) { throw new RuntimeException("Test run failed to start in 10s."); } // Check that there are updates to the test run String jsonNow = api.getTestRunSummary(testName, testRunName); if (jsonLastChange != null && jsonLastChange.equals(jsonNow)) { if ((now - timeLastChange) > 60000L) { throw new RuntimeException("Test run has not been updated in the last 60s"); } } // Store values for next iteration timeLastChange = now; jsonLastChange = jsonNow; synchronized (testRunStateStr) { try { testRunStateStr.wait(1000L); } catch (InterruptedException e) { } } } // Call listeners: the test run has finished for (BMTestRunnerListener listener : listeners) { listener.testRunFinished(ctx, testName, testRunName); } } finally { // Close the context if (ctx != null) { try { ctx.close(); } catch (Exception e) { logger.error("Failed to shut down application context.", e); } } // Close the local Mongo instance if (mongoDBForTestsFactory != null) { try { mongoDBForTestsFactory.destroy(); } catch (Exception e) { logger.error("Failed to stop in-memory MongoDB instance.", e); } } } }
From source file:tor.HiddenService.java
public static String fetchHSDescriptor(TorSocket sock, final String onion) throws IOException { // get list of ORs with resposibility for this HS OnionRouter ors[] = findResposibleDirectories(onion); // loop through responsible directories until successful for (int i = 0; i < ors.length; i++) { OnionRouter or = ors[i];/*from w ww. ja v a 2 s . c om*/ log.debug("Trying Directory Server: {}", or); // establish circuit to responsible director TorCircuit circ = sock.createCircuit(true); try { circ.create(); circ.extend(ors[0]); } catch (TorCircuitException e) { log.error("HS fetched failed due to circuit failure - moving to next directory"); continue; } final int replica = i < 3 ? 0 : 1; // asynchronous call TorStream st = circ.createDirStream(new TorStream.TorStreamListener() { @Override public void dataArrived(TorStream s) { } @Override public void connected(TorStream s) { try { s.sendHTTPGETRequest("/tor/rendezvous2/" + new Base32().encodeAsString(HiddenService.getDescId(onion, (byte) replica)), "dirreq"); } catch (IOException e) { e.printStackTrace(); } } @Override public void disconnected(TorStream s) { synchronized (onion) { onion.notify(); } } @Override public void failure(TorStream s) { synchronized (onion) { onion.notify(); } } }); // wait for notification from the above listener that data is here! (that remote side ended connection - data could be blank synchronized (onion) { try { onion.wait(1000); if (circ.state == TorCircuit.STATES.DESTROYED) { System.out.println("HS - Desc Fetch - Circuit Destroyed"); throw new TorCircuitException("circuit destroyed"); } } catch (InterruptedException e) { e.printStackTrace(); } } // get HTTP response and body String data = IOUtils.toString(st.getInputStream()); circ.destroy(); // HTTP success code if (data.length() < 1 || !data.split(" ")[1].equals("200")) { continue; } int dataIndex = data.indexOf("\r\n\r\n"); return data.substring(dataIndex); } log.warn("Not found hs descriptor!"); return null; }
From source file:tor.HiddenService.java
public static String HSDescriptorRequest(TorSocket sock, final String descriptor_id, final String fprint, final String descriptor) throws IOException { // Send GET and POST requests to specified HSDir. Consensus con = Consensus.getConsensus(); OnionRouter or = null;/*from www.j a va 2s . c o m*/ // Try get the requested OR from the consensus if (con.routers.containsKey(fprint)) { or = con.routers.get(fprint); } else { log.error("Could not find the request HSDir in the consensus"); throw new IOException( "Could not find the requested HSDir in the consensus. Check the fingerprint is correct"); } log.debug("Trying Directory Server: {}", or); // establish circuit to responsible directory TorCircuit circ = sock.createCircuit(true); try { circ.create(); circ.extend(or); } catch (TorCircuitException e) { throw new IOException("HS Fetch failed due to circuit failure, you should retry."); } // asynchronous call TorStream st = circ.createDirStream(new TorStream.TorStreamListener() { @Override public void dataArrived(TorStream s) { } @Override public void connected(TorStream s) { try { if (descriptor != null && !descriptor.isEmpty()) { s.sendHTTPPOSTRequest("/tor/rendezvous2/publish", "dirreq", descriptor); } else { s.sendHTTPGETRequest("/tor/rendezvous2/" + descriptor_id, "dirreq"); } } catch (IOException e) { e.printStackTrace(); } } @Override public void disconnected(TorStream s) { synchronized (fprint) { fprint.notify(); } } @Override public void failure(TorStream s) { synchronized (fprint) { fprint.notify(); } } }); // wait for notification from the above listener that data is here! (that remote side ended connection - data could be blank synchronized (fprint) { try { fprint.wait(1000); if (circ.state == TorCircuit.STATES.DESTROYED) { System.out.println("HS - Desc Fetch - Circuit Destroyed"); throw new TorCircuitException("circuit destroyed"); } } catch (InterruptedException e) { e.printStackTrace(); throw new IOException("Circuit failed"); } } // get HTTP response and body String data = IOUtils.toString(st.getInputStream()); circ.destroy(); // HTTP success code if (data.length() < 1 || !data.split(" ")[1].equals("200")) { throw new IOException("HTTPError: " + data); // Throw the error } int dataIndex = data.indexOf("\r\n\r\n"); return data.substring(dataIndex); }