예제 #1
0
  public Integer call() {
    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;
  }
예제 #2
0
 protected void handleMapGetAsync(String[] args) {
   try {
     println(getMap().getAsync(args[1]).get());
   } catch (InterruptedException e) {
     e.printStackTrace();
   } catch (ExecutionException e) {
     e.printStackTrace();
   }
 }
예제 #3
0
    /**
     * Waits for completed requests. Once the first request has been taken, the method will wait
     * WAIT_TIMEOUT ms longer to collect more completed requests.
     *
     * @return Collected feeds or null if the method has been interrupted during the first waiting
     *     period.
     */
    private List<Feed> collectCompletedRequests() {
      List<Feed> results = new LinkedList<Feed>();
      DownloadRequester requester = DownloadRequester.getInstance();
      int tasks = 0;

      try {
        DownloadRequest request = completedRequests.take();
        parserService.submit(new FeedParserTask(request));
        tasks++;
      } catch (InterruptedException e) {
        return null;
      }

      tasks += pollCompletedDownloads();

      isCollectingRequests = true;

      if (requester.isDownloadingFeeds()) {
        // wait for completion of more downloads
        long startTime = System.currentTimeMillis();
        long currentTime = startTime;
        while (requester.isDownloadingFeeds() && (currentTime - startTime) < WAIT_TIMEOUT) {
          try {
            if (BuildConfig.DEBUG)
              Log.d(TAG, "Waiting for " + (startTime + WAIT_TIMEOUT - currentTime) + " ms");
            sleep(startTime + WAIT_TIMEOUT - currentTime);
          } catch (InterruptedException e) {
            if (BuildConfig.DEBUG) Log.d(TAG, "interrupted while waiting for more downloads");
            tasks += pollCompletedDownloads();
          } finally {
            currentTime = System.currentTimeMillis();
          }
        }

        tasks += pollCompletedDownloads();
      }

      isCollectingRequests = false;

      for (int i = 0; i < tasks; i++) {
        try {
          Feed f = parserService.take().get();
          if (f != null) {
            results.add(f);
          }
        } catch (InterruptedException e) {
          e.printStackTrace();

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

      return results;
    }
예제 #4
0
        @Override
        public void run() {
          if (BuildConfig.DEBUG) Log.d(TAG, "downloadCompletionThread was started");
          while (!isInterrupted()) {
            try {
              Downloader downloader = downloadExecutor.take().get();
              if (BuildConfig.DEBUG) Log.d(TAG, "Received 'Download Complete' - message.");
              removeDownload(downloader);
              DownloadStatus status = downloader.getResult();
              boolean successful = status.isSuccessful();

              final int type = status.getFeedfileType();
              if (successful) {
                if (type == Feed.FEEDFILETYPE_FEED) {
                  handleCompletedFeedDownload(downloader.getDownloadRequest());
                } else if (type == FeedImage.FEEDFILETYPE_FEEDIMAGE) {
                  handleCompletedImageDownload(status, downloader.getDownloadRequest());
                } else if (type == FeedMedia.FEEDFILETYPE_FEEDMEDIA) {
                  handleCompletedFeedMediaDownload(status, downloader.getDownloadRequest());
                }
              } else {
                numberOfDownloads.decrementAndGet();
                if (!status.isCancelled()) {
                  if (status.getReason() == DownloadError.ERROR_UNAUTHORIZED) {
                    postAuthenticationNotification(downloader.getDownloadRequest());
                  } else if (status.getReason() == DownloadError.ERROR_HTTP_DATA_ERROR
                      && Integer.valueOf(status.getReasonDetailed())
                          == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) {

                    Log.d(TAG, "Requested invalid range, restarting download from the beginning");
                    FileUtils.deleteQuietly(
                        new File(downloader.getDownloadRequest().getDestination()));
                    DownloadRequester.getInstance()
                        .download(DownloadService.this, downloader.getDownloadRequest());
                  } else {
                    Log.e(TAG, "Download failed");
                    saveDownloadStatus(status);
                    handleFailedDownload(status, downloader.getDownloadRequest());
                  }
                }
                sendDownloadHandledIntent();
                queryDownloadsAsync();
              }
            } catch (InterruptedException e) {
              if (BuildConfig.DEBUG) Log.d(TAG, "DownloadCompletionThread was interrupted");
            } catch (ExecutionException e) {
              e.printStackTrace();
              numberOfDownloads.decrementAndGet();
            }
          }
          if (BuildConfig.DEBUG) Log.d(TAG, "End of downloadCompletionThread");
        }
예제 #5
0
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter base directory (e.g. /usr/local/jdk5.0/src): ");
    String directory = in.nextLine();
    System.out.print("Enter keyword (e.g. volatile): ");
    String keyword = in.nextLine();

    MatchCounter counter = new MatchCounter(new File(directory), keyword);
    FutureTask<Integer> task = new FutureTask<Integer>(counter);
    Thread t = new Thread(task);
    t.start();
    try {
      System.out.println(task.get() + " matching files.");
    } catch (ExecutionException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
    }
  }
예제 #6
0
 @Override
 public void run() {
   if (request.isDeleteOnFailure()) {
     if (BuildConfig.DEBUG) Log.d(TAG, "Ignoring failed download, deleteOnFailure=true");
   } else {
     File dest = new File(request.getDestination());
     if (dest.exists() && request.getFeedfileType() == FeedMedia.FEEDFILETYPE_FEEDMEDIA) {
       Log.d(TAG, "File has been partially downloaded. Writing file url");
       FeedMedia media = DBReader.getFeedMedia(DownloadService.this, request.getFeedfileId());
       media.setFile_url(request.getDestination());
       try {
         DBWriter.setFeedMedia(DownloadService.this, media).get();
       } catch (InterruptedException e) {
         e.printStackTrace();
       } catch (ExecutionException e) {
         e.printStackTrace();
       }
     }
   }
 }
예제 #7
0
  private SpecificationTestCasesListener<T> run(
      final URL[] classpath, final Collection<TestCase> failures, ClassLoader unitTestClassLoader) {
    final SpecificationTestCasesListener<T> listener =
        new SpecificationTestCasesListener<>(runtimeValues);

    // create the classpath for JPF
    String stringClassPath = createClassPath(classpath);

    String mainClass = "nopol.repair.NopolTestRunner";
    // TestExecutorProcessor.createMainTestClass(spoon, mainClass);

    List<TestCase> passedTest = new ArrayList<>(failures.size());
    Iterator<TestCase> iterator = failures.iterator();
    while (iterator.hasNext()) {
      TestCase testCase = iterator.next();
      logger.debug("SYMBOLIC EXECUTION on " + sourceLocation + " Test " + testCase);
      String[] args = new String[1];
      args[0] = testCase.className() + "." + testCase.testName();

      Config conf =
          JPFUtil.createConfig(
              args, mainClass, stringClassPath, outputSourceFile.getAbsolutePath());
      final JPF jpf = new JPF(conf);

      // executes JPF
      JPFListener jpfListener = new JPFListener();
      jpf.addSearchListener(jpfListener);

      ExecutorService executor = Executors.newFixedThreadPool(1);

      Future<?> future =
          executor.submit(
              new Runnable() {
                @Override
                public void run() {
                  jpf.run();
                }
              });

      executor.shutdown();
      try {
        future.get(60, TimeUnit.SECONDS);
      } catch (InterruptedException e) {
        continue;
      } catch (ExecutionException e) {
        e.printStackTrace();
        continue;
      } catch (TimeoutException e) {
        future.cancel(true);
        continue;
      }

      // get the JPF result
      Object result = jpfListener.getResult();
      if (result == null) {
        continue;
      }
      logger.debug(
          "SYMBOLIC VALUE on " + sourceLocation + " for Test " + testCase + " Value: " + result);
      // collect runtime
      boolean passed =
          executeTestAndCollectRuntimeValues(result, testCase, unitTestClassLoader, listener);
      if (passed) {
        this.find = true;
        TestSuiteExecution.runTestCases(failures, unitTestClassLoader, listener);
        if (!passedTest.contains(testCase)) {
          passedTest.add(testCase);
        }
        if (passedTest.size() == failures.size()) {
          break;
        }
      }
    }

    return listener;
  }
예제 #8
0
    @Override
    public void run() {
      while (isActive) {
        final List<Feed> feeds = collectCompletedRequests();

        if (feeds == null) {
          continue;
        }

        if (BuildConfig.DEBUG) Log.d(TAG, "Bundling " + feeds.size() + " feeds");

        for (Feed feed : feeds) {
          removeDuplicateImages(
              feed); // duplicate images have to removed because the DownloadRequester does not
                     // accept two downloads with the same download URL yet.
        }

        // Save information of feed in DB
        if (dbUpdateFuture != null) {
          try {
            dbUpdateFuture.get();
          } catch (InterruptedException e) {
            e.printStackTrace();
          } catch (ExecutionException e) {
            e.printStackTrace();
          }
        }

        dbUpdateFuture =
            dbService.submit(
                new Runnable() {
                  @Override
                  public void run() {
                    Feed[] savedFeeds =
                        DBTasks.updateFeed(
                            DownloadService.this, feeds.toArray(new Feed[feeds.size()]));

                    for (Feed savedFeed : savedFeeds) {
                      // Download Feed Image if provided and not downloaded
                      if (savedFeed.getImage() != null
                          && savedFeed.getImage().isDownloaded() == false) {
                        if (BuildConfig.DEBUG) Log.d(TAG, "Feed has image; Downloading....");
                        savedFeed.getImage().setOwner(savedFeed);
                        final Feed savedFeedRef = savedFeed;
                        try {
                          requester.downloadImage(DownloadService.this, savedFeedRef.getImage());
                        } catch (DownloadRequestException e) {
                          e.printStackTrace();
                          DBWriter.addDownloadStatus(
                              DownloadService.this,
                              new DownloadStatus(
                                  savedFeedRef.getImage(),
                                  savedFeedRef.getImage().getHumanReadableIdentifier(),
                                  DownloadError.ERROR_REQUEST_ERROR,
                                  false,
                                  e.getMessage()));
                        }
                      }
                      numberOfDownloads.decrementAndGet();
                    }

                    sendDownloadHandledIntent();

                    queryDownloadsAsync();
                  }
                });
      }

      if (dbUpdateFuture != null) {
        try {
          dbUpdateFuture.get();
        } catch (InterruptedException e) {
        } catch (ExecutionException e) {
          e.printStackTrace();
        }
      }

      if (BuildConfig.DEBUG) Log.d(TAG, "Shutting down");
    }
예제 #9
0
    @Override
    public void run() {
      FeedMedia media = DBReader.getFeedMedia(DownloadService.this, request.getFeedfileId());
      if (media == null) {
        throw new IllegalStateException("Could not find downloaded media object in database");
      }
      boolean chaptersRead = false;
      media.setDownloaded(true);
      media.setFile_url(request.getDestination());

      // Get duration
      MediaMetadataRetriever mmr = null;
      try {
        mmr = new MediaMetadataRetriever();
        mmr.setDataSource(media.getFile_url());
        String durationStr = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        media.setDuration(Integer.parseInt(durationStr));
        if (BuildConfig.DEBUG) Log.d(TAG, "Duration of file is " + media.getDuration());
      } catch (NumberFormatException e) {
        e.printStackTrace();
      } catch (RuntimeException e) {
        e.printStackTrace();
      } finally {
        if (mmr != null) {
          mmr.release();
        }
      }

      if (media.getItem().getChapters() == null) {
        ChapterUtils.loadChaptersFromFileUrl(media);
        if (media.getItem().getChapters() != null) {
          chaptersRead = true;
        }
      }

      try {
        if (chaptersRead) {
          DBWriter.setFeedItem(DownloadService.this, media.getItem()).get();
        }
        DBWriter.setFeedMedia(DownloadService.this, media).get();
        if (!DBTasks.isInQueue(DownloadService.this, media.getItem().getId())) {
          DBWriter.addQueueItem(DownloadService.this, media.getItem().getId()).get();
        }
      } catch (ExecutionException e) {
        e.printStackTrace();
        status =
            new DownloadStatus(
                media,
                media.getEpisodeTitle(),
                DownloadError.ERROR_DB_ACCESS_ERROR,
                false,
                e.getMessage());
      } catch (InterruptedException e) {
        e.printStackTrace();
        status =
            new DownloadStatus(
                media,
                media.getEpisodeTitle(),
                DownloadError.ERROR_DB_ACCESS_ERROR,
                false,
                e.getMessage());
      }

      saveDownloadStatus(status);
      sendDownloadHandledIntent();

      numberOfDownloads.decrementAndGet();
      queryDownloadsAsync();
    }