List of usage examples for java.lang InterruptedException getCause
public synchronized Throwable getCause()
From source file:org.seasar.dbflute.helper.thread.CountDownRace.java
protected void handleFuture(final List<Future<Void>> futureList) { for (Future<Void> future : futureList) { try {/*from ww w .java 2s . c o m*/ future.get(); } catch (InterruptedException e) { String msg = "future.get() was interrupted!"; throw new IllegalStateException(msg, e); } catch (ExecutionException e) { String msg = "Failed to fire the thread: " + future; throw new ThreadFireFailureException(msg, e.getCause()); } } }
From source file:org.pentaho.di.repository.pur.WebServiceManager.java
@Override @SuppressWarnings("unchecked") public <T> T createService(final String username, final String password, final Class<T> clazz) throws MalformedURLException { final Future<Object> resultFuture; synchronized (serviceCache) { // if this is true, a coder did not make sure that clearServices was called on disconnect if (lastUsername != null && !lastUsername.equals(username)) { throw new IllegalStateException(); }//from w ww . j a v a 2 s.c om final WebServiceSpecification webServiceSpecification = serviceNameMap.get(clazz); final String serviceName = webServiceSpecification.getServiceName(); if (serviceName == null) { throw new IllegalStateException(); } if (webServiceSpecification.getServiceType().equals(ServiceType.JAX_WS)) { // build the url handling whether or not baseUrl ends with a slash // String baseUrl = repositoryMeta.getRepositoryLocation().getUrl(); final URL url = new URL( baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "webservices/" + serviceName + "?wsdl"); //$NON-NLS-1$ //$NON-NLS-2$ String key = url.toString() + '_' + serviceName + '_' + clazz.getName(); if (!serviceCache.containsKey(key)) { resultFuture = executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { Service service = Service.create(url, new QName(NAMESPACE_URI, serviceName)); T port = service.getPort(clazz); // add TRUST_USER if necessary if (StringUtils .isNotBlank(System.getProperty("pentaho.repository.client.attemptTrust"))) { ((BindingProvider) port).getRequestContext().put( MessageContext.HTTP_REQUEST_HEADERS, Collections.singletonMap(TRUST_USER, Collections.singletonList(username))); } else { // http basic authentication ((BindingProvider) port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username); ((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password); } // accept cookies to maintain session on server ((BindingProvider) port).getRequestContext() .put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true); // support streaming binary data // TODO mlowery this is not portable between JAX-WS implementations (uses com.sun) ((BindingProvider) port).getRequestContext() .put(JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE, 8192); SOAPBinding binding = (SOAPBinding) ((BindingProvider) port).getBinding(); binding.setMTOMEnabled(true); return port; } }); serviceCache.put(key, resultFuture); } else { resultFuture = serviceCache.get(key); } } else { if (webServiceSpecification.getServiceType().equals(ServiceType.JAX_RS)) { String key = baseUrl.toString() + '_' + serviceName + '_' + clazz.getName(); if (!serviceCache.containsKey(key)) { resultFuture = executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { ClientConfig clientConfig = new DefaultClientConfig(); Client client = Client.create(clientConfig); client.addFilter(new HTTPBasicAuthFilter(username, password)); Class<?>[] parameterTypes = new Class<?>[] { Client.class, URI.class }; String factoryClassName = webServiceSpecification.getServiceClass().getName(); factoryClassName = factoryClassName.substring(0, factoryClassName.lastIndexOf("$")); Class<?> factoryClass = Class.forName(factoryClassName); Method method = factoryClass.getDeclaredMethod( webServiceSpecification.getServiceName(), parameterTypes); T port = (T) method.invoke(null, new Object[] { client, new URI(baseUrl + "/plugin") }); return port; } }); serviceCache.put(key, resultFuture); } else { resultFuture = serviceCache.get(key); } } else { resultFuture = null; } } try { if (clazz.isInterface()) { return UnifiedRepositoryInvocationHandler.forObject((T) resultFuture.get(), clazz); } else { return (T) resultFuture.get(); } } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause != null) { if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof MalformedURLException) { throw (MalformedURLException) cause; } } throw new RuntimeException(e); } } }
From source file:com.mirth.connect.plugins.datatypes.hl7v2.ER7BatchAdaptor.java
private String getMessageFromReader() throws Exception { SplitType splitType = batchProperties.getSplitType(); if (splitType == SplitType.MSH_Segment) { // TODO: The values of these parameters should come from the protocol // properties passed to processBatch // TODO: src is a character stream, not a byte stream byte startOfMessage = (byte) 0x0B; byte endOfMessage = (byte) 0x1C; StringBuilder message = new StringBuilder(); if (StringUtils.isNotBlank(previousLine)) { message.append(previousLine); message.append(segmentDelimiter); }/*from w w w. j a v a 2s. c om*/ while (scanner.hasNext()) { String line = StringUtils .remove(StringUtils.remove(scanner.next(), (char) startOfMessage), (char) endOfMessage) .trim(); if ((line.length() == 0) || line.equals((char) endOfMessage) || line.startsWith("MSH")) { if (message.length() > 0) { previousLine = line; return message.toString(); } while ((line.length() == 0) && scanner.hasNext()) { line = scanner.next(); } if (line.length() > 0) { message.append(line); message.append(segmentDelimiter); } } else if (line.startsWith("FHS") || line.startsWith("BHS") || line.startsWith("BTS") || line.startsWith("FTS")) { // ignore batch headers } else { message.append(line); message.append(segmentDelimiter); } } /* * MIRTH-2058: Now that the file has been completely read, make sure to process anything * remaining in the message buffer. There could have been lines read in that were not * closed with an EOM. */ if (message.length() > 0) { previousLine = null; return message.toString(); } } else if (splitType == SplitType.JavaScript) { if (StringUtils.isEmpty(batchProperties.getBatchScript())) { throw new BatchMessageException("No batch script was set."); } try { final String batchScriptId = ScriptController.getScriptId(ScriptController.BATCH_SCRIPT_KEY, sourceConnector.getChannelId()); MirthContextFactory contextFactory = contextFactoryController .getContextFactory(sourceConnector.getChannel().getResourceIds()); if (!factory.getContextFactoryId().equals(contextFactory.getId())) { synchronized (factory) { contextFactory = contextFactoryController .getContextFactory(sourceConnector.getChannel().getResourceIds()); if (!factory.getContextFactoryId().equals(contextFactory.getId())) { JavaScriptUtil.recompileGeneratedScript(contextFactory, batchScriptId); factory.setContextFactoryId(contextFactory.getId()); } } } String result = JavaScriptUtil.execute( new JavaScriptTask<String>(contextFactory, "HL7 v2.x Batch Adaptor", sourceConnector) { @Override public String doCall() throws Exception { Script compiledScript = CompiledScriptCache.getInstance() .getCompiledScript(batchScriptId); if (compiledScript == null) { logger.error("Batch script could not be found in cache"); return null; } else { Logger scriptLogger = Logger .getLogger(ScriptController.BATCH_SCRIPT_KEY.toLowerCase()); try { Scriptable scope = JavaScriptScopeUtil.getBatchProcessorScope( getContextFactory(), scriptLogger, sourceConnector.getChannelId(), sourceConnector.getChannel().getName(), getScopeObjects(bufferedReader)); return (String) Context.jsToJava(executeScript(compiledScript, scope), String.class); } finally { Context.exit(); } } } }); if (StringUtils.isEmpty(result)) { return null; } else { return result; } } catch (InterruptedException e) { throw e; } catch (JavaScriptExecutorException e) { logger.error(e.getCause()); } catch (Throwable e) { logger.error(e); } } else { throw new BatchMessageException("No valid batch splitting method detected"); } return null; }
From source file:com.aliyun.oss.common.comm.TimeoutServiceClient.java
@Override public ResponseMessage sendRequestCore(ServiceClient.Request request, ExecutionContext context) throws IOException { HttpRequestBase httpRequest = httpRequestFactory.createHttpRequest(request, context); HttpClientContext httpContext = HttpClientContext.create(); httpContext.setRequestConfig(this.requestConfig); CloseableHttpResponse httpResponse = null; HttpRequestTask httpRequestTask = new HttpRequestTask(httpRequest, httpContext); Future<CloseableHttpResponse> future = executor.submit(httpRequestTask); try {//from www .j av a2 s. c o m httpResponse = future.get(this.config.getRequestTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { logException("[ExecutorService]The current thread was interrupted while waiting: ", e); httpRequest.abort(); throw new ClientException(e.getMessage(), e); } catch (ExecutionException e) { RuntimeException ex; httpRequest.abort(); if (e.getCause() instanceof IOException) { ex = ExceptionFactory.createNetworkException((IOException) e.getCause()); } else { ex = new OSSException(e.getMessage(), e); } logException("[ExecutorService]The computation threw an exception: ", ex); throw ex; } catch (TimeoutException e) { logException("[ExecutorService]The wait " + this.config.getRequestTimeout() + " timed out: ", e); httpRequest.abort(); throw new ClientException(e.getMessage(), OSSErrorCode.REQUEST_TIMEOUT, "Unknown", e); } return buildResponse(request, httpResponse); }
From source file:com.bazaarvoice.seo.sdk.BVUIContentServiceProvider.java
/** * Self executioner method./* w w w .j a v a 2 s .com*/ * * @param reload * @return */ public StringBuilder executeCall(boolean reload) { if (reload) { return new StringBuilder(_uiContent); } boolean isSearchBot = showUserAgentSEOContent(); long executionTimeout = isSearchBot ? Long.parseLong( _bvConfiguration.getProperty(BVClientConfig.EXECUTION_TIMEOUT_BOT.getPropertyName())) : Long.parseLong(_bvConfiguration.getProperty(BVClientConfig.EXECUTION_TIMEOUT.getPropertyName())); if (!isSearchBot && executionTimeout == 0) { _message.append(BVMessageUtil.getMessage("MSG0004")); return null; } if (isSearchBot && executionTimeout < 100) { executionTimeout = 100; _message.append(BVMessageUtil.getMessage("MSG0005")); } ExecutorService executorService = BVThreadPool.getExecutorService(); Future<StringBuilder> future = executorService.submit(this); try { _uiContent = future.get(executionTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // e.printStackTrace(); } catch (ExecutionException e) { // e.printStackTrace(); if (e.getCause() instanceof BVSdkException) { throw new BVSdkException(e.getCause().getMessage()); } } catch (TimeoutException e) { String err = isSearchBot ? "ERR0026" : "ERR0018"; _message.append(MessageFormat.format(BVMessageUtil.getMessage(err), new Object[] { executionTimeout })); } return new StringBuilder(_uiContent); }
From source file:org.squidy.nodes.laserpointer.configclient.MainConfigFrameDirector.java
private boolean refreshCamera(final Camera camera) { SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override/*w w w .j av a2 s .c om*/ protected Void doInBackground() throws Exception { cService.refreshCamera(camera); return null; } }; new WorkerDialog("Refreshing camera " + camera.getId(), null, worker); try { worker.get(); } catch (InterruptedException e) { } catch (CancellationException e) { fullReset(); return false; } catch (ExecutionException e) { fullReset(); JOptionPane.showMessageDialog(null, e.getCause().getMessage(), "Error", JOptionPane.ERROR_MESSAGE); return false; } return true; }
From source file:eu.scidipes.toolkits.pawebapp.preservation.PreservationJobImpl.java
@Override public void run() { LOG.info(format("Preservation job for dataset: '%s' started", dataset.getDatasetName())); final int numJobItems = preservationJobItemMap.size(); for (int i = 0; i < numJobItems; i++) { try {// www .jav a2s.c om final PreservationJobItemResult<Preservable, ?> presObj = completionService.take().get(); preservationJobItemMap.put(presObj.getPreservable(), presObj); LOG.debug("Added ({}) to preservationJobItemMap", presObj); } catch (final InterruptedException e) { LOG.error(e.getMessage(), e); Thread.currentThread().interrupt(); } catch (final ExecutionException e) { LOG.error(e.getMessage(), e); final Throwable cause = e.getCause(); if (cause instanceof PreservationStorageException) { /* Wrap the preservation exception in a job item and add to the list: */ final PreservationStorageException pse = (PreservationStorageException) cause; LOG.error(pse.getCause().getMessage(), pse.getCause()); preservationJobItemMap.put(pse.getPreservable(), new PreservationJobItemResultImpl(pse.getPreservable(), pse.getCause())); } else { throw launderThrowable(cause); } } completed.incrementAndGet(); } LOG.info(format( "Preservation job for dataset: '%s' finished preserving %d manifests, digital objects and RILs", dataset.getDatasetName(), Integer.valueOf(numJobItems))); /* Update the RILs in the persistence context: */ for (final DatasetRIL ril : dataset.getRils()) { datasetRepo.updateDatasetRIL((UploadRepInfoLabel) ril.getRil(), ril.getRilCPID()); } datasetRepo.save((FormsBundleImpl) dataset); }
From source file:org.squidy.nodes.laserpointer.configclient.MainConfigFrameDirector.java
/** * Stop a camera.//from w w w .j ava 2 s. c om * @param camera * @return */ private boolean stopTracking(final Camera camera) { SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { cService.stopTracking(camera); return null; }; }; new WorkerDialog("Stopping Tracking", null, worker); try { worker.get(); } catch (InterruptedException e) { } catch (CancellationException e) { fullReset(); return false; } catch (ExecutionException e) { fullReset(); JOptionPane.showMessageDialog(null, e.getCause().getMessage(), "Error", JOptionPane.ERROR_MESSAGE); return false; } if (camera.getMsg() != null) { assert (false) : "Unexpected return message."; camera.setTracking(null); return false; } camera.setTracking(false); return true; }
From source file:org.squidy.nodes.laserpointer.configclient.MainConfigFrameDirector.java
/** * Starts a camera.//from w ww .java 2 s.com * @param camera * @return */ private boolean startTracking(final Camera camera) { SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { cService.startTracking(camera); return null; }; }; new WorkerDialog("Starting camera " + camera.getId(), null, worker); try { worker.get(); } catch (InterruptedException e) { } catch (CancellationException e) { fullReset(); return false; } catch (ExecutionException e) { fullReset(); JOptionPane.showMessageDialog(null, e.getCause().getMessage(), "Error", JOptionPane.ERROR_MESSAGE); return false; } if (!camera.isOnline()) { JOptionPane.showMessageDialog(null, "Camera " + camera.getId() + " is offline. Unable to start tracking.", "Communication Failure", JOptionPane.ERROR_MESSAGE); camera.setTracking(false); return false; } if (camera.getMsg() != null && !camera.getMsg().equals(Protocol.CAM_STARTTRACKING)) { JOptionPane.showMessageDialog(null, "Camera reported an error when starting tracking. Message: " + camera.getMsg(), "Property Message", JOptionPane.INFORMATION_MESSAGE); CommHelper.clearMessages(camera); return false; } camera.setTracking(true); return true; }
From source file:org.opendaylight.netvirt.neutronvpn.NeutronvpnUtils.java
@SuppressWarnings("checkstyle:IllegalCatch") protected static boolean lock(String lockName) { if (locks.get(lockName) != null) { synchronized (locks) { if (locks.get(lockName) == null) { locks.putIfAbsent(lockName, new ImmutablePair<>(new ReentrantReadWriteLock(), new AtomicInteger(0))); }//from w ww. j a v a2s. com locks.get(lockName).getRight().incrementAndGet(); } try { if (locks.get(lockName) != null) { locks.get(lockName).getLeft().writeLock().tryLock(LOCK_WAIT_TIME, secUnit); } } catch (InterruptedException e) { locks.get(lockName).getRight().decrementAndGet(); LOG.error("Unable to acquire lock for {}", lockName); throw new RuntimeException(String.format("Unable to acquire lock for %s", lockName), e.getCause()); } } else { locks.putIfAbsent(lockName, new ImmutablePair<>(new ReentrantReadWriteLock(), new AtomicInteger(0))); locks.get(lockName).getRight().incrementAndGet(); try { locks.get(lockName).getLeft().writeLock().tryLock(LOCK_WAIT_TIME, secUnit); } catch (Exception e) { locks.get(lockName).getRight().decrementAndGet(); LOG.error("Unable to acquire lock for {}", lockName); throw new RuntimeException(String.format("Unable to acquire lock for %s", lockName), e.getCause()); } } return true; }