public static void randomToolActions(int numStrokes, boolean brushOnly) {
    Composition comp = ImageComponents.getActiveComp().get();
    Random random = new Random();

    if (comp != null) {
      int canvasWidth = comp.getCanvasWidth();
      int canvasHeight = comp.getCanvasHeight();

      ProgressMonitor progressMonitor = Utils.createPercentageProgressMonitor("1001 Tool Actions");

      // So far we are on the EDT
      Runnable notEDTThreadTask =
          () -> {
            assert !SwingUtilities.isEventDispatchThread();
            for (int i = 0; i < numStrokes; i++) {
              int progressPercentage = (int) ((float) i * 100 / numStrokes);
              progressMonitor.setProgress(progressPercentage);
              progressMonitor.setNote(progressPercentage + "%");

              Runnable edtRunnable =
                  () -> testToolAction(comp, random, canvasWidth, canvasHeight, brushOnly);

              try {
                SwingUtilities.invokeAndWait(edtRunnable);
              } catch (InterruptedException | InvocationTargetException e) {
                e.printStackTrace();
              }

              comp.repaint();
            }
            progressMonitor.close();
          };
      new Thread(notEDTThreadTask).start();
    }
  }
Exemple #2
0
  private void commandLoad(Options options) {
    LoadResult result;
    Project project = codeAssist.getProject(options);
    try {
      progressMonitor.attach(project);
      if (options.isFileStdin()) {
        result = codeAssist.load(project, new File("(stdin)"), options.getHereDocReader(inReader));
      } else {
        result = codeAssist.load(project, options.getFile(), options.getEncoding());
      }

      if (options.isPrintAST()) {
        Logger.debug("AST:\n%s", result.getAST());
      }

      if (options.isEmacsFormat()) {
        out.print("(");
        codeAssistError(result, options);
        out.println(")");
      } else {
        codeAssistError(result, options);
      }
    } catch (Exception e) {
      commandException(e, options);
    } finally {
      progressMonitor.detach(project);
    }
  }
 public static SubMonitor convert(
     ProgressMonitor paramProgressMonitor, String paramString, int paramInt) {
   if ((paramProgressMonitor instanceof SubMonitor)) {
     paramProgressMonitor.beginTask(paramString, paramInt, paramProgressMonitor.isCancelable());
     return (SubMonitor) paramProgressMonitor;
   }
   paramProgressMonitor.beginTask(paramString, 1000, paramProgressMonitor.isCancelable());
   return new SubMonitor(paramProgressMonitor, 1000, paramInt);
 }
Exemple #4
0
  private void commandTypeInference(Options options) {
    TypeInferenceResult result;
    Project project = codeAssist.getProject(options);
    try {
      progressMonitor.attach(project);
      if (options.isFileStdin()) {
        result =
            codeAssist.typeInference(
                project,
                new File("(stdin)"),
                options.getHereDocReader(inReader),
                options.getLocation());
      } else {
        result =
            codeAssist.typeInference(
                project, options.getFile(), options.getEncoding(), options.getLocation());
      }

      if (options.isPrintAST()) {
        Logger.debug("AST:\n%s", result.getAST());
      }

      if (options.isTest()) {
        Set<String> data = new HashSet<String>();
        for (IRubyObject klass : result.getTypeSet()) {
          data.add(klass.toString());
        }
        test(options, data);
      } else {
        if (options.isEmacsFormat()) {
          out.print("(");
          out.print("(type");
          for (IRubyObject klass : result.getTypeSet()) {
            out.print(" \"");
            out.print(klass);
            out.print("\"");
          }
          out.println(")");
          codeAssistError(result, options);
          out.println(")");
        } else {
          for (IRubyObject klass : result.getTypeSet()) {
            out.print("type: ");
            out.println(klass);
          }
          codeAssistError(result, options);
        }
      }
    } catch (Exception e) {
      if (options.isTest()) {
        testError(options);
      }
      commandException(e, options);
    } finally {
      progressMonitor.detach(project);
    }
  }
 /**
  * Overrides <code>FilterInputStream.read</code> to update the progress monitor after the read.
  */
 public int read(byte b[], int off, int len) throws IOException {
   int nr = in.read(b, off, len);
   if (nr > 0) monitor.setProgress(nread += nr);
   if (monitor.isCanceled()) {
     InterruptedIOException exc = new InterruptedIOException("progress");
     exc.bytesTransferred = nread;
     throw exc;
   }
   return nr;
 }
 /**
  * Overrides <code>FilterInputStream.read</code> to update the progress monitor after the read.
  */
 public int read() throws IOException {
   int c = in.read();
   if (c >= 0) monitor.setProgress(++nread);
   if (monitor.isCanceled()) {
     InterruptedIOException exc = new InterruptedIOException("progress");
     exc.bytesTransferred = nread;
     throw exc;
   }
   return c;
 }
  private ProgressMonitorInputStream getMonitorableStream(InputStream stream, String message) {

    final ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(this, message, stream);

    ProgressMonitor progress = pmis.getProgressMonitor();
    progress.setMillisToDecideToPopup(1);
    progress.setMillisToPopup(1);

    return pmis;
  }
 /** Construct progress source object. */
 public ProgressSource(URL url, String method, int expected) {
   this.url = url;
   this.method = method;
   this.contentType = "content/unknown";
   this.progress = 0;
   this.lastProgress = 0;
   this.expected = expected;
   this.state = State.NEW;
   this.progressMonitor = ProgressMonitor.getDefault();
   this.threshold = progressMonitor.getProgressUpdateThreshold();
 }
Exemple #9
0
  private void commandFindDefinition(Options options) {
    FindDefinitionResult result;
    Project project = codeAssist.getProject(options);
    try {
      progressMonitor.attach(project);
      if (options.isFileStdin()) {
        result =
            codeAssist.findDefinition(
                project,
                new File("(stdin)"),
                options.getHereDocReader(inReader),
                options.getLocation());
      } else {
        result =
            codeAssist.findDefinition(
                project, options.getFile(), options.getEncoding(), options.getLocation());
      }

      if (options.isPrintAST()) {
        Logger.debug("AST:\n%s", result.getAST());
      }

      if (options.isTest()) {
        Set<String> data = new HashSet<String>();
        for (SourceLocation location : result.getLocations()) {
          data.add(location.toString());
        }
        test(options, data);
      } else {
        if (options.isEmacsFormat()) {
          out.print("(");
          out.print("(location");
          for (SourceLocation location : result.getLocations()) {
            if (location.getFile() != null)
              out.printf(" (%s . %d)", emacsStringLiteral(location.getFile()), location.getLine());
          }
          out.println(")");
          codeAssistError(result, options);
          out.println(")");
        } else {
          for (SourceLocation location : result.getLocations()) {
            out.printf("location: %d %s\n", location.getLine(), location.getFile());
          }
          codeAssistError(result, options);
        }
      }
    } catch (Exception e) {
      if (options.isTest()) testError(options);
      commandException(e, options);
    } finally {
      progressMonitor.detach(project);
    }
  }
Exemple #10
0
  private void init(Options options) {
    codeAssist = new CodeAssist(options);

    Integer interval = options.getProgress();
    progressMonitor = new ProgressMonitor(out, interval != null ? interval * 1000 : -1);
    progressMonitor.setDaemon(true);
  }
  @Before
  public void setUp() throws DaoException {
    DaoCancerStudy.reCacheAll();
    DaoGeneOptimized.getInstance().reCache();
    ProgressMonitor.resetWarnings();

    studyId = DaoCancerStudy.getCancerStudyByStableId("study_tcga_pub").getInternalId();

    GeneticProfile newGeneticProfile = new GeneticProfile();
    newGeneticProfile.setCancerStudyId(studyId);
    newGeneticProfile.setGeneticAlterationType(GeneticAlterationType.COPY_NUMBER_ALTERATION);
    newGeneticProfile.setStableId("study_tcga_pub_test");
    newGeneticProfile.setProfileName("Barry CNA Results");
    newGeneticProfile.setDatatype("test");
    DaoGeneticProfile.addGeneticProfile(newGeneticProfile);

    geneticProfileId =
        DaoGeneticProfile.getGeneticProfileByStableId("study_tcga_pub_test").getGeneticProfileId();

    sample1 =
        DaoSample.getSampleByCancerStudyAndSampleId(studyId, "TCGA-A1-A0SB-01").getInternalId();
    sample2 =
        DaoSample.getSampleByCancerStudyAndSampleId(studyId, "TCGA-A1-A0SD-01").getInternalId();
    sample3 =
        DaoSample.getSampleByCancerStudyAndSampleId(studyId, "TCGA-A1-A0SE-01").getInternalId();
    sample4 =
        DaoSample.getSampleByCancerStudyAndSampleId(studyId, "TCGA-A1-A0SF-01").getInternalId();
    sample5 =
        DaoSample.getSampleByCancerStudyAndSampleId(studyId, "TCGA-A1-A0SG-01").getInternalId();
  }
Exemple #12
0
  /**
   * Read word list from file with name WORDLISTFILENAME, and pass a Set containing those words to
   * the computer player to intialize its lexicon.
   */
  private void initLexicon(InputStream stream) {

    ProgressMonitorInputStream pmis;
    ProgressMonitor progress = null;
    pmis = new ProgressMonitorInputStream(this, "reading words", stream);
    progress = pmis.getProgressMonitor();
    progress.setMillisToDecideToPopup(10);
    Scanner s = new Scanner(pmis);
    myLexicon.load(s);
    try {
      pmis.close();
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          null, "Error Closing Stream", "Error", JOptionPane.ERROR_MESSAGE);
    }
  }
  // command line utility
  public static void main(String[] args) throws IOException, DaoException {

    if (args.length != 2) {
      System.out.printf(
          "command line usage:  importGistic.pl <gistic-data-file.txt> <cancer-study-id>\n"
              + "\t <gistic-data-file.txt> Note that gistic-data-file.txt must be a massaged file, it does not come straight from the Broad\n"
              + "\t <cancer-study-id> e.g. 'tcga_gbm'");
      return;
    }
    SpringUtil.initDataSource();
    GisticReader gisticReader = new GisticReader();

    File gistic_f = new File(args[0]);
    int cancerStudyInternalId = gisticReader.getCancerStudyInternalId(args[1]);

    ProgressMonitor.setConsoleMode(false);

    System.out.println("Reading data from: " + gistic_f.getAbsolutePath());
    System.out.println("CancerStudyId: " + cancerStudyInternalId);

    int lines = FileUtil.getNumLines(gistic_f);
    System.out.println(" --> total number of lines: " + lines);
    ProgressMonitor.setMaxValue(lines);

    ArrayList<Gistic> gistics = null;

    gistics = gisticReader.parse(gistic_f, cancerStudyInternalId);

    if (gistics == null) {
      System.out.println("Error: didn't get any data");
      return;
    }

    // add to CGDS database
    for (Gistic g : gistics) {
      try {
        DaoGistic.addGistic(g);
      } catch (validationException e) {
        // only catching validationException, not DaoException
        logger.debug(e);
      } catch (DaoException e) {
        System.err.println(e);
      }
    }
    ConsoleUtil.showWarnings();
  }
Exemple #14
0
  private void commandWhere(Options options) {
    WhereResult result;
    Project project = codeAssist.getProject(options);
    try {
      progressMonitor.attach(project);
      if (options.isFileStdin()) {
        result =
            codeAssist.where(
                project,
                new File("(stdin)"),
                options.getHereDocReader(inReader),
                options.getLine());
      } else {
        result =
            codeAssist.where(project, options.getFile(), options.getEncoding(), options.getLine());
      }

      if (options.isPrintAST()) {
        Logger.debug("AST:\n%s", result.getAST());
      }

      if (options.isTest()) {
        Set<String> data = new HashSet<String>();
        if (result.getName() != null) data.add(result.getName());
        test(options, data);
      } else {
        if (options.isEmacsFormat()) {
          out.print("(");
          if (result.getName() != null) out.printf("(name . \"%s\")", result.getName());
          codeAssistError(result, options);
          out.println(")");
        } else {
          if (result.getName() != null) {
            out.print("name: ");
            out.println(result.getName());
          }
          codeAssistError(result, options);
        }
      }
    } catch (Exception e) {
      if (options.isTest()) testError(options);
      commandException(e, options);
    } finally {
      progressMonitor.detach(project);
    }
  }
  @Override
  public void setActiveAlgorithm(int indexFamily, String name, Object cookie) {
    if (input == null) {
      return;
    }
    GeneralFeatureIntensity<T, D> intensity = (GeneralFeatureIntensity<T, D>) cookie;

    gui.reset();
    BufferedImage b = VisualizeImageData.grayMagnitude(workImage, null, 255);
    gui.addImage(b, "Gray Image");

    final ProgressMonitor progressMonitor =
        new ProgressMonitor(
            this, "Computing Scale Space Pyramid Response", "", 0, pyramid.getNumLayers());

    for (int i = 0; i < pyramid.getNumLayers() && !progressMonitor.isCanceled(); i++) {
      double scale = pyramid.getScale(i);
      T scaledImage = pyramid.getLayer(i);

      anyDerivative.setInput(scaledImage);
      D derivX = anyDerivative.getDerivative(true);
      D derivY = anyDerivative.getDerivative(false);
      D derivXX = anyDerivative.getDerivative(true, true);
      D derivYY = anyDerivative.getDerivative(false, false);
      D derivXY = anyDerivative.getDerivative(true, false);

      intensity.process(scaledImage, derivX, derivY, derivXX, derivYY, derivXY);

      ImageFloat32 featureImg = intensity.getIntensity();

      // scale it up to full resolution
      DistortImageOps.scale(featureImg, scaledIntensity, TypeInterpolate.NEAREST_NEIGHBOR);
      // visualize the rescaled intensity
      b = VisualizeImageData.colorizeSign(scaledIntensity, null, PixelMath.maxAbs(scaledIntensity));
      gui.addImage(b, String.format("Scale %6.2f", scale));

      final int progressStatus = i + 1;
      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              progressMonitor.setProgress(progressStatus);
            }
          });
    }
    gui.requestFocusInWindow();
  }
  private ProgressMonitorInputStream getMonitorableStream(File file, String message) {
    try {
      FileInputStream stream = new FileInputStream(file);
      if (stream == null) {
        System.out.println("null on " + file.getCanonicalPath());
      }
      final ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(this, message, stream);

      ProgressMonitor progress = pmis.getProgressMonitor();
      progress.setMillisToDecideToPopup(1);
      progress.setMillisToPopup(1);

      return pmis;
    } catch (IOException e) {
      showError("could not open " + file.getName());
      e.printStackTrace();
      return null;
    }
  }
  private void runImportCnaData() throws DaoException, IOException {

    DaoGeneticAlteration dao = DaoGeneticAlteration.getInstance();
    DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();

    // the largest current true Entrez gene ID counts 8 digits
    daoGene.addGene(new CanonicalGene(999999207, "TESTAKT1"));
    daoGene.addGene(new CanonicalGene(999999208, "TESTAKT2"));
    daoGene.addGene(new CanonicalGene(999910000, "TESTAKT3"));
    daoGene.addGene(new CanonicalGene(999999369, "TESTARAF"));
    daoGene.addGene(new CanonicalGene(999999472, "TESTATM"));
    daoGene.addGene(new CanonicalGene(999999673, "TESTBRAF"));
    daoGene.addGene(new CanonicalGene(999999672, "TESTBRCA1"));
    daoGene.addGene(new CanonicalGene(999999675, "TESTBRCA2"));

    ProgressMonitor.setConsoleMode(false);
    // TBD: change this to use getResourceAsStream()
    File file = new File("src/test/resources/cna_test.txt");
    ImportTabDelimData parser = new ImportTabDelimData(file, "Barry", geneticProfileId, null);
    int numLines = FileUtil.getNumLines(file);
    parser.importData(numLines);

    String value = dao.getGeneticAlteration(geneticProfileId, sample1, 999999207);
    assertEquals("0", value);
    value = dao.getGeneticAlteration(geneticProfileId, sample4, 999999207);
    assertEquals("-1", value);
    value = dao.getGeneticAlteration(geneticProfileId, sample2, 999999207);
    assertEquals("0", value);
    value = dao.getGeneticAlteration(geneticProfileId, sample2, 999910000);
    assertEquals("2", value);
    value = dao.getGeneticAlteration(geneticProfileId, sample3, 999910000);
    assertEquals("2", value);

    int cnaStatus =
        Integer.parseInt(dao.getGeneticAlteration(geneticProfileId, sample3, 999910000));
    assertEquals(CopyNumberStatus.COPY_NUMBER_AMPLIFICATION, cnaStatus);
    cnaStatus = Integer.parseInt(dao.getGeneticAlteration(geneticProfileId, sample2, 999910000));
    assertEquals(CopyNumberStatus.COPY_NUMBER_AMPLIFICATION, cnaStatus);
    cnaStatus = Integer.parseInt(dao.getGeneticAlteration(geneticProfileId, sample4, 999999207));
    assertEquals(CopyNumberStatus.HEMIZYGOUS_DELETION, cnaStatus);

    Patient patient = DaoPatient.getPatientByCancerStudyAndPatientId(studyId, "TCGA-A1-A0SB");
    Sample sample =
        DaoSample.getSampleByPatientAndSampleId(patient.getInternalId(), "TCGA-A1-A0SB-01");
    assertTrue(
        DaoSampleProfile.sampleExistsInGeneticProfile(sample.getInternalId(), geneticProfileId));

    patient = DaoPatient.getPatientByCancerStudyAndPatientId(studyId, "TCGA-A1-A0SJ");
    sample = DaoSample.getSampleByPatientAndSampleId(patient.getInternalId(), "TCGA-A1-A0SJ-01");
    assertTrue(
        DaoSampleProfile.sampleExistsInGeneticProfile(sample.getInternalId(), geneticProfileId));

    ArrayList caseIds = DaoSampleProfile.getAllSampleIdsInProfile(geneticProfileId);
    assertEquals(14, caseIds.size());
  }
 public void test_checkAllConditions_isCancelled() throws Exception {
   Refactoring refactoring = mock(RefactoringImpl.class);
   when(refactoring.checkAllConditions(any(ProgressMonitor.class))).thenCallRealMethod();
   // make monitor as cancelled
   when(pm.isCanceled()).thenReturn(true);
   // check all conditions
   try {
     refactoring.checkAllConditions(pm);
     fail();
   } catch (OperationCanceledException e) {
   }
   verify(refactoring).checkInitialConditions(any(ProgressMonitor.class));
   verify(refactoring, times(0)).checkFinalConditions(any(ProgressMonitor.class));
 }
 @Override
 public void compile(
     final CCTask task,
     final File outputDir,
     final String[] sourceFiles,
     final boolean relentless,
     final ProgressMonitor monitor)
     throws BuildException {
   if (monitor != null) {
     monitor.start(this);
   }
   try {
     this.compiler.compile(
         task, outputDir, sourceFiles, this.args, this.endArgs, relentless, this, monitor);
     if (monitor != null) {
       monitor.finish(this, true);
     }
   } catch (final BuildException ex) {
     if (monitor != null) {
       monitor.finish(this, false);
     }
     throw ex;
   }
 }
  private void runImportRnaData1() throws DaoException, IOException {

    DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
    DaoGeneticAlteration dao = DaoGeneticAlteration.getInstance();

    daoGene.addGene(new CanonicalGene(999999780, "A"));
    daoGene.addGene(new CanonicalGene(999995982, "B"));
    daoGene.addGene(new CanonicalGene(999993310, "C"));
    daoGene.addGene(new CanonicalGene(999997849, "D"));
    daoGene.addGene(new CanonicalGene(999992978, "E"));
    daoGene.addGene(new CanonicalGene(999997067, "F"));
    daoGene.addGene(new CanonicalGene(999911099, "G"));
    daoGene.addGene(new CanonicalGene(999999675, "6352"));

    GeneticProfile geneticProfile = new GeneticProfile();

    geneticProfile.setCancerStudyId(studyId);
    geneticProfile.setStableId("gbm_mrna");
    geneticProfile.setGeneticAlterationType(GeneticAlterationType.MRNA_EXPRESSION);
    geneticProfile.setDatatype("CONTINUOUS");
    geneticProfile.setProfileName("MRNA Data");
    geneticProfile.setProfileDescription("mRNA Data");
    DaoGeneticProfile.addGeneticProfile(geneticProfile);

    int newGeneticProfileId =
        DaoGeneticProfile.getGeneticProfileByStableId("gbm_mrna").getGeneticProfileId();

    ProgressMonitor.setConsoleMode(true);
    // TBD: change this to use getResourceAsStream()
    File file = new File("src/test/resources/mrna_test.txt");
    ImportTabDelimData parser = new ImportTabDelimData(file, newGeneticProfileId, null);
    int numLines = FileUtil.getNumLines(file);
    parser.importData(numLines);
    ConsoleUtil.showMessages();

    int sampleId = DaoSample.getSampleByCancerStudyAndSampleId(studyId, "DD639").getInternalId();
    String value = dao.getGeneticAlteration(newGeneticProfileId, sampleId, 999992978);
    assertEquals("2.01", value);

    sampleId = DaoSample.getSampleByCancerStudyAndSampleId(studyId, "DD638").getInternalId();
    value = dao.getGeneticAlteration(newGeneticProfileId, sampleId, 999997849);
    assertEquals("0.55", value);
  }
  private void runImportCnaData2() throws DaoException, IOException {

    DaoGeneticAlteration dao = DaoGeneticAlteration.getInstance();

    ProgressMonitor.setConsoleMode(false);
    // TBD: change this to use getResourceAsStream()
    File file = new File("src/test/resources/cna_test2.txt");
    ImportTabDelimData parser = new ImportTabDelimData(file, geneticProfileId, null);
    int numLines = FileUtil.getNumLines(file);
    parser.importData(numLines);

    String value = dao.getGeneticAlteration(geneticProfileId, sample1, 207);
    assertEquals(value, "0");
    value = dao.getGeneticAlteration(geneticProfileId, sample4, 207);
    assertEquals(value, "-1");
    value = dao.getGeneticAlteration(geneticProfileId, sample2, 207);
    assertEquals(value, "0");
    value = dao.getGeneticAlteration(geneticProfileId, sample2, 10000);
    assertEquals(value, "2");
    value = dao.getGeneticAlteration(geneticProfileId, sample3, 10000);
    assertEquals(value, "2");

    int cnaStatus = Integer.parseInt(dao.getGeneticAlteration(geneticProfileId, sample3, 10000));
    assertEquals(CopyNumberStatus.COPY_NUMBER_AMPLIFICATION, cnaStatus);
    cnaStatus = Integer.parseInt(dao.getGeneticAlteration(geneticProfileId, sample2, 10000));
    assertEquals(CopyNumberStatus.COPY_NUMBER_AMPLIFICATION, cnaStatus);
    cnaStatus = Integer.parseInt(dao.getGeneticAlteration(geneticProfileId, sample4, 207));
    assertEquals(CopyNumberStatus.HEMIZYGOUS_DELETION, cnaStatus);

    Patient patient = DaoPatient.getPatientByCancerStudyAndPatientId(studyId, "TCGA-A1-A0SB");
    Sample sample =
        DaoSample.getSampleByPatientAndSampleId(patient.getInternalId(), "TCGA-A1-A0SB-01");
    assertTrue(
        DaoSampleProfile.sampleExistsInGeneticProfile(sample.getInternalId(), geneticProfileId));

    patient = DaoPatient.getPatientByCancerStudyAndPatientId(studyId, "TCGA-A1-A0SJ");
    sample = DaoSample.getSampleByPatientAndSampleId(patient.getInternalId(), "TCGA-A1-A0SJ-01");
    assertTrue(
        DaoSampleProfile.sampleExistsInGeneticProfile(sample.getInternalId(), geneticProfileId));
    ArrayList sampleIds = DaoSampleProfile.getAllSampleIdsInProfile(geneticProfileId);
    assertEquals(14, sampleIds.size());
  }
  public EntryDialog(Activity context) {
    super(context, android.R.style.Theme_Light);
    mMenuInflater = context.getMenuInflater();

    // Request a progress bar to display while the HTML content is loading.
    Window window = getWindow();
    ProgressMonitor.requestWindowFeatures(window);

    setContentView(R.layout.atom_entry);

    // Find the ScrollView
    mScrollView = (ScrollView) findViewById(android.R.id.tabcontent);

    // Find the title view, and make it a clickable link
    mTitleView = (TextView) findViewById(android.R.id.text1);
    addLinkMovementMethod(mTitleView);

    // Find the content view, and configure the progress monitor.
    mContentView = (WebView) findViewById(android.R.id.text2);
    WebChromeClient monitor = new ProgressMonitor(window);
    mContentView.setWebChromeClient(monitor);
  }
  /** Update progress. */
  public void updateProgress(int latestProgress, int expectedProgress) {
    lastProgress = progress;
    progress = latestProgress;
    expected = expectedProgress;

    if (connected() == false) state = State.CONNECTED;
    else state = State.UPDATE;

    // The threshold effectively divides the progress into
    // different set of ranges:
    //
    //	Range 0: 0..threshold-1,
    //	Range 1: threshold .. 2*threshold-1
    //	....
    //	Range n: n*threshold .. (n+1)*threshold-1
    //
    // To determine which range the progress belongs to, it
    // would be calculated as follow:
    //
    //	range number = progress / threshold
    //
    // Notification should only be triggered when the current
    // progress and the last progress are in different ranges,
    // i.e. they have different range numbers.
    //
    // Using this range scheme, notification will be generated
    // only once when the progress reaches each range.
    //
    if (lastProgress / threshold != progress / threshold) {
      progressMonitor.updateProgress(this);
    }

    // Detect read overrun
    if (expected != -1) {
      if (progress >= expected && progress != 0) close();
    }
  }
  public void run() {
    WindowBlocker blocker = new WindowBlocker(NearInfinity.getInstance());
    blocker.setBlocked(true);
    List<ResourceEntry> creFiles = ResourceFactory.getInstance().getResources("CRE");
    creFiles.addAll(ResourceFactory.getInstance().getResources("CHR"));
    ProgressMonitor progress =
        new ProgressMonitor(
            NearInfinity.getInstance(), "Checking inventories...", null, 0, creFiles.size());
    table =
        new SortableTable(
            new String[] {"File", "Name", "Item", "Message"},
            new Class[] {Object.class, Object.class, Object.class, Object.class},
            new int[] {100, 100, 200, 200});
    for (int i = 0; i < creFiles.size(); i++) {
      ResourceEntry entry = creFiles.get(i);
      try {
        if (typeButtons[0].isSelected())
          checkCreatureInventory((CreResource) ResourceFactory.getResource(entry));
        if (typeButtons[1].isSelected())
          checkItemAttribute((CreResource) ResourceFactory.getResource(entry));
      } catch (Exception e) {
        e.printStackTrace();
      }
      progress.setProgress(i + 1);
      if (progress.isCanceled()) {
        JOptionPane.showMessageDialog(
            NearInfinity.getInstance(),
            "Operation canceled",
            "Info",
            JOptionPane.INFORMATION_MESSAGE);
        blocker.setBlocked(false);
        return;
      }
    }

    if (table.getRowCount() == 0)
      JOptionPane.showMessageDialog(
          NearInfinity.getInstance(), "No hits found", "Info", JOptionPane.INFORMATION_MESSAGE);
    else {
      resultFrame = new ChildFrame("Result of CRE inventory check", true);
      resultFrame.setIconImage(Icons.getIcon("Refresh16.gif").getImage());
      bopen = new JButton("Open", Icons.getIcon("Open16.gif"));
      bopennew = new JButton("Open in new window", Icons.getIcon("Open16.gif"));
      JLabel count = new JLabel(table.getRowCount() + " hit(s) found", JLabel.CENTER);
      count.setFont(count.getFont().deriveFont((float) count.getFont().getSize() + 2.0f));
      bopen.setMnemonic('o');
      bopennew.setMnemonic('n');
      resultFrame.getRootPane().setDefaultButton(bopennew);
      JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
      panel.add(bopen);
      panel.add(bopennew);
      JScrollPane scrollTable = new JScrollPane(table);
      scrollTable.getViewport().setBackground(table.getBackground());
      JPanel pane = (JPanel) resultFrame.getContentPane();
      pane.setLayout(new BorderLayout(0, 3));
      pane.add(count, BorderLayout.NORTH);
      pane.add(scrollTable, BorderLayout.CENTER);
      pane.add(panel, BorderLayout.SOUTH);
      bopen.setEnabled(false);
      bopennew.setEnabled(false);
      table.setFont(BrowserMenuBar.getInstance().getScriptFont());
      table.getSelectionModel().addListSelectionListener(this);
      table.addMouseListener(
          new MouseAdapter() {
            public void mouseReleased(MouseEvent event) {
              if (event.getClickCount() == 2) {
                int row = table.getSelectedRow();
                if (row != -1) {
                  ResourceEntry resourceEntry = (ResourceEntry) table.getValueAt(row, 0);
                  Resource resource = ResourceFactory.getResource(resourceEntry);
                  new ViewFrame(resultFrame, resource);
                  ((AbstractStruct) resource)
                      .getViewer()
                      .selectEntry(((Item) table.getValueAt(row, 2)).getName());
                }
              }
            }
          });
      bopen.addActionListener(this);
      bopennew.addActionListener(this);
      pane.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
      resultFrame.pack();
      Center.center(resultFrame, NearInfinity.getInstance().getBounds());
      resultFrame.setVisible(true);
    }
    blocker.setBlocked(false);
    //    for (int i = 0; i < table.getRowCount(); i++) {
    //      CreInvError error = (CreInvError)table.getTableItemAt(i);
    //      System.out.println(error.resourceEntry + " (" + error.resourceEntry.getSearchString() +
    // ") -> " + error.itemRef.getAttribute("Item"));
    //    }
  }
 /**
  * Overrides <code>FilterInputStream.reset</code> to reset the progress monitor as well as the
  * stream.
  */
 public synchronized void reset() throws IOException {
   in.reset();
   nread = size - in.available();
   monitor.setProgress(nread);
 }
 /**
  * Overrides <code>FilterInputStream.close</code> to close the progress monitor as well as the
  * stream.
  */
 public void close() throws IOException {
   in.close();
   monitor.close();
 }
 /**
  * Overrides <code>FilterInputStream.skip</code> to update the progress monitor after the skip.
  */
 public long skip(long n) throws IOException {
   long nr = in.skip(n);
   if (nr > 0) monitor.setProgress(nread += nr);
   return nr;
 }
 public void run() {
   WindowBlocker blocker = new WindowBlocker(NearInfinity.getInstance());
   blocker.setBlocked(true);
   List<ResourceEntry> files = new ArrayList<ResourceEntry>();
   for (final String fileType : FILETYPES)
     files.addAll(ResourceFactory.getInstance().getResources(fileType));
   ProgressMonitor progress =
       new ProgressMonitor(NearInfinity.getInstance(), "Searching...", null, 0, files.size());
   table =
       new SortableTable(
           new String[] {"String", "StrRef"},
           new Class[] {Object.class, Integer.class},
           new int[] {450, 20});
   StringResource.getStringRef(0);
   strUsed = new boolean[StringResource.getMaxIndex() + 1];
   for (int i = 0; i < files.size(); i++) {
     ResourceEntry entry = files.get(i);
     Resource resource = ResourceFactory.getResource(entry);
     if (resource instanceof DlgResource) checkDialog((DlgResource) resource);
     else if (resource instanceof BcsResource) checkScript((BcsResource) resource);
     else if (resource instanceof PlainTextResource) checkTextfile((PlainTextResource) resource);
     else if (resource != null) checkStruct((AbstractStruct) resource);
     progress.setProgress(i + 1);
     if (progress.isCanceled()) {
       JOptionPane.showMessageDialog(
           NearInfinity.getInstance(),
           "Operation canceled",
           "Info",
           JOptionPane.INFORMATION_MESSAGE);
       blocker.setBlocked(false);
       return;
     }
   }
   for (int i = 0; i < strUsed.length; i++)
     if (!strUsed[i]) table.addTableItem(new UnusedStringTableItem(new Integer(i)));
   if (table.getRowCount() == 0)
     JOptionPane.showMessageDialog(
         NearInfinity.getInstance(),
         "No unused strings found",
         "Info",
         JOptionPane.INFORMATION_MESSAGE);
   else {
     table.tableComplete(1);
     textArea = new JTextArea(10, 40);
     textArea.setEditable(false);
     textArea.setWrapStyleWord(true);
     textArea.setLineWrap(true);
     JScrollPane scrollText = new JScrollPane(textArea);
     resultFrame = new ChildFrame("Result", true);
     save = new JMenuItem("Save");
     save.addActionListener(this);
     JMenu fileMenu = new JMenu("File");
     fileMenu.add(save);
     JMenuBar menuBar = new JMenuBar();
     menuBar.add(fileMenu);
     resultFrame.setJMenuBar(menuBar);
     resultFrame.setIconImage(Icons.getIcon("Find16.gif").getImage());
     JLabel count = new JLabel(table.getRowCount() + " unused string(s) found", JLabel.CENTER);
     count.setFont(count.getFont().deriveFont((float) count.getFont().getSize() + 2.0f));
     JScrollPane scrollTable = new JScrollPane(table);
     scrollTable.getViewport().setBackground(table.getBackground());
     JPanel pane = (JPanel) resultFrame.getContentPane();
     pane.setLayout(new BorderLayout(0, 3));
     pane.add(count, BorderLayout.NORTH);
     pane.add(scrollTable, BorderLayout.CENTER);
     JPanel bottomPanel = new JPanel(new BorderLayout());
     JPanel searchPanel = SearchMaster.createAsPanel(this, resultFrame);
     bottomPanel.add(scrollText, BorderLayout.CENTER);
     bottomPanel.add(searchPanel, BorderLayout.EAST);
     pane.add(bottomPanel, BorderLayout.SOUTH);
     table.setFont(BrowserMenuBar.getInstance().getScriptFont());
     pane.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
     table.getSelectionModel().addListSelectionListener(this);
     resultFrame.pack();
     Center.center(resultFrame, NearInfinity.getInstance().getBounds());
     resultFrame.setVisible(true);
   }
   blocker.setBlocked(false);
 }
  /**
   * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's
   * multipart classes (see class description).
   *
   * @param saveDir the directory to save off the file
   * @param servletRequest the request containing the multipart
   * @throws java.io.IOException is thrown if encoding fails.
   */
  @SuppressWarnings("unchecked")
  @Override
  public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {
    DiskFileItemFactory fac = new DiskFileItemFactory();
    // Make sure that the data is written to file
    fac.setSizeThreshold(0);
    if (saveDir != null) {
      fac.setRepository(new File(saveDir));
    }

    ProgressMonitor monitor = null;
    // Parse the request
    try {
      ServletFileUpload upload = new ServletFileUpload(fac);
      upload.setSizeMax(maxSize);

      monitor = new ProgressMonitor();
      upload.setProgressListener(monitor);
      servletRequest.getSession().setAttribute(ProgressMonitor.SESSION_PROGRESS_MONITOR, monitor);

      List<FileItem> items = upload.parseRequest(createRequestContext(servletRequest));

      for (FileItem item1 : items) {
        FileItem item = item1;

        if (log.isDebugEnabled()) {
          log.debug("Found item " + item.getFieldName());
        }
        if (item.isFormField()) {
          if (log.isDebugEnabled()) {
            log.debug("Item is a normal form field");
          }
          List<String> values;
          if (params.get(item.getFieldName()) != null) {
            values = params.get(item.getFieldName());
          } else {
            values = new ArrayList<String>();
          }

          // note: see http://jira.opensymphony.com/browse/WW-633
          // basically, in some cases the charset may be null, so
          // we're just going to try to "other" method (no idea if this
          // will work)
          String charset = servletRequest.getCharacterEncoding();
          if (charset != null) {
            values.add(item.getString(charset));
          } else {
            values.add(item.getString());
          }
          params.put(item.getFieldName(), values);
        } else {
          if (log.isDebugEnabled()) {
            log.debug("Item is a file upload");
          }
          List<FileItem> values;
          if (files.get(item.getFieldName()) != null) {
            values = files.get(item.getFieldName());
          } else {
            values = new ArrayList<FileItem>();
          }

          values.add(item);
          files.put(item.getFieldName(), values);
        }
      }
    } catch (FileUploadException e) {
      e.printStackTrace();
      if (monitor != null) monitor.abort();
      log.error(e);
      errors.add(e.getMessage());
    } catch (Exception e) {
      e.printStackTrace();
      if (monitor != null) monitor.abort();
    }
  }
 @Override
 public int read(char[] cbuf, int off, int len) throws IOException {
   int res = inReader.read(cbuf, off, len);
   monitor.reportProgress(countingIn.getByteCount());
   return res;
 }