コード例 #1
0
ファイル: HashDbManager.java プロジェクト: lorz/autopsy
 @Override
 protected Object doInBackground() {
   hashDb.indexing = true;
   progress =
       ProgressHandleFactory.createHandle(
           NbBundle.getMessage(
               this.getClass(), "HashDbManager.progress.indexingHashSet", hashDb.hashSetName));
   progress.start();
   progress.switchToIndeterminate();
   try {
     SleuthkitJNI.createLookupIndexForHashDatabase(hashDb.handle);
   } catch (TskCoreException ex) {
     Logger.getLogger(HashDb.class.getName())
         .log(Level.SEVERE, "Error indexing hash database", ex); // NON-NLS
     JOptionPane.showMessageDialog(
         null,
         NbBundle.getMessage(
             this.getClass(),
             "HashDbManager.dlgMsg.errorIndexingHashSet",
             hashDb.getHashSetName()),
         NbBundle.getMessage(this.getClass(), "HashDbManager.hashDbIndexingErr"),
         JOptionPane.ERROR_MESSAGE);
   }
   return null;
 }
コード例 #2
0
    @Override
    public void run() {
      if (!EventQueue.isDispatchThread()) {
        ProgressHandle ph;
        ph =
            ProgressHandleFactory.createHandle(
                NbBundle.getMessage(ResultsTopComponent.class, "PreparingResultsWindow.msg"));
        ph.start();
        n = new ResultsNode(query);
        rtcsc = query.getColumns();
        List cols = Arrays.asList(rtcsc);
        Iterator colsIt = cols.iterator();
        alps = new ArrayList();
        while (colsIt.hasNext()) {
          RtcQueryColumn rsc = (RtcQueryColumn) colsIt.next();
          alps.add(rsc.getColumnIdentifier());
          alps.add(rsc.getColumnDisplayName());
        }
        actualCols = alps.toArray(new String[] {});
        EventQueue.invokeLater(this);
        ph.finish();
      } else {
        outlineView.setPropertyColumns(alps.toArray(new String[] {}));
        Outline outline = outlineView.getOutline();
        removeDefaultColumn(outline);
        ETableColumnModel etcm = (ETableColumnModel) outline.getColumnModel();

        // TODO: szymon : change j to proper sort order
        int j = 1;
        for (int i = 1; i < rtcsc.length; i++) {
          ETableColumn etc = (ETableColumn) etcm.getColumn(i);
          if (alps.get(i * 2 - 2).equals("id")) {
            etc.setMaxWidth(20);
          }
          if (alps.get(i * 2 - 2).equals("internalSeverity")) {
            etc.setMaxWidth(20);
          }
          if (alps.get(i * 2 - 2).equals("internalPriority")) {
            etc.setMaxWidth(20);
          }
          if (alps.get(i * 2 - 2).equals("workItemType")) {
            etc.setMaxWidth(20);
          }
          if (alps.get(i * 2 - 2).equals("internalState")) {
            etc.setMaxWidth(85);
          }
          if (alps.get(i * 2 - 2).equals("summary")) {
            etc.setMaxWidth(550);
            etc.setWidth(475);
            etc.setMinWidth(400);
          }
          if (rtcsc[i].isSortColumn()) {
            etcm.setColumnSorted(etc, rtcsc[i].isAscending(), j);
            j++;
          }
        }

        manager.setRootContext(n);
      }
    }
コード例 #3
0
  protected void onStateChange() {
    switch (getState()) {
      case DONE:
        makeBusy(false);

        loadingPanel.setLoading(false);
        raView.refresh();

        if (progressHandle != null) {
          progressHandle.finish();
        }

        break;
      case PENDING:
        runButton.setEnabled(true);
        break;
      case STARTED:
        runButton.setEnabled(false);
        loadingPanel.setLoading(true);
        progressHandle =
            ProgressHandleFactory.createHandle(
                "Processing Time Series...",
                new Cancellable() {
                  @Override
                  public boolean cancel() {
                    runButton.setEnabled(true);
                    return worker.cancel(true);
                  }
                });
        progressHandle.start();
        break;
    }
  }
コード例 #4
0
 public void run() {
   ProgressHandle ph =
       ProgressHandleFactory.createHandle(
           NbBundle.getMessage(RetrieverEngineImpl.class, "LBL_PROGRESSBAR_Retrieve_XML"),
           new Cancellable() {
             public boolean cancel() {
               synchronized (RetrieverEngineImpl.this) {
                 if (!RetrieverEngineImpl.this.STOP_PULL) {
                   RetrieverEngineImpl.this.STOP_PULL = true;
                   // taskThread.interrupt();
                 }
               }
               return true;
             }
           },
           new AbstractAction() {
             public void actionPerformed(ActionEvent e) {
               getOPWindow().setOutputVisible(true);
               getOPWindow().select();
             }
           });
   ph.start();
   ph.switchToIndeterminate();
   try {
     pullRecursively();
   } finally {
     ph.finish();
   }
 }
コード例 #5
0
  @Override
  public Set instantiate(ProgressHandle handle) throws IOException {
    handle.start(2);
    handle.progress(
        NbBundle.getMessage(
            JavaEESamplesWizardIterator.class,
            "LBL_NewSampleProjectWizardIterator_WizardProgress_CreatingProject"),
        1);

    Set resultSet = new LinkedHashSet();
    File dirF = FileUtil.normalizeFile((File) wiz.getProperty(WizardProperties.PROJ_DIR));
    String name = (String) wiz.getProperty(WizardProperties.NAME);
    FileObject template = Templates.getTemplate(wiz);

    FileObject dir = null;
    if ("web".equals(template.getAttribute("prjType"))) {
      // Use generator from web.examples to create project with specified name
      dir = WebSampleProjectGenerator.createProjectFromTemplate(template, dirF, name);
    } else {
      // Unzip prepared project only (no way to change name of the project)
      // FIXME: should be modified to create projects with specified name (project.xml files in
      // sub-projects should be modified too)
      // FIXME: web.examples and j2ee.samples modules may be merged into one module
      createFolder(dirF);
      dir = FileUtil.toFileObject(dirF);
      unZipFile(template.getInputStream(), dir);
      WebSampleProjectGenerator.configureServer(dir);
      for (FileObject child : dir.getChildren()) {
        WebSampleProjectGenerator.configureServer(child);
      }
    }

    ProjectManager.getDefault().clearNonProjectCache();
    handle.progress(
        NbBundle.getMessage(
            JavaEESamplesWizardIterator.class,
            "LBL_NewSampleProjectWizardIterator_WizardProgress_PreparingToOpen"),
        2);

    // Always open top dir as a project:
    resultSet.add(dir);
    // Look for nested projects to open as well:
    Enumeration e = dir.getFolders(true);
    while (e.hasMoreElements()) {
      FileObject subfolder = (FileObject) e.nextElement();
      if (ProjectManager.getDefault().isProject(subfolder)) {
        resultSet.add(subfolder);
      }
    }

    File parent = dirF.getParentFile();
    if (parent != null && parent.exists()) {
      ProjectChooser.setProjectsFolder(parent);
    }

    handle.finish();
    return resultSet;
  }
コード例 #6
0
 private ProgressHandle createProgress() {
   ProgressHandle ph =
       ProgressHandleFactory.createHandle(
           NbBundle.getMessage(
               TakeScreenshotActionProvider.class, "MSG_TakingApplicationScreenshot"));
   ph.setInitialDelay(500);
   ph.start();
   return ph;
 }
コード例 #7
0
 @Override
 public Spatial loadAsset() {
   ProgressHandle handle = ProgressHandleFactory.createHandle("Converting OgreBinary");
   handle.start();
   // mesh
   OgreXMLConvertOptions options = new OgreXMLConvertOptions(getPrimaryFile().getPath());
   options.setBinaryFile(true);
   OgreXMLConvert conv = new OgreXMLConvert();
   conv.doConvert(options, handle);
   // try skeleton
   if (getPrimaryFile().existsExt("skeleton")) {
     OgreXMLConvertOptions options2 =
         new OgreXMLConvertOptions(
             getPrimaryFile()
                 .getParent()
                 .getFileObject(getPrimaryFile().getName(), "skeleton")
                 .getPath());
     options2.setBinaryFile(true);
     OgreXMLConvert conv2 = new OgreXMLConvert();
     conv2.doConvert(options2, handle);
   }
   handle.progress("Convert Model");
   ProjectAssetManager mgr = getLookup().lookup(ProjectAssetManager.class);
   if (mgr == null) {
     DialogDisplayer.getDefault()
         .notifyLater(
             new NotifyDescriptor.Message(
                 "File is not part of a project!\nCannot load without ProjectAssetManager."));
     return null;
   }
   String assetKey = mgr.getRelativeAssetPath(options.getDestFile());
   FileLock lock = null;
   try {
     lock = getPrimaryFile().lock();
     listListener.start();
     Spatial spatial = mgr.loadModel(assetKey);
     // replace transient xml files in list of assets for this model
     replaceXmlFiles();
     listListener.stop();
     savable = spatial;
     lock.releaseLock();
     File deleteFile = new File(options.getDestFile());
     deleteFile.delete();
     handle.finish();
     return spatial;
   } catch (IOException ex) {
     Exceptions.printStackTrace(ex);
     if (lock != null) {
       lock.releaseLock();
     }
   }
   File deleteFile = new File(options.getDestFile());
   deleteFile.delete();
   handle.finish();
   return null;
 }
コード例 #8
0
 public void start() {
   int totalFiles = buildFiles.length + runFiles.length;
   if (totalFiles == 0) {
     return;
   }
   progress = ProgressHandleFactory.createHandle("Executing...", this);
   progress.setInitialDelay(0);
   progress.start(totalFiles);
   next();
 }
コード例 #9
0
ファイル: AnalysisWorker.java プロジェクト: rforge/timpgui
 public void run() {
   try {
     ph.start();
     ph.switchToIndeterminate();
     doAnalysis();
     Thread.sleep(0);
   } catch (InterruptedException ex) {
     Exceptions.printStackTrace(ex);
   }
 }
コード例 #10
0
ファイル: HashDbManager.java プロジェクト: lorz/autopsy
    @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);
      }
    }
コード例 #11
0
ファイル: IngestManager.java プロジェクト: raman-bt/autopsy
    /* clean up or start the worker threads */
    @Override
    protected void done() {
      try {
        super.get(); // block and get all exceptions thrown while doInBackground()
      } catch (CancellationException e) {
        // task was cancelled
        handleInterruption(e);
      } catch (InterruptedException ex) {
        handleInterruption(ex);
      } catch (ExecutionException ex) {
        handleInterruption(ex);

      } catch (Exception ex) {
        handleInterruption(ex);

      } finally {
        // queing end
        if (this.isCancelled()) {
          // empty queues
          handleInterruption(new Exception());
        } else {
          // start ingest workers
          startAll();
        }
        progress.finish();
      }
    }
コード例 #12
0
 private void next() {
   index++;
   if (index >= (buildFiles.length + runFiles.length)) {
     done();
     return;
   }
   FileObject file;
   //            ExecutionLevel level;
   if (index < buildFiles.length) {
     file = buildFiles[index];
     executedBuildFiles.add(file);
     level = ExecutionLevel.BUILD;
   } else {
     file = runFiles[index - buildFiles.length];
     level = ExecutionLevel.RUN;
   }
   FileHandler handler = findHandler(level, file);
   String msg = FileUtil.getRelativePath(getProjectDirectory(), file) + " [" + level + "]";
   progress.progress(msg, index);
   try {
     handler.process(new CallbackImpl(handler, file));
   } catch (Exception ex) {
     Exceptions.printStackTrace(ex);
     if (continueOnError(handler, file, null)) {
       next();
     } else {
       done();
     }
   }
 }
コード例 #13
0
ファイル: ContentUtils.java プロジェクト: sleuthkit/autopsy
    public Void visitDir(AbstractFile dir) {

      // don't extract . and .. directories
      if (isDotDirectory(dir)) {
        return null;
      }

      dest.mkdir();

      try {
        int numProcessed = 0;
        // recurse on children
        for (Content child : dir.getChildren()) {
          java.io.File childFile = getFsContentDest(child);
          ExtractFscContentVisitor<T, V> childVisitor =
              new ExtractFscContentVisitor<>(childFile, progress, worker, false);
          // If this is the source directory of an extract it
          // will have a progress and worker, and will keep track
          // of the progress bar's progress
          if (worker != null && worker.isCancelled()) {
            break;
          }
          if (progress != null && source) {
            progress.progress(child.getName(), numProcessed);
          }
          child.accept(childVisitor);
          numProcessed++;
        }
      } catch (TskException ex) {
        logger.log(Level.SEVERE, "Trouble fetching children to extract.", ex); // NON-NLS
      }

      return null;
    }
コード例 #14
0
 private void done() {
   progress.finish();
   if (warnings != null) {
     ProjectDialogManager.getDefault()
         .showWarningsDialog(DefaultPraxisProject.this, warnings, level);
   }
   actionsEnabled = true;
 }
コード例 #15
0
  public void run() {
    assert task != null;
    try {
      startTime = System.currentTimeMillis();
      ProgressHandle handle = ProgressHandleFactory.createHandle(title, this);
      handle.setDisplayName(titleMsg);
      handle.start();
      try {
        handle.switchToIndeterminate();
        dataView.setInfoStatusText(""); // NOI18N
        errorMsg = ""; // NOI18N
        dataView.disableButtons();

        conn = DBConnectionFactory.getInstance().getConnection(dataView.getDatabaseConnection());
        String msg = "";
        if (conn == null) {
          Throwable connEx = DBConnectionFactory.getInstance().getLastException();
          if (connEx != null) {
            msg = connEx.getMessage();
          } else {
            msg =
                NbBundle.getMessage(
                    SQLStatementExecutor.class,
                    "MSG_connection_failure",
                    dataView.getDatabaseConnection());
          }
          NotifyDescriptor nd = new NotifyDescriptor.Message(msg);
          DialogDisplayer.getDefault().notify(nd);
          return;
        }
        lastCommitState = setAutocommit(conn, false);
        execute(); // delegate
      } finally {
        handle.finish();
      }
    } catch (Exception e) {
      this.ex = e;
    } finally {
      if (ex != null) {
        errorMsg += ex.getMessage();
        error = true;
      }
      finished(); // delegate
      resetAutocommitState(conn, lastCommitState);
    }
  }
コード例 #16
0
ファイル: ContentUtils.java プロジェクト: sleuthkit/autopsy
  /**
   * Reads all the data from any content object and writes (extracts) it to a file.
   *
   * @param content Any content object.
   * @param outputFile Will be created if it doesn't exist, and overwritten if it does
   * @param progress progress bar handle to update, if available. null otherwise
   * @param worker the swing worker background thread the process runs within, or null, if in the
   *     main thread, used to handle task cancellation
   * @param source true if source file
   * @return number of bytes extracted
   * @throws IOException if file could not be written
   */
  public static <T> long writeToFile(
      Content content,
      java.io.File outputFile,
      ProgressHandle progress,
      Future<T> worker,
      boolean source)
      throws IOException {
    InputStream in = new ReadContentInputStream(content);

    // Get the unit size for a progress bar
    int unit = (int) (content.getSize() / 100);
    long totalRead = 0;

    try (FileOutputStream out = new FileOutputStream(outputFile, false)) {
      byte[] buffer = new byte[TO_FILE_BUFFER_SIZE];
      int len = in.read(buffer);
      while (len != -1) {
        // If there is a worker, check for a cancelation
        if (worker != null && worker.isCancelled()) {
          break;
        }
        out.write(buffer, 0, len);
        len = in.read(buffer);
        totalRead += len;
        // If there is a progress bar and this is the source file,
        // report any progress
        if (progress != null && source && totalRead >= TO_FILE_BUFFER_SIZE) {
          int totalProgress = (int) (totalRead / unit);
          progress.progress(content.getName(), totalProgress);
          // If it's not the source, just update the file being processed
        } else if (progress != null && !source) {
          progress.progress(content.getName());
        }
      }
    } finally {
      in.close();
    }
    return totalRead;
  }
コード例 #17
0
 @NbBundle.Messages({
   "# {0} - project name",
   "InternalWebServer.stopping=Stopping PHP built-in web server for project {0}..."
 })
 @SuppressWarnings("SleepWhileHoldingLock")
 private static boolean ensureServerStopped(InternalWebServer instance) {
   assert !EventQueue.isDispatchThread();
   ProgressHandle progressHandle =
       ProgressHandleFactory.createHandle(
           Bundle.InternalWebServer_stopping(instance.project.getName()));
   try {
     progressHandle.start();
     // stop server
     instance.stop();
     // wait for shutdown
     RunConfigInternal runConfig = RunConfigInternal.forProject(instance.project);
     String host = runConfig.getHostname();
     int port = Integer.valueOf(runConfig.getPort());
     for (int i = 0; i < 20; ++i) {
       try {
         Socket socket = new Socket(host, port);
         socket.close();
         Thread.sleep(200);
       } catch (InterruptedException ex) {
         Thread.currentThread().interrupt();
       } catch (UnknownHostException ex) {
         return true;
       } catch (IOException ex) {
         return true;
       }
     }
     return false;
   } finally {
     progressHandle.finish();
   }
 }
コード例 #18
0
 @Override
 public void actionPerformed(ActionEvent ev) {
   Runnable runnable =
       new Runnable() {
         @Override
         public void run() {
           cssMinify();
         }
       };
   final RequestProcessor.Task theTask = RP.create(runnable);
   final ProgressHandle ph =
       ProgressHandleFactory.createHandle(
           "Minifying CSS " + context.getPrimaryFile().getName(), theTask);
   theTask.addTaskListener(
       new TaskListener() {
         @Override
         public void taskFinished(org.openide.util.Task task) {
           // JOptionPane.showMessageDialog(null, "Image Compressed Successfully");
           ph.finish();
         }
       });
   ph.start();
   theTask.schedule(0);
 }
コード例 #19
0
ファイル: IngestManager.java プロジェクト: raman-bt/autopsy
    @Override
    protected void done() {
      try {
        super.get(); // block and get all exceptions thrown while doInBackground()
        // notify modules of completion
        if (!this.isCancelled()) {
          for (IngestModuleAbstractFile s : abstractFileModules) {
            s.complete();
            IngestManager.fireModuleEvent(IngestModuleEvent.COMPLETED.toString(), s.getName());
          }
        }

        logger.log(Level.INFO, PlatformUtil.getAllMemUsageInfo());
        logger.log(Level.INFO, "Freeing jvm heap resources post file pipeline run");
        System.gc();
        logger.log(Level.INFO, PlatformUtil.getAllMemUsageInfo());

      } catch (CancellationException e) {
        // task was cancelled
        handleInterruption();

      } catch (InterruptedException ex) {
        handleInterruption();
      } catch (ExecutionException ex) {
        handleInterruption();
        logger.log(Level.SEVERE, "Fatal error during ingest.", ex);

      } catch (Exception ex) {
        handleInterruption();
        logger.log(Level.SEVERE, "Fatal error during ingest.", ex);
      } finally {
        stats.end();
        progress.finish();

        if (!this.isCancelled()) {
          logger.log(Level.INFO, "Summary Report: " + stats.toString());
          logger.log(Level.INFO, "File module timings: " + stats.getFileModuleStats());
          if (ui != null) {
            logger.log(Level.INFO, "Ingest messages count: " + ui.getMessagesCount());
          }

          IngestManager.this.postMessage(
              IngestMessage.createManagerMessage("File Ingest Complete", stats.toHtmlString()));
        }
      }
    }
コード例 #20
0
  @Override
  public Result loadModels(
      NbGradleProject project, ProjectConnection connection, ProgressHandle progress)
      throws IOException, GradleModelLoadError {

    ProjectModelFetcher modelFetcher = new ProjectModelFetcher(project, gradleTarget);
    FetchedModelsOrError fetchedModelsOrError = modelFetcher.getModels(connection, setup);
    FetchedModels fetchedModels = fetchedModelsOrError.getModels();
    if (fetchedModels == null) {
      throw new GradleModelLoadError(
          project,
          fetchedModelsOrError.getBuildScriptEvaluationError(),
          fetchedModelsOrError.getUnexpectedError());
    }

    progress.progress(NbStrings.getParsingModel());

    ProjectModelParser parser = new ProjectModelParser(project, modelFetcher);
    return parser.parseModel(fetchedModels);
  }
コード例 #21
0
ファイル: IngestManager.java プロジェクト: raman-bt/autopsy
    @Override
    protected Object doInBackground() throws Exception {

      final String displayName = "Queueing Ingest";
      progress =
          ProgressHandleFactory.createHandle(
              displayName,
              new Cancellable() {
                @Override
                public boolean cancel() {
                  logger.log(Level.INFO, "Queueing ingest cancelled by user.");
                  if (progress != null) {
                    progress.setDisplayName(displayName + " (Cancelling...)");
                  }
                  return EnqueueWorker.this.cancel(true);
                }
              });

      progress.start(2 * inputs.size());
      // progress.switchToIndeterminate();
      queueAll(modules, inputs);
      return null;
    }
コード例 #22
0
ファイル: IngestManager.java プロジェクト: raman-bt/autopsy
    private void queueAll(List<IngestModuleAbstract> modules, final List<Content> inputs) {

      int processed = 0;
      for (Content input : inputs) {
        final String inputName = input.getName();

        final List<IngestModuleDataSource> dataSourceMods = new ArrayList<IngestModuleDataSource>();
        final List<IngestModuleAbstractFile> fileMods = new ArrayList<IngestModuleAbstractFile>();

        for (IngestModuleAbstract module : modules) {
          if (isCancelled()) {
            logger.log(Level.INFO, "Terminating ingest queueing due to cancellation.");
            return;
          }

          final String moduleName = module.getName();
          progress.progress(moduleName + " " + inputName, processed);

          switch (module.getType()) {
            case DataSource:
              final IngestModuleDataSource newModuleInstance =
                  (IngestModuleDataSource) moduleLoader.getNewIngestModuleInstance(module);
              if (newModuleInstance != null) {
                dataSourceMods.add(newModuleInstance);
              } else {
                logger.log(
                    Level.INFO,
                    "Error loading module and adding input "
                        + inputName
                        + " with module "
                        + module.getName());
              }
              break;

            case AbstractFile:
              // enqueue the same singleton AbstractFile module
              logger.log(
                  Level.INFO,
                  "Adding input " + inputName + " for AbstractFileModule " + module.getName());

              fileMods.add((IngestModuleAbstractFile) module);
              break;

            default:
              logger.log(Level.SEVERE, "Unexpected module type: " + module.getType().name());
          }
        } // for modules

        // queue to schedulers

        // queue to datasource-level ingest pipeline(s)
        final boolean processUnalloc = getProcessUnallocSpace();
        final ScheduledTask<IngestModuleDataSource> dataSourceTask =
            new ScheduledTask<IngestModuleDataSource>(input, dataSourceMods);
        final PipelineContext<IngestModuleDataSource> dataSourcePipelineContext =
            new PipelineContext<IngestModuleDataSource>(dataSourceTask, processUnalloc);
        logger.log(Level.INFO, "Queing data source ingest task: " + dataSourceTask);
        progress.progress("DataSource Ingest" + " " + inputName, processed);
        final IngestScheduler.DataSourceScheduler dataSourceScheduler =
            scheduler.getDataSourceScheduler();
        dataSourceScheduler.schedule(dataSourcePipelineContext);
        progress.progress("DataSource Ingest" + " " + inputName, ++processed);

        // queue to file-level ingest pipeline
        final ScheduledTask<IngestModuleAbstractFile> fTask = new ScheduledTask(input, fileMods);
        final PipelineContext<IngestModuleAbstractFile> filepipelineContext =
            new PipelineContext<IngestModuleAbstractFile>(fTask, processUnalloc);
        logger.log(Level.INFO, "Queing file ingest task: " + fTask);
        progress.progress("File Ingest" + " " + inputName, processed);
        final IngestScheduler.FileScheduler fileScheduler = scheduler.getFileScheduler();
        fileScheduler.schedule(filepipelineContext);
        progress.progress("File Ingest" + " " + inputName, ++processed);
      } // for data sources

      // logger.log(Level.INFO, AbstractFileQueue.printQueue());
    }
コード例 #23
0
ファイル: IngestManager.java プロジェクト: raman-bt/autopsy
    @Override
    protected Object doInBackground() throws Exception {

      logger.log(Level.INFO, "Starting background ingest file processor");
      logger.log(Level.INFO, PlatformUtil.getAllMemUsageInfo());

      stats.start();

      // notify main thread modules started
      for (IngestModuleAbstractFile s : abstractFileModules) {
        IngestManager.fireModuleEvent(IngestModuleEvent.STARTED.toString(), s.getName());
      }

      final String displayName = "File Ingest";
      progress =
          ProgressHandleFactory.createHandle(
              displayName,
              new Cancellable() {
                @Override
                public boolean cancel() {
                  logger.log(Level.INFO, "Filed ingest cancelled by user.");
                  if (progress != null) {
                    progress.setDisplayName(displayName + " (Cancelling...)");
                  }
                  return IngestAbstractFileProcessor.this.cancel(true);
                }
              });

      final IngestScheduler.FileScheduler fileScheduler = scheduler.getFileScheduler();

      // initialize the progress bar
      progress.start();
      progress.switchToIndeterminate();
      // set initial totals and processed (to be updated as we process or new files are scheduled)
      int totalEnqueuedFiles = fileScheduler.getFilesEnqueuedEst();
      progress.switchToDeterminate(totalEnqueuedFiles);
      int processedFiles = 0;
      // process AbstractFiles queue
      while (fileScheduler.hasNext()) {
        final ProcessTask fileTask = fileScheduler.next();
        final PipelineContext<IngestModuleAbstractFile> filepipelineContext = fileTask.context;
        final ScheduledTask<IngestModuleAbstractFile> fileIngestTask =
            filepipelineContext.getScheduledTask();
        final AbstractFile fileToProcess = fileTask.file;

        // clear return values from modules for last file
        synchronized (abstractFileModulesRetValues) {
          abstractFileModulesRetValues.clear();
        }

        // logger.log(Level.INFO, "IngestManager: Processing: {0}", fileToProcess.getName());

        for (IngestModuleAbstractFile module : fileIngestTask.getModules()) {
          // process the file with every file module
          if (isCancelled()) {
            logger.log(Level.INFO, "Terminating file ingest due to cancellation.");
            return null;
          }
          progress.progress(
              fileToProcess.getName() + " (" + module.getName() + ")", processedFiles);

          try {
            stats.logFileModuleStartProcess(module);
            IngestModuleAbstractFile.ProcessResult result =
                module.process(filepipelineContext, fileToProcess);
            stats.logFileModuleEndProcess(module);

            // store the result for subsequent modules for this file
            synchronized (abstractFileModulesRetValues) {
              abstractFileModulesRetValues.put(module.getName(), result);
            }

          } catch (Exception e) {
            logger.log(
                Level.SEVERE, "Error: unexpected exception from module: " + module.getName(), e);
            stats.addError(module);
          } catch (OutOfMemoryError e) {
            logger.log(Level.SEVERE, "Error: out of memory from module: " + module.getName(), e);
            stats.addError(module);
          }
        } // end for every module

        // free the internal file resource after done with every module
        fileToProcess.close();

        int newTotalEnqueuedFiles = fileScheduler.getFilesEnqueuedEst();
        if (newTotalEnqueuedFiles > totalEnqueuedFiles) {
          // update if new enqueued
          totalEnqueuedFiles = newTotalEnqueuedFiles + 1; // + processedFiles + 1;
          // processedFiles = 0;
          // reset
          progress.switchToIndeterminate();
          progress.switchToDeterminate(totalEnqueuedFiles);
        }
        if (processedFiles
            < totalEnqueuedFiles) { // fix for now to handle the same datasource Content enqueued
                                    // twice
          ++processedFiles;
        }
        // --totalEnqueuedFiles;

      } // end of for every AbstractFile
      logger.log(Level.INFO, "IngestManager: Finished processing files");
      return null;
    }
コード例 #24
0
 synchronized void show() {
   progressHandle.start();
 }
コード例 #25
0
 /** Sets a message to be displayed in the progress GUI. */
 synchronized void setMessage(final String msg) {
   progressHandle.progress(msg);
 }
コード例 #26
0
 synchronized void hide() {
   progressHandle.finish();
 }
コード例 #27
0
  @Override
  public void doAction(Object action) {
    String msg = null;
    setEnabled(ScreenshotUIManager.ACTION_TAKE_SCREENSHOT, false);
    try {
      ProgressHandle ph = createProgress();

      RemoteScreenshot[] screenshots = null;
      try {
        screenshots = RemoteAWTScreenshot.takeCurrent(debugger);
        for (int i = 0; i < screenshots.length; i++) {
          final RemoteScreenshot screenshot = screenshots[i];
          screenshot.getScreenshotUIManager().open();
          bpListener.addScreenshot(screenshot);
          /*
          SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
          ScreenshotComponent sc = new ScreenshotComponent(screenshot);
          sc.open();
          sc.requestActive();
          }
          });*/
        }
        if (screenshots != null && screenshots.length != 0) {
          GestureSubmitter.logSnapshotTaken("Swing", debugger);
          return;
        }
      } finally {
        ph.finish();
      }

      ph = createProgress();
      try {
        screenshots = RemoteFXScreenshot.takeCurrent(debugger);
        for (int i = 0; i < screenshots.length; i++) {
          final RemoteScreenshot screenshot = screenshots[i];
          screenshot.getScreenshotUIManager().open();
          bpListener.addScreenshot(screenshot);
        }

        if (screenshots != null && screenshots.length != 0) {
          GestureSubmitter.logSnapshotTaken("JavaFX", debugger);
          return;
        }
      } finally {
        ph.finish();
      }
      msg = NbBundle.getMessage(TakeScreenshotActionProvider.class, "MSG_NoScreenshots");
    } catch (RetrievalException ex) {
      msg = ex.getLocalizedMessage();
      if (ex.getCause() != null) {
        Exceptions.printStackTrace(ex);
      }
    } finally {
      setEnabled(ScreenshotUIManager.ACTION_TAKE_SCREENSHOT, true);
    }
    if (msg != null) {
      NotifyDescriptor nd = new NotifyDescriptor.Message(msg);
      DialogDisplayer.getDefault().notify(nd);
    }
  }
コード例 #28
0
  @Override
  public void actionPerformed(ActionEvent e) {
    JFileChooser fc = new JFileChooser();
    fc.setFileFilter(ImportAction.getFileFilter());
    fc.setCurrentDirectory(
        new File(Settings.get().get(Settings.DIRECTORY, Settings.DIRECTORY_DEFAULT)));
    fc.setMultiSelectionEnabled(true);

    if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
      for (final File file : fc.getSelectedFiles()) {
        File dir = file;
        if (!dir.isDirectory()) {
          dir = dir.getParentFile();
        }

        Settings.get().put(Settings.DIRECTORY, dir.getAbsolutePath());
        try {
          final FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.READ);
          final ProgressHandle handle =
              ProgressHandleFactory.createHandle("Opening file " + file.getName());
          handle.start(WORKUNITS);
          final long startTime = System.currentTimeMillis();
          final long start = channel.size();
          ParseMonitor monitor =
              new ParseMonitor() {
                @Override
                public void updateProgress() {
                  try {
                    int prog = (int) (WORKUNITS * (double) channel.position() / (double) start);
                    handle.progress(prog);
                  } catch (IOException ex) {
                  }
                }

                @Override
                public void setState(String state) {
                  updateProgress();
                  handle.progress(state);
                }
              };
          final GraphParser parser;
          final OutlineTopComponent component = OutlineTopComponent.findInstance();
          if (file.getName().endsWith(".xml")) {
            parser = new Parser(channel, monitor, null);
          } else if (file.getName().endsWith(".bgv")) {
            parser = new BinaryParser(channel, monitor, component.getDocument(), null);
          } else {
            parser = null;
          }
          RequestProcessor.getDefault()
              .post(
                  new Runnable() {
                    @Override
                    public void run() {
                      try {
                        final GraphDocument document = parser.parse();
                        if (document != null) {
                          SwingUtilities.invokeLater(
                              new Runnable() {
                                @Override
                                public void run() {
                                  component.requestActive();
                                  component.getDocument().addGraphDocument(document);
                                }
                              });
                        }
                      } catch (IOException ex) {
                        Exceptions.printStackTrace(ex);
                      }
                      handle.finish();
                      long stop = System.currentTimeMillis();
                      Logger.getLogger(getClass().getName())
                          .log(
                              Level.INFO,
                              "Loaded in "
                                  + file
                                  + " in "
                                  + ((stop - startTime) / 1000.0)
                                  + " seconds");
                    }
                  });
        } catch (FileNotFoundException ex) {
          Exceptions.printStackTrace(ex);
        } catch (IOException ex) {
          Exceptions.printStackTrace(ex);
        }
      }
    }
  }
コード例 #29
0
  public boolean generateTarget(ProgressHandle ph, String target) {
    if (mapping.getServiceMapping(target) != null) {
      String msg = NbBundle.getMessage(ClientJavonTemplate.class, "MSG_Client"); // NOI18N
      ph.progress(msg);
      OutputLogger.getInstance().log(msg);
      mapping.setProperty("target", "client");

      JavonMapping.Service service = mapping.getServiceMapping(target);
      FileObject outputDir =
          FileUtil.toFileObject(
              FileUtil.normalizeFile(new File(mapping.getClientMapping().getOutputDirectory())));
      outputDir =
          outputDir.getFileObject(mapping.getClientMapping().getPackageName().replace('.', '/'));

      FileObject outputFile =
          outputDir.getFileObject(mapping.getClientMapping().getClassName(), "java");
      if (outputFile == null) {
        OutputLogger.getInstance()
            .log(
                MessageFormat.format(
                    NbBundle.getMessage(ClientJavonTemplate.class, "MSG_ClientJavonCreation"),
                    mapping.getClientMapping().getClassName())); // NOI18N
        try {
          outputFile = outputDir.createData(mapping.getClientMapping().getClassName(), "java");
        } catch (IOException e) {
          OutputLogger.getInstance()
              .log(
                  LogLevel.ERROR,
                  MessageFormat.format(
                      NbBundle.getMessage(ClientJavonTemplate.class, "MSG_FailClientJavonCreation"),
                      mapping.getClientMapping().getClassName())); // NOI18N
        }
      }
      OutputFileFormatter off = null;
      try {
        off = new OutputFileFormatter(outputFile);
      } catch (DataObjectNotFoundException e) {
        generationFailed(e, outputFile);
        return false;
      } catch (IOException e) {
        generationFailed(e, outputFile);
        return false;
      }

      ScriptEngineManager mgr = new ScriptEngineManager();
      ScriptEngine eng = mgr.getEngineByName("freemarker");
      Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);

      FileObject template = FileUtil.getConfigFile("Templates/Client/Client.java");

      OutputLogger.getInstance()
          .log(NbBundle.getMessage(ClientJavonTemplate.class, "MSG_ConfigureBindings")); // NOI18N
      Set<ClassData> returnTypes = service.getReturnTypes();
      Set<ClassData> parameterTypes = service.getParameterTypes();
      bind.put("mapping", mapping);
      bind.put("registry", mapping.getRegistry());
      bind.put("returnTypes", returnTypes);
      bind.put("parameterTypes", parameterTypes);
      bind.put("service", service);
      bind.put("utils", new Utils(mapping.getRegistry()));

      // Compute imports for JavaBeans
      Set<String> imports = new HashSet<String>();
      for (ClassData cd : parameterTypes) {
        while (cd.isArray()) {
          cd = cd.getComponentType();
        }
        if (cd.isPrimitive()) continue;
        if (cd.getPackage().equals("java.lang")) continue;
        if (cd.getFullyQualifiedName().equals("java.util.List")) continue;
        imports.add(cd.getFullyQualifiedName());
      }
      for (ClassData cd : returnTypes) {
        while (cd.isArray()) {
          cd = cd.getComponentType();
        }
        if (cd.isPrimitive()) continue;
        if (cd.getPackage().equals("java.lang")) continue;
        if (cd.getFullyQualifiedName().equals("java.util.List")) continue;
        imports.add(cd.getFullyQualifiedName());
      }
      bind.put("imports", imports);

      OutputLogger.getInstance()
          .log(
              MessageFormat.format(
                  NbBundle.getMessage(ClientBeanGeneratorTemplate.class, "MSG_GenerateJavonClient"),
                  FileUtil.toFile(outputFile))); // NOI18N
      Writer w = null;
      Reader is = null;
      try {
        try {
          w = new StringWriter();
          is = new InputStreamReader(template.getInputStream());

          eng.getContext().setWriter(w);
          eng.getContext()
              .setAttribute(FileObject.class.getName(), template, ScriptContext.ENGINE_SCOPE);
          eng.getContext()
              .setAttribute(
                  ScriptEngine.FILENAME, template.getNameExt(), ScriptContext.ENGINE_SCOPE);

          eng.eval(is);
        } catch (FileNotFoundException e) {
          OutputLogger.getInstance().log(e);
          ErrorManager.getDefault().notify(e);
          return false;
        } catch (ScriptException e) {
          OutputLogger.getInstance().log(e);
          ErrorManager.getDefault().notify(e);
          return false;
        } finally {
          if (w != null) {
            off.write(w.toString());
            // System.err.println( "" + w.toString());
            w.close();
          }
          if (is != null) is.close();
          off.close();
        }
      } catch (IOException e) {
        generationFailed(e, FileUtil.toFile(outputFile));
        return false;
      }

      OutputLogger.getInstance()
          .log(
              MessageFormat.format(
                  NbBundle.getMessage(ClientJavonTemplate.class, "MSG_ClientGenerated"),
                  FileUtil.toFile(outputFile)));
    }
    return true;
  }
コード例 #30
0
  /**
   * Executes given JPQL query and returns the result.
   *
   * @param jpql the query
   * @return JPQLResult containing the execution result (including any errors).
   */
  public JPQLResult execute(
      String jpql,
      PersistenceUnit pu,
      PersistenceEnvironment pe,
      int maxRowCount,
      ProgressHandle ph) {
    JPQLResult result = new JPQLResult();
    try {
      ph.progress(60);

      Class pClass =
          Thread.currentThread().getContextClassLoader().loadClass("javax.persistence.Persistence");
      javax.persistence.Persistence p = (javax.persistence.Persistence) pClass.newInstance();

      EntityManagerFactory emf = p.createEntityManagerFactory(pu.getName());

      EntityManager em = emf.createEntityManager();

      Query query = em.createQuery(jpql);
      //
      Provider provider = ProviderUtil.getProvider(pu);
      String queryStr = null;
      if (provider.equals(ProviderUtil.ECLIPSELINK_PROVIDER)) { // NOI18N
        Class qClass = Thread.currentThread().getContextClassLoader().loadClass(ECLIPSELINK_QUERY);
        if (qClass != null) {
          Method method = qClass.getMethod(ECLIPSELINK_QUERY_SQL0);
          if (method != null) {
            Object dqOject = method.invoke(query);
            Method method2 =
                (dqOject != null ? dqOject.getClass().getMethod(ECLIPSELINK_QUERY_SQL1) : null);
            if (method2 != null) {
              queryStr = (String) method2.invoke(dqOject);
            }
          }
        }
      }
      //            else if (provider.equals(ProviderUtil.HIBERNATE_PROVIDER2_0)){//NOI18N
      //                Class qClass =
      // Thread.currentThread().getContextClassLoader().loadClass(HIBERNATE_QUERY);
      //                if(qClass !=null) {
      //                    Method method = qClass.getMethod(HIBERNATE_QUERY_SQL);
      //                    if(method != null){
      //                        queryStr = (String) method.invoke(query);
      //                    }
      //                }
      //            } else if (provider.getProviderClass().contains("openjpa")){//NOI18N
      //                Class qClass =
      // Thread.currentThread().getContextClassLoader().loadClass(OPENJPA_QUERY);
      //                if(qClass !=null) {
      //                    Method method = qClass.getMethod(OPENJPA_QUERY_SQL);
      //                    if(method != null){
      //                        queryStr = (String) method.invoke(query);
      //                    }
      //                }
      //            }
      result.setSqlQuery(queryStr);
      //
      ph.progress(70);

      query.setMaxResults(maxRowCount);

      jpql = jpql.trim();
      jpql = jpql.toUpperCase();

      if (jpql.startsWith("UPDATE") || jpql.startsWith("DELETE")) { // NOI18N
        result.setUpdateOrDeleteResult(query.executeUpdate());
      } else {
        result.setQueryResults(query.getResultList());
      }
    } catch (Exception e) {
      result.getExceptions().add(e);
    }
    return result;
  }