Example #1
0
  /**
   * Somewhat multi-threaded depth-first search. Performs a DFS of the subtrees from the current
   * node in parallel.
   *
   * @param s The tile sequence
   * @param b The board to search
   * @param pool The thread pool in which to submit jobs to.
   * @return The board with the highest evaluation or null if no board can continue.
   */
  private Board solve_pdfs(Board b, ExecutorService pool) {
    List<Future<Board>> rets = new ArrayList<>(BOARD_WIDTH);
    Board best = null;
    int best_score = -1;

    for (Direction d : directions) {
      Board n = new Board(b);
      if (n.move(tileSequence, d)) {
        rets.add(pool.submit(new ParallelDFS(n)));
      }
    }

    for (Future<Board> ret : rets) {
      try {
        Board c = ret.get();
        if (c != null) {
          int score = evaluate(c);
          if (score > best_score) {
            best = c;
            best_score = score;
          }
        }
      } catch (InterruptedException | ExecutionException e) {
        System.err.println("Error: " + e.getMessage());
      }
    }

    return best;
  }
Example #2
0
 private NormalizedNode<?, ?> readDataViaTransaction(
     final DOMDataReadTransaction transaction,
     final LogicalDatastoreType datastore,
     final YangInstanceIdentifier path) {
   LOG.trace("Read {} via Restconf: {}", datastore.name(), path);
   final ListenableFuture<Optional<NormalizedNode<?, ?>>> listenableFuture =
       transaction.read(datastore, path);
   if (listenableFuture != null) {
     Optional<NormalizedNode<?, ?>> optional;
     try {
       LOG.debug("Reading result data from transaction.");
       optional = listenableFuture.get();
     } catch (InterruptedException | ExecutionException e) {
       LOG.warn("Exception by reading {} via Restconf: {}", datastore.name(), path, e);
       throw new RestconfDocumentedException(
           "Problem to get data from transaction.", e.getCause());
     }
     if (optional != null) {
       if (optional.isPresent()) {
         return optional.get();
       }
     }
   }
   return null;
 }
Example #3
0
  @Override
  public <T extends StoredObject> List<T> getStoredObjects(final Class<T> tClass) {
    List<T> list = Collections.emptyList();

    emLock.lock();

    try {
      final Future<List<T>> future =
          executorService.submit(
              () -> {
                final CriteriaBuilder cb = em.getCriteriaBuilder();
                final CriteriaQuery<T> cq = cb.createQuery(tClass);
                final Root<T> root = cq.from(tClass);
                cq.select(root);

                final TypedQuery<T> q = em.createQuery(cq);

                return new ArrayList<>(q.getResultList());
              });

      list = future.get();
    } catch (InterruptedException | ExecutionException e) {
      logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
    } finally {
      emLock.unlock();
    }

    return stripMarkedForRemoval(list);
  }
Example #4
0
  /*
   * @see jgnash.engine.ReminderDAOInterface#getReminderList()
   */
  @Override
  @SuppressWarnings("unchecked")
  public List<Reminder> getReminderList() {

    List<Reminder> reminderList = Collections.emptyList();

    emLock.lock();

    try {
      Future<List<Reminder>> future =
          executorService.submit(
              () -> {
                CriteriaBuilder cb = em.getCriteriaBuilder();
                CriteriaQuery<Reminder> cq = cb.createQuery(Reminder.class);
                Root<Reminder> root = cq.from(Reminder.class);
                cq.select(root);

                TypedQuery<Reminder> q = em.createQuery(cq);

                return stripMarkedForRemoval(new ArrayList<>(q.getResultList()));
              });

      reminderList = future.get();
    } catch (final InterruptedException | ExecutionException e) {
      logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
    } finally {
      emLock.unlock();
    }

    return reminderList;
  }
Example #5
0
 private CudaEngine(final int deviceId) {
   exe = Executors.newSingleThreadExecutor(); // mandatory: Only one cuda thread per context
   Id = deviceId;
   try {
     exe.submit(
             new Runnable() {
               @Override
               public void run() {
                 CUdevice device = new CUdevice();
                 JCudaDriver.cuDeviceGet(device, deviceId);
                 int array[] = {0};
                 JCudaDriver.cuDeviceGetAttribute(
                     array, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, device);
                 maxThreads = (int) Math.sqrt(array[0]);
                 context = new CUcontext();
                 //					JCudaDriver.cuCtxCreate(context, CUctx_flags.CU_CTX_SCHED_BLOCKING_SYNC,
                 // device);
                 JCudaDriver.cuCtxCreate(context, 0, device);
                 CUmodule m = new CUmodule();
                 initModules(m);
                 for (Kernel k : Kernel.values()) {
                   initFunction(m, k);
                 }
                 //					JCudaDriver.cuCtxSetCacheConfig(CUfunc_cache.CU_FUNC_CACHE_PREFER_NONE);>
                 //
                 //	JCudaDriver.cuCtxSetSharedMemConfig(CUsharedconfig.CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE);
               }
             })
         .get();
   } catch (InterruptedException | ExecutionException e) {
     throw new RuntimeException(e.getMessage());
   }
   neigborsPtrs = new HashMap<>();
 }
 @Override
 protected void onHandleIntent(Intent intent) {
   String url = null;
   String userName = intent.getStringExtra(PROVIDED_USER_NAME);
   String instrumentName = intent.getStringExtra(PROVIDED_INSTRUMENT);
   try {
     url = URLDecoder.decode(getString(R.string.poll_post_url, instrumentName, userName), "UTF-8");
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
   if (url == null) return;
   RequestFuture<String> future = RequestFuture.newFuture();
   StringRequest request = new StringRequest(Request.Method.POST, url, future, future);
   Volley.newRequestQueue(getApplicationContext()).add(request);
   try {
     String response = future.get(30, TimeUnit.SECONDS);
     PostPollDto dto = new Gson().fromJson(response, PostPollDto.class);
     if (dto.getStatus().toLowerCase().equalsIgnoreCase("ok")) {
       PreferencesUtil.savePollInstrument(getApplicationContext(), instrumentName);
       PreferencesUtil.saveUserName(getApplicationContext(), userName);
       EventBus.getDefault().post(new PollPostEvent());
     } else {
       EventBus.getDefault().post(new PollPostEvent(dto.getMsg()));
     }
   } catch (InterruptedException | ExecutionException | TimeoutException e) {
     EventBus.getDefault().post(new PollPostEvent(e.getLocalizedMessage()));
   }
 }
 public void submit() {
   dbTextArea.clear();
   LocalDate from = fromDate.getValue(), to = toDate.getValue();
   Future<String[]> fwarNames = db.getWarNamesByDate(from, to);
   HashSet<Future<long[]>> fstats = new HashSet<Future<long[]>>();
   try {
     String[] warNames = fwarNames.get();
     for (String war : warNames) {
       fstats.add(db.getWarStats(war));
     }
     int i = 0;
     for (Future<long[]> fWarStats : fstats) {
       long[] stats = fWarStats.get();
       dbTextArea.appendText("\t" + warNames[i++] + " Statistics\n");
       dbTextArea.appendText("=========================================\n");
       dbTextArea.appendText('\t' + stats[0] == 0 ? "War is still running" : "\tWar has ended\n");
       dbTextArea.appendText("\tNum of launch missiles: " + stats[1] + "\n");
       dbTextArea.appendText("\tNum of intercept missiles: " + stats[2] + "\n");
       dbTextArea.appendText("\tNum of hit target missiles: " + stats[3] + "\n");
       dbTextArea.appendText("\tNum of launchers destroyed: " + stats[4] + "\n");
       dbTextArea.appendText("\ttotal damage: " + stats[5] + "\n");
       dbTextArea.appendText("==========================================\n");
     }
   } catch (InterruptedException | ExecutionException e) {
     e.printStackTrace();
   }
 }
Example #8
0
  /*
   * @see jgnash.engine.TransactionDAO#addTransaction(jgnash.engine.Transaction)
   */
  @Override
  public synchronized boolean addTransaction(final Transaction transaction) {
    boolean result = false;

    emLock.lock();

    try {
      Future<Boolean> future =
          executorService.submit(
              () -> {
                em.getTransaction().begin();
                em.persist(transaction);

                transaction.getAccounts().forEach(em::persist);
                em.getTransaction().commit();

                return true;
              });

      result = future.get();
    } catch (final InterruptedException | ExecutionException e) {
      logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
    } finally {
      emLock.unlock();
    }

    return result;
  }
  public static void main(String[] args) {
    Macros.SHIFT_DURATION = 24 * 60;
    Schedule schedule = new Schedule();
    schedule.addJob(new Job("J1", 10 * 24, 200, Job.JOB_NORMAL));
    schedule.addJob(new Job("J2", 10 * 24, 200, Job.JOB_NORMAL));
    schedule.addJob(new Job("J3", 10 * 24, 200, Job.JOB_NORMAL));
    schedule.addJob(new Job("J4", 10 * 24, 200, Job.JOB_NORMAL));
    schedule.addJob(new Job("J5", 10 * 24, 200, Job.JOB_NORMAL));
    schedule.addJob(new Job("J6", 10 * 24, 200, Job.JOB_NORMAL));
    // machine = new Machine(0,1);
    pmoList = schedule.getPMOpportunities();
    ExecutorService threadPool = Executors.newSingleThreadExecutor();
    CompletionService<SimulationResult> pool =
        new ExecutorCompletionService<SimulationResult>(threadPool);
    pool.submit(
        new SimulationThread(
            schedule, getCombolist((long) (Math.pow(2, 31) - 1)), pmoList, false, machine));

    try {
      SimulationResult result = pool.take().get();
      System.out.println(result.cost);
    } catch (InterruptedException | ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #10
0
  @Override
  public List<TrashObject> getTrashObjects() {
    List<TrashObject> trashObjectList = Collections.emptyList();

    emLock.lock();

    try {
      final Future<List<TrashObject>> future =
          executorService.submit(
              () -> {
                final CriteriaBuilder cb = em.getCriteriaBuilder();
                final CriteriaQuery<TrashObject> cq = cb.createQuery(TrashObject.class);
                final Root<TrashObject> root = cq.from(TrashObject.class);
                cq.select(root);

                final TypedQuery<TrashObject> q = em.createQuery(cq);

                return new ArrayList<>(q.getResultList());
              });

      trashObjectList = future.get();
    } catch (final InterruptedException | ExecutionException e) {
      logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
    } finally {
      emLock.unlock();
    }

    return trashObjectList;
  }
Example #11
0
  /** @see jgnash.engine.dao.TransactionDAO#getTransactions() */
  @Override
  @SuppressWarnings("unchecked")
  public List<Transaction> getTransactions() {
    List<Transaction> transactionList = Collections.emptyList();

    emLock.lock();

    try {
      Future<List<Transaction>> future =
          executorService.submit(
              () -> {
                Query q =
                    em.createQuery("SELECT t FROM Transaction t WHERE t.markedForRemoval = false");

                return new ArrayList<>(q.getResultList());
              });

      transactionList = future.get();
    } catch (final InterruptedException | ExecutionException e) {
      logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
    } finally {
      emLock.unlock();
    }

    return transactionList;
  }
  public static <T> List<T> execiteMyTask(String sql) {
    ExecutorService threadPool = Executors.newFixedThreadPool(8);

    final List<T> batches = new ArrayList<T>();

    Callable<T> t =
        new Callable<T>() {

          public T call() {
            T result = callDatabase(sql);
            synchronized (batches) {
              batches.add(result);
            }
            return result;
          }

          private T callDatabase(String sql) {
            // TODO Auto-generated method stub
            return null;
          }
        };

    Future<T> f = threadPool.submit(t);
    try {
      T result = f.get();
    } catch (InterruptedException | ExecutionException e) {
      e.printStackTrace();
    }
    return batches;
  }
  public void createEntry(Map<String, String> data) {
    if (data == null || data.isEmpty()) {
      log.debug("empty input data");
      return;
    }
    List<EntryField> fields = new ArrayList<>();
    for (String key : data.keySet()) {
      EntryFieldBuilder fieldBuilder = new EntryFieldBuilder();
      fieldBuilder.setKey(key);
      fieldBuilder.setValue(data.get(key));
      fields.add(fieldBuilder.build());
    }

    SaveEntryInputBuilder inputbuilder = new SaveEntryInputBuilder();
    inputbuilder.setEntryId(String.valueOf(rand.nextInt(1000000000)));
    inputbuilder.setEntryField(fields);
    try {
      RpcResult<Void> result = service.saveEntry(inputbuilder.build()).get();
      if (result.isSuccessful()) {
        log.debug("Successfully Added entry");
      }
    } catch (InterruptedException | ExecutionException e) {
      e.printStackTrace();
    }
  }
Example #14
0
  @Override
  public void remove(final TrashObject trashObject) {
    emLock.lock();

    try {
      final Future<Void> future =
          executorService.submit(
              () -> {
                em.getTransaction().begin();

                final StoredObject object = trashObject.getObject();

                em.remove(object);
                em.remove(trashObject);

                logger.info("Removed TrashObject");

                em.getTransaction().commit();
                return null;
              });

      future.get(); // block
    } catch (final InterruptedException | ExecutionException e) {
      logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
    } finally {
      emLock.unlock();
    }
  }
Example #15
0
  @Override
  public ArrayList<String> autocomplete(String input) {
    ArrayList<String> resultList = null;

    String url = Urls.getAutocompleteUrl(input);
    RequestFuture<JSONObject> future = RequestFuture.newFuture();
    JsonObjectRequest request = new JsonObjectRequest(url, null, future, future);
    requestQueue.add(request);

    try {
      JSONObject response = future.get(10, TimeUnit.SECONDS);
      JSONArray predictions = response.getJSONArray("predictions");

      // Extract the Place descriptions from the results
      resultList = new ArrayList<String>(predictions.length());
      for (int i = 0; i < predictions.length(); i++) {
        JSONArray terms = predictions.getJSONObject(i).getJSONArray("terms");
        resultList.add(terms.getJSONObject(0).getString("value"));
      }

    } catch (InterruptedException | ExecutionException | TimeoutException | JSONException e) {
      e.printStackTrace();
    }
    return resultList;
  }
Example #16
0
    @Override
    protected void done() {
      hashDb.indexing = false;
      progress.finish();

      // see if we got any errors
      try {
        get();
      } catch (InterruptedException | ExecutionException ex) {
        logger.log(Level.SEVERE, "Error creating index", ex); // NON-NLS
        MessageNotifyUtil.Notify.show(
            NbBundle.getMessage(this.getClass(), "HashDbManager.errCreatingIndex.title"),
            NbBundle.getMessage(
                this.getClass(), "HashDbManager.errCreatingIndex.msg", ex.getMessage()),
            MessageNotifyUtil.MessageType.ERROR);
      } // catch and ignore if we were cancelled
      catch (java.util.concurrent.CancellationException ex) {
      }

      try {
        hashDb.propertyChangeSupport.firePropertyChange(
            HashDb.Event.INDEXING_DONE.toString(), null, hashDb);
        hashDb.propertyChangeSupport.firePropertyChange(
            HashDbManager.SetEvt.DB_INDEXED.toString(), null, hashDb.getHashSetName());
      } catch (Exception e) {
        logger.log(Level.SEVERE, "HashDbManager listener threw exception", e); // NON-NLS
        MessageNotifyUtil.Notify.show(
            NbBundle.getMessage(this.getClass(), "HashDbManager.moduleErr"),
            NbBundle.getMessage(this.getClass(), "HashDbManager.moduleErrorListeningToUpdatesMsg"),
            MessageNotifyUtil.MessageType.ERROR);
      }
    }
Example #17
0
  public static void main(String[] args) {
    ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS);
    List<Future<Long>> summationTasks = new ArrayList<>();
    long nByTen = N / 10;
    for (int i = 0; i < NUM_THREADS; i++) {
      long fromInnerRange = (nByTen * i) + 1;
      long toInnerRange = nByTen * (i + 1);
      System.out.printf(
          "Spawning threads for summing in range %d to %d %n", fromInnerRange, toInnerRange);
      Callable<Long> summationTask = new SumClass(fromInnerRange, toInnerRange);
      Future<Long> futureSum = executorService.submit(summationTask);
      summationTasks.add(futureSum);
    }
    for (Future<Long> partialSum : summationTasks) {
      try {
        calculatedSum += partialSum.get();
      } catch (InterruptedException | ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    long formulaSum = (N * (N + 1)) / 2;
    System.out.printf("Sum by threads = %d, sum using the formula = %d", calculatedSum, formulaSum);
  }
Example #18
0
  @Override
  public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
    if (!args.hasAny("old")) {
      src.sendMessage(invalidArg());
      return CommandResult.empty();
    }

    String oldWorldName = args.<String>getOne("old").get();

    if (oldWorldName.equalsIgnoreCase("@w")) {
      if (src instanceof Player) {
        oldWorldName = ((Player) src).getWorld().getName();
      }
    }

    if (!args.hasAny("new")) {
      src.sendMessage(invalidArg());
      return CommandResult.empty();
    }

    String newWorldName = args.<String>getOne("new").get();

    for (WorldProperties world : Main.getGame().getServer().getAllWorldProperties()) {
      if (!world.getWorldName().equalsIgnoreCase(newWorldName)) {
        continue;
      }

      src.sendMessage(Text.of(TextColors.DARK_RED, newWorldName, " already exists"));
      return CommandResult.empty();
    }

    if (!Main.getGame().getServer().getWorld(oldWorldName).isPresent()) {
      src.sendMessage(Text.of(TextColors.DARK_RED, "World ", oldWorldName, " does not exists"));
      return CommandResult.empty();
    }

    Optional<WorldProperties> copy = null;
    try {
      copy =
          Main.getGame()
              .getServer()
              .copyWorld(
                  Main.getGame().getServer().getWorld(oldWorldName).get().getProperties(),
                  newWorldName)
              .get();
    } catch (InterruptedException | ExecutionException e) {
      e.printStackTrace();
    }

    if (!copy.isPresent()) {
      src.sendMessage(Text.of(TextColors.DARK_RED, "Could not copy ", oldWorldName));
      return CommandResult.empty();
    }

    src.sendMessage(Text.of(TextColors.DARK_GREEN, oldWorldName, " copied to ", newWorldName));

    return CommandResult.success();
  }
  private JSONObject encrypt(JSONObject plain) {
    JSONObject result = null;
    try {
      result = Utils.encrypt(plain, preparePublicKey.get());
    } catch (InterruptedException | ExecutionException e) {
      e.printStackTrace();
    }

    return result;
  }
Example #20
0
  @Override
  protected void done() {
    super.done();

    try {
      instance.put(imagePath, get());
    } catch (InterruptedException | ExecutionException e) {
      e.printStackTrace();
    }
  }
  @RequestMapping("/hello/contacts")
  @ResponseStatus(HttpStatus.OK)
  public DeferredResult<ResponseEntity<List<Contact>>> contacts(
      @RequestParam(value = "nameFilter") String regexp, HttpServletRequest request) {
    identifier =
        "ip:"
            + getClientIpAddress(request)
            + ", sessionId:"
            + RequestContextHolder.currentRequestAttributes().getSessionId();

    logger.info("Client [" + identifier + "] was connected.");

    if (regexp == null || regexp.isEmpty()) {
      logger.error("The 'nameFilter' parameter must not be null or empty");

      throw new IllegalArgumentException("The 'nameFilter' parameter must not be null or empty");
    }

    DeferredResult<ResponseEntity<List<Contact>>> deferredResult = new DeferredResult<>();

    ResponseEntity<List<Contact>> response = null;

    Future<List<Contact>> asyncResponse = contactService.getContacts(regexp);

    try {
      response = new ResponseEntity<>(asyncResponse.get(timeout, TimeUnit.SECONDS), HttpStatus.OK);

      deferredResult.setResult(response);

      logger.info("Request was executed successfully for client [" + identifier + "]");
    } catch (TimeoutException e) {
      logger.error("Request has timed out for [" + identifier + "]", e);

      deferredResult.setErrorResult(
          new ResponseEntity<>("Sorry.Request has timed out.", HttpStatus.REQUEST_TIMEOUT));
    } catch (InterruptedException | ExecutionException e) {
      if (e.getCause() instanceof PersistenceException) {
        logger.error("Database is not available.", e);

        deferredResult.setErrorResult(
            new ResponseEntity<String>(
                "Sorry.Database is not available.", HttpStatus.SERVICE_UNAVAILABLE));

      } else {
        logger.error("Contacts processing was interrrupted or aborted for [" + identifier + "]", e);

        deferredResult.setErrorResult(
            new ResponseEntity<>(
                "Sorry.Contacts processing was interrrupted or aborted.",
                HttpStatus.SERVICE_UNAVAILABLE));
      }
    }
    return deferredResult;
  }
 @Override
 protected void onPostExecute(Integer result) {
   if (dialog.isShowing()) dialog.dismiss();
   if (listener != null) {
     try {
       listener.processFinish(result);
     } catch (InterruptedException | ExecutionException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
   }
 }
 @Override
 public void logOut(String token) throws SynchronizationException {
   try {
     ResponseSerializer response = new LogOutAsyncTask(token).execute().get();
     if (validateServerResponse(response)) {
       TOKEN = null;
       USER_ACCOUNT = null;
     }
   } catch (InterruptedException | ExecutionException e) {
     e.printStackTrace();
   }
 }
  @Test
  public void testUpdate() {

    UpdateRequest updateRequest =
        new UpdateRequest("asdf2014", "asdf", "1").script("ctx._source.sex=\"man\"");
    try {
      client.update(updateRequest).get();
    } catch (InterruptedException | ExecutionException e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }
  @Override
  public double[] getLogLikelihoods(List<Beacon> beacons, State[] locations) {
    List<Beacon> beaconsCleansed = Beacon.filterBeacons(beacons, minRssi, maxRssi);

    beaconsCleansed = beaconFilter.setBLEBeacon(bleBeacons).filter(beaconsCleansed, locations);
    BLEBeacon.setBLEBeaconIdsToMeasuredBeacons(bleBeacons, beaconsCleansed);
    int[] activeBeaconList = ModelAdaptUtils.beaconsToActiveBeaconArray(beaconsCleansed);

    final double[] ySub = ModelAdaptUtils.beaconsToVecSubset(beaconsCleansed);
    final double[][] X = ModelAdaptUtils.locationsToMat(locations);

    // Adjust bias by average bias
    final double[] rssiBiases = ModelAdaptUtils.biasesToVec(locations);

    double logLLs[] = null;
    try {
      Class<?> cls = gpLDPL.getClass();
      Constructor<?> cst = cls.getConstructor(gpLDPL.getClass());
      final GaussianProcessLDPLMean gpLDPLtmp = (GaussianProcessLDPLMean) cst.newInstance(gpLDPL);
      gpLDPLtmp.updateByActiveBeaconList(activeBeaconList);
      int n = X.length;
      final double logpro[] = new double[n];
      Future<?>[] futures = new Future<?>[n];
      for (int i = 0; i < n; i++) {
        final int idx = i;
        futures[idx] =
            ExecutorServiceHolder.getExecutorService()
                .submit(
                    new Runnable() {
                      public void run() {
                        // Subtract bias from an observation vector.
                        double[] ySubAdjusted = ArrayUtils.addScalar(ySub, -rssiBiases[idx]);
                        logpro[idx] = gpLDPLtmp.logProbaygivenx(X[idx], ySubAdjusted);
                      }
                    });
      }
      for (int i = 0; i < n; i++) {
        futures[i].get();
      }
      logLLs = logpro;
    } catch (InstantiationException
        | IllegalAccessException
        | IllegalArgumentException
        | InvocationTargetException
        | NoSuchMethodException
        | SecurityException e) {
      e.printStackTrace();
    } catch (InterruptedException | ExecutionException e) {
      e.printStackTrace();
    }
    return logLLs;
  }
 @Override
 protected void done() {
   FlightConditions fc;
   try {
     fc = get();
     NotificationCenter.getInstance()
         .notify(AirnoiseNotifications.FLIGHT_CONDITIONS_UPDATED, this, fc);
     this.progressBar.dispose();
   } catch (InterruptedException | ExecutionException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Example #27
0
 /*
  * Implements an abstract method from VizConnection.
  */
 @Override
 protected boolean disconnectFromWidget(IParaViewWebClient widget) {
   boolean closed = false;
   // Attempt to disconnect, returning the success of the operation.
   if (widget != null) {
     try {
       closed = widget.disconnect().get();
     } catch (InterruptedException | ExecutionException e) {
       e.printStackTrace();
     }
   }
   return closed;
 }
  static void runExample() {

    ExecutorService es = Executors.newFixedThreadPool(2);
    Future<Integer> f = es.submit(new Calculator());

    try {
      System.out.println("Result: " + f.get());
    } catch (InterruptedException | ExecutionException e) {
      e.printStackTrace();
    }

    es.shutdown();
  }
Example #29
0
 @Override
 public void done() {
   try {
     get();
   } catch (InterruptedException | ExecutionException ex) {
     System.err.println(ex.getCause());
     setProgressNote(String.format("%s\n", UiString.get(_S1)));
   } catch (CancellationException ex) {
     // cancelled by user.
   }
   setProgressNote("");
   setProgress(0);
 }
  public static void main(String[] args) throws IOException {

    String workDir = "E:/dev_workspace/tmp/workspace/duc2007";
    String idfFilename = "duc2007.idf";

    final double TOTAL_PAGE_COUNT = 30000000000.0D;

    Map<String, Double> idfValues = new HashMap<String, Double>();
    File idfFIle = FileUtils.getFile(workDir + "/" + DIR_IDF_FILE, idfFilename);
    log.info("Loading idf value file[" + idfFIle.getAbsolutePath() + "]");
    LineIterator lineIterator = null;
    try {
      lineIterator = FileUtils.lineIterator(idfFIle, DEFAULT_CHARSET.toString());
      while (lineIterator.hasNext()) {
        String line = lineIterator.nextLine();
        String[] strs = line.split("###");
        if (strs.length != 2) {
          log.warn("Line[" + line + "] format is illegal, ignore it!");
          continue;
        }
        idfValues.put(strs[0].trim(), Long.parseLong(strs[1]) / TOTAL_PAGE_COUNT);
      }
      log.info("Load idf value file[" + idfFIle.getAbsolutePath() + "] finished!");
    } catch (IOException e) {
      log.error("Load idf value file[" + idfFIle.getAbsolutePath() + "] error!", e);
      throw e;
    } finally {
      if (lineIterator != null) {
        lineIterator.close();
      }
    }

    String question =
        "Describe the legal battle between various recording artists and members of the record industry and the Internet music site Napster. What support, or lack thereof, have the litigants received?";

    EhCacheUtil ehCacheUtil = new EhCacheUtil("db_cache_vec", "lab");

    SummaryBuilderByVector summaryBuilder =
        new SummaryBuilderByVector(
            workDir, "0", "D0714D.txt", 10, idfValues, question, ehCacheUtil, 1.0f, 1.6f);
    ExecutorService es = Executors.newSingleThreadExecutor();
    Future<Boolean> future = es.submit(summaryBuilder);
    try {
      future.get();
    } catch (InterruptedException | ExecutionException e) {
      e.printStackTrace();
    }
    es.shutdown();
    EhCacheUtil.close();
  }