List of usage examples for java.lang Thread join
public final void join() throws InterruptedException
From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.BaseJpaDaoTest.java
/** * Executes the callback in a new thread inside of a {@link JpaInterceptor}. Waits for the * Thread to return./* w ww . j a va2 s .com*/ */ public final <T> T executeInThread(String name, final Callable<T> callable) { final List<RuntimeException> exception = new LinkedList<RuntimeException>(); final List<T> retVal = new LinkedList<T>(); final Thread t2 = new Thread(new Runnable() { @Override public void run() { try { final T val = execute(callable); retVal.add(val); } catch (Throwable e) { if (e instanceof RuntimeException) { exception.add((RuntimeException) e); } else { exception.add(new RuntimeException(e)); } } } }, name); t2.start(); try { t2.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } if (exception.size() == 1) { throw exception.get(0); } return retVal.get(0); }
From source file:de.innovationgate.wgpublisher.design.sync.DesignSyncManager.java
private void prepareSync(boolean doInitSync) throws WGAPIException, FileSystemException, IOException, WGDesignSyncException { // Sync mode// w w w. ja v a2s .c om String mode = getSyncMode(); if (mode.equals(MODE_FULL)) { /*// Test for correct design key OBSOLETE if (!getSyncInfo().getDesignKey().equals(_designKey)) { throw new WGDesignKeyException(getBaseFolder().getURL().toString(), getSyncInfo().getDesignKey(), _designKey); }*/ // Disable modification of the served doctypes Iterator<Integer> doctypes = _syncedDoctypes.iterator(); while (doctypes.hasNext()) { Integer doctype = doctypes.next(); _db.setDoctypeModifiable(doctype.intValue(), false); } } else if (mode.equals(MODE_VIRTUAL)) { // Register a virtual design provider for this database so that designs in the database do not get modified // Deployment information must be reset to do an inital update of the provider _log.info("Creating virtual design provider for database '" + _db.getDbReference() + "' to be filled with designs from file system"); _db.setDesignProvider(new VirtualDesignProvider(_designReference, "Virtual design provider, receiving designs from directory " + getBaseFolder().getURL().toString(), _db, WGFactory.getTempDir())); initSyncStatus(); } else { throw new WGDesignSyncException("Unknown sync mode: " + mode); } // Do initial sync right now and wait for it: // This must not be executed when init() was triggered by an event, bc. synchronisations // may lead to a deadlock if (doInitSync) { Thread initSyncThread = new Thread(new PollingTask()); initSyncThread.start(); try { initSyncThread.join(); } catch (InterruptedException e) { } } // If autoupdate enabled start the update task if (_autoUpdate && !AUTOUPDATE_GLOBALLY_DISABLED) { _pollingTask = new PollingTask(); _timer = new Timer(); int pollingInterval = _core.getWgaConfiguration().getDesignConfiguration().getPollingInterval() * 1000; _timer.schedule(_pollingTask, pollingInterval, pollingInterval); } }
From source file:org.marietjedroid.connect.MarietjeMessenger.java
/** * Sends a stream/*www . ja va 2 s. c o m*/ * * FIXME probably massively broken * * @param token * @param stream * @param blocking */ public void sendStream(String token, ContentBody stream, boolean blocking) { if (!this.token.equals(token)) throw new IllegalArgumentException("Wrong token!"); MultipartEntity multipartStream = new MultipartEntity(); multipartStream.addPart("stream", stream); final HttpPost post = new HttpPost(String.format("http://%s:%s%s", host, port, path)); // FIXME sowieso stuk post.setEntity(multipartStream); Thread t = new Thread(new Runnable() { public void run() { try { httpClient.execute(post); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); t.start(); if (blocking) { try { t.join(); } catch (InterruptedException e) { } } }
From source file:com.cloudant.sync.indexing.IndexManagerIndexTest.java
/** * A sanity-check that updating the datastore from many threads * doesn't cause the index manager to balk. *//*from w ww .jav a2s . c o m*/ @Test public void index_UpdateCrudMultiThreaded() throws IndexExistsException, SQLException, ConflictException, InterruptedException { int n_threads = 3; final int n_docs = 100; // We'll later search for search == success final Map<String, String> matching = ImmutableMap.of("search", "success"); final Map<String, String> nonmatching = ImmutableMap.of("search", "failure"); indexManager.ensureIndexed("search", "search", IndexType.STRING); final List<String> matching_ids = Collections.synchronizedList(new ArrayList<String>()); // When run, this thread creates n_docs documents with unique // names in the datastore. A subset of these // will be matched by our query to the datastore later, which // we record in the matching_ids list. class PopulateThread extends Thread { @Override public void run() { String docId; final String thread_id; DocumentBody body; thread_id = Thread.currentThread().getName(); for (int i = 0; i < n_docs; i++) { docId = String.format("%s-%s", thread_id, i); if ((i % 2) == 0) { // even numbers create matching docs body = DocumentBodyFactory.create(matching); matching_ids.add(docId); } else { body = DocumentBodyFactory.create(nonmatching); } datastore.createDocument(docId, body); } // we're not on the main thread, so we must close our own connection datastore.getSQLDatabase().close(); } } List<Thread> threads = new ArrayList<Thread>(); // Create, start and wait for the threads to complete for (int i = 0; i < n_threads; i++) { threads.add(new PopulateThread()); } for (Thread t : threads) { t.start(); } for (Thread t : threads) { t.join(); } // Check appropriate entries in index QueryBuilder q = new QueryBuilder(); q.index("search").equalTo("success"); QueryResult result = indexManager.query(q.build()); List<DocumentRevision> docRevisions = Lists.newArrayList(result); List<String> docIds = new ArrayList<String>(); for (DocumentRevision r : docRevisions) { docIds.add(r.getId()); } Assert.assertEquals(matching_ids.size(), docIds.size()); for (String id : matching_ids) { Assert.assertTrue(docIds.contains(id)); } }
From source file:com.entertailion.java.fling.RampClient.java
public void launchApp(String app, DialServer dialServer) { this.app = app; this.dialServer = dialServer; this.activityId = UUID.randomUUID().toString(); try {//w w w . j a v a 2 s . c om String device = "http://" + dialServer.getIpAddress().getHostAddress() + ":" + dialServer.getPort(); Log.d(LOG_TAG, "device=" + device); Log.d(LOG_TAG, "apps url=" + dialServer.getAppsUrl()); // application instance url String location = null; DefaultHttpClient defaultHttpClient = HttpRequestHelper.createHttpClient(); CustomRedirectHandler handler = new CustomRedirectHandler(); defaultHttpClient.setRedirectHandler(handler); BasicHttpContext localContext = new BasicHttpContext(); // check if any app is running HttpGet httpGet = new HttpGet(dialServer.getAppsUrl()); httpGet.setHeader(HEADER_CONNECTION, HEADER_CONNECTION_VALUE); httpGet.setHeader(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE); httpGet.setHeader(HEADER_ACCEPT, HEADER_ACCEPT_VALUE); httpGet.setHeader(HEADER_DNT, HEADER_DNT_VALUE); httpGet.setHeader(HEADER_ACCEPT_ENCODING, HEADER_ACCEPT_ENCODING_VALUE); httpGet.setHeader(HEADER_ACCEPT_LANGUAGE, HEADER_ACCEPT_LANGUAGE_VALUE); HttpResponse httpResponse = defaultHttpClient.execute(httpGet); if (httpResponse != null) { int responseCode = httpResponse.getStatusLine().getStatusCode(); Log.d(LOG_TAG, "get response code=" + httpResponse.getStatusLine().getStatusCode()); if (responseCode == 204) { // nothing is running } else if (responseCode == 200) { // app is running // Need to get real URL after a redirect // http://stackoverflow.com/a/10286025/594751 String lastUrl = dialServer.getAppsUrl(); if (handler.lastRedirectedUri != null) { lastUrl = handler.lastRedirectedUri.toString(); Log.d(LOG_TAG, "lastUrl=" + lastUrl); } String response = EntityUtils.toString(httpResponse.getEntity()); Log.d(LOG_TAG, "get response=" + response); parseXml(new StringReader(response)); Header[] headers = httpResponse.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Log.d(LOG_TAG, headers[i].getName() + "=" + headers[i].getValue()); } // stop the app instance HttpDelete httpDelete = new HttpDelete(lastUrl); httpResponse = defaultHttpClient.execute(httpDelete); if (httpResponse != null) { Log.d(LOG_TAG, "delete response code=" + httpResponse.getStatusLine().getStatusCode()); response = EntityUtils.toString(httpResponse.getEntity()); Log.d(LOG_TAG, "delete response=" + response); } else { Log.d(LOG_TAG, "no delete response"); } } } else { Log.i(LOG_TAG, "no get response"); return; } // Check if app is installed on device int responseCode = getAppStatus(defaultHttpClient, dialServer.getAppsUrl() + app); if (responseCode != 200) { return; } parseXml(new StringReader(response)); Log.d(LOG_TAG, "state=" + state); // start the app with POST HttpPost httpPost = new HttpPost(dialServer.getAppsUrl() + app); httpPost.setHeader(HEADER_CONNECTION, HEADER_CONNECTION_VALUE); httpPost.setHeader(HEADER_ORIGN, HEADER_ORIGIN_VALUE); httpPost.setHeader(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE); httpPost.setHeader(HEADER_DNT, HEADER_DNT_VALUE); httpPost.setHeader(HEADER_ACCEPT_ENCODING, HEADER_ACCEPT_ENCODING_VALUE); httpPost.setHeader(HEADER_ACCEPT, HEADER_ACCEPT_VALUE); httpPost.setHeader(HEADER_ACCEPT_LANGUAGE, HEADER_ACCEPT_LANGUAGE_VALUE); httpPost.setHeader(HEADER_CONTENT_TYPE, HEADER_CONTENT_TYPE_TEXT_VALUE); if (app.equals(FlingFrame.CHROMECAST)) { httpPost.setEntity(new StringEntity( "v=release-d4fa0a24f89ec5ba83f7bf3324282c8d046bf612&id=local%3A1&idle=windowclose")); } httpResponse = defaultHttpClient.execute(httpPost, localContext); if (httpResponse != null) { Log.d(LOG_TAG, "post response code=" + httpResponse.getStatusLine().getStatusCode()); response = EntityUtils.toString(httpResponse.getEntity()); Log.d(LOG_TAG, "post response=" + response); Header[] headers = httpResponse.getHeaders("LOCATION"); if (headers.length > 0) { location = headers[0].getValue(); Log.d(LOG_TAG, "post response location=" + location); } headers = httpResponse.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Log.d(LOG_TAG, headers[i].getName() + "=" + headers[i].getValue()); } } else { Log.i(LOG_TAG, "no post response"); return; } // Keep trying to get the app status until the // connection service URL is available state = STATE_STOPPED; do { responseCode = getAppStatus(defaultHttpClient, dialServer.getAppsUrl() + app); if (responseCode != 200) { break; } parseXml(new StringReader(response)); Log.d(LOG_TAG, "state=" + state); Log.d(LOG_TAG, "connectionServiceUrl=" + connectionServiceUrl); Log.d(LOG_TAG, "protocol=" + protocol); try { Thread.sleep(1000); } catch (Exception e) { } } while (state.equals(STATE_RUNNING) && connectionServiceUrl == null); if (connectionServiceUrl == null) { Log.i(LOG_TAG, "connectionServiceUrl is null"); return; // oops, something went wrong } // get the websocket URL String webSocketAddress = null; httpPost = new HttpPost(connectionServiceUrl); // "http://192.168.0.17:8008/connection/YouTube" httpPost.setHeader(HEADER_CONNECTION, HEADER_CONNECTION_VALUE); httpPost.setHeader(HEADER_ORIGN, HEADER_ORIGIN_VALUE); httpPost.setHeader(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE); httpPost.setHeader(HEADER_DNT, HEADER_DNT_VALUE); httpPost.setHeader(HEADER_ACCEPT_ENCODING, HEADER_ACCEPT_ENCODING_VALUE); httpPost.setHeader(HEADER_ACCEPT, HEADER_ACCEPT_VALUE); httpPost.setHeader(HEADER_ACCEPT_LANGUAGE, HEADER_ACCEPT_LANGUAGE_VALUE); httpPost.setHeader(HEADER_CONTENT_TYPE, HEADER_CONTENT_TYPE_JSON_VALUE); httpPost.setEntity(new StringEntity("{\"channel\":0,\"senderId\":{\"appName\":\"" + app + "\", \"senderId\":\"" + senderId + "\"}}")); httpResponse = defaultHttpClient.execute(httpPost, localContext); if (httpResponse != null) { responseCode = httpResponse.getStatusLine().getStatusCode(); Log.d(LOG_TAG, "post response code=" + responseCode); if (responseCode == 200) { // should return JSON payload response = EntityUtils.toString(httpResponse.getEntity()); Log.d(LOG_TAG, "post response=" + response); Header[] headers = httpResponse.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Log.d(LOG_TAG, headers[i].getName() + "=" + headers[i].getValue()); } // http://code.google.com/p/json-simple/ JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new StringReader(response)); // {"URL":"ws://192.168.0.17:8008/session?33","pingInterval":0} JSONObject jsonObject = (JSONObject) obj; webSocketAddress = (String) jsonObject.get("URL"); Log.d(LOG_TAG, "webSocketAddress: " + webSocketAddress); long pingInterval = (Long) jsonObject.get("pingInterval"); // TODO } catch (Exception e) { Log.e(LOG_TAG, "parse JSON", e); } } } else { Log.i(LOG_TAG, "no post response"); return; } // Make a web socket connection for doing RAMP // to control media playback this.started = false; this.closed = false; if (webSocketAddress != null) { // https://github.com/TooTallNate/Java-WebSocket URI uri = URI.create(webSocketAddress); rampWebSocketClient = new RampWebSocketClient(uri, this); new Thread(new Runnable() { public void run() { Thread t = new Thread(rampWebSocketClient); t.start(); try { t.join(); } catch (InterruptedException e1) { e1.printStackTrace(); } finally { rampWebSocketClient.close(); } } }).start(); } else { Log.i(LOG_TAG, "webSocketAddress is null"); } } catch (Exception e) { Log.e(LOG_TAG, "launchApp", e); } }
From source file:org.thomwiggers.Jjoyce.comet.CometJoyceClientRelay.java
public void sendStream(String token, Stream stream, boolean blocking) { if (!this.token.equals(token)) throw new IllegalArgumentException("Wrong token!"); this.conditionMessageIn = lock.newCondition(); this.conditionOut = lock.newCondition(); MultipartEntity multipartStream = new MultipartEntity(); multipartStream.addPart("stream", stream); final HttpPost post = new HttpPost( String.format("http://%s:%s%s?m=%s", hub.getHost(), hub.getPort(), hub.getPath())); post.setEntity(multipartStream);/* w ww . j a va 2 s . co m*/ Thread t = new Thread(new Runnable() { public void run() { try { httpClient.execute(post); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); t.start(); if (blocking) { try { t.join(); } catch (InterruptedException e) { } } }
From source file:eu.stratosphere.pact.runtime.task.ReduceTaskTest.java
@Test public void testCancelReduceTaskWhileSorting() { addInputComparator(this.comparator); setOutput(new NirvanaOutputList()); getTaskConfig().setDriverStrategy(DriverStrategy.SORTED_GROUP_REDUCE); final GroupReduceDriver<Record, Record> testTask = new GroupReduceDriver<Record, Record>(); try {//from ww w. j a va2 s .co m addInputSorted(new DelayingInfinitiveInputIterator(100), this.comparator.duplicate()); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } final AtomicBoolean success = new AtomicBoolean(false); Thread taskRunner = new Thread() { @Override public void run() { try { testDriver(testTask, MockReduceStub.class); success.set(true); } catch (Exception ie) { ie.printStackTrace(); } } }; taskRunner.start(); TaskCancelThread tct = new TaskCancelThread(1, taskRunner, this); tct.start(); try { tct.join(); taskRunner.join(); } catch (InterruptedException ie) { Assert.fail("Joining threads failed"); } Assert.assertTrue("Test threw an exception even though it was properly canceled.", success.get()); }
From source file:eu.stratosphere.pact.runtime.task.ReduceTaskTest.java
@Test public void testCancelReduceTaskWhileReducing() { final int keyCnt = 1000; final int valCnt = 2; addInput(new UniformRecordGenerator(keyCnt, valCnt, true)); addInputComparator(this.comparator); setOutput(new NirvanaOutputList()); getTaskConfig().setDriverStrategy(DriverStrategy.SORTED_GROUP_REDUCE); final GroupReduceDriver<Record, Record> testTask = new GroupReduceDriver<Record, Record>(); final AtomicBoolean success = new AtomicBoolean(false); Thread taskRunner = new Thread() { @Override// w w w .j a va2 s. com public void run() { try { testDriver(testTask, MockDelayingReduceStub.class); success.set(true); } catch (Exception ie) { ie.printStackTrace(); } } }; taskRunner.start(); TaskCancelThread tct = new TaskCancelThread(2, taskRunner, this); tct.start(); try { tct.join(); taskRunner.join(); } catch (InterruptedException ie) { Assert.fail("Joining threads failed"); } }
From source file:com.emc.ecs.sync.CasMigrationTest.java
@Test public void testCASSingleObject() throws Exception { FPPool sourcePool = new FPPool(connectString1); FPPool targetPool = new FPPool(connectString2); // create clip in source (<=1MB blob size) - capture summary for comparison StringWriter sourceSummary = new StringWriter(); List<String> clipIds = createTestClips(sourcePool, 1048576, 1, sourceSummary); String clipID = clipIds.iterator().next(); // open clip in source FPClip clip = new FPClip(sourcePool, clipID, FPLibraryConstants.FP_OPEN_FLAT); // buffer CDF ByteArrayOutputStream baos = new ByteArrayOutputStream(); clip.RawRead(baos);/*from w w w. j a va 2 s . c o m*/ // write CDF to target FPClip targetClip = new FPClip(targetPool, clipID, new ByteArrayInputStream(baos.toByteArray()), CLIP_OPTIONS); // migrate blobs FPTag tag, targetTag; int tagCount = 0; while ((tag = clip.FetchNext()) != null) { targetTag = targetClip.FetchNext(); Assert.assertEquals("Tag names don't match", tag.getTagName(), targetTag.getTagName()); Assert.assertTrue("Tag " + tag.getTagName() + " attributes not equal", Arrays.equals(tag.getAttributes(), targetTag.getAttributes())); int blobStatus = tag.BlobExists(); if (blobStatus == 1) { PipedInputStream pin = new PipedInputStream(BUFFER_SIZE); PipedOutputStream pout = new PipedOutputStream(pin); BlobReader reader = new BlobReader(tag, pout); // start reading in parallel Thread readThread = new Thread(reader); readThread.start(); // write inside this thread targetTag.BlobWrite(pin); readThread.join(); // this shouldn't do anything, but just in case if (!reader.isSuccess()) throw new Exception("blob read failed", reader.getError()); } else { if (blobStatus != -1) System.out.println("blob unavailable, clipId=" + clipID + ", tagNum=" + tagCount + ", blobStatus=" + blobStatus); } tag.Close(); targetTag.Close(); tagCount++; } clip.Close(); Assert.assertEquals("clip IDs not equal", clipID, targetClip.Write()); targetClip.Close(); // check target blob data targetClip = new FPClip(targetPool, clipID, FPLibraryConstants.FP_OPEN_FLAT); Assert.assertEquals("content mismatch", sourceSummary.toString(), summarizeClip(targetClip)); targetClip.Close(); // delete in source and target FPClip.Delete(sourcePool, clipID); FPClip.Delete(targetPool, clipID); }
From source file:gov.hhs.fha.nhinc.lift.proxy.client.ClientConnector.java
@Override public void run() { /*/*from w ww.j av a 2s . c o m*/ * Accept a connection and tunnel messages through the proxy system. */ Socket socket = null; try { Thread toProxyThread; Thread fromProxyThread; socket = server.accept(); log.debug("Server accepting to socket " + socket.getInetAddress()); Connector toProxy = new Connector(socket.getInputStream(), proxyConnection.getOutStream(), bufferSize); Connector fromProxy = new Connector(proxyConnection.getInStream(), socket.getOutputStream(), bufferSize); toProxyThread = new Thread(toProxy, "Client To Proxy"); fromProxyThread = new Thread(fromProxy, "Client From Proxy"); toProxyThread.start(); fromProxyThread.start(); log.debug("Waiting to finish " + toProxyThread.getName()); toProxyThread.join(); } catch (IOException e) { String errorMsg = "Problem in creating client to proxy connectors: " + e.getMessage(); log.error(errorMsg); controller.reportFailure(proxyConnection.getToken().getRequest(), errorMsg); } catch (InterruptedException e) { String errorMsg = "Client to proxy communication thread interrupted: " + e.getMessage(); log.error(errorMsg); controller.reportFailure(proxyConnection.getToken().getRequest(), errorMsg); } finally { if (socket != null) { try { log.debug("Closing socket " + socket.getInetAddress() + ": " + socket.getPort()); // Also closes associated streams socket.close(); } catch (IOException ex) { log.warn("Unable to close client to proxy socket: " + ex.getMessage()); } } if (proxyConnection != null) { try { log.debug("Closing proxy connection " + proxyConnection.getSocket().getInetAddress() + ": " + proxyConnection.getSocket().getPort()); proxyConnection.close(); } catch (IOException ex) { log.warn("Unable to close proxy connection: " + ex.getMessage()); } } if (server != null) { try { log.debug("Closing client connection server" + server.getInetAddress() + ": " + server.getLocalPort()); server.close(); } catch (IOException ex) { log.warn("Unable to close proxy connection: " + ex.getMessage()); } } } }