示例#1
0
  @Override
  public void close() {
    for (R2Store store : this.rawStoreList) {
      store.close();
    }
    // shutdown the transportclient in the case when no r2store is created
    if (this.transportClient != null) {
      final FutureCallback<None> clientShutdownCallback = new FutureCallback<None>();
      this.transportClient.shutdown(clientShutdownCallback);
      try {
        clientShutdownCallback.get();
      } catch (InterruptedException e) {
        logger.error("Interrupted while shutting down the TransportClient: " + e.getMessage(), e);
      } catch (ExecutionException e) {
        logger.error(
            "Execution exception occurred while shutting down the TransportClient: "
                + e.getMessage(),
            e);
      }
    }

    final FutureCallback<None> factoryShutdownCallback = new FutureCallback<None>();
    this._clientFactory.shutdown(factoryShutdownCallback);
    try {
      factoryShutdownCallback.get();
    } catch (InterruptedException e) {
      logger.error("Interrupted while shutting down the HttpClientFactory: " + e.getMessage(), e);
    } catch (ExecutionException e) {
      logger.error(
          "Execution exception occurred while shutting down the HttpClientFactory: "
              + e.getMessage(),
          e);
    }
  }
示例#2
0
 public BarChartTrader getBarchartTrader(String experimentAccession, String accessKey) {
   try {
     return barchartTraders.get(Pair.of(experimentAccession, accessKey));
   } catch (ExecutionException e) {
     LOGGER.error(e.getMessage(), e);
     throw new IllegalStateException(
         "Exception while loading histogram data from file: " + e.getMessage(), e.getCause());
   }
 }
示例#3
0
  public void onClickCreat(View view) {

    CurrencyAd ad =
        new CurrencyAd(
            editTextName.getText().toString(),
            editTextCurrency.getText().toString(),
            editTextCountSits.getText().toString(),
            null,
            editTextPrice.getText().toString(),
            user.getEmail(),
            editTextAbout.getText().toString(),
            editTextCityEnd.getText().toString(),
            editTextCityStart.getText().toString(),
            editTextDateEnd.getText().toString(),
            editTextDateStart.getText().toString(),
            editTextTimeEnd.getText().toString(),
            editTextTimeStart.getText().toString());
    GsonBuilder builder1 = new GsonBuilder();
    Gson gson1 = builder1.create();
    String a = gson1.toJson(ad);
    try {
      sent = new CreatAdAsyncTask().execute(gson1.toJson(ad)).get(5, TimeUnit.SECONDS);
      startActivity(new Intent(this, MainActivity.class));
      Toast.makeText(this, "Ваша заявка создана!", Toast.LENGTH_LONG).show();

    } catch (InterruptedException e) {
      Logger.getAnonymousLogger().warning(e.getMessage());
    } catch (ExecutionException e) {
      Logger.getAnonymousLogger().warning(e.getMessage());
    } catch (TimeoutException e) {
      Toast.makeText(this, "Oooops!", Toast.LENGTH_SHORT).show();
    }
  }
示例#4
0
 public boolean moveItemAtPath_toPath_error(
     final String source, final String destination, long /*ObjCObjectByReference*/ error) {
   log.debug("moveItemAtPath_toPath_error:" + source);
   final Future<Boolean> future =
       background(
           new FilesystemBackgroundAction<Boolean>(session) {
             @Override
             public Boolean call() {
               final Path file = PathFactory.createPath(session, source, Path.FILE_TYPE);
               if (!file.exists()) {
                 return false;
               }
               if (!session.isRenameSupported(file)) {
                 return false;
               }
               file.rename(PathFactory.createPath(session, destination, Path.FILE_TYPE));
               return true;
             }
           });
   try {
     return future.get();
   } catch (InterruptedException e) {
     log.error("Error executing action for mounted disk:" + e.getMessage());
   } catch (ExecutionException e) {
     log.error("Error executing action for mounted disk:" + e.getMessage());
   }
   return false;
 }
示例#5
0
 public boolean createFileAtPath_attributes_userData_error(
     final String path,
     NSDictionary attributes,
     ID userData,
     long /*ObjCObjectByReference*/ error) {
   log.debug("createFileAtPath_attributes_userData_error:" + path);
   final Future<Boolean> future =
       background(
           new FilesystemBackgroundAction<Boolean>(session) {
             @Override
             public Boolean call() {
               final Path file = PathFactory.createPath(session, path, Path.DIRECTORY_TYPE);
               if (session.isCreateFileSupported(file.getParent())) {
                 file.touch();
                 return true;
               }
               return false;
             }
           });
   try {
     return future.get();
   } catch (InterruptedException e) {
     log.error("Error executing action for mounted disk:" + e.getMessage());
   } catch (ExecutionException e) {
     log.error("Error executing action for mounted disk:" + e.getMessage());
   }
   return false;
 }
示例#6
0
 private static void send(PaymentSession session) {
   try {
     System.out.println("Payment Request");
     System.out.println("Amount: " + session.getValue().doubleValue() / 100000 + "mDOGE");
     System.out.println("Date: " + session.getDate());
     System.out.println("Memo: " + session.getMemo());
     if (session.pkiVerificationData != null) {
       System.out.println("Pki-Verified Name: " + session.pkiVerificationData.name);
       if (session.pkiVerificationData.orgName != null)
         System.out.println("Pki-Verified Org: " + session.pkiVerificationData.orgName);
       System.out.println(
           "PKI data verified by: " + session.pkiVerificationData.rootAuthorityName);
     }
     final Wallet.SendRequest req = session.getSendRequest();
     if (password != null) {
       if (!wallet.checkPassword(password)) {
         System.err.println("Password is incorrect.");
         return;
       }
       req.aesKey = wallet.getKeyCrypter().deriveKey(password);
     }
     wallet.completeTx(req); // may throw InsufficientMoneyException.
     if (options.has("offline")) {
       wallet.commitTx(req.tx);
       return;
     }
     setup();
     // No refund address specified, no user-specified memo field.
     ListenableFuture<PaymentSession.Ack> future =
         session.sendPayment(ImmutableList.of(req.tx), null, null);
     if (future == null) {
       // No payment_url for submission so, broadcast and wait.
       peers.startAndWait();
       peers.broadcastTransaction(req.tx).get();
     } else {
       PaymentSession.Ack ack = future.get();
       wallet.commitTx(req.tx);
       System.out.println("Memo from server: " + ack.getMemo());
     }
   } catch (PaymentRequestException e) {
     System.err.println("Failed to send payment " + e.getMessage());
     System.exit(1);
   } catch (VerificationException e) {
     System.err.println("Failed to send payment " + e.getMessage());
     System.exit(1);
   } catch (ExecutionException e) {
     System.err.println("Failed to send payment " + e.getMessage());
     System.exit(1);
   } catch (IOException e) {
     System.err.println("Invalid payment " + e.getMessage());
     System.exit(1);
   } catch (InterruptedException e1) {
     // Ignore.
   } catch (InsufficientMoneyException e) {
     System.err.println(
         "Insufficient funds: have " + Utils.bitcoinValueToFriendlyString(wallet.getBalance()));
   } catch (BlockStoreException e) {
     throw new RuntimeException(e);
   }
 }
示例#7
0
  /**
   * Invokes this method with the provided arguments
   *
   * @param args @return @throws WiseException If an unknown exception is received
   * @throws WiseWebServiceException There are 4 known failure conditions - The wsdl (url) could not
   *     be found - The wsdl is password protected - The endpoint (url) could not be found - The
   *     endpoint is password protected
   * @throws InvocationException
   * @throws IllegalArgumentException
   */
  InvocationResultImpl invoke(Map<String, Object> args)
      throws WiseWebServiceException, InvocationException, IllegalArgumentException {
    InvocationResultImpl result = null;
    Map<String, Object> emptyHolder = Collections.emptyMap();

    try {
      EndpointMethodCaller caller =
          new EndpointMethodCaller(
              this.getEndpoint(), this.getMethod(), this.getParametersInRightPositionArray(args));
      Future<Object> invocation = ((WSEndpointImpl) this.getEndpoint()).getService().submit(caller);
      if (isOneWay()) {
        invocation.get();
        result = new InvocationResultImpl(null, null, null, emptyHolder);
      } else {
        result =
            new InvocationResultImpl(
                RESULT, method.getGenericReturnType(), invocation.get(), getHoldersResult(args));
      }
    } catch (java.util.concurrent.ExecutionException wse) {
      Throwable ite = wse.getCause();
      if (ite != null && ite != wse && ite instanceof InvocationTargetException) {
        Throwable t = ite.getCause();

        // unchecked exception ?
        if (t != null && t != ite && t != wse && t instanceof WebServiceException) {
          // authentication exception ?
          if (isAuthenticationException(t, new HashSet<Throwable>())) {
            throw new WiseWebServiceException(
                "Authentication exception", null); // TODO improve this
          }
          throw new WiseWebServiceException(t.getMessage(), t);
        }

        // checked exception ?
        if (t != null && t != ite && t != wse && t instanceof Exception) {
          Method methodPointer = this.getMethod();
          if (methodPointer != null && methodPointer.getExceptionTypes() != null) {
            for (int i = 0; i < methodPointer.getExceptionTypes().length; i++) {
              Class<?> excType = methodPointer.getExceptionTypes()[i];
              if (t.getClass().isAssignableFrom(excType)) {
                // checked exception
                result = new InvocationResultImpl("exception", excType, t, emptyHolder);
                return result;
              }
            }
          }
        }

        throw new InvocationException("Unknown exception received: " + ite.getMessage(), ite);
      }
      throw new WiseWebServiceException(wse.getMessage(), wse);
    } catch (Throwable e) {
      throw new InvocationException("Generic Error during method invocation!", e);
    }
    return result;
  }
示例#8
0
 private void drawImage(Graphics2D g, Future<BufferedImage> future) {
   try {
     BufferedImage image = future.get();
     g.drawImage(image, 0, 0, noActionImageObserver);
   } catch (InterruptedException e) {
     log.warn(e.getMessage(), e);
   } catch (ExecutionException e) {
     log.error(e.getMessage(), e);
   }
 }
示例#9
0
 @Override
 protected MatrixStore<N> makeQ2() {
   try {
     return myFutureQ2.get();
   } catch (final InterruptedException anException) {
     throw new ProgrammingError(anException.getMessage());
   } catch (final ExecutionException anException) {
     throw new ProgrammingError(anException.getMessage());
   }
 }
示例#10
0
 private long getNTPFuture() {
   try {
     return ntpFuture.get();
   } catch (InterruptedException e) {
     logger.error("InterruptedException: " + e.getMessage());
   } catch (ExecutionException e) {
     logger.error("ExecutionException: " + e.getMessage());
   }
   return 0L;
 }
示例#11
0
 @Override
 public ValueWrapper get(Object key) {
   if (this.cache instanceof LoadingCache) {
     try {
       Object value = ((LoadingCache<Object, Object>) this.cache).get(key);
       return toWrapper(value);
     } catch (ExecutionException ex) {
       throw new UncheckedExecutionException(ex.getMessage(), ex);
     }
   }
   return toWrapper(this.cache.getIfPresent(key));
 }
示例#12
0
 // This may be aborted if there are stagnant requests sitting in queue.
 // This needs fixed to discard outstanding save requests.
 public synchronized void forceSave() {
   try {
     Future<?> future = delayedSave(configFile);
     if (future != null) {
       future.get();
     }
   } catch (InterruptedException ex) {
     LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
   } catch (ExecutionException ex) {
     LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
   }
 }
 /*
  * Store these and poll checking for completion until them all finish
  */
 @Override
 public double testNeuralNetwork(double[] testDataSet, boolean dump) {
   double testResult = 0.;
   try {
     testResult = testNeuralNetworkAsync(testDataSet, dump).get();
   } catch (InterruptedException ie) {
     System.err.println("InterruptedException: " + ie.getMessage());
   } catch (ExecutionException ee) {
     System.err.println("ExecutionException: " + ee.getMessage());
   }
   return testResult;
 }
示例#14
0
  @Override
  public List<SecretAuthenticationKey> authenticate(
      @WebParam(name = "authenticationData", targetNamespace = "")
          List<AuthenticationTriple> authenticationData)
      throws AuthenticationExceptionException, SNAAExceptionException {

    Map<String, Set<AuthenticationTriple>> intersectionPrefixSet =
        getIntersectionPrefixSetAT(authenticationData);

    Set<Future<List<SecretAuthenticationKey>>> futures =
        new HashSet<Future<List<SecretAuthenticationKey>>>();

    for (String wsEndpointUrl : intersectionPrefixSet.keySet()) {
      AuthenticationCallable authenticationCallable =
          new AuthenticationCallable(
              wsEndpointUrl,
              new ArrayList<AuthenticationTriple>(intersectionPrefixSet.get(wsEndpointUrl)));
      Future<List<SecretAuthenticationKey>> future = executorService.submit(authenticationCallable);
      futures.add(future);
    }

    List<SecretAuthenticationKey> resultSet = new LinkedList<SecretAuthenticationKey>();

    for (Future<List<SecretAuthenticationKey>> future : futures) {
      try {
        resultSet.addAll(future.get());
      } catch (InterruptedException e) {
        SNAAException exception = new SNAAException();
        exception.setMessage(e.getMessage());
        throw new SNAAExceptionException(e.getMessage(), exception, e);
      } catch (ExecutionException e) {
        SNAAException exception = new SNAAException();
        exception.setMessage(e.getMessage());
        throw new SNAAExceptionException(e.getMessage(), exception, e);
      }
    }

    return resultSet;
  }
示例#15
0
 public <T> T get(final Future<T> future) {
   try {
     return future.get();
   } catch (InterruptedException e1) {
     throw new InternalException("Future.get interrupted:" + e1.getMessage());
   } catch (ExecutionException e1) {
     if (e1.getCause() instanceof RuntimeException) {
       throw (RuntimeException) e1.getCause();
     } else {
       throw new InternalException("Caught exception thrown by Future.get:" + e1.getMessage());
     }
   }
 }
 /*
  * Store these and poll checking for completion until them all finish
  */
 @Override
 public double[] testNeuralNetwork(double[][] testDataSet, boolean dump) {
   double[] testResult = new double[testDataSet.length];
   Future<Double>[] futureResult = testNeuralNetworkAsync(testDataSet, dump);
   try {
     for (int n = 0; n < futureResult.length; n++) testResult[n] = futureResult[n].get();
   } catch (InterruptedException ie) {
     System.err.println("InterruptedException: " + ie.getMessage());
   } catch (ExecutionException ee) {
     System.err.println("ExecutionException: " + ee.getMessage());
   }
   return testResult;
 }
示例#17
0
  @Override
  public void execute(Tuple inputTuple) {
    /* Processing tuples of the shape
    (DATASOURCE_ID, TIMESTAMP_FIELD, CONTENT_FIELD) */

    // get datasource
    String datasource = inputTuple.getStringByField(RestIngestionSpout.DATASOURCE_ID);
    // compute month
    long timestamp = inputTuple.getLongByField(RestIngestionSpout.TIMESTAMP_FIELD);
    // this computation is completely stateless
    String month = timestampToMonth(timestamp);

    // now get the DataFileWriter
    DataFileWriter<GenericRecord> writer = null;
    try {
      writer = this.writersCache.get(DatasourceMonth.create(datasource, month));
    } catch (ExecutionException ee) {
      LOGGER.error(
          "Error getting DataFileWriter for tuple for datasource "
              + datasource
              + " and timestamp "
              + timestamp
              + " : "
              + ee.getMessage());
      this.collector.fail(inputTuple);
      return;
    }

    // create and write a new record
    GenericRecord newDataRecord = new GenericData.Record(AVRO_SCHEMA);
    newDataRecord.put(AVRO_TIMESTAMP_FIELD, new Long(timestamp));
    newDataRecord.put(
        AVRO_CONTENT_FIELD, inputTuple.getStringByField(RestIngestionSpout.CONTENT_FIELD));
    try {
      writer.append(newDataRecord);
    } catch (IOException ioe) {
      LOGGER.error(
          "Error writing Avro record for datasource "
              + datasource
              + " and timestamp "
              + timestamp
              + " : "
              + ioe.getMessage());
      this.collector.fail(inputTuple);
      return;
    }

    // ACK processing for this tupe as ok
    this.collector.ack(inputTuple);
  }
  public void commit(
      TransactionId txid, boolean wasPrepared, Runnable preCommit, Runnable postCommit)
      throws IOException {
    if (txid != null) {
      if (!txid.isXATransaction() && theStore.isConcurrentStoreAndDispatchTransactions()) {
        if (preCommit != null) {
          preCommit.run();
        }
        Tx tx = inflightTransactions.remove(txid);
        if (tx != null) {
          List<Future<Object>> results = tx.commit();
          boolean doneSomething = false;
          for (Future<Object> result : results) {
            try {
              result.get();
            } catch (InterruptedException e) {
              theStore.brokerService.handleIOException(new IOException(e.getMessage()));
            } catch (ExecutionException e) {
              theStore.brokerService.handleIOException(new IOException(e.getMessage()));
            } catch (CancellationException e) {
            }
            if (!result.isCancelled()) {
              doneSomething = true;
            }
          }
          if (postCommit != null) {
            postCommit.run();
          }
          if (doneSomething) {
            KahaTransactionInfo info = getTransactionInfo(txid);
            theStore.store(new KahaCommitCommand().setTransactionInfo(info), true, null, null);
          }
        } else {
          // The Tx will be null for failed over clients - lets run their post commits
          if (postCommit != null) {
            postCommit.run();
          }
        }

      } else {
        KahaTransactionInfo info = getTransactionInfo(txid);
        theStore.store(
            new KahaCommitCommand().setTransactionInfo(info), true, preCommit, postCommit);
        forgetRecoveredAcks(txid);
      }
    } else {
      LOG.error("Null transaction passed on commit");
    }
  }
 public BugzillaRestConfiguration getRepositoryConfiguration(TaskRepository repository)
     throws CoreException {
   if (clientCache.getIfPresent(new RepositoryKey(repository)) == null) {
     getClient(repository);
   }
   try {
     Optional<BugzillaRestConfiguration> configurationOptional =
         configurationCache.get(new RepositoryKey(repository));
     return configurationOptional.isPresent() ? configurationOptional.get() : null;
   } catch (UncheckedExecutionException e) {
     throw new CoreException(
         new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, e.getMessage(), e));
   } catch (ExecutionException e) {
     throw new CoreException(
         new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, e.getMessage(), e));
   }
 }
 @Override
 protected void done() {
   super.done();
   try {
     this.get();
     listener.done();
   } catch (InterruptedException e) {
     listener.setStatus("Interrupted Exception: " + e.getMessage());
     e.printStackTrace(new PrintStream(callbacks.getStderr()));
   } catch (ExecutionException e) {
     listener.setStatus("Execution Exception: " + e.getMessage());
     e.printStackTrace(new PrintStream(callbacks.getStderr()));
   } catch (Throwable e) {
     listener.setStatus(e.getMessage());
     e.printStackTrace(new PrintStream(callbacks.getStderr()));
   }
 }
示例#21
0
  /**
   * Initializes the async task manager then send a request with it.
   *
   * @param request The request to send.
   */
  public void sendRequest(RemoteCommand.Request request) {

    if (AsyncMessageMgr.availablePermits() > 0) {
      AsyncMessageMgr task = new AsyncMessageMgr(mDevice, null);
      task.execute(request);
      Logger.info(TAG, "#sendRequest - Command sent.");

      try {
        checkResponse(task.get());
      } catch (InterruptedException e) {
        Assert.fail("#sendRequest - InterruptedException : " + e.getMessage());
      } catch (ExecutionException e) {
        Assert.fail("#sendRequest - ExecutionException : " + e.getMessage());
      }

    } else {
      Assert.fail("#sendRequest - No more permit available!");
    }
  }
  public boolean sendToSumologic(String data) throws IOException {
    int retries = RETRIES;
    int sleep_time = SLEEP_TIME;
    int statusCode = -1;

    do {
      BoundRequestBuilder builder = null;
      builder = this.clientPreparePost(url);

      byte[] compressedData = SumologicKinesisUtils.compressGzip(data);

      builder.setHeader("Content-Encoding", "gzip");
      builder.setBody(compressedData);

      Response response = null;
      try {
        response = builder.execute().get();
        statusCode = response.getStatusCode();
      } catch (InterruptedException e) {
        LOG.error("Can't send POST to Sumologic " + e.getMessage());
      } catch (ExecutionException e) {
        LOG.error("Can't send POST to Sumologic " + e.getMessage());
      }

      if (statusCode == 429) {
        LOG.warn("Got TOO MANY REQUESTS from Sumologic");
        retries--;
        try {
          Thread.sleep(sleep_time);
        } catch (InterruptedException ignore) {
        }
      }
    } while (statusCode == 429 && retries > 0);

    // Check if the request was successful;
    if (statusCode != 200) {
      LOG.warn(String.format("Received HTTP error from Sumo Service: %d", statusCode));
      return false;
    } else {
      return true;
    }
  }
示例#23
0
  public static void main(String[] args) {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<List<String>> future = executor.submit(new ReadWebPageCallable());

    try {
      List<String> lines = future.get(5, TimeUnit.SECONDS);
      for (String line : lines) System.out.println(line);
    } catch (InterruptedException e) {
      System.err.println("Callable through exception: " + e.getMessage());
      e.printStackTrace();
    } catch (ExecutionException e) {
      System.err.println("Callable through exception: " + e.getMessage());
      e.printStackTrace();
    } catch (TimeoutException e) {
      System.err.println("URL not responding");
      e.printStackTrace();
    }

    executor.shutdown();
  }
示例#24
0
 @Override
 public void done() {
   try {
     Stx stx = get();
     if (stx == null) {
       return;
     }
     if (stx.getSampleCount() > 0) {
       if (autoMinMaxEnabled) {
         histogramComputing = true;
         xAxisRangeControl.adjustComponents(
             stx.getHistogramScaling().scale(stx.getMinimum()),
             stx.getHistogramScaling().scale(stx.getMaximum()),
             4);
         histogramComputing = false;
       }
       setStx(stx);
     } else {
       SnapDialogs.showError(
           "Either the selected ROI is empty or no pixels have been found within the minimum and maximum values specified.\n"
               + "No valid histogram could be computed.\n");
       handleStxChange();
     }
   } catch (ExecutionException e) {
     if (histogramPlotConfig.useRoiMask) {
       SnapDialogs.showError(
           "An internal error occurred.\n"
               + "No valid histogram could be computed.\n"
               + "Possible reason: The selected ROI is empty.");
     } else {
       SnapDialogs.showError(
           "An internal error occurred.\n"
               + "No valid histogram could be computed. Reason:\n"
               + e.getMessage());
     }
     handleStxChange();
   } catch (InterruptedException e) {
     SnapDialogs.showError("The histogram computation has been interrupted.");
     handleStxChange();
   }
 }
示例#25
0
 // A few retries and a failure
 public void testFailingRetryableCallable() throws Exception {
   TestRtryCallable<String> tc = new TestRtryCallable<String>("X", 4, 3);
   assertEquals(0, tc.runs);
   assertEquals(0, tc.retries);
   Future<String> f = schedPooled.submit(tc);
   try {
     String s = f.get();
     fail("Expected failure, got " + s);
   } catch (ExecutionException e) {
     assertEquals("Too many failures", e.getMessage());
     assertEquals(4, ((CompositeExecutorException) e).getExceptions().size());
     StringWriter sw = new StringWriter();
     PrintWriter pw = new PrintWriter(sw);
     e.printStackTrace(pw);
     assertTrue("Hey, no also caused by", sw.toString().indexOf("Also caused by") > 0);
     assertSame(e, tc.result);
   }
   assertTrue(tc.gaveUp);
   assertEquals(4, tc.runs);
   assertEquals(3, tc.retries);
 }
 @Override
 public void onPreReceive(final ReceivePack rp, final Collection<ReceiveCommand> commands) {
   try {
     progress.waitFor(
         executor.submit(scopePropagator.wrap(new Worker(commands))),
         timeoutMillis,
         TimeUnit.MILLISECONDS);
   } catch (ExecutionException e) {
     log.warn("Error in ReceiveCommits", e);
     rc.addError("internal error while processing changes " + e.getMessage());
     // ReceiveCommits has tried its best to catch errors, so anything at this
     // point is very bad.
     for (final ReceiveCommand c : commands) {
       if (c.getResult() == Result.NOT_ATTEMPTED) {
         c.setResult(Result.REJECTED_OTHER_REASON, "internal error");
       }
     }
   } finally {
     rc.sendMessages();
   }
 }
示例#27
0
  @Override
  public boolean isAuthorized(
      @WebParam(name = "authenticationData", targetNamespace = "")
          List<SecretAuthenticationKey> authenticationData,
      @WebParam(name = "action", targetNamespace = "") Action action)
      throws SNAAExceptionException {

    if (authenticationData == null || action == null) {
      throw createSNAAException("Arguments must not be null!");
    }

    Map<String, Set<SecretAuthenticationKey>> intersectionPrefixSet =
        getIntersectionPrefixSetSAK(authenticationData);

    Set<Future<Boolean>> futures = new HashSet<Future<Boolean>>();

    for (String urnPrefix : intersectionPrefixSet.keySet()) {
      IsAuthorizedCallable authenticationCallable =
          new IsAuthorizedCallable(
              getWsnUrlFromUrnPrefix(urnPrefix),
              new ArrayList<SecretAuthenticationKey>(intersectionPrefixSet.get(urnPrefix)),
              action);
      Future<Boolean> future = executorService.submit(authenticationCallable);
      futures.add(future);
    }

    for (Future<Boolean> future : futures) {
      try {
        if (!future.get()) {
          return false;
        }
      } catch (InterruptedException e) {
        throw createSNAAException(e.getMessage());
      } catch (ExecutionException e) {
        throw createSNAAException(e.getMessage());
      }
    }

    return true;
  }
  /**
   * Waits until all generation threads have finish.
   *
   * @param tasks the tasks.
   * @param log the {@link Log} instance.
   */
  protected void waitUntilGenerationThreadsFinish(
      @NotNull final List<Future<? extends QueryJTemplate<QueryJTemplateContext>>> tasks,
      @Nullable final Log log) {
    for (@Nullable final Future<? extends QueryJTemplate<QueryJTemplateContext>> t_Task : tasks) {
      if (t_Task != null) {
        while (!t_Task.isDone()) {
          try {
            if (log != null) {
              log.debug(
                  "Waiting for "
                      + t_Task.get().getTemplateContext().getTemplateName()
                      + " to finish");
            }
          } catch (@NotNull final InterruptedException interrupted) {
            log.info(INTERRUPTED_WHILE_WAITING_FOR_THE_THREADS_TO_FINISH, interrupted);
          } catch (@NotNull final ExecutionException interrupted) {
            log.info(interrupted.getMessage());

            Throwable cause = interrupted.getCause();

            while (cause != null) {
              log.error(cause.getMessage(), cause);
              cause = cause.getCause();
            }
          }

          synchronized (LOCK) {
            try {
              LOCK.wait(1000);
            } catch (@NotNull final InterruptedException interrupted) {
              if (log != null) {
                log.info(INTERRUPTED_WHILE_WAITING_FOR_THE_THREADS_TO_FINISH, interrupted);
              }
            }
          }
        }
      }
    }
  }
示例#29
0
 public boolean removeDirectoryAtPath_error(
     final String path, long /*ObjCObjectByReference*/ error) {
   log.debug("removeDirectoryAtPath_error:" + path);
   final Future<Boolean> future =
       background(
           new FilesystemBackgroundAction<Boolean>(session) {
             @Override
             public Boolean call() {
               final Path file = PathFactory.createPath(session, path, Path.DIRECTORY_TYPE);
               file.delete();
               return true;
             }
           });
   try {
     return future.get();
   } catch (InterruptedException e) {
     log.error("Error executing action for mounted disk:" + e.getMessage());
   } catch (ExecutionException e) {
     log.error("Error executing action for mounted disk:" + e.getMessage());
   }
   return false;
 }
示例#30
0
  /**
   * returns recent version of given dependency (from internal versions cache)
   *
   * @param partialPath the path of dependency
   * @return recent version
   */
  public static String recentVersion(final String partialPath) {
    if (!VERSIONS_CACHE.containsKey(partialPath)) {
      final FutureTask<String> futureTask = RecentVersionCallable.createFutureTask(partialPath);
      final FutureTask<String> prevFutureTask = VERSIONS_CACHE.putIfAbsent(partialPath, futureTask);

      if (prevFutureTask == null) {
        futureTask.run();
      }
    }

    try {
      return VERSIONS_CACHE.get(partialPath).get(5000, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      LOG.error("can't collect recent version of {}; {}", partialPath, e.getMessage());
    } catch (ExecutionException e) {
      LOG.error("can't collect recent version of {}; {}", partialPath, e.getMessage());
    } catch (TimeoutException e) {
      LOG.error("can't collect recent version of {}; {}", partialPath, e.getMessage());
    }

    throw new IllegalArgumentException("there is no webjars dependency for: " + partialPath);
  }