List of usage examples for java.lang InterruptedException getMessage
public String getMessage()
From source file:eu.stratosphere.runtime.io.network.ChannelManager.java
@Override public void dispatchFromOutputChannel(Envelope envelope) throws IOException, InterruptedException { EnvelopeReceiverList receiverList = getReceiverListForEnvelope(envelope, true); Buffer srcBuffer = envelope.getBuffer(); Buffer destBuffer = null;/*from w w w .ja v a 2 s .c om*/ boolean success = false; try { if (receiverList.hasLocalReceiver()) { ChannelID receiver = receiverList.getLocalReceiver(); Channel channel = this.channels.get(receiver); if (channel == null) { throw new LocalReceiverCancelledException(receiver); } if (!channel.isInputChannel()) { throw new IOException("Local receiver " + receiver + " is not an input channel."); } InputChannel<?> inputChannel = (InputChannel<?>) channel; // copy the buffer into the memory space of the receiver if (srcBuffer != null) { try { destBuffer = inputChannel.requestBufferBlocking(srcBuffer.size()); } catch (InterruptedException e) { throw new IOException(e.getMessage()); } srcBuffer.copyToBuffer(destBuffer); envelope.setBuffer(destBuffer); srcBuffer.recycleBuffer(); } inputChannel.queueEnvelope(envelope); success = true; } else if (receiverList.hasRemoteReceiver()) { RemoteReceiver remoteReceiver = receiverList.getRemoteReceiver(); // Generate sender hint before sending the first envelope over the network if (envelope.getSequenceNumber() == 0) { generateSenderHint(envelope, remoteReceiver); } this.nettyConnectionManager.enqueue(envelope, remoteReceiver); success = true; } } finally { if (!success) { if (srcBuffer != null) { srcBuffer.recycleBuffer(); } if (destBuffer != null) { destBuffer.recycleBuffer(); } } } }
From source file:edu.ucsb.nceas.MCTestCase.java
/** * Create a unique docid for testing insert and update. Does not * include the 'revision' part of the id. * //from w w w . j a va 2 s. c om * @return a String docid based on the current date and time */ protected String generateDocumentId() { try { Thread.sleep(1010); } catch (InterruptedException ie) { debug("Could not sleep: " + ie.getMessage()); } StringBuffer docid = new StringBuffer(prefix); docid.append("."); // Create a calendar to get the date formatted properly String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000); SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]); pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); Calendar calendar = new GregorianCalendar(pdt); Date trialTime = new Date(); calendar.setTime(trialTime); docid.append(calendar.get(Calendar.YEAR)); docid.append(calendar.get(Calendar.DAY_OF_YEAR)); docid.append(calendar.get(Calendar.HOUR_OF_DAY)); docid.append(calendar.get(Calendar.MINUTE)); docid.append(calendar.get(Calendar.SECOND)); return docid.toString(); }
From source file:org.excalibur.driver.google.compute.GoogleCompute.java
@Override public Instances createInstances(InstanceTemplate template) { Instances instances = new Instances(); CountDownLatch latch = new CountDownLatch(template.getMaxCount()); ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(this.executorService); List<DeployInstanceTask> tasks = Lists.newArrayList(); final Instance model = createInstanceFromTemplate(template); for (int i = 0; i < template.getMaxCount(); i++) { Instance instance = model.clone(); if (template.getMaxCount() > 1) { instance.setName(String.format("%s-%s", model.getName(), i + 1)); instance.getDisks().get(0).getInitializeParams().setDiskName(instance.getName()); instance.getDisks().get(0).setDeviceName(instance.getName()); }/*from w w w.j a va 2s . c o m*/ tasks.add(new DeployInstanceTask(instance, latch)); } try { List<Future<VirtualMachine>> submittedTasks = listeningExecutorService.invokeAll(tasks); latch.await(5, TimeUnit.MINUTES); for (Future<VirtualMachine> f : submittedTasks) { instances.addInstance(f.get()); } } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } catch (ExecutionException e) { LOGGER.error(e.getMessage(), e); } listeningExecutorService.shutdown(); LOGGER.debug("Waiting the instances' ready state...."); ThreadUtils.sleep(30 * 1000); LOGGER.debug("Created [{}] instance(s) of [{}/{}]", instances.size(), template.getMinCount(), template.getMaxCount()); return instances; }
From source file:org.apache.manifoldcf.authorities.authorities.generic.GenericAuthority.java
protected AuthorizationResponse getAuthorizationResponseUncached(HttpClient client, String userName) throws ManifoldCFException { StringBuilder url = new StringBuilder(genericEntryPoint); url.append("?").append(ACTION_PARAM_NAME).append("=").append(ACTION_AUTH); url.append("&username=").append(URLEncoder.encode(userName)); try {// w ww . j ava 2s. co m FetchTokensThread t = new FetchTokensThread(client, url.toString()); t.start(); t.join(); if (t.getException() != null) { return unreachableResponse; } Auth auth = t.getAuthResponse(); if (auth == null) { return userNotFoundResponse; } if (!auth.exists) { return userNotFoundResponse; } if (auth.tokens == null) { return new AuthorizationResponse(new String[] {}, AuthorizationResponse.RESPONSE_OK); } String[] tokens = new String[auth.tokens.size()]; int k = 0; while (k < tokens.length) { tokens[k] = (String) auth.tokens.get(k); k++; } return new AuthorizationResponse(tokens, AuthorizationResponse.RESPONSE_OK); } catch (InterruptedException ex) { throw new ManifoldCFException(ex.getMessage(), ex, ManifoldCFException.INTERRUPTED); } }
From source file:com.mgmtp.perfload.core.daemon.LtDaemon.java
/** * Starts the daemon creating the server. Further actions are triggered by requests from * management console and test processes. *///from w ww .j a v a 2 s.c om public void execute() { log().info("Initializing..."); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { // Count down the latch, so the daemon can exit. // Also executed when the user hits Ctrl-C if (doneLatch != null) { doneLatch.countDown(); try { // TODO timeouts configurable? Thread.sleep(2000L); } catch (InterruptedException ex) { // } } server.shutdown(); log().info("Good bye."); } }); server.bind(); try { // Keep the daemon alive doneLatch.await(); log().info("Exiting..."); } catch (InterruptedException ex) { // cannot normally happen log().error(ex.getMessage(), ex); } }
From source file:fr.gael.dhus.datastore.scanner.ScannerFactory.java
/** * Process passed file scanner attached to a the passed user within * a separate thread. If the requested scanner is already running ( * from schedule or UI), it will not restart. * @param scan_id//from w ww . j av a2s .c o m * @param user * @throws ScannerException when scanner cannot be started. */ public void processScan(final Long scan_id, final User user) throws ScannerException { fr.gael.dhus.database.object.FileScanner fileScanner = null; SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd MMMM yyyy - HH:mm:ss", Locale.ENGLISH); // Check if scanner is already running. If not set it status. //fileScannerDao.printCurrentSessions (); //synchronized (fileScannerDao) //{ fileScanner = fileScannerDao.read(scan_id); if (fr.gael.dhus.database.object.FileScanner.STATUS_RUNNING.equals(fileScanner.getStatus())) { throw new ScannerException("Scanner to \"" + fileScanner.getUsername() + "@" + fileScanner.getUrl() + "\" already running."); } fileScanner.setStatus(fr.gael.dhus.database.object.FileScanner.STATUS_RUNNING); fileScanner.setStatusMessage("Started on " + sdf.format(new Date()) + "<br>"); fileScannerDao.update(fileScanner); //} List<Collection> collections = new ArrayList<Collection>(); List<Long> colIds = fileScannerDao.getScannerCollections(scan_id); for (Long colId : colIds) { Collection col = collectionDao.read(colId); if (col != null) { collections.add(col); } } // Processing scanner is used to manage synchronization between // processing and this scanner. It is in charge of setting and updating // the scanner status. FileScannerWrapper wrapper = new FileScannerWrapper(fileScanner); Hook hook = new Hook(fileScanner); String status = fr.gael.dhus.database.object.FileScanner.STATUS_OK; String message = "Error while scanning."; try { Scanner scanner = getUploadScanner(fileScanner.getUrl(), fileScanner.getUsername(), fileScanner.getPassword(), fileScanner.getPattern(), user, collections, wrapper); runningScanners.put(scan_id, scanner); Runtime.getRuntime().addShutdownHook(hook); int total = scanner.scan(); message = "Successfully completed on " + sdf.format(new Date()) + " with " + total + " product" + (total > 1 ? "s" : "") + " scanned."; } catch (InterruptedException e) { status = fr.gael.dhus.database.object.FileScanner.STATUS_OK; message = "Scanner stopped by user on " + sdf.format(new Date()); } catch (Exception e) { status = fr.gael.dhus.database.object.FileScanner.STATUS_ERROR; message = "Scanner error occurs on " + sdf.format(new Date()) + ": " + e.getMessage(); } finally { Runtime.getRuntime().removeShutdownHook(hook); wrapper.setScannerDone(status, message); } }
From source file:edu.mit.ll.graphulo.pig.backend.AbstractGraphuloStorage.java
@Override public Tuple getNext() throws IOException { try {// ww w . j a va 2 s . c o m // load the next pair if (!reader.nextKeyValue()) return null; Key key = (Key) reader.getCurrentKey(); Value value = (Value) reader.getCurrentValue(); assert key != null && value != null; return getTuple(key, value); } catch (InterruptedException e) { throw new IOException(e.getMessage()); } }
From source file:edu.isi.wings.execution.engine.api.impl.distributed.DistributedExecutionEngine.java
@Override public ProcessStatus call() throws Exception { File tempdir = File.createTempFile(planName + "-", "-" + exeName); if (!tempdir.delete() || !tempdir.mkdirs()) throw new Exception("Cannot create temp directory"); ProcessStatus status = new ProcessStatus(); try {//w w w . j av a 2s.c o m File codef = new File(this.codeBinary); codef.setExecutable(true); PrintWriter fout = null; if (outfilepath != null) { File f = new File(outfilepath); f.getParentFile().mkdirs(); fout = new PrintWriter(f); } ProcessBuilder pb = new ProcessBuilder(args); pb.directory(tempdir); pb.redirectErrorStream(true); // Set environment variables for (String var : this.environment.keySet()) pb.environment().put(var, this.environment.get(var)); this.process = pb.start(); // Read output stream StreamGobbler outputGobbler = new StreamGobbler(this.process.getInputStream(), fout); outputGobbler.start(); // Wait for the process to exit this.process.waitFor(); status.setExitValue(this.process.exitValue()); status.setLog(outputGobbler.getLog()); } catch (InterruptedException e) { if (this.process != null) { //System.out.println("Stopping remote process"); this.process.destroy(); } status.setLog("!! Stopping Remotely !! .. " + exeName); status.setExitValue(-1); } catch (Exception e) { status.setLog(e.getMessage()); status.setExitValue(-1); } // Delete temp directory FileUtils.deleteDirectory(tempdir); return status; }
From source file:eu.esdihumboldt.hale.io.haleconnect.internal.HaleConnectServiceImpl.java
/** * @see eu.esdihumboldt.hale.io.haleconnect.HaleConnectService#uploadProjectFile(java.lang.String, * eu.esdihumboldt.hale.io.haleconnect.Owner, java.io.File, * eu.esdihumboldt.hale.common.core.io.ProgressIndicator) *///from w ww. j a v a2s. com @Override public boolean uploadProjectFile(String projectId, Owner owner, File file, ProgressIndicator progress) throws HaleConnectException { if (!this.isLoggedIn()) { throw new HaleConnectException("Not logged in"); } String apiKey = this.getSession().getToken(); SettableFuture<Boolean> future = SettableFuture.create(); try { FilesApi filesApi = ProjectStoreHelper.getFilesApi(this, apiKey); // POST /raw int totalWork = computeTotalWork(file); ApiCallback<Feedback> apiCallback = createUploadFileCallback(future, progress, file, totalWork); progress.begin("Uploading project archive", totalWork); filesApi.addFilesAsync(owner.getType().getJsonValue(), owner.getId(), projectId, file, apiCallback); return future.get(); } catch (com.haleconnect.api.projectstore.v1.ApiException e1) { throw new HaleConnectException(e1.getMessage(), e1, e1.getCode(), e1.getResponseHeaders()); } catch (ExecutionException e2) { Throwable t = e2.getCause(); if (t instanceof HaleConnectException) { throw (HaleConnectException) t; } else { throw new HaleConnectException(t.getMessage(), t); } } catch (InterruptedException e3) { throw new HaleConnectException(e3.getMessage(), e3); } }
From source file:android.net.http.Request.java
/** * Receive a single http response.//from w w w.j a v a 2 s.c om * * @param httpClientConnection the request to receive the response for. */ void readResponse(AndroidHttpClientConnection httpClientConnection) throws IOException, ParseException { if (mCancelled) return; // don't send cancelled requests StatusLine statusLine = null; boolean hasBody = false; httpClientConnection.flush(); int statusCode = 0; Headers header = new Headers(); do { statusLine = httpClientConnection.parseResponseHeader(header); statusCode = statusLine.getStatusCode(); } while (statusCode < HttpStatus.SC_OK); if (HttpLog.LOGV) HttpLog.v("Request.readResponseStatus() " + statusLine.toString().length() + " " + statusLine); ProtocolVersion v = statusLine.getProtocolVersion(); mEventHandler.status(v.getMajor(), v.getMinor(), statusCode, statusLine.getReasonPhrase()); mEventHandler.headers(header); HttpEntity entity = null; hasBody = canResponseHaveBody(mHttpRequest, statusCode); if (hasBody) entity = httpClientConnection.receiveResponseEntity(header); // restrict the range request to the servers claiming that they are // accepting ranges in bytes boolean supportPartialContent = "bytes".equalsIgnoreCase(header.getAcceptRanges()); if (entity != null) { InputStream is = entity.getContent(); // process gzip content encoding Header contentEncoding = entity.getContentEncoding(); InputStream nis = null; byte[] buf = null; int count = 0; try { if (contentEncoding != null && contentEncoding.getValue().equals("gzip")) { nis = new GZIPInputStream(is); } else { nis = is; } /* accumulate enough data to make it worth pushing it * up the stack */ buf = mConnection.getBuf(); int len = 0; int lowWater = buf.length / 2; while (len != -1) { synchronized (this) { while (mLoadingPaused) { // Put this (network loading) thread to sleep if WebCore // has asked us to. This can happen with plugins for // example, if we are streaming data but the plugin has // filled its internal buffers. try { wait(); } catch (InterruptedException e) { HttpLog.e("Interrupted exception whilst " + "network thread paused at WebCore's request." + " " + e.getMessage()); } } } len = nis.read(buf, count, buf.length - count); if (len != -1) { count += len; if (supportPartialContent) mReceivedBytes += len; } if (len == -1 || count >= lowWater) { if (HttpLog.LOGV) HttpLog.v("Request.readResponse() " + count); mEventHandler.data(buf, count); count = 0; } } } catch (EOFException e) { /* InflaterInputStream throws an EOFException when the server truncates gzipped content. Handle this case as we do truncated non-gzipped content: no error */ if (count > 0) { // if there is uncommited content, we should commit them mEventHandler.data(buf, count); } if (HttpLog.LOGV) HttpLog.v("readResponse() handling " + e); } catch (IOException e) { // don't throw if we have a non-OK status code if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_PARTIAL_CONTENT) { if (supportPartialContent && count > 0) { // if there is uncommited content, we should commit them // as we will continue the request mEventHandler.data(buf, count); } throw e; } } finally { if (nis != null) { nis.close(); } } } mConnection.setCanPersist(entity, statusLine.getProtocolVersion(), header.getConnectionType()); mEventHandler.endData(); complete(); if (HttpLog.LOGV) HttpLog.v("Request.readResponse(): done " + mHost.getSchemeName() + "://" + getHostPort() + mPath); }