Java Code Examples for java.util.concurrent.ExecutionException

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project camel-zookeeper, under directory /src/main/java/org/apache/camel/component/zookeeper/operations/.

Source file: AnyOfOperations.java

  34 
vote

@Override public OperationResult get() throws InterruptedException, ExecutionException {
  for (  ZooKeeperOperation op : keeperOperations) {
    try {
      OperationResult result=op.get();
      if (result.isOk()) {
        return result;
      }
    }
 catch (    Exception e) {
    }
  }
  throw new ExecutionException("All operations exhausted without one result",null);
}
 

Example 2

From project cloudify, under directory /dsl/src/main/java/org/cloudifysource/dsl/internal/context/.

Source file: InvocationFuture.java

  33 
vote

private Object handleInvocationResponse(final Object result) throws ExecutionException {
  @SuppressWarnings("unchecked") final Map<String,Object> map=(Map<String,Object>)result;
  final Boolean success=(Boolean)map.get(CloudifyConstants.INVOCATION_RESPONSE_STATUS);
  if (success == null) {
    throw new IllegalStateException("Was expecting: " + CloudifyConstants.INVOCATION_RESPONSE_STATUS + " field in invocation response");
  }
  if (success) {
    return map.get(CloudifyConstants.INVOCATION_RESPONSE_RESULT);
  }
 else {
    final Exception e=(Exception)map.get(CloudifyConstants.INVOCATION_RESPONSE_EXCEPTION);
    throw new ExecutionException(e);
  }
}
 

Example 3

From project AeminiumRuntime, under directory /src/aeminium/runtime/implementations/implicitworkstealing/.

Source file: ImplicitWorkStealingRuntime.java

  31 
vote

@Override public <T>T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
  Exception ex=null;
  for (  Callable<T> c : tasks) {
    Future<T> f=submit(c);
    if (f.get() == null || (f.get() != null && !(f.get() instanceof Exception))) {
      return f.get();
    }
 else     if (f.get() != null && f.get() instanceof Exception) {
      ex=(Exception)f.get();
    }
  }
  throw new ExecutionException(ex);
}
 

Example 4

From project AndroidDevWeekendDub-BookLibrary, under directory /src/org/curiouscreature/android/shelves/util/.

Source file: UserTask.java

  31 
vote

/** 
 * Creates a new user task. This constructor must be invoked on the UI thread.
 */
public UserTask(){
  mWorker=new WorkerRunnable<Params,Result>(){
    public Result call() throws Exception {
      Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
      return doInBackground(mParams);
    }
  }
;
  mFuture=new FutureTask<Result>(mWorker){
    @Override protected void done(){
      Message message;
      Result result=null;
      try {
        result=get();
      }
 catch (      InterruptedException e) {
        android.util.Log.w(LOG_TAG,e);
      }
catch (      ExecutionException e) {
        throw new RuntimeException("An error occured while executing doInBackground()",e.getCause());
      }
catch (      CancellationException e) {
        message=sHandler.obtainMessage(MESSAGE_POST_CANCEL,new UserTaskResult<Result>(UserTask.this,(Result[])null));
        message.sendToTarget();
        return;
      }
catch (      Throwable t) {
        throw new RuntimeException("An error occured while executing " + "doInBackground()",t);
      }
      message=sHandler.obtainMessage(MESSAGE_POST_RESULT,new UserTaskResult<Result>(UserTask.this,result));
      message.sendToTarget();
    }
  }
;
}
 

Example 5

From project android_external_guava, under directory /src/com/google/common/util/concurrent/.

Source file: AbstractFuture.java

  31 
vote

/** 
 * Implementation of completing a task.  Either  {@code v} or {@code t} willbe set but not both.  The  {@code finalState} is the state to change tofrom  {@link #RUNNING}.  If the state is not in the RUNNING state we return  {@code false}.
 * @param v the value to set as the result of the computation.
 * @param t the exception to set as the result of the computation.
 * @param finalState the state to transition to.
 */
private boolean complete(V v,Throwable t,int finalState){
  if (compareAndSetState(RUNNING,COMPLETING)) {
    this.value=v;
    this.exception=t == null ? null : new ExecutionException(t);
    releaseShared(finalState);
    return true;
  }
  return false;
}
 

Example 6

From project android_packages_apps_Gallery2, under directory /src/com/android/gallery3d/app/.

Source file: AlbumDataLoader.java

  31 
vote

private <T>T executeAndWait(Callable<T> callable){
  FutureTask<T> task=new FutureTask<T>(callable);
  mMainHandler.sendMessage(mMainHandler.obtainMessage(MSG_RUN_OBJECT,task));
  try {
    return task.get();
  }
 catch (  InterruptedException e) {
    return null;
  }
catch (  ExecutionException e) {
    throw new RuntimeException(e);
  }
}
 

Example 7

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/media/.

Source file: BaseCancelable.java

  31 
vote

private T handleTerminalStates() throws ExecutionException {
  if (mState == STATE_CANCELED) {
    throw new CancellationException();
  }
  if (mState == STATE_ERROR) {
    throw new ExecutionException(mError);
  }
  if (mState == STATE_COMPLETE)   return mResult;
  throw new IllegalStateException();
}
 

Example 8

From project avro, under directory /lang/java/ipc/src/main/java/org/apache/avro/ipc/.

Source file: CallFuture.java

  31 
vote

@Override public T get() throws InterruptedException, ExecutionException {
  latch.await();
  if (error != null) {
    throw new ExecutionException(error);
  }
  return result;
}
 

Example 9

From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/.

Source file: CropBaseCancelable.java

  31 
vote

private T handleTerminalStates() throws ExecutionException {
  if (mState == STATE_CANCELED) {
    throw new CancellationException();
  }
  if (mState == STATE_ERROR) {
    throw new ExecutionException(mError);
  }
  if (mState == STATE_COMPLETE)   return mResult;
  throw new IllegalStateException();
}
 

Example 10

From project cropimage, under directory /src/com/droid4you/util/cropimage/.

Source file: BaseCancelable.java

  31 
vote

private T handleTerminalStates() throws ExecutionException {
  if (mState == STATE_CANCELED) {
    throw new CancellationException();
  }
  if (mState == STATE_ERROR) {
    throw new ExecutionException(mError);
  }
  if (mState == STATE_COMPLETE)   return mResult;
  throw new IllegalStateException();
}
 

Example 11

From project danbo, under directory /src/us/donmai/danbooru/danbo/cropimage/.

Source file: BaseCancelable.java

  31 
vote

private T handleTerminalStates() throws ExecutionException {
  if (mState == STATE_CANCELED) {
    throw new CancellationException();
  }
  if (mState == STATE_ERROR) {
    throw new ExecutionException(mError);
  }
  if (mState == STATE_COMPLETE)   return mResult;
  throw new IllegalStateException();
}
 

Example 12

From project floodlight, under directory /src/main/java/net/floodlightcontroller/storage/.

Source file: SynchronousExecutorService.java

  31 
vote

@Override public <T>T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
  for (  Callable<T> task : tasks) {
    try {
      task.call();
    }
 catch (    Exception e) {
    }
  }
  throw new ExecutionException(new Exception("no task completed successfully"));
}
 

Example 13

From project AdminCmd, under directory /src/main/java/be/Balor/Manager/Permissions/Plugins/.

Source file: SuperPermissions.java

  30 
vote

@Override public String getPermissionLimit(final Player p,final String limit){
  String result=null;
  if (mChat) {
    result=Reader.getInfo(p.getName(),InfoType.USER,p.getWorld().getName(),"admincmd." + limit);
  }
  if (result == null || (result != null && result.isEmpty())) {
    final Pattern regex=Pattern.compile("admincmd\\." + limit.toLowerCase() + "\\.[0-9]+");
    Set<PermissionAttachmentInfo> permissions=null;
    if (ACHelper.isMainThread()) {
      permissions=p.getEffectivePermissions();
    }
 else {
      final Callable<Set<PermissionAttachmentInfo>> perms=new Callable<Set<PermissionAttachmentInfo>>(){
        @Override public Set<PermissionAttachmentInfo> call() throws Exception {
          return p.getEffectivePermissions();
        }
      }
;
      final Future<Set<PermissionAttachmentInfo>> permTask=ACPluginManager.getScheduler().callSyncMethod(ACPluginManager.getCorePlugin(),perms);
      try {
        permissions=permTask.get();
        DebugLog.INSTANCE.info("Perms got for " + p.getName());
      }
 catch (      final InterruptedException e) {
        DebugLog.INSTANCE.info("Problem while gettings ASYNC perm of " + p.getName());
      }
catch (      final ExecutionException e) {
        DebugLog.INSTANCE.info("Problem while gettings ASYNC perm of " + p.getName());
      }
    }
    return permissionCheck(permissions,regex);
  }
 else {
    return result;
  }
}
 

Example 14

From project aether-core, under directory /aether-connector-asynchttpclient/src/main/java/org/eclipse/aether/connector/async/.

Source file: AsyncRepositoryConnector.java

  30 
vote

private boolean resourceExist(String url) throws IOException, ExecutionException, InterruptedException, TransferException, AuthorizationException {
  int statusCode=httpClient.prepareHead(url).setHeaders(headers).execute().get().getStatusCode();
switch (statusCode) {
case HttpURLConnection.HTTP_OK:
    return true;
case HttpURLConnection.HTTP_FORBIDDEN:
  throw new AuthorizationException(String.format("Access denied to %s . Status code %s",url,statusCode));
case HttpURLConnection.HTTP_NOT_FOUND:
return false;
case HttpURLConnection.HTTP_UNAUTHORIZED:
throw new AuthorizationException(String.format("Access denied to %s . Status code %s",url,statusCode));
default :
throw new TransferException("Failed to look for file: " + buildUrl(url) + ". Return code is: "+ statusCode);
}
}
 

Example 15

From project agraph-java-client, under directory /src/test/stress/.

Source file: Events.java

  30 
vote

private <Type>void invokeAndGetAll(ExecutorService executor,List<Callable<Type>> tasks){
  try {
    List<Future<Type>> fs=executor.invokeAll(tasks);
    for (    Future f : fs) {
      f.get();
    }
  }
 catch (  InterruptedException e) {
    errors++;
    e.printStackTrace();
  }
catch (  ExecutionException e) {
    errors++;
    e.printStackTrace();
  }
}
 

Example 16

From project airlift, under directory /discovery/src/main/java/io/airlift/discovery/client/.

Source file: DiscoveryFutures.java

  30 
vote

static <T>CheckedFuture<T,DiscoveryException> toDiscoveryFuture(final String name,ListenableFuture<T> future){
  return Futures.makeChecked(future,new Function<Exception,DiscoveryException>(){
    @Override public DiscoveryException apply(    Exception e){
      if (e instanceof InterruptedException) {
        Thread.currentThread().interrupt();
        return new DiscoveryException(name + " was interrupted");
      }
      if (e instanceof CancellationException) {
        return new DiscoveryException(name + " was canceled");
      }
      Throwable cause=e;
      if (e instanceof ExecutionException) {
        if (e.getCause() != null) {
          cause=e.getCause();
        }
      }
      if (cause instanceof DiscoveryException) {
        return (DiscoveryException)cause;
      }
      return new DiscoveryException(name + " failed",cause);
    }
  }
);
}
 

Example 17

From project akubra, under directory /akubra-rmi/src/main/java/org/akubraproject/rmi/client/.

Source file: ClientTransactionListener.java

  30 
vote

/** 
 * Gets the connection stub from the server.
 * @return the remote connection stub
 * @throws IOException on an error in getting the connection
 * @throws RuntimeException runtime errors reported locally as well as from remote
 */
@SuppressWarnings("unchecked") public RemoteConnection getConnection() throws IOException {
  while (con == null) {
    Operation<?> op;
    try {
      op=remote.getNextOperation();
    }
 catch (    InterruptedException e) {
      throw new IOException("Interrupted while waiting for next operation");
    }
    if (!(op instanceof Result)) {
      try {
        remote.postResult(processRequest(op));
      }
 catch (      InterruptedException e) {
        throw new IOException("Interrupted while waiting for posted result to be picked up");
      }
    }
 else {
      try {
        con=((Result<RemoteConnection>)op).get();
        if (log.isDebugEnabled())         log.debug("Received a connection stub from remote");
      }
 catch (      ExecutionException e) {
        Throwable t=e.getCause();
        if (log.isDebugEnabled())         log.debug("Received an error in opencCnnection() from emote",t);
        if (t instanceof IOException)         throw (IOException)t;
        if (t instanceof RuntimeException)         throw (RuntimeException)t;
        throw new RuntimeException("Unexpected exception",t);
      }
    }
  }
  return con;
}
 

Example 18

From project android-rss, under directory /src/main/java/org/mcsoxford/rss/.

Source file: RSSLoader.java

  30 
vote

@Override public synchronized RSSFeed get() throws InterruptedException, ExecutionException {
  if (feed == null && cause == null) {
    try {
      waiting=true;
      while (waiting) {
        wait();
      }
    }
  finally {
      waiting=false;
    }
  }
  if (cause != null) {
    throw new ExecutionException(cause);
  }
  return feed;
}
 

Example 19

From project E12Planner, under directory /src/com/neoware/rss/.

Source file: RSSLoader.java

  30 
vote

@Override public synchronized RSSFeed get() throws InterruptedException, ExecutionException {
  if (feed == null && cause == null) {
    try {
      waiting=true;
      while (waiting) {
        wait();
      }
    }
  finally {
      waiting=false;
    }
  }
  if (cause != null) {
    throw new ExecutionException(cause);
  }
  return feed;
}
 

Example 20

From project adbcj, under directory /api/src/main/java/org/adbcj/support/.

Source file: DbFutureConcurrentProxy.java

  29 
vote

public T get() throws DbException, InterruptedException {
  try {
    if (isDone() && set) {
      return value;
    }
    return future.get();
  }
 catch (  ExecutionException e) {
    throw new DbException(e);
  }
}
 

Example 21

From project AmDroid, under directory /AmDroid/src/main/java/com/jaeckel/amenoid/cwac/task/.

Source file: AsyncTaskEx.java

  29 
vote

/** 
 * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
 */
public AsyncTaskEx(){
  mWorker=new WorkerRunnable<Params,Result>(){
    public Result call() throws Exception {
      Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
      return doInBackground(mParams);
    }
  }
;
  mFuture=new FutureTask<Result>(mWorker){
    @Override protected void done(){
      Message message;
      Result result=null;
      try {
        result=get();
      }
 catch (      InterruptedException e) {
        com.jaeckel.amenoid.util.Log.w(LOG_TAG,e);
      }
catch (      ExecutionException e) {
        throw new RuntimeException("An error occured while executing doInBackground()",e.getCause());
      }
catch (      CancellationException e) {
        message=sHandler.obtainMessage(MESSAGE_POST_CANCEL,new AsyncTaskExResult<Result>(AsyncTaskEx.this,(Result[])null));
        message.sendToTarget();
        return;
      }
catch (      Throwable t) {
        throw new RuntimeException("An error occured while executing " + "doInBackground()",t);
      }
      message=sHandler.obtainMessage(MESSAGE_POST_RESULT,new AsyncTaskExResult<Result>(AsyncTaskEx.this,result));
      message.sendToTarget();
    }
  }
;
}
 

Example 22

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/taskcontrol/.

Source file: DefaultPrioritizedTask.java

  29 
vote

public R get(){
  ApplicationIllegalStateException.checkState(result.isDone() || this.taskGroup != null,"Cannot get value if not assigned to a taskGroup (no value will ever be available)");
  try {
    return result.get();
  }
 catch (  InterruptedException e) {
    return null;
  }
catch (  ExecutionException e) {
    return null;
  }
}
 

Example 23

From project anadix, under directory /integration/anadix-selenium/src/main/java/org/anadix/utils/.

Source file: MultithreadedAnalyzer.java

  29 
vote

public Report getResult(int id,boolean block) throws ResultException {
  Future<Report> future=results.get(id);
  try {
    if (future != null) {
      if (block) {
        return future.get();
      }
 else {
        try {
          return future.get(1,TimeUnit.MILLISECONDS);
        }
 catch (        TimeoutException ex) {
        }
      }
    }
  }
 catch (  InterruptedException ex) {
    throw new ResultException("Interrupted",ex);
  }
catch (  ExecutionException ex) {
    throw new ResultException("Error during execution",ex.getCause());
  }
  return null;
}
 

Example 24

From project ANNIS, under directory /annis-kickstarter/src/main/java/de/hu_berlin/german/korpling/annis/kickstarter/.

Source file: InitDialog.java

  29 
vote

@Override protected void done(){
  pbInit.setIndeterminate(false);
  btOk.setEnabled(true);
  btCancel.setEnabled(true);
  try {
    if ("".equals(this.get())) {
      pbInit.setValue(100);
      if (corpora != null && corpora.size() > 0) {
        setVisible(false);
        ImportDialog importDlg=new ImportDialog(parentFrame,true,corpusAdministration,corpora);
        importDlg.setVisible(true);
      }
 else {
        JOptionPane.showMessageDialog(null,"Database initialized.","INFO",JOptionPane.INFORMATION_MESSAGE);
        setVisible(false);
      }
    }
 else {
      pbInit.setValue(0);
    }
  }
 catch (  InterruptedException ex) {
    log.error(null,ex);
  }
catch (  ExecutionException ex) {
    log.error(null,ex);
  }
}
 

Example 25

From project apps-for-android, under directory /AnyCut/src/com/google/android/photostream/.

Source file: UserTask.java

  29 
vote

/** 
 * Creates a new user task. This constructor must be invoked on the UI thread.
 */
public UserTask(){
  mWorker=new WorkerRunnable<Params,Result>(){
    public Result call() throws Exception {
      Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
      return doInBackground(mParams);
    }
  }
;
  mFuture=new FutureTask<Result>(mWorker){
    @Override protected void done(){
      Message message;
      Result result=null;
      try {
        result=get();
      }
 catch (      InterruptedException e) {
        android.util.Log.w(LOG_TAG,e);
      }
catch (      ExecutionException e) {
        throw new RuntimeException("An error occured while executing doInBackground()",e.getCause());
      }
catch (      CancellationException e) {
        message=sHandler.obtainMessage(MESSAGE_POST_CANCEL,new UserTaskResult<Result>(UserTask.this,(Result[])null));
        message.sendToTarget();
        return;
      }
catch (      Throwable t) {
        throw new RuntimeException("An error occured while executing " + "doInBackground()",t);
      }
      message=sHandler.obtainMessage(MESSAGE_POST_RESULT,new UserTaskResult<Result>(UserTask.this,result));
      message.sendToTarget();
    }
  }
;
}
 

Example 26

From project ardverk-dht, under directory /components/core/src/test/java/org/ardverk/dht/io/.

Source file: NodeResponseHandlerTest.java

  29 
vote

private static List<DHTFuture<BootstrapEntity>> bootstrap(List<? extends DHT> dhts) throws InterruptedException, ExecutionException {
  if (dhts.size() <= 1) {
    throw new IllegalArgumentException();
  }
  DHT first=dhts.get(0);
  List<DHTFuture<BootstrapEntity>> futures1=bootstrap(first.getIdentity(),dhts,1,dhts.size() - 1);
  ((DefaultRouteTable)first.getRouteTable()).clear();
  TestCase.assertEquals(1,first.getRouteTable().size());
  List<DHTFuture<BootstrapEntity>> futures2=bootstrap(dhts.get(1).getIdentity(),dhts,0,1);
  futures2.addAll(futures1);
  return futures2;
}
 

Example 27

From project Arecibo, under directory /collector/src/main/java/com/ning/arecibo/collector/persistent/.

Source file: TimelineEventHandler.java

  29 
vote

@VisibleForTesting public void processSamples(final HostSamplesForTimestamp hostSamples) throws ExecutionException, IOException {
  final int hostId=hostSamples.getHostId();
  final String category=hostSamples.getCategory();
  final int categoryId=timelineDAO.getEventCategoryId(category);
  final DateTime timestamp=hostSamples.getTimestamp();
  final TimelineHostEventAccumulator accumulator=getOrAddHostEventAccumulator(hostId,categoryId,timestamp);
  accumulator.addHostSamples(hostSamples);
}
 

Example 28

From project arquillian-extension-android, under directory /android-impl/src/main/java/org/jboss/arquillian/android/impl/.

Source file: AndroidDeviceSelector.java

  29 
vote

@SuppressWarnings("serial") public void getOrCreateAndroidDevice(@Observes AndroidBridgeInitialized event,ProcessExecutor executor,AndroidExtensionConfiguration configuration,AndroidSdk sdk) throws AndroidConfigurationException, AndroidExecutionException {
  String avdName=configuration.getAvdName();
  String serialId=configuration.getSerialId();
  AndroidBridge bridge=event.getBridge();
  AndroidDevice device=checkIfRealDeviceIsConnected(bridge,serialId);
  if (device != null) {
    androidDevice.set(device);
    androidDeviceReady.fire(new AndroidDeviceReady(device));
    return;
  }
  Set<String> devices=getAvdDeviceNames(executor,sdk);
  if (!devices.contains(avdName) || configuration.isForce()) {
    if (log.isLoggable(Level.FINE)) {
      log.fine("Creating an Android virtual device named " + avdName);
    }
    Validate.notNullOrEmpty(configuration.getSdSize(),"Memory SD card size must be defined");
    try {
      executor.execute(new HashMap<String,String>(){
{
          put("Do you wish to create a custom hardware profile [no]","no\n");
        }
      }
,sdk.getAndroidPath(),"create","avd","-n",avdName,"-t","android-" + configuration.getApiLevel(),"-f","-p",avdName,"-c",configuration.getSdSize());
    }
 catch (    InterruptedException e) {
      throw new AndroidExecutionException("Unable to create a new AVD Device",e);
    }
catch (    ExecutionException e) {
      throw new AndroidExecutionException("Unable to create a new AVD Device",e);
    }
    log.info("Android virtual device " + avdName + " was created");
    avdCreated.fire(new AndroidVirtualDeviceCreated(avdName));
  }
 else {
    log.info("Android virtual device " + avdName + " already exists, will be reused in tests");
    avdAvailable.fire(new AndroidVirtualDeviceAvailable(avdName));
  }
}
 

Example 29

From project arquillian-rusheye, under directory /rusheye-api/src/main/java/org/jboss/rusheye/suite/.

Source file: Mask.java

  29 
vote

/** 
 * Gets the mask.
 * @return the mask
 */
private BufferedImage getMaskImage(){
  run();
  try {
    return get();
  }
 catch (  ExecutionException e) {
    throw new RuntimeException(e);
  }
catch (  InterruptedException e) {
    throw new RuntimeException(e);
  }
}
 

Example 30

From project astyanax, under directory /src/main/java/com/netflix/astyanax/thrift/.

Source file: ThriftKeyspaceImpl.java

  29 
vote

@SuppressWarnings("unchecked") @Override public List<TokenRange> describeRing(boolean cached) throws ConnectionException {
  if (cached) {
    try {
      return (List<TokenRange>)this.cache.get(CassandraOperationType.DESCRIBE_RING.name(),new Callable<Object>(){
        @Override public Object call() throws Exception {
          return describeRing();
        }
      }
);
    }
 catch (    ExecutionException e) {
      throw ThriftConverter.ToConnectionPoolException(e);
    }
  }
 else {
    return describeRing();
  }
}
 

Example 31

From project atlas, under directory /src/main/java/com/ning/atlas/.

Source file: ActualDeployment.java

  29 
vote

public boolean isFinished(){
  if (future.get().isDone()) {
    Status s;
    try {
      s=future.get().get();
    }
 catch (    InterruptedException e) {
      log.debug("Provisioning %s was interrupted",server.getId());
      Thread.currentThread().interrupt();
      s=Status.abort("interrupted");
    }
catch (    ExecutionException e) {
      log.warn(e,"unexpected exception provisioning %s",server.getId());
      s=Status.abort("unexpected exception, killing deployment");
    }
    log.info("%s finished provisioning with status %s",server.getId(),s);
    deployment.bus.post(new FinishedServerProvision(server.getId(),uri));
    return true;
  }
  return false;
}
 

Example 32

From project AudioBox.fm-JavaLib, under directory /audiobox.fm-core/src/main/java/fm/audiobox/configurations/.

Source file: DefaultRequestMethod.java

  29 
vote

public Response getResponse() throws ServiceException, LoginException {
  try {
    Response response=this.futureResponse.get();
    this.running=false;
    this.aborted=false;
    if (response != null) {
      if (response.getException() != null) {
        AudioBoxException ex=response.getException();
        ex.setConfiguration(this.configuration);
        if (ex instanceof LoginException) {
          throw (LoginException)ex;
        }
 else {
          throw (ServiceException)ex;
        }
      }
      return response;
    }
  }
 catch (  InterruptedException e) {
    log.error("Request has been interrupted: " + getHttpMethod().getURI().toString());
    return null;
  }
catch (  CancellationException ce) {
    log.error("Request has been cancelled: " + getHttpMethod().getURI().toString());
    return null;
  }
catch (  ExecutionException e) {
    log.error("An error occurred while executing request",e);
    return null;
  }
  throw new ServiceException(HttpStatus.SC_PRECONDITION_FAILED,"No response");
}
 

Example 33

From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/ingest/.

Source file: IngestManager.java

  29 
vote

@Override protected void done(){
  try {
    super.get();
    if (!this.isCancelled()) {
      for (      IngestModuleAbstractFile s : abstractFileModules) {
        s.complete();
        IngestManager.fireModuleEvent(IngestModuleEvent.COMPLETED.toString(),s.getName());
      }
    }
  }
 catch (  CancellationException e) {
    handleInterruption();
  }
catch (  InterruptedException ex) {
    handleInterruption();
  }
catch (  ExecutionException ex) {
    handleInterruption();
    logger.log(Level.SEVERE,"Fatal error during ingest.",ex);
  }
catch (  Exception ex) {
    handleInterruption();
    logger.log(Level.SEVERE,"Fatal error during ingest.",ex);
  }
 finally {
    stats.end();
    progress.finish();
    if (!this.isCancelled()) {
      logger.log(Level.INFO,"Summary Report: " + stats.toString());
      logger.log(Level.INFO,"File module timings: " + stats.getFileModuleStats());
      if (ui != null) {
        logger.log(Level.INFO,"Ingest messages count: " + ui.getMessagesCount());
      }
      IngestManager.this.postMessage(IngestMessage.createManagerMessage("File Ingest Complete",stats.toHtmlString()));
    }
  }
}
 

Example 34

From project aws-tasks, under directory /src/main/java/datameer/awstasks/aws/ec2/ssh/.

Source file: SshClientImpl.java

  29 
vote

private static void waitForSshCommandCompletion(List<Future<SshCallable>> futureList) throws IOException {
  boolean interrupted=false;
  for (  Future<SshCallable> future : futureList) {
    try {
      if (interrupted) {
        future.cancel(true);
      }
 else {
        SshCallable sshTask=null;
        try {
          sshTask=future.get();
        }
  finally {
          IoUtil.closeQuietly(sshTask);
        }
      }
    }
 catch (    InterruptedException ex) {
      interrupted=true;
    }
catch (    ExecutionException ex) {
      Throwables.propagateIfInstanceOf(ex.getCause(),IOException.class);
      Throwables.propagate(ex.getCause());
    }
  }
}
 

Example 35

From project Axon-trader, under directory /web-ui/src/main/java/org/axonframework/samples/trader/webui/security/.

Source file: TraderAuthenticationProvider.java

  29 
vote

@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  if (!supports(authentication.getClass())) {
    return null;
  }
  UsernamePasswordAuthenticationToken token=(UsernamePasswordAuthenticationToken)authentication;
  String username=token.getName();
  String password=String.valueOf(token.getCredentials());
  FutureCallback<UserAccount> accountCallback=new FutureCallback<UserAccount>();
  AuthenticateUserCommand command=new AuthenticateUserCommand(username,password.toCharArray());
  commandBus.dispatch(new GenericCommandMessage<AuthenticateUserCommand>(command),accountCallback);
  UserAccount account;
  try {
    account=accountCallback.get();
    if (account == null) {
      throw new BadCredentialsException("Invalid username and/or password");
    }
  }
 catch (  InterruptedException e) {
    throw new AuthenticationServiceException("Credentials could not be verified",e);
  }
catch (  ExecutionException e) {
    throw new AuthenticationServiceException("Credentials could not be verified",e);
  }
  UsernamePasswordAuthenticationToken result=new UsernamePasswordAuthenticationToken(account,authentication.getCredentials(),userAuthorities);
  result.setDetails(authentication.getDetails());
  return result;
}
 

Example 36

From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/processor/.

Source file: RepairProcessor.java

  29 
vote

/** 
 * Removes data in the specified repository.
 * @param repository the specified repository
 * @throws ExecutionException execution exception
 * @throws InterruptedException interrupted exception
 */
private void remove(final Repository repository) throws ExecutionException, InterruptedException {
  final long startTime=System.currentTimeMillis();
  final long step=20000;
  final Transaction transaction=repository.beginTransaction();
  try {
    final JSONObject result=repository.get(new Query());
    final JSONArray array=result.getJSONArray(Keys.RESULTS);
    for (int i=0; i < array.length(); i++) {
      final JSONObject object=array.getJSONObject(i);
      repository.remove(object.getString(Keys.OBJECT_ID));
      if (System.currentTimeMillis() >= startTime + step) {
        break;
      }
    }
    transaction.commit();
  }
 catch (  final Exception e) {
    if (transaction.isActive()) {
      transaction.rollback();
    }
    LOGGER.log(Level.SEVERE,"Removes all data in repository[name=" + repository.getName() + "] failed",e);
  }
}
 

Example 37

From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/.

Source file: BlueprintEventDispatcher.java

  29 
vote

private void callListener(final BlueprintListener listener,final BlueprintEvent event) throws RejectedExecutionException {
  try {
    executor.invokeAny(Collections.<Callable<Void>>singleton(new Callable<Void>(){
      public Void call() throws Exception {
        listener.blueprintEvent(event);
        return null;
      }
    }
),60L,TimeUnit.SECONDS);
  }
 catch (  InterruptedException ie) {
    LOGGER.warn("Thread interrupted",ie);
    Thread.currentThread().interrupt();
  }
catch (  TimeoutException te) {
    LOGGER.warn("Listener timed out, will be ignored",te);
    listeners.remove(listener);
  }
catch (  ExecutionException ee) {
    LOGGER.warn("Listener caused an exception, will be ignored",ee);
    listeners.remove(listener);
  }
}
 

Example 38

From project bonecp, under directory /bonecp/src/main/java/com/jolbox/bonecp/.

Source file: BoneCPDataSource.java

  29 
vote

/** 
 * {@inheritDoc}
 * @see javax.sql.DataSource#getConnection(java.lang.String,java.lang.String)
 */
public Connection getConnection(String username,String password) throws SQLException {
  try {
    return this.multiDataSource.get(new UsernamePassword(username,password)).getConnection();
  }
 catch (  ExecutionException e) {
    throw new SQLException(e);
  }
}
 

Example 39

From project c2dm4j, under directory /src/test/java/org/whispercomm/c2dm4j/async/.

Source file: AsyncC2dmManagerTest.java

  29 
vote

@Test(timeout=1000) public void testRetriesOnFailure() throws InterruptedException, ExecutionException {
  new GlobalBackoffThrottle(new ExponentialBackoff(),handlers);
  manager.enqueue(ResponseType.QuotaExceeded);
  manager.enqueue(ResponseType.QuotaExceeded);
  manager.enqueue(ResponseType.QuotaExceeded);
  manager.enqueue(ResponseType.QuotaExceeded);
  manager.enqueue(ResponseType.Success);
  Future<Response> fut=cut.pushMessage(msg);
  assertThat(fut.get().getResponseType(),is(ResponseType.Success));
}
 

Example 40

From project capedwarf-blue, under directory /images/src/test/java/org/jboss/test/capedwarf/images/.

Source file: TransformationsTestCase.java

  29 
vote

@Test public void asyncTransformRendersSameImageAsNonAsyncTransform() throws ExecutionException, InterruptedException {
  Transform transform=ImagesServiceFactory.makeHorizontalFlip();
  Image synchronouslyTransformedImage=imagesService.applyTransform(transform,createTestImage());
  Future<Image> future=imagesService.applyTransformAsync(transform,createTestImage());
  Image asynchronouslyTransformedImage=future.get();
  assertImagesEqual(synchronouslyTransformedImage,asynchronouslyTransformedImage);
}
 

Example 41

From project Carolina-Digital-Repository, under directory /services/src/test/java/edu/unc/lib/dl/cdr/services/processing/.

Source file: CatchUpServiceTest.java

  29 
vote

/** 
 * Verify that extra calls to the catchup method cannot run while it is already executing.
 * @throws EnhancementException
 * @throws InterruptedException
 * @throws ExecutionException
 */
@Test public void lockoutCatchUp() throws EnhancementException, InterruptedException, ExecutionException {
  when(techmd.isActive()).thenReturn(true);
  when(image.isActive()).thenReturn(true);
  List<PID> results=getResultSet(catchup.getPageSize());
  when(techmd.findCandidateObjects(anyInt())).thenReturn(results);
  ScheduledExecutorService scheduler=Executors.newScheduledThreadPool(1);
  Runnable activateRunnable=new Runnable(){
    public void run(){
      while (!catchup.isActive())       ;
      boolean response=catchup.activate();
      assertFalse(response);
    }
  }
;
  Runnable deactivateRunnable=new Runnable(){
    public void run(){
      catchup.deactivate();
      System.out.println("Deactivated " + System.currentTimeMillis());
    }
  }
;
  ScheduledFuture<?> activateHandler=scheduler.schedule(activateRunnable,100,TimeUnit.MILLISECONDS);
  ScheduledFuture<?> deactivateHandler=scheduler.schedule(deactivateRunnable,500,TimeUnit.MILLISECONDS);
  boolean response=catchup.activate();
  assertTrue(response);
  deactivateHandler.get();
  activateHandler.get();
  scheduler.shutdown();
}
 

Example 42

From project Cassandra-Client-Tutorial, under directory /src/main/java/com/jeklsoft/cassandraclient/astyanax/.

Source file: AstyanaxProtocolBufferWithStandardColumnExample.java

  29 
vote

@Override public void addReadings(List<Reading> readings){
  MutationBatch m=keyspace.prepareMutationBatch();
  for (  Reading reading : readings) {
    m.withRow(columnFamilyInfo,reading.getSensorId()).putColumn(reading.getTimestamp(),reading,ReadingSerializer.get(),ttl);
  }
  try {
    Future<OperationResult<Void>> future=m.executeAsync();
    OperationResult<Void> result=future.get();
  }
 catch (  ConnectionException e) {
    throw new RuntimeException("Storage of readings failed",e);
  }
catch (  InterruptedException e) {
    throw new RuntimeException("Storage of readings failed",e);
  }
catch (  ExecutionException e) {
    throw new RuntimeException("Storage of readings failed",e);
  }
}
 

Example 43

From project ceres, under directory /ceres-ui/src/main/java/com/bc/ceres/swing/update/.

Source file: ModuleManagerPane.java

  29 
vote

@Override protected void done(){
  if (isCancelled()) {
    return;
  }
  try {
    get();
  }
 catch (  InterruptedException e) {
    handleRepositoryConnectionFailed(e.getMessage());
    return;
  }
catch (  ExecutionException e) {
    handleRepositoryConnectionFailed(e.getCause().getMessage());
    return;
  }
  updateModuleTable();
  updateUiState();
}
 

Example 44

From project cipango, under directory /cipango-server/src/main/java/org/cipango/server/nio/.

Source file: SelectSipConnection.java

  29 
vote

@Override public synchronized void write(ByteBuffer buffer) throws IOException {
  try {
    FutureCallback<Void> fcb=new FutureCallback<Void>();
    if (BufferUtil.hasContent(buffer))     getEndPoint().write(null,fcb,buffer);
 else     fcb.completed(null);
    fcb.get();
  }
 catch (  InterruptedException x) {
    throw (IOException)new InterruptedIOException().initCause(x);
  }
catch (  ExecutionException x) {
    Throwable cause=x.getCause();
    if (cause instanceof IOException)     throw (IOException)cause;
 else     if (cause instanceof Exception)     throw new IOException(cause);
 else     throw (Error)cause;
  }
}
 

Example 45

From project clj-ds, under directory /src/main/java/com/trifork/clj_ds/.

Source file: PersistentVector.java

  29 
vote

public Node compute(){
  if (node == null) {
    return null;
  }
  if (this.shift <= 5) {
    return mapNode(f,node,shift);
  }
  PMapTask[] tasks=new PMapTask[node.array.length];
  shift-=5;
  for (int i=0; i < tasks.length; i++) {
    tasks[i]=new PMapTask(f,shift,(Node)node.array[i]);
  }
  invokeAll(tasks);
  Node[] nodes=new Node[node.array.length];
  try {
    for (int i=0; i < tasks.length; i++) {
      nodes[i]=tasks[i].get();
    }
    return new Node(null,nodes);
  }
 catch (  InterruptedException e) {
    Thread.currentThread().interrupt();
    throw new RuntimeException(e);
  }
catch (  ExecutionException e) {
    throw new RuntimeException(e);
  }
}
 

Example 46

From project clustermeister, under directory /api/src/main/java/com/github/nethad/clustermeister/sample/.

Source file: ReadmeExample.java

  29 
vote

public static void main(String... args){
  Clustermeister clustermeister=null;
  try {
    clustermeister=ClustermeisterFactory.create();
    for (    ExecutorNode executorNode : clustermeister.getAllNodes()) {
      ListenableFuture<String> resultFuture=executorNode.execute(new HelloWorldCallable());
      String result=resultFuture.get();
      System.out.println("Node " + executorNode.getID() + ", result: "+ result);
    }
  }
 catch (  InterruptedException ex) {
    System.err.println("Exception while waiting for result: " + ex.getMessage());
  }
catch (  ExecutionException ex) {
    System.err.println("Exception while waiting for result: " + ex.getMessage());
  }
 finally {
    if (clustermeister != null) {
      clustermeister.shutdown();
    }
  }
}
 

Example 47

From project cogroo4, under directory /cogroo-nlp/src/main/java/org/cogroo/dictionary/impl/.

Source file: FSADictionary.java

  29 
vote

public String[] getTags(String word){
  try {
    return tagCache.get(word).orNull();
  }
 catch (  ExecutionException e) {
    LOGGER.info("Getting tags for word generated an exception: " + word,e);
    return null;
  }
}
 

Example 48

From project collector, under directory /src/test/java/com/ning/metrics/collector/endpoint/resources/.

Source file: TestBodyResource.java

  29 
vote

private Event sendPostEvent(final ByteArrayOutputStream out,final String name,final String dateTime,final String contentType) throws IOException, ExecutionException, InterruptedException {
  assertCleanQueues(incomingQueue);
  final AsyncHttpClient.BoundRequestBuilder requestBuilder=client.preparePost("http://127.0.0.1:" + config.getLocalPort() + "/rest/1.0/event").addHeader("Content-Type",contentType).setBody(out.toByteArray());
  if (name != null) {
    requestBuilder.addQueryParameter("name",name);
  }
  if (dateTime != null) {
    requestBuilder.addQueryParameter("date",dateTime);
  }
  final Response response=requestBuilder.execute().get();
  Assert.assertEquals(response.getStatusCode(),202);
  return assertEventWasWrittenToHDFS(incomingQueue,hdfsWriter);
}
 

Example 49

From project cometd, under directory /cometd-java/cometd-java-server/src/test/java/org/cometd/server/.

Source file: ServerShutdownTest.java

  29 
vote

@Test public void testServerShutdown() throws Exception {
  Request handshake=newBayeuxRequest("" + "[{" + "\"channel\": \"/meta/handshake\","+ "\"version\": \"1.0\","+ "\"minimumVersion\": \"1.0\","+ "\"supportedConnectionTypes\": [\"long-polling\"]"+ "}]");
  ContentResponse response=handshake.send().get(5,TimeUnit.SECONDS);
  Assert.assertEquals(200,response.status());
  String clientId=extractClientId(response);
  Request connect=newBayeuxRequest("" + "[{" + "\"channel\": \"/meta/connect\","+ "\"clientId\": \"" + clientId + "\","+ "\"connectionType\": \"long-polling\","+ "\"advice\": { \"timeout\": 0 }"+ "}]");
  response=connect.send().get(5,TimeUnit.SECONDS);
  Assert.assertEquals(200,response.status());
  connect=newBayeuxRequest("" + "[{" + "\"channel\": \"/meta/connect\","+ "\"clientId\": \"" + clientId + "\","+ "\"connectionType\": \"long-polling\""+ "}]");
  Future<ContentResponse> futureResponse=connect.send();
  Thread.sleep(1000);
  server.stop();
  server.join();
  try {
    futureResponse.get(timeout * 2,TimeUnit.SECONDS);
    Assert.fail();
  }
 catch (  ExecutionException expected) {
  }
}
 

Example 50

From project CommitCoin, under directory /src/com/google/bitcoin/core/.

Source file: Wallet.java

  29 
vote

/** 
 * Sends coins to the given address, via the given  {@link PeerGroup}. Change is returned to  {@link Wallet#getChangeAddress()}. The method will block until the transaction has been announced to at least one node.
 * @param peerGroup a PeerGroup to use for broadcast or null.
 * @param to        Which address to send coins to.
 * @param nanocoins How many nanocoins to send. You can use Utils.toNanoCoins() to calculate this.
 * @return The {@link Transaction} that was created or null if there was insufficient balance to send the coins.
 */
public synchronized Transaction sendCoins(PeerGroup peerGroup,Address to,BigInteger nanocoins){
  Transaction tx=sendCoinsOffline(to,nanocoins);
  if (tx == null)   return null;
  try {
    return peerGroup.broadcastTransaction(tx).get();
  }
 catch (  InterruptedException e) {
    throw new RuntimeException(e);
  }
catch (  ExecutionException e) {
    throw new RuntimeException(e);
  }
}
 

Example 51

From project core_4, under directory /impl/src/main/java/org/richfaces/skin/.

Source file: AbstractSkinFactory.java

  29 
vote

@Override public Skin getSkin(FacesContext context,String name){
  if (null == name) {
    throw new SkinNotFoundException(Messages.getMessage(Messages.NULL_SKIN_NAME_ERROR));
  }
  FutureTask<Skin> skinFuture=skins.get(name);
  if (skinFuture == null) {
    FutureTask<Skin> newSkinFuture=new FutureTask<Skin>(new SkinBuilder(name));
    skinFuture=skins.putIfAbsent(name,newSkinFuture);
    if (skinFuture == null) {
      skinFuture=newSkinFuture;
    }
  }
  try {
    skinFuture.run();
    return skinFuture.get();
  }
 catch (  InterruptedException e) {
    throw new SkinNotFoundException(Messages.getMessage(Messages.SKIN_NOT_FOUND_ERROR,name),e);
  }
catch (  ExecutionException e) {
    throw new SkinNotFoundException(Messages.getMessage(Messages.SKIN_NOT_FOUND_ERROR,name),e);
  }
}
 

Example 52

From project cp-common-utils, under directory /src/com/clarkparsia/common/util/concurrent/.

Source file: ParallelTaskExecutor.java

  29 
vote

/** 
 * Checks if all the submitted tasks are done and returns true if there is no running task. If an error was thrown during the execution of any submitted task, it will be thrown.
 */
public boolean isDone() throws InterruptedException, ExecutionException {
  while (!mFutures.isEmpty()) {
    boolean isDone=mFutures.peek().isDone();
    if (!isDone) {
      return false;
    }
 else {
      mFutures.remove().get();
    }
  }
  return true;
}
 

Example 53

From project cron, under directory /tck/src/test/java/org/jboss/seam/cron/test/asynchronous/tck/.

Source file: SeamCronAsynchronousTCKTest.java

  29 
vote

@Test public void testAsynchReturningFuture() throws InterruptedException, InterruptedException, ExecutionException, TimeoutException {
  log.info("Testing asynchronous methods return a future as expected");
  assertNotNull(asynchBean);
  asynchBean.reset();
  assertNull(asynchBean.getStatusEvent());
  assertNull(asynchBean.getHaystackCount());
  String statusToSet="blue";
  Future<Status> result=asynchBean.returnStatusInFuture(statusToSet);
  assertNotNull(result);
  Status resultStatus=result.get(4,TimeUnit.SECONDS);
  assertNotNull(resultStatus);
  assertNotNull(resultStatus.getDescription());
  assertEquals(statusToSet,resultStatus.getDescription());
  assertNull(asynchBean.getHaystackCount());
}
 

Example 54

From project curator, under directory /curator-framework/src/main/java/com/netflix/curator/framework/imps/.

Source file: NamespaceFacadeCache.java

  29 
vote

NamespaceFacade get(String namespace){
  try {
    return (namespace != null) ? cache.get(namespace) : nullNamespace;
  }
 catch (  ExecutionException e) {
    throw new RuntimeException(e);
  }
}
 

Example 55

From project cytoscape-plugins, under directory /org.openbel.cytoscape.navigator/src/org/openbel/cytoscape/navigator/task/.

Source file: AbstractSearchKamTask.java

  29 
vote

private List<KamNode> searchKAMNodes(){
  ExecutorService e=Executors.newSingleThreadExecutor();
  Future<List<KamNode>> future=e.submit(buildCallable());
  while (!(future.isDone() || future.isCancelled()) && !e.isShutdown()) {
    try {
      if (halt) {
        e.shutdownNow();
        future.cancel(true);
      }
      Thread.sleep(100);
    }
 catch (    InterruptedException ex) {
      halt=true;
    }
  }
  if (future.isCancelled()) {
    return null;
  }
  try {
    return future.get();
  }
 catch (  InterruptedException ex) {
    log.warn("Error searching kam nodes",ex);
    return null;
  }
catch (  ExecutionException ex) {
    log.warn("Error searching kam nodes",ex);
    return null;
  }
}
 

Example 56

From project DirectMemory, under directory /server/directmemory-server-client/src/main/java/org/apache/directmemory/server/client/providers/asynchttpclient/.

Source file: AsyncHttpClientDirectMemoryHttpClient.java

  29 
vote

@Override public DirectMemoryResponse put(DirectMemoryRequest request) throws DirectMemoryException {
  try {
    return internalPut(request).get(configuration.getReadTimeOut(),TimeUnit.MILLISECONDS);
  }
 catch (  InterruptedException e) {
    throw new DirectMemoryException(e.getMessage(),e);
  }
catch (  TimeoutException e) {
    throw new DirectMemoryException(e.getMessage(),e);
  }
catch (  ExecutionException e) {
    throw new DirectMemoryException(e.getMessage(),e);
  }
}
 

Example 57

From project distributed_loadgen, under directory /src/com/couchbase/loadgen/memcached/.

Source file: SpymemcachedClient.java

  29 
vote

@Override public int add(String key,Object value){
  try {
    if (!client.add(key,0,value).get().booleanValue()) {
      System.out.println("ADD: error getting data");
      return -1;
    }
  }
 catch (  InterruptedException e) {
    System.out.println("ADD Interrupted");
  }
catch (  ExecutionException e) {
    System.out.println("ADD Execution");
  }
catch (  RuntimeException e) {
    System.out.println("ADD Runtime");
  }
  return 0;
}
 

Example 58

From project enterprise, under directory /ha/src/main/java/org/neo4j/kernel/ha/.

Source file: MasterTxIdGenerator.java

  29 
vote

private boolean isSuccessfull(Future<Void> committer){
  try {
    committer.get();
    return true;
  }
 catch (  InterruptedException e) {
    return false;
  }
catch (  ExecutionException e) {
    return false;
  }
catch (  CancellationException e) {
    return false;
  }
}
 

Example 59

From project Enterprise-Application-Samples, under directory /CCA/PushApp/src/eclserver/threads/.

Source file: ContactsLoader.java

  29 
vote

@Override protected void done(){
  setProgress(100);
  System.out.println("Thread wrapping up");
  resultsBox.append("\nCompleted Loading Contacts Details.  You can review" + " the results on the Contacts Editor page.  Remember you can make " + " modifications to individual records as well as create new records.");
  List<AddressObject> contacts=null;
  try {
    contacts=(List<AddressObject>)get();
  }
 catch (  ExecutionException ex) {
    System.out.println("ContactsLoader Thread Execution Exception: " + ex.getMessage());
    ex.printStackTrace();
  }
catch (  InterruptedException ex) {
    System.out.println("ContactsLoader Thread Interrupted Exception: " + ex.getMessage());
  }
  if (contacts.size() == 0) {
    resultsBox.append("Didn't retrieve anything from file in DONE() thread.");
  }
}
 

Example 60

From project fiftyfive-wicket, under directory /fiftyfive-wicket-core/src/main/java/fiftyfive/wicket/util/.

Source file: LoggingUtils.java

  29 
vote

/** 
 * Attempts to find the most meaningful exception in a runtime exception chain by stripping away the exceptions commonly used as "wrappers", namely: RuntimeException, WicketRuntimeException, InvocationTargetException and ExecutionException. These four exception types are usually language cruft that don't add much desciptive value. <p> For example, if the exception chain is: <pre class="example"> WicketRuntimeException -> InvocationTargetException -> MyBusinessException -> SQLException</pre> <p> Then the unwrapped exception would be  {@code MyBusinessException}. 
 */
public static Throwable unwrap(Throwable e){
  Args.notNull(e,"e");
  Throwable unwrapped=e;
  while (true) {
    Throwable cause=null;
    if (unwrapped instanceof WicketRuntimeException || unwrapped instanceof InvocationTargetException || unwrapped instanceof ExecutionException|| unwrapped.getClass().equals(RuntimeException.class)) {
      cause=unwrapped.getCause();
    }
    if (null == cause || unwrapped == cause) {
      break;
    }
    unwrapped=cause;
  }
  return unwrapped;
}
 

Example 61

From project fire-samples, under directory /cache-demo/src/main/java/demo/vmware/commands/schemaspecific/.

Source file: CommandCreateData.java

  29 
vote

@Override public CommandResult run(ConfigurableApplicationContext mainContext,List<String> parameters){
  List<String> messages=new ArrayList<String>();
  int attributeCounter=0;
  CommandTimer timer=new CommandTimer();
  LOG.info("creating test data for " + numCompanies + ","+ numRegions+ ","+ numGroups+ ","+ numBranches);
  ExecutorService taskExecutor=Executors.newFixedThreadPool(2);
  Collection tasks=new ArrayList<CompanyHierarchyPopulator>();
  for (int i=0; i < numCompanies; i++) {
    CompanyHierarchyPopulator poper=new CompanyHierarchyPopulator();
    tasks.add(poper);
  }
  try {
    List<Future<?>> futures=taskExecutor.invokeAll(tasks);
    taskExecutor.shutdown();
    for (int i=0; i < numCompanies; i++) {
      attributeCounter+=((Integer)futures.get(i).get()).intValue();
    }
    timer.stop();
    messages.add("Created " + attributeCounter + " attributes and "+ " took "+ timer.getTimeDiffInSeconds()+ " sec");
  }
 catch (  ExecutionException e) {
    LOG.warn("something bad happend",e);
    messages.add("Something bad happend " + e.getMessage());
  }
catch (  InterruptedException e) {
    LOG.warn("something bad happend",e);
    messages.add("Something bad happend " + e.getMessage());
  }
  return new CommandResult(null,messages);
}
 

Example 62

From project FlickrCity, under directory /src/com/FlickrCity/FlickrAPI/.

Source file: FlickrAPI.java

  29 
vote

private String httpGETCityPhotos(String placeId,int woeId,Context context){
  String url="http://api.flickr.com/services/rest/?&method=flickr.photos.search" + "&api_key=" + Constants.API_KEY + "&has_geo="+ has_geo+ "&page="+ page+ "&per_page="+ per_page+ "&place_id="+ placeId+ "&woe_id="+ woeId+ "&format=json&nojsoncallback=1";
  try {
    return new HttpGetNetworkTask(context).execute(url).get();
  }
 catch (  InterruptedException e) {
    e.printStackTrace();
    return null;
  }
catch (  ExecutionException e) {
    e.printStackTrace();
    return null;
  }
}