Esempio n. 1
1
  /**
   * Test the same robot trying to wait twice (not allowed in single thread mode)
   *
   * @throws Throwable
   */
  @Test(expectedExceptions = IllegalArgumentException.class, timeOut = 3000)
  public void testMutipleWaitsSameRobot() throws Throwable {

    TU.addListener(332);

    Callable<Boolean> second =
        new Callable<Boolean>() {

          @Override
          public Boolean call() throws Exception {
            TU.waitFor(332, 4, "testMutipleWaitsSameRobot-second");
            return true;
          }
        };

    FutureTask<Boolean> secondTask = new FutureTask<>(second);
    Thread secondThread = new Thread(secondTask, "Fake second robot");
    secondThread.start();

    while (secondThread.getState() != State.WAITING) {
      Thread.yield();
    }

    TU.waitFor(
        332,
        2,
        "testMutipleWaitsSameRobot"); // should fail since fake second should be blocked already
    try {
      secondTask.get();
    } catch (ExecutionException exc) {
      throw exc.getCause();
    }
    fail("Should throw exception");
  }
Esempio n. 2
0
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, final String url) {
      FutureTask<Integer> task = PostOnUrlChangeTask(url);

      while (!task.isDone()) {
        Thread.yield();
      }

      int res = 0;
      try {
        res = task.get();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (ExecutionException e) {
        e.printStackTrace();
      }

      /*enum eAction
      {
      	PROCESS_IN_WEBVIEW = 0,
      	PROCESS_IN_SYSTEM_BROWSER,
      	NO_PROCESS,
      	ACTIONS_COUNT
      };*/

      if (res == 0) {
        return false;
      } else if (res == 1) {
        Intent exWeb = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        JNIActivity.GetActivity().startActivity(exWeb);
        return true;
      }
      return true;
    }
Esempio n. 3
0
  @Test
  public void failureMonitor() throws Exception {
    ProducerToken token = ProducerToken.create(SimpleProducerModule_SettableFutureStrFactory.class);

    SettableFuture<String> strFuture = SettableFuture.create();
    SettableFuture<SettableFuture<String>> strFutureFuture = SettableFuture.create();
    Producer<SettableFuture<String>> strFutureProducer = producerOfFuture(strFutureFuture);
    Producer<String> producer =
        new SimpleProducerModule_SettableFutureStrFactory(
            executorProvider, componentMonitorProvider, strFutureProducer);
    assertThat(producer.get().isDone()).isFalse();

    InOrder order = inOrder(componentMonitor, monitor);
    order.verify(componentMonitor).producerMonitorFor(token);

    strFutureFuture.set(strFuture);
    order.verify(monitor).methodStarting();
    order.verify(monitor).methodFinished();
    assertThat(producer.get().isDone()).isFalse();

    Throwable t = new RuntimeException("monkey");
    strFuture.setException(t);
    try {
      producer.get().get();
      fail();
    } catch (ExecutionException e) {
      assertThat(e.getCause()).isSameAs(t);
      order.verify(monitor).failed(t);
    }

    order.verifyNoMoreInteractions();
  }
  /**
   * This method checks if the reader thread has finished, and re-throw any exceptions thrown by the
   * reader thread.
   *
   * @throws SqoopException if the consumer thread threw it.
   * @throws RuntimeException if some other exception was thrown.
   */
  private void waitForConsumer() {
    try {
      consumerFuture.get();
    } catch (ExecutionException ex) {
      // In almost all cases, the exception will be SqoopException,
      // because all exceptions are caught and propagated as
      // SqoopExceptions

      // There are race conditions with exceptions where the free sema is
      // no released.  So sense we are in single threaded mode at this point
      // we can ask if there are availablePermits and release if needed
      if (free.availablePermits() == 0) {
        free.release();
      }

      Throwable t = ex.getCause();
      if (t instanceof SqoopException) {
        throw (SqoopException) t;
      }
      // In the rare case, it was not a SqoopException
      Throwables.propagate(t);
    } catch (Exception ex) {

      // There are race conditions with exceptions where the free sema is
      // no released.  So sense we are in single threaded mode at this point
      // we can ask if there are availablePermits and release if needed
      if (free.availablePermits() == 0) {
        free.release();
      }

      throw new SqoopException(SparkExecutionError.SPARK_EXEC_0019, ex);
    }
  }
  @org.junit.Test
  public void Test() {

    idMgr = Test1083.getCommMgr().getIdManager();
    privateId = idMgr.getThisNetworkNode();

    assertNotNull(idMgr);
    assertNotNull(privateId);

    IndividualCtxEntity operator = null;

    try {
      operator = Test1083.ctxBroker.retrieveCssOperator().get();

      LOG.info("[#1859] Id from broker is " + operator.getId().getOperatorId());
      LOG.info("[#1859] Id directly from idMgr is " + privateId);

    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (CtxException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    assertNotNull(operator);
    assertEquals(operator.getId().getOperatorId(), privateId.getBareJid());

    LOG.info(
        "[#1859] Using equals with getOperatorId() - "
            + operator.getId().getOperatorId().equals(privateId.getBareJid()));
  }
Esempio n. 6
0
  @Override
  public Integer call() throws Exception {
    count = 0;

    try {
      File[] files = directory.listFiles();
      ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>();

      for (File file : files) {
        if (file.isDirectory()) {
          MatchCounter counter = new MatchCounter(file, keyword);
          FutureTask<Integer> task = new FutureTask<Integer>(counter);
          results.add(task);
          Thread t = new Thread(task);
          t.start();
        } else {
          if (search(file)) count++;
        }

        for (Future<Integer> result : results) {
          try {
            count += result.get();
          } catch (ExecutionException e) {
            e.printStackTrace();
          }
        }
      }
    } catch (InterruptedException e) {
    }
    return count;
  }
Esempio n. 7
0
  /**
   * Registers an artist if that artist is a user.
   *
   * @param v the v
   */
  public void registerArtistAction(View v) {
    String artistName = registerArtistNameInput.getText().toString();
    String artistGenre = registerArtistGenreInput.getText().toString();

    try {
      RestResult<ArtistEntity> restResult =
          registerArtistTaskProvider
              .get()
              .execute(this.vistingUser.getUserId(), artistName, artistGenre)
              .get();
      if (restResult.isFailure()) {
        InsiemeExceptionEntity insiemeExceptionEntity = restResult.getError();
        Toast.makeText(this, insiemeExceptionEntity.getException(), Toast.LENGTH_LONG).show();
      } else {
        ArtistEntity newArtist = restResult.getRestResult();
        Toast.makeText(this, "Welcome: " + newArtist.getName(), Toast.LENGTH_LONG).show();
        // you are now an artist and cant register.
        registerArtistLayout.setVisibility(View.INVISIBLE);
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (ExecutionException e) {
      e.printStackTrace();
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * org.societies.api.internal.servicelifecycle.IServiceDiscovery#getServices
   * ()
   */
  @Override
  @Async
  public Future<List<Service>> getServices(String jid) throws ServiceDiscoveryException {

    Future<List<Service>> asyncResult = null;
    List<Service> result = null;

    try {

      asyncResult = this.getServices(commMngr.getIdManager().fromJid(jid));

      result = asyncResult.get();

    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidFormatException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return new AsyncResult<List<Service>>(result);
  }
Esempio n. 9
0
  public List<TravelQuote> getRankedTravelQuotes(
      TravelInfo travelInfo,
      Set<TravelCompany> companies,
      Comparator<TravelQuote> ranking,
      long time,
      TimeUnit unit)
      throws InterruptedException {
    List<QuoteTask> tasks = new ArrayList<QuoteTask>();
    for (TravelCompany company : companies) tasks.add(new QuoteTask(company, travelInfo));

    List<Future<TravelQuote>> futures = exec.invokeAll(tasks, time, unit);

    List<TravelQuote> quotes = new ArrayList<TravelQuote>(tasks.size());
    Iterator<QuoteTask> taskIter = tasks.iterator();
    for (Future<TravelQuote> f : futures) {
      QuoteTask task = taskIter.next();
      try {
        quotes.add(f.get());
      } catch (ExecutionException e) {
        quotes.add(task.getFailureQuote(e.getCause()));
      } catch (CancellationException e) {
        quotes.add(task.getTimeoutQuote(e));
      }
    }

    Collections.sort(quotes, ranking);
    return quotes;
  }
Esempio n. 10
0
 @Override
 public Session connectToServer(Class annotatedEndpointClass, URI path)
     throws DeploymentException, IOException {
   if (annotatedEndpointClass.getAnnotation(ClientEndpoint.class) == null) {
     throw new DeploymentException(
         String.format(
             "Class argument in connectToServer(Class, URI) is to be annotated endpoint class."
                 + "Class %s does not have @ClientEndpoint",
             annotatedEndpointClass.getName()));
   }
   try {
     return connectToServer(
             annotatedEndpointClass, null, path.toString(), new SameThreadExecutorService())
         .get();
   } catch (InterruptedException e) {
     throw new DeploymentException(e.getMessage(), e);
   } catch (ExecutionException e) {
     final Throwable cause = e.getCause();
     if (cause instanceof DeploymentException) {
       throw (DeploymentException) cause;
     } else if (cause instanceof IOException) {
       throw (IOException) cause;
     } else {
       throw new DeploymentException(cause.getMessage(), cause);
     }
   }
 }
Esempio n. 11
0
  /*
   * Implements an abstract method from VizConnection.
   */
  @Override
  protected IParaViewWebClient connectToWidget() {
    // Set the default return value.
    IParaViewWebClient client = null;

    // Try to create and connect to a ParaView web client.
    boolean connected = false;
    try {
      // Create an HTTP implementation of the ParaView web client..
      client = new HttpParaViewWebClient();
      // Set up the HTTP URL
      String host = getHost();
      String port = Integer.toString(getPort());
      String url = "http://" + host + ":" + port + "/rpc-http/";
      // Try to connect.
      connected = client.connect(url).get();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (ExecutionException e) {
      e.printStackTrace();
    }

    // If the connection was not successful, we should return null.
    if (!connected) {
      client = null;
    }

    return client;
  }
  @Override
  @Test
  public void win7DisconnectTest() throws Throwable {
    final AtomicInteger count = new AtomicInteger(0);

    AsyncHttpClient client = getAsyncHttpClient(new AsyncHttpClientConfig.Builder().build());
    AsyncCompletionHandler<Response> handler =
        new AsyncCompletionHandlerAdapter() {

          @Override
          public Response onCompleted(Response response) throws Exception {

            count.incrementAndGet();
            StackTraceElement e =
                new StackTraceElement("sun.nio.ch.SocketDispatcher", "read0", null, -1);
            IOException t = new IOException();
            t.setStackTrace(new StackTraceElement[] {e});
            throw t;
          }
        };

    try {
      client.prepareGet(getTargetUrl()).execute(handler).get();
      fail("Must have received an exception");
    } catch (ExecutionException ex) {
      assertNotNull(ex);
      assertNotNull(ex.getCause());
      assertEquals(ex.getCause().getClass(), IOException.class);
      assertEquals(count.get(), 1);
    }
    client.close();
  }
Esempio n. 13
0
 @Override
 protected void done() {
   try {
     progressBar.setValue(0);
     btn_limpa_dados.setEnabled(true);
     btn_processa.setEnabled(true);
     getContentPane().setCursor(Cursor.getDefaultCursor());
     // Descobre como está o processo. É responsável por lançar
     // as exceptions
     get();
     // JOptionPane.showMessageDialog(getContentPane(),
     // "Processamento de dados realizado com sucesso",
     // "Informação", JOptionPane.INFORMATION_MESSAGE);
   } catch (ExecutionException e) {
     final String msg = String.format("Erro ao exportar dados: %s", e.getCause().toString());
     SwingUtilities.invokeLater(
         new Runnable() {
           @Override
           public void run() {
             JOptionPane.showMessageDialog(
                 getContentPane(),
                 "Erro ao exportar: " + msg,
                 "Erro",
                 JOptionPane.ERROR_MESSAGE);
           }
         });
   } catch (InterruptedException e) {
     System.out.println("Processo de exportação foi interrompido");
   }
 }
Esempio n. 14
0
    private HttpResponse executeRequest(
        final Callable<HttpResponse> task, final long timeout, final TimeUnit unit)
        throws TimeoutException, IOException {
      ExecutorService executor = Executors.newSingleThreadExecutor();
      try {
        Throwable lastCause = null;
        long endTime = System.currentTimeMillis() + unit.toMillis(timeout);
        while (System.currentTimeMillis() < endTime) {
          Future<HttpResponse> result = executor.submit(task);
          try {
            return result.get(timeout, unit);
          } catch (InterruptedException ex) {
            throw new IllegalStateException(ex);
          } catch (ExecutionException ex) {
            lastCause = ex.getCause();

            // HttpURLConnection throws FileNotFoundException on 404 so handle this
            if (lastCause instanceof FileNotFoundException) {
              HttpResponse httpResult = new HttpResponse();
              httpResult.setStatusCode(HttpURLConnection.HTTP_NOT_FOUND);
              return httpResult;
            } else {
              continue;
            }
          }
        }
        TimeoutException toex = new TimeoutException();
        if (lastCause != null) {
          toex.initCause(lastCause);
        }
        throw toex;
      } finally {
        executor.shutdownNow();
      }
    }
Esempio n. 15
0
  @Override
  public void run() {

    while (!_shutDown
        || _futureOrders.size()
            > 0) { // Procceed if there's no shut down request OR there are still orders being
                   // cooked.

      try {
        Future<Order> futureOrder =
            _superExecutor.take(); // Waiting until the future object is done, then take it.

        _futureOrders.remove(futureOrder); // remove the future order from the vector.

        try {
          releaseOrder(futureOrder.get()); // Release the order back to the management.
        } catch (ExecutionException e) {
          e.printStackTrace();
        }
        _management.notifyThis(); // notify Management, so he knows a chef has done his work.

      } catch (InterruptedException e) {
      }
    }
    _executor.shutdown(); // shut down the Callable Cook Whole Order.

    // }
  }
  @Test
  public void testStupidlyLargeSetAndSizeOverride() throws Exception {
    Random r = new Random();
    SerializingTranscoder st = new SerializingTranscoder(Integer.MAX_VALUE);

    st.setCompressionThreshold(Integer.MAX_VALUE);

    byte[] data = new byte[21 * 1024 * 1024];
    r.nextBytes(data);

    try {
      client.set("bigobject", 60, data, st).get();
      fail("Didn't fail setting big object.");
    } catch (ExecutionException e) {
      System.err.println(
          "Successful failure setting big object.  Object size "
              + data.length
              + " bytes doesn't fit.");
      e.printStackTrace();
      OperationException oe = (OperationException) e.getCause();
      assertSame(OperationErrorType.SERVER, oe.getType());
    }

    // But I should still be able to do something.
    client.set("k", 5, "Blah");
    assertEquals("Blah", client.get("k"));
  }
  private ArrayList<String> getAppUsersId() {
    // TODO: Fetch user ids from database
    ArrayList<String> usersID = new ArrayList<String>();

    try {
      String response =
          new GetUsersTask()
              .execute("http://katanaserver.no-ip.org/gcm_server_php/get_users.php")
              .get();

      // Parse the response
      JsonElement jelement = new JsonParser().parse(response);
      JsonArray jarray = jelement.getAsJsonArray();
      for (int i = 0; i < jarray.size(); i++) {
        usersID.add(jarray.get(i).getAsJsonObject().get("UserID").toString());
      }

    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (ExecutionException e) {
      e.printStackTrace();
    }

    return usersID;
  }
Esempio n. 18
0
  @Test
  public void testCollectUnknownReference() throws Throwable {
    expectedException.expect(UnhandledServerException.class);
    expectedException.expectMessage("Unknown Reference some.table.some_column");

    Reference unknownReference =
        new Reference(
            new ReferenceInfo(
                new ReferenceIdent(new TableIdent("some", "table"), "some_column"),
                RowGranularity.NODE,
                DataTypes.BOOLEAN));
    CollectPhase collectNode =
        new CollectPhase(
            UUID.randomUUID(),
            0,
            "unknown",
            testRouting,
            Collections.<Symbol>singletonList(unknownReference),
            EMPTY_PROJECTIONS);
    collectNode.maxRowGranularity(RowGranularity.NODE);
    try {
      getBucket(collectNode);
    } catch (ExecutionException e) {
      throw e.getCause();
    }
  }
Esempio n. 19
0
  protected void checkExceptionHandling(
      final LinkedBlockingQueue<Throwable> unexpectedExceptions,
      ExecutorTaskAgent agent,
      Future<?> future,
      Class<? extends Exception> expectedKlass,
      boolean isExpected)
      throws InterruptedException {

    try {
      future.get();
    } catch (ExecutionException ce) {
      assertTrue(expectedKlass.isInstance(ce.getCause()));
      // ok
    }
    agent.awaitPendingTasks();

    if (expectedKlass == null || isExpected) {
      assertTrue(unexpectedExceptions.size() == 0);
      return;
    } else {
      assertTrue(unexpectedExceptions.size() == 1);
      Throwable removed = unexpectedExceptions.remove();
      assertTrue(expectedKlass.isInstance(removed));
    }
  }
Esempio n. 20
0
  @Test
  public void testUnknownFunction() throws Throwable {
    // will be wrapped somewhere above
    expectedException.expect(IllegalArgumentException.class);
    expectedException.expectMessage("Cannot find implementation for function unknown()");

    Symbol unknownFunction =
        new Function(
            new FunctionInfo(
                new FunctionIdent("unknown", ImmutableList.<DataType>of()), DataTypes.BOOLEAN),
            ImmutableList.<Symbol>of());
    CollectPhase collectNode =
        new CollectPhase(
            UUID.randomUUID(),
            0,
            "unknownFunction",
            testRouting,
            Collections.singletonList(unknownFunction),
            EMPTY_PROJECTIONS);
    try {
      getBucket(collectNode);
    } catch (ExecutionException e) {
      throw e.getCause();
    }
  }
 protected void waitForConfirms(final String testTitle) throws Exception
 {
     try {
         FutureTask<?> waiter = new FutureTask<Object>(new Runnable() {
                 public void run() {
                     try {
                         channel.waitForConfirmsOrDie();
                     } catch (IOException e) {
                         throw (ShutdownSignalException)e.getCause();
                     } catch (InterruptedException _) {
                         fail(testTitle + ": interrupted");
                     }
                 }
             }, null);
         (Executors.newSingleThreadExecutor()).execute(waiter);
         waiter.get(10, TimeUnit.SECONDS);
     } catch (ExecutionException ee) {
         Throwable t = ee.getCause();
         if (t instanceof ShutdownSignalException) throw (ShutdownSignalException) t;
         if (t instanceof AssertionFailedError) throw (AssertionFailedError) t;
         throw (Exception)t;
     } catch (TimeoutException _) {
         fail(testTitle + ": timeout");
     }
 }
 private T internalGetResult(Long timeout, TimeUnit unit)
     throws OperationCanceledException, IOException, AuthenticatorException {
   try {
     if (timeout == null) {
       return get();
     } else {
       return get(timeout, unit);
     }
   } catch (InterruptedException e) {
     // fall through and cancel
   } catch (TimeoutException e) {
     // fall through and cancel
   } catch (CancellationException e) {
     // fall through and cancel
   } catch (ExecutionException e) {
     final Throwable cause = e.getCause();
     if (cause instanceof IOException) {
       throw (IOException) cause;
     } else if (cause instanceof UnsupportedOperationException) {
       throw new AuthenticatorException(cause);
     } else if (cause instanceof AuthenticatorException) {
       throw (AuthenticatorException) cause;
     } else if (cause instanceof RuntimeException) {
       throw (RuntimeException) cause;
     } else if (cause instanceof Error) {
       throw (Error) cause;
     } else {
       throw new IllegalStateException(cause);
     }
   } finally {
     boolean mayInterruptIfRunning = true;
     cancel(mayInterruptIfRunning);
   }
   throw new OperationCanceledException();
 }
Esempio n. 23
0
  public static void downloadEncrypted(List<NUSTitleInformation> output_, final Progress progress) {
    ForkJoinPool pool = ForkJoinPool.commonPool();
    List<ForkJoinTask<Boolean>> list = new ArrayList<>();

    for (final NUSTitleInformation nus : output_) {
      final long tID = nus.getTitleID();
      list.add(
          pool.submit(
              new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                  NUSTitle nusa =
                      new NUSTitle(
                          tID, nus.getSelectedVersion(), Util.ByteArrayToString(nus.getKey()));
                  Progress childProgress = new Progress();
                  progress.add(childProgress);
                  nusa.downloadEncryptedFiles(progress);

                  return true;
                }
              }));
    }
    for (ForkJoinTask<Boolean> task : list) {
      try {
        task.get();
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
Esempio n. 24
0
  /**
   * Synchronously sends an opaque message to the RpcHandler on the server-side, waiting for up to a
   * specified timeout for a response.
   */
  public ByteBuffer sendRpcSync(ByteBuffer message, long timeoutMs) {
    final SettableFuture<ByteBuffer> result = SettableFuture.create();

    sendRpc(
        message,
        new RpcResponseCallback() {
          @Override
          public void onSuccess(ByteBuffer response) {
            result.set(response);
          }

          @Override
          public void onFailure(Throwable e) {
            result.setException(e);
          }
        });

    try {
      return result.get(timeoutMs, TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
      throw Throwables.propagate(e.getCause());
    } catch (Exception e) {
      throw Throwables.propagate(e);
    }
  }
Esempio n. 25
0
  /** Invokes the effector so that its progress is tracked. */
  public static <T> T invokeEffector(Entity entity, Effector<T> eff, Object[] args) {
    String id = entity.getId();
    String name = eff.getName();

    try {
      if (log.isDebugEnabled())
        log.debug("Invoking effector {} on {}", new Object[] {name, entity});
      if (log.isTraceEnabled())
        log.trace("Invoking effector {} on {} with args {}", new Object[] {name, entity, args});
      EntityManagementSupport mgmtSupport = ((EntityInternal) entity).getManagementSupport();
      if (!mgmtSupport.isDeployed()) {
        mgmtSupport.attemptLegacyAutodeployment(name);
      }
      ManagementContextInternal mgmtContext =
          (ManagementContextInternal) ((EntityInternal) entity).getManagementContext();

      mgmtSupport.getEntityChangeListener().onEffectorStarting(eff);
      try {
        return mgmtContext.invokeEffectorMethodSync(entity, eff, args);
      } finally {
        mgmtSupport.getEntityChangeListener().onEffectorCompleted(eff);
      }
    } catch (CancellationException ce) {
      log.info("Execution of effector {} on entity {} was cancelled", name, id);
      throw ce;
    } catch (ExecutionException ee) {
      log.info("Execution of effector {} on entity {} failed with {}", new Object[] {name, id, ee});
      // Exceptions thrown in Futures are wrapped
      // FIXME Shouldn't pretend exception came from this thread?! Should we remove this unwrapping?
      if (ee.getCause() != null) throw Exceptions.propagate(ee.getCause());
      else throw Exceptions.propagate(ee);
    }
  }
Esempio n. 26
0
  public Translation project(
      String sentence,
      String translation,
      Locale sourceLanguage,
      Locale targetLanguage,
      SymmetrizationStrategy strategy)
      throws TranslationException, LanguagePairNotSupportedException {
    boolean inverted = isLanguagesInverted(sourceLanguage, targetLanguage);
    ProjectTagsOperation operation =
        new ProjectTagsOperation(sentence, translation, inverted, strategy);
    try {
      return ModernMT.node.submit(operation).get();
    } catch (InterruptedException e) {
      throw new SystemShutdownException();
    } catch (ExecutionException e) {
      Throwable cause = e.getCause();

      if (cause instanceof ProcessingException)
        throw new TranslationException("Problem while processing translation", cause);
      else if (cause instanceof AlignerException)
        throw new TranslationException("Problem while computing alignments", cause);
      else if (cause instanceof RuntimeException)
        throw new TranslationException("Unexpected exceptions while projecting tags", cause);
      else throw new Error("Unexpected exception: " + cause.getMessage(), cause);
    }
  }
    @Override
    public void evaluate() throws Throwable {
      ProcessCallable<Serializable> processCallable =
          new TestProcessCallable(
              _testClassName, _beforeMethodKeys, _testMethodKey, _afterMethodKeys);

      processCallable = processProcessCallable(processCallable, _testMethodKey);

      ProcessChannel<Serializable> processChannel =
          _processExecutor.execute(_processConfig, processCallable);

      Future<Serializable> future = processChannel.getProcessNoticeableFuture();

      try {
        future.get();
      } catch (ExecutionException ee) {
        Throwable cause = ee.getCause();

        while ((cause instanceof ProcessException)
            || (cause instanceof InvocationTargetException)) {

          cause = cause.getCause();
        }

        throw cause;
      }
    }
Esempio n. 28
0
  public static void main(String[] args) {
    ExecutorService executor = Executors.newCachedThreadPool();
    ResultTask[] resultTasks = new ResultTask[5];
    for (int i = 0; i < resultTasks.length; i++) {
      ExecutableTask executableTask = new ExecutableTask("Task-" + i);
      resultTasks[i] = new ResultTask(executableTask);
      executor.submit(resultTasks[i]);
    }

    try {
      TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    for (int i = 0; i < resultTasks.length; i++) {
      resultTasks[i].cancel(true);
    }

    for (int i = 0; i < resultTasks.length; i++) {
      try {
        if (!resultTasks[i].isCancelled()) {
          System.out.printf("%s\n", resultTasks[i].get());
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (ExecutionException e) {
        e.printStackTrace();
      }
    }

    executor.shutdown();
  }
Esempio n. 29
0
 @Override
 public V compute(final A arg) throws InterruptedException {
   while (true) {
     Future<V> f = cache.get(arg);
     if (f == null) {
       Callable<V> eval =
           new Callable<V>() {
             @Override
             public V call() throws Exception {
               return c.compute(arg);
             }
           };
       FutureTask<V> ft = new FutureTask<V>(eval);
       f = cache.putIfAbsent(arg, ft);
       if (f == null) {
         f = ft;
         ft.run();
       }
     }
     try {
       return f.get();
     } catch (CancellationException e) {
       cache.remove(arg, f);
     } catch (ExecutionException e) {
       throw launderThrowable(e.getCause());
     }
   }
 }
Esempio n. 30
0
  private Pair<Map<String, String>, /*was it created now?*/ Boolean> getOrCreateIndexConfig(
      Class<? extends PropertyContainer> cls,
      String indexName,
      Map<String, String> suppliedConfig) {
    Pair<Map<String, String>, Boolean> result =
        findIndexConfig(cls, indexName, suppliedConfig, config.getParams());
    boolean createdNow = false;
    if (result.other()) { // Ok, we need to create this config
      synchronized (this) { // Were we the first ones to get here?
        Map<String, String> existing = indexStore.get(cls, indexName);
        if (existing != null) {
          // No, someone else made it before us, cool
          assertConfigMatches(
              getIndexProvider(existing.get(PROVIDER)), indexName, existing, result.first());
          return Pair.of(result.first(), false);
        }

        // We were the first one here, let's create this config
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        try {
          executorService.submit(new IndexCreatorJob(cls, indexName, result.first())).get();
          indexStore.set(cls, indexName, result.first());
          createdNow = true;
        } catch (ExecutionException ex) {
          throw new TransactionFailureException(
              "Index creation failed for " + indexName + ", " + result.first(), ex.getCause());
        } catch (InterruptedException ex) {
          Thread.interrupted();
        } finally {
          executorService.shutdownNow();
        }
      }
    }
    return Pair.of(result.first(), createdNow);
  }