List of usage examples for java.util NoSuchElementException getMessage
public String getMessage()
From source file:de.suse.swamp.core.workflow.WorkflowTemplate.java
/** * Checks if the User has the given role in the Workflowtemplate. * This is configured in the Workflow definition. * Example roles are "admin" - "starter" - "user" - "owner" * * swampadmins as defined in the SWAMP usermanagement have all roles * @throws Exception if named role does not exist *///from w ww . j a va 2 s . c o m public boolean hasRole(String username, String role) { boolean hasRole = false; WorkflowRole wfrole = getWorkflowRole(role); // check if the user is in the role the regular way, // but mind that the needed databit may not yet be attached try { if (wfrole.hasRole(username, this)) { hasRole = true; } } catch (NoSuchElementException e) { // skip exception, because templates often haven't yet attached the needed values } catch (Exception e) { Logger.ERROR("Error when checking for role " + role + " Msg: " + e.getMessage()); return false; } //for anonymous users, we can stop here: if (username.equals("anonymous")) { return hasRole; } try { if (hasRole == false) { SWAMPUser user = null; try { user = SecurityManager.getUser(username); } catch (StorageException e) { Logger.ERROR("Error fetching user: " + username + ". Reason: " + e.getMessage()); return false; } // SWAMPAdmins, Workflow-Admins and "Owner" // always have all permissions in a workflow if (SecurityManager.isGroupMember(user, "swampadmins") || getWorkflowRole("admin").hasRole(username, this)) { hasRole = true; } } // at last if the user has a role in any single instance of that workflowtemplate // he has that role of that template if (!hasRole && !wfrole.isStaticRole(this)) { long time = System.currentTimeMillis(); List ids = new ArrayList(); PropertyFilter templateFilter = new PropertyFilter(); templateFilter.addWfTemplate(this.getName()); // if we have more databitpaths, the id lists need to be merged, // because the different roles are like an OR statement List paths = new ArrayList(); if (wfrole instanceof DatabitRole) { paths.add(((DatabitRole) wfrole).getRoleDatabit()); } else if (wfrole instanceof ReferencesRole) { paths = ((ReferencesRole) wfrole).getAllRoleDatabits(this); } for (Iterator it = paths.iterator(); it.hasNext();) { ArrayList filters = new ArrayList(); filters.add(templateFilter); String datapath = (String) it.next(); ContentFilter cfilter = new ContentFilter(); cfilter.setDatabitPath(datapath); // names are stored: name1, name2... String regexp = "(" + username + "$|" + username + ",)"; cfilter.setDatabitValueRegex(regexp); filters.add(cfilter); ids.addAll(WorkflowManager.getInstance().getWorkflowIds(filters, null)); if (ids.size() > 0) { hasRole = true; break; } } Logger.DEBUG("non-static check for " + role + "/" + username + "/" + this.getName() + " (" + hasRole + ") took " + (System.currentTimeMillis() - time) + "ms"); } } catch (NoSuchElementException e) { // skip exception, because templates often haven't yet attached the needed values } catch (Exception e) { Logger.ERROR("Error when checking for role " + role + " Msg: " + e.getMessage()); e.printStackTrace(); return false; } return hasRole; }
From source file:com.eucalyptus.images.Images.java
public static ImageInfo createFromDeviceMapping(final UserFullName userFullName, final String imageName, final String imageDescription, final ImageMetadata.Platform platform, String eki, String eri, final String rootDeviceName, final List<BlockDeviceMappingItemType> blockDeviceMappings) throws EucalyptusCloudException { final ImageMetadata.Architecture imageArch = ImageMetadata.Architecture.x86_64;//TODO:GRZE:OMGFIXME: track parent vol info; needed here final ImageMetadata.Platform imagePlatform = platform; if (ImageMetadata.Platform.windows.equals(imagePlatform)) { eki = null;/*from w w w. j a v a2s .c om*/ eri = null; } // Block device mappings have been verified before control gets here. // If anything has changed with regard to the snapshot state, it will be caught while data structures for the image. final BlockDeviceMappingItemType rootBlockDevice = Iterables.find(blockDeviceMappings, findEbsRoot(rootDeviceName), null); if (rootBlockDevice == null) { throw new EucalyptusCloudException( "Failed to create image, root device mapping not found: " + rootDeviceName); } final String snapshotId = ResourceIdentifiers.tryNormalize() .apply(rootBlockDevice.getEbs().getSnapshotId()); Snapshot snap; try { snap = Transactions.one(Snapshot.named(userFullName.asAccountFullName(), snapshotId), RestrictedTypes.filterPrivileged(), Functions.<Snapshot>identity()); } catch (NoSuchElementException ex) { throw new EucalyptusCloudException("Failed to create image from specified block device mapping: " + rootBlockDevice + " because of: Snapshot not found " + snapshotId); } catch (TransactionExecutionException ex) { throw new EucalyptusCloudException("Failed to create image from specified block device mapping: " + rootBlockDevice + " because of: " + ex.getMessage()); } catch (ExecutionException ex) { LOG.error(ex, ex); throw new EucalyptusCloudException("Failed to create image from specified block device mapping: " + rootBlockDevice + " because of: " + ex.getMessage()); } final Integer suppliedVolumeSize = rootBlockDevice.getEbs().getVolumeSize() != null ? rootBlockDevice.getEbs().getVolumeSize() : snap.getVolumeSize(); final Long imageSizeBytes = suppliedVolumeSize * 1024l * 1024l * 1024l; final Boolean targetDeleteOnTermination = Boolean.TRUE .equals(rootBlockDevice.getEbs().getDeleteOnTermination()); final String imageId = ResourceIdentifiers.generateString(ImageMetadata.Type.machine.getTypePrefix()); final boolean mapRoot = DEFAULT_PARTITIONED_ROOT_DEVICE.equals(rootDeviceName); BlockStorageImageInfo ret = new BlockStorageImageInfo(userFullName, imageId, imageName, imageDescription, imageSizeBytes, imageArch, imagePlatform, eki, eri, snap.getDisplayName(), targetDeleteOnTermination, mapRoot ? DEFAULT_ROOT_DEVICE : rootDeviceName); final EntityTransaction tx = Entities.get(BlockStorageImageInfo.class); try { ret = Entities.merge(ret); Iterables.addAll(ret.getDeviceMappings(), Iterables.transform(blockDeviceMappings, Images.deviceMappingGenerator(ret, suppliedVolumeSize, mapRoot ? Collections.singletonMap(DEFAULT_PARTITIONED_ROOT_DEVICE, DEFAULT_ROOT_DEVICE) : Collections.<String, String>emptyMap()))); ret.setImageFormat(ImageMetadata.ImageFormat.fulldisk.toString()); ret.setState(ImageMetadata.State.available); tx.commit(); LOG.info("Registering image pk=" + ret.getDisplayName() + " ownerId=" + userFullName); } catch (Exception e) { throw new EucalyptusCloudException( "Failed to register image using snapshot: " + snapshotId + " because of: " + e.getMessage(), e); } finally { if (tx.isActive()) tx.rollback(); } return ret; }
From source file:org.zenoss.app.consumer.metric.impl.OpenTsdbWriter.java
void runUntilCanceled() throws InterruptedException { ExponentialBackOff backoffTracker = null; while (!isCanceled()) { if (Thread.interrupted()) { throw new InterruptedException(); }/*from ww w .j av a 2s .com*/ Collection<Metric> metrics = metricsQueue.poll(batchSize, maxIdleTime); log.debug("Back from polling metricsQueue. metrics.size = {}", null == metrics ? "null" : metrics.size()); // Check to see if we should down this writer entirely. log.debug("Checking for shutdown. lastWorkTime = {}; maxIdleTime = {}; sum = {}; currentTime ={}", lastWorkTime, maxIdleTime, lastWorkTime + maxIdleTime, System.currentTimeMillis()); if (isNullOrEmpty(metrics) && // No records could be read from the metrics queue lastWorkTime > 0 && // This thread has done work at least once maxIdleTime > 0 && // The max idle time is set to something meaningful System.currentTimeMillis() > lastWorkTime + maxIdleTime) // The max idle time has expired { log.info("Shutting down writer due to dearth of work"); break; } /* * If all the conditions were not met for shutting this writer down, * we still might want to just abort this run if we didn't get any * data from the metrics queue */ if (isNullOrEmpty(metrics)) { log.debug("No work to do, so checking again."); continue; } // We have some work to do, some process what we got from the metrics queue if (backoffTracker == null) { backoffTracker = createExponentialBackOff(); } try { processBatch(metrics); backoffTracker.reset(); } catch (NoSuchElementException e) { long backOff = this.minBackOff; try { backOff = backoffTracker.nextBackOffMillis(); } catch (IOException e1) { // shouldn't happen but if it does we'll use the default backOff log.debug("caught IOException backing off tracker - should go to default backOff."); } if (ExponentialBackOff.STOP == backOff) { // We've reached the max amount of time to backoff, use max backoff backOff = backoffTracker.getMaxIntervalMillis(); log.warn("Error getting OpenTsdbClient after {} ms: {}", backoffTracker.getElapsedTimeMillis(), e.getMessage()); } log.debug("Connection back off, sleeping {} ms", backOff); Thread.sleep(backOff); } } log.debug("work canceled."); }
From source file:org.geotools.arcsde.session.SessionPool.java
/** * @see org.geotools.arcsde.session.ISessionPool#getSession(boolean) *///from www . j a v a2 s . c om public ISession getSession(final boolean transactional) throws IOException, UnavailableConnectionException { checkOpen(); try { Session connection = null; if (transactional) { LOGGER.finest("Borrowing session from pool for transactional access"); connection = (Session) pool.borrowObject(); } else { synchronized (openSessionsNonTransactional) { try { if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer("Grabbing session from pool on " + Thread.currentThread().getName()); } connection = (Session) pool.borrowObject(); if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer("Got session from the pool on " + Thread.currentThread().getName()); } } catch (NoSuchElementException e) { if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer("No available sessions in the pool, falling back to queued session"); } connection = openSessionsNonTransactional.remove(); } openSessionsNonTransactional.add(connection); if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer("Got session from the in use queue on " + Thread.currentThread().getName()); } } } connection.markActive(); return connection; } catch (NoSuchElementException e) { LOGGER.log(Level.WARNING, "Out of connections: " + e.getMessage() + ". Config: " + this.config); throw new UnavailableConnectionException(config.getMaxConnections(), this.config); } catch (SeException se) { ArcSdeException sdee = new ArcSdeException(se); LOGGER.log(Level.WARNING, "ArcSDE error getting connection for " + config, sdee); throw sdee; } catch (Exception e) { LOGGER.log(Level.WARNING, "Unknown problem getting connection: " + e.getMessage(), e); throw (IOException) new IOException("Unknown problem fetching connection from connection pool") .initCause(e); } }
From source file:com.eucalyptus.blockstorage.BlockStorageController.java
public GetVolumeTokenResponseType GetVolumeToken(GetVolumeTokenType request) throws EucalyptusCloudException { GetVolumeTokenResponseType reply = (GetVolumeTokenResponseType) request.getReply(); String volumeId = request.getVolumeId(); LOG.info("Processing GetVolumeToken request for volume " + volumeId); if (null == volumeId) { LOG.error("Cannot get token for a null-valued volumeId"); throw new EucalyptusCloudException("No volumeId specified in token request"); }//from w w w.j a v a2s . c om EntityTransaction db = Entities.get(VolumeInfo.class); try { VolumeInfo vol = Entities.uniqueResult(new VolumeInfo(volumeId)); VolumeToken token = vol.getOrCreateAttachmentToken(); //Encrypt the token with the NC's private key String encryptedToken = BlockStorageUtil.encryptForNode(token.getToken(), BlockStorageUtil.getPartitionForLocalService(Storage.class)); reply.setToken(encryptedToken); reply.setVolumeId(volumeId); db.commit(); return reply; } catch (NoSuchElementException e) { throw new EucalyptusCloudException("Volume " + request.getVolumeId() + " not found", e); } catch (Exception e) { LOG.error("Failed to get volume token: " + e.getMessage()); throw new EucalyptusCloudException("Could not get volume token for volume " + request.getVolumeId(), e); } finally { if (db.isActive()) { db.rollback(); } } }
From source file:org.speechforge.cairo.server.config.ReceiverConfig.java
/** * TODOC/* w w w .j ava 2s . c o m*/ * @param index * @param config * @throws ConfigurationException */ public ReceiverConfig(int index, XMLConfiguration config) throws ConfigurationException { super(index, config); try { try { String sphinxConfigURL = config.getString("resources.resource(" + index + ").sphinxConfigURL"); if (sphinxConfigURL != null && sphinxConfigURL.length() > 0) { _sphinxConfigURL = new URL(sphinxConfigURL); } } catch (NoSuchElementException e) { // ignore } if (_sphinxConfigURL == null) { _sphinxConfigURL = this.getClass().getResource("/config/sphinx-config.xml"); if (_sphinxConfigURL == null) { throw new ConfigurationException( "Sphinx config URL not found in either cairo config file or cairo classpath!"); } else if (_logger.isDebugEnabled()) { _logger.debug("SphinxConfigURL: " + _sphinxConfigURL); } } try { String sphinxRecorderConfigURL = config .getString("resources.resource(" + index + ").sphinxRecorderConfigURL"); if (sphinxRecorderConfigURL != null && sphinxRecorderConfigURL.length() > 0) { _sphinxRecorderConfigURL = new URL(sphinxRecorderConfigURL); } } catch (NoSuchElementException e) { // ignore } if (_sphinxRecorderConfigURL == null) { _sphinxRecorderConfigURL = this.getClass().getResource("/config/sphinx-recorder-config.xml"); if (_sphinxRecorderConfigURL == null) { throw new ConfigurationException( "Sphinx recorder config URL not found in either cairo config file or cairo classpath!"); } else if (_logger.isDebugEnabled()) { _logger.debug("SphinxRecorderConfigURL: " + _sphinxRecorderConfigURL); } } _baseGrammarDir = new File(config.getString("resources.resource(" + index + ").baseGrammarDir")); ensureDir(_baseGrammarDir); _baseRecordingDir = new File(config.getString("resources.resource(" + index + ").baseRecordingDir")); ensureDir(_baseRecordingDir); _recorderEngines = config.getInt("resources.resource(" + index + ").recorderEngines"); } catch (RuntimeException e) { throw new ConfigurationException(e.getMessage(), e); } catch (MalformedURLException e) { throw new ConfigurationException(e.getMessage(), e); } }
From source file:com.eucalyptus.blockstorage.BlockStorageController.java
public CreateStorageSnapshotResponseType CreateStorageSnapshot(CreateStorageSnapshotType request) throws EucalyptusCloudException { CreateStorageSnapshotResponseType reply = (CreateStorageSnapshotResponseType) request.getReply(); StorageProperties.updateWalrusUrl(); if (!StorageProperties.enableSnapshots) { LOG.error("Snapshots have been disabled. Please check connection to ObjectStorage."); return reply; }// w w w . j a v a 2 s . c om String volumeId = request.getVolumeId(); LOG.info("Processing CreateStorageSnapshot request for volume " + volumeId); String snapshotId = request.getSnapshotId(); EntityTransaction dbTrans = Entities.get(VolumeInfo.class); VolumeInfo sourceVolumeInfo = null; try { VolumeInfo volumeInfo = new VolumeInfo(volumeId); sourceVolumeInfo = Entities.uniqueResult(volumeInfo); dbTrans.commit(); } catch (NoSuchElementException e) { LOG.debug("Volume " + volumeId + " not found in db"); throw new NoSuchVolumeException(volumeId); } catch (final Throwable e) { LOG.warn("Volume " + volumeId + " error getting info from db. May not exist. " + e.getMessage()); throw new EucalyptusCloudException("Could not get volume information for volume " + volumeId, e); } finally { if (dbTrans.isActive()) { dbTrans.rollback(); } dbTrans = null; } if (sourceVolumeInfo == null) { //Another check to be sure that we have the source volume throw new NoSuchVolumeException(volumeId); } else { //check status if (!sourceVolumeInfo.getStatus().equals(StorageProperties.Status.available.toString())) { throw new VolumeNotReadyException(volumeId); } else { //create snapshot if (StorageProperties.shouldEnforceUsageLimits) { int maxSize = -1; try { maxSize = BlockStorageGlobalConfiguration.getInstance() .getGlobal_total_snapshot_size_limit_gb(); } catch (Exception e) { LOG.error("Could not determine max global snapshot limit. Aborting snapshot creation", e); throw new EucalyptusCloudException("Total size limit not found.", e); } if (maxSize <= 0) { LOG.warn("Total snapshot size limit is less than or equal to 0"); throw new EucalyptusCloudException("Total snapshot size limit is less than or equal to 0"); } if (totalSnapshotSizeLimitExceeded(snapshotId, sourceVolumeInfo.getSize(), maxSize)) { LOG.info("Snapshot " + snapshotId + " exceeds total snapshot size limit of " + maxSize + "GB"); throw new SnapshotTooLargeException(snapshotId, maxSize); } } Snapshotter snapshotter = null; SnapshotInfo snapshotInfo = new SnapshotInfo(snapshotId); EntityTransaction snapTrans = Entities.get(SnapshotInfo.class); Date startTime = new Date(); try { snapshotInfo.setUserName(sourceVolumeInfo.getUserName()); snapshotInfo.setVolumeId(volumeId); snapshotInfo.setStartTime(startTime); snapshotInfo.setProgress("0"); snapshotInfo.setSizeGb(sourceVolumeInfo.getSize()); snapshotInfo.setStatus(StorageProperties.Status.creating.toString()); /* Change to support sync snap consistency point set on CLC round-trip */ /* * Always do this operation. On backends that don't support it they will * return null. In that case it is effectively a no-op and we continue normal * async snapshot. * * If the snap point is set, then we update the DB properly. */ String snapPointId = null; try { //This will be a no-op if the backend doesn't support it. Will return null. snapPointId = blockManager.createSnapshotPoint(volumeId, snapshotId); if (snapPointId == null) { LOG.debug("Synchronous snap point not supported for this backend. Cleanly skipped."); } else { snapshotInfo.setSnapPointId(snapPointId); } //Do a commit here because the snapshotter expects to find db entry. snapshotInfo.setStatus(StorageProperties.Status.creating.toString()); Context ctx = null; try { ctx = Contexts.lookup(request.getCorrelationId()); if (!ctx.getChannel().isOpen()) { throw new NoSuchContextException("Channel is closed"); } } catch (NoSuchContextException e) { if (snapPointId != null) { //Other end hung up, mark this as failed since this is a sync operation throw new EucalyptusCloudException("Channel closed, aborting snapshot."); } } } catch (EucalyptusCloudException e) { //If the snapshot was done but took too long then delete the snap and fail the op. try { blockManager.deleteSnapshotPoint(volumeId, snapshotId, snapPointId); } catch (Exception ex) { LOG.error("Snapshot " + snapshotId + " exception on snap point cleanup after failure: " + e.getMessage()); } LOG.error("Snapshot " + snapshotId + " failed to create snap point successfully: " + e.getMessage()); throw e; } finally { Entities.persist(snapshotInfo); } /* Resume old code path and finish the snapshot process if already started */ //snapshot asynchronously snapshotter = new Snapshotter(volumeId, snapshotId, snapPointId); reply.setSnapshotId(snapshotId); reply.setVolumeId(volumeId); reply.setStartTime( DateUtils.format(startTime.getTime(), DateUtils.ISO8601_DATETIME_PATTERN) + ".000Z"); reply.setProgress(snapshotInfo.getProgress()); } catch (EucalyptusCloudException cloudEx) { snapshotInfo.setStatus(StorageProperties.Status.failed.toString()); LOG.error("Snapshot " + snapshotId + " creation failed with exception ", cloudEx); throw cloudEx; } catch (final Throwable e) { snapshotInfo.setStatus(StorageProperties.Status.failed.toString()); LOG.error("Snapshot " + snapshotId + " Error committing state update to failed", e); throw new EucalyptusCloudException( "Snapshot " + snapshotId + " unexpected throwable exception caught", e); } finally { if (snapTrans.isActive()) { snapTrans.commit(); } snapTrans = null; } reply.setStatus(snapshotInfo.getStatus()); if (snapshotter != null) { // Kick off the snapshotter task after persisting snapshot to database snapshotService.add(snapshotter); } } } return reply; }
From source file:com.eucalyptus.blockstorage.BlockStorageController.java
public DeleteStorageVolumeResponseType DeleteStorageVolume(DeleteStorageVolumeType request) throws EucalyptusCloudException { DeleteStorageVolumeResponseType reply = (DeleteStorageVolumeResponseType) request.getReply(); if (!StorageProperties.enableStorage) { LOG.error("BlockStorage has been disabled. Please check your setup"); return reply; }// w ww .ja v a 2s . c o m String volumeId = request.getVolumeId(); LOG.info("Processing DeleteStorageVolume request for volume " + volumeId); EntityWrapper<VolumeInfo> db = StorageProperties.getEntityWrapper(); VolumeInfo volumeInfo = new VolumeInfo(); volumeInfo.setVolumeId(volumeId); try { VolumeInfo foundVolume = db.getUnique(volumeInfo); //check its status String status = foundVolume.getStatus(); if (status == null) { throw new EucalyptusCloudException("Invalid volume status: null"); } else if (status.equals(StorageProperties.Status.available.toString()) || status.equals(StorageProperties.Status.failed.toString())) { //Set status, for cleanup thread to find. LOG.trace("Marking volume " + volumeId + " for deletion"); foundVolume.setStatus(StorageProperties.Status.deleting.toString()); } else if (status.equals(StorageProperties.Status.deleting.toString()) || status.equals(StorageProperties.Status.deleted.toString())) { LOG.debug("Volume " + volumeId + " already in deleting/deleted. No-op for delete request."); } else { throw new EucalyptusCloudException( "Cannot delete volume in state: " + status + ". Please retry later"); } // Delete operation should be idempotent as multiple attempts can be made to delete the same volume // Set the response element to true if the volume entity is found. EUCA-6093 reply.set_return(Boolean.TRUE); db.commit(); } catch (NoSuchElementException e) { // Set the response element to false if the volume entity does not exist in the SC database LOG.error("Unable to find volume in SC database: " + volumeId); throw new EucalyptusCloudException("Volume record not found", e); } catch (EucalyptusCloudException e) { LOG.error("Error marking volume " + volumeId + " for deletion: " + e.getMessage()); throw e; } catch (final Throwable e) { LOG.error("Exception looking up volume: " + volumeId, e); throw new EucalyptusCloudException(e); } finally { db.rollback(); } return reply; }
From source file:org.hyperic.hq.control.agent.server.ActionThread.java
public void run() { int result = -1; String errMsg = null;/*w w w . ja v a 2 s . c o m*/ // add ourselves to the job queue this.log.debug("Adding job " + id + " to " + pluginName + " queue"); this.manager.addJob(pluginName, id); // wait for our turn while (true) { String nextJob; try { nextJob = this.manager.getNextJob(pluginName); if (nextJob.equals(id)) break; } catch (NoSuchElementException e) { // should never happen this.log.error("Job queue empty"); return; } this.log.debug("Plugin busy with job " + nextJob + " requeueing in " + REQUEUE_INTERVAL + "ms"); try { Thread.sleep(REQUEUE_INTERVAL); } catch (InterruptedException e) { } } this.log.debug("Running job " + id); long startTime = System.currentTimeMillis(); final ControlSendCommandResult_args resultsMetadata = this.client.newResultsMetadata(this.pluginName, Integer.parseInt(id), startTime); try { this.manager.doAction(this.pluginName, this.action, this.args, resultsMetadata); result = this.manager.getResult(this.pluginName); errMsg = this.manager.getMessage(this.pluginName); } catch (PluginNotFoundException e) { // The plugin has not been configured locally, or the plugin // type is not found on this agent. Try to get the config // from the server try { this.log.info("Fetching plugin configuration from server"); byte[] configBytes = this.client.controlGetPluginConfiguration(this.pluginName); if (configBytes == null || configBytes.length == 0) { // log something or send a message back to the server errMsg = "Plugin configuration not found"; this.log.error(errMsg); return; } ConfigResponse config = ConfigResponse.decode(configBytes); this.log.info("Config finished, running control action"); this.manager.createControlPlugin(this.pluginName, this.pluginType, config); this.manager.doAction(this.pluginName, this.action, this.args, resultsMetadata); result = this.manager.getResult(this.pluginName); errMsg = this.manager.getMessage(this.pluginName); } catch (Exception exc) { errMsg = "Unable to fetch plugin configuration: " + exc.getMessage(); this.log.error(errMsg, exc); } } catch (PluginException e) { errMsg = "Unable to run control action: " + e.getMessage(); this.log.error(errMsg, e); } finally { // Remove this job from the queue try { this.manager.removeNextJob(pluginName); this.log.debug("Removed job " + id + " from the queue"); } catch (NoSuchElementException e) { // will never happen } // Lastly, send the status back to the server try { this.client.controlSendCommandResult(resultsMetadata, result, errMsg); } catch (AgentCallbackClientException e) { this.log.error("Unable to send command result: " + e.getMessage()); } } }
From source file:ch.cyberduck.core.worker.ConcurrentTransferWorker.java
@Override protected Session<?> borrow() throws BackgroundException { try {/*from w w w . j ava 2 s . co m*/ if (this.isCanceled()) { throw new ConnectionCanceledException(); } Session session; while (true) { try { session = pool.borrowObject(); break; } catch (NoSuchElementException e) { if (this.isCanceled()) { throw new ConnectionCanceledException(e); } if (e.getCause() instanceof BackgroundException) { final BackgroundException cause = (BackgroundException) e.getCause(); log.warn(String.format("Failure %s obtaining connection for %s", cause, this)); if (diagnostics.determine(cause) == FailureDiagnostics.Type.network) { // Downgrade pool to single connection final int max = pool.getMaxTotal() - 1; log.warn(String.format("Lower maximum pool size to %d connections.", max)); pool.setMaxTotal(max); pool.setMaxIdle(pool.getMaxIdle() - 1); if (this.retry()) { if (log.isInfoEnabled()) { log.info(String.format("Connect failed with failure %s", e)); } // This is an automated retry. Wait some time first. this.pause(); if (!isCanceled()) { repeat.set(repeat.get() + 1); // Retry to connect continue; } } } throw cause; } if (null == e.getCause()) { log.warn(String.format("Timeout borrowing session from pool %s. Wait for another %dms", pool, BORROW_MAX_WAIT_INTERVAL)); // Timeout continue; } log.error(String.format("Borrowing session from pool %s failed with %s", pool, e)); throw new BackgroundException(e); } } if (log.isInfoEnabled()) { log.info(String.format("Borrow session %s from pool", session)); } return session; } catch (BackgroundException e) { throw e; } catch (Exception e) { if (e.getCause() instanceof BackgroundException) { throw ((BackgroundException) e.getCause()); } throw new BackgroundException(e.getMessage(), e); } }