@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; }
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; } }
@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); } }
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(); } }
@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); } }
/* 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(); } }
private void done() { progress.finish(); if (warnings != null) { ProjectDialogManager.getDefault() .showWarningsDialog(DefaultPraxisProject.this, warnings, level); } actionsEnabled = true; }
@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; }
@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())); } } }
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); } }
@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(); } }
synchronized void hide() { progressHandle.finish(); }
@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); } }
public static synchronized ServiceGeneratorResult generate(final E2EDataObject dataObject) { if (dataObject.getServerProject() == null) { final NotifyDescriptor.Message dd = new NotifyDescriptor.Message( NbBundle.getMessage( E2EDataObject.class, "ERR_ServerProjectNotOpened", // NOI18N dataObject.getConfiguration().getServerConfigutation().getProjectName())); DialogDisplayer.getDefault().notify(dd); if (Util.openProject(dataObject.getConfiguration().getServerConfigutation().getProjectPath()) == null) { // It is OK don't notify user here. All notifications // are already inside <code>openProject</code> method return null; } } // Call save before generate final SaveCookie saveCookie = dataObject.getCookie(SaveCookie.class); if (saveCookie != null) { try { saveCookie.save(); } catch (IOException ex) { ErrorManager.getDefault().notify(ex); } } // Get configuration final Configuration config = dataObject.getConfiguration(); if (config == null) { final NotifyDescriptor.Message dd = new NotifyDescriptor.Message( NbBundle.getMessage(E2EDataObject.class, "ERR_ConfigurationFileCorrupted")); // NOI18N DialogDisplayer.getDefault().notify(dd); return null; } if (Configuration.WSDLCLASS_TYPE.equals(config.getServiceType())) { final FileObject fo = dataObject .getServerProject() .getProjectDirectory() .getFileObject("build/generated/wsimport/"); // NOI18N if (fo == null) { DialogDisplayer.getDefault() .notify( new NotifyDescriptor.Message( NbBundle.getMessage( ConnectionGenerator.class, "MSG_WebProjectNotBuilt"))); // NOI18N return null; } } /* * All failures notifications was done via dialog windows. * Starting now logging will be done via OutputLogger class. */ final ProgressHandle ph = ProgressHandleFactory.createHandle( NbBundle.getMessage(ConnectionGenerator.class, "MSG_GeneratingJavonBridge"), // NOI18N new AbstractAction() { public void actionPerformed(ActionEvent e) { OutputLogger.getInstance().open(); } }); ph.start(); ph.switchToIndeterminate(); String message = NbBundle.getMessage(ConnectionGenerator.class, "MSG_GeneratingProxyStubs"); // NOI18N ph.progress(message); OutputLogger.getInstance().log(message); // FIXME: check for proper type // config.getServices(); // if (Configuration.WSDLCLASS_TYPE.equals(config.getServiceType())) { ph.progress(NbBundle.getMessage(ConnectionGenerator.class, "MSG_GeneratingProxyStubs")); final ProxyGenerator pg = new ProxyGenerator(dataObject); final String className = pg.generate(); if (className == null) { ph.finish(); StatusDisplayer.getDefault() .setStatusText(NbBundle.getMessage(ConnectionGenerator.class, "MSG_Failure")); // NOI18N return null; } config.getServices().get(0).getData().get(0).setProxyClassType(className); } // JavonOutput[] outputs; // Type type = null; // // final InputOutput io = IOProvider.getDefault().getIO( // NbBundle.getMessage( ConnectionGenerator.class, "LBL_JavonTab" ) // NOI18N // , true); // final OutputWriter ow = io.getOut(); try { String scanning = NbBundle.getMessage(ConnectionGenerator.class, "MSG_ScanningDataStructures"); // NOI18N ph.progress(scanning); OutputLogger.getInstance().log(scanning); final JavonMappingImpl mapping = dataObject.getMapping(); if (Configuration.WSDLCLASS_TYPE.equals(config.getServiceType())) { mapping.setProperty("serviceType", "WSDL"); } else { mapping.setProperty("serviceType", "CLASS"); } // //ph.progress(70); String creating = NbBundle.getMessage(ConnectionGenerator.class, "MSG_CreatingJavaFiles"); // NOI18N ph.progress(creating); OutputLogger.getInstance().log(creating); // Javon javon = new Javon(mapping); if (javon.generate(ph)) { StatusDisplayer.getDefault() .setStatusText( NbBundle.getMessage(ConnectionGenerator.class, "MSG_SuccessGenerated")); // NOI18N OutputLogger.getInstance() .log(NbBundle.getMessage(ConnectionGenerator.class, "TXT_GenerationSuccess")); // NOI18N } else { StatusDisplayer.getDefault() .setStatusText(NbBundle.getMessage(ConnectionGenerator.class, "MSG_Failure")); // NOI18N OutputLogger.getInstance() .log( NbBundle.getMessage( ConnectionGenerator.class, "TXT_GenerationUnsuccess")); // NOI18N } // Streams.setOut(ow); // Streams.setErr(ow); // outputs = new Main().run( mapping, "" ); // NOI18N // // for( int j = 0; j < outputs.length; j++ ) { // final String list[] = outputs[j].getCreatedFiles(); // for( int i = 0; i < list.length; i++ ) { // final File f = new File(list[i]); // final FileObject fo = FileUtil.toFileObject(FileUtil.normalizeFile(f)); // fo.refresh(); // JavaModel.getResource(fo); // } // } // //add servlet to container // Util.addServletToWebProject(dataObject.getServerProject(), // dataObject.getConfiguration().getServerConfigutation().getClassDescriptor().getType()); // // final ClassDescriptor clientClassDescriptor = // dataObject.getConfiguration().getClientConfiguration().getClassDescriptor(); // final Sources s = ProjectUtils.getSources(dataObject.getClientProject()); // final SourceGroup sourceGroup = Util.getPreselectedGroup( // s.getSourceGroups( JavaProjectConstants.SOURCES_TYPE_JAVA ), // clientClassDescriptor.getLocation()); // final FileObject srcDirectory = sourceGroup.getRootFolder(); // final ClassPath cp = ClassPath.getClassPath(srcDirectory,ClassPath.SOURCE); // JavaModel.getJavaRepository().beginTrans(false); // try { // JavaModel.setClassPath(cp); // type = // JavaModel.getDefaultExtent().getType().resolve(clientClassDescriptor.getType()); // } catch (Exception e){ // ErrorManager.getDefault().notify(e); // } finally { // JavaModel.getJavaRepository().endTrans(); // } } finally { ph.finish(); OutputLogger.getInstance().close(); } // if (type != null){ // //ow.println("Run / Redeploy Web Project to get changes reflected!"); // StatusDisplayer.getDefault().setStatusText(NbBundle.getMessage( // ConnectionGenerator.class, "MSG_SuccessGenerated" )); // NOI18N // } else { // StatusDisplayer.getDefault().setStatusText(NbBundle.getMessage( // ConnectionGenerator.class, "MSG_Failure" )); // NOI18N // return null; // } // final JavaClass resultClass = (JavaClass)type; // final List<Feature> features = resultClass.getFeatures(); // final List<Method> methods = new ArrayList<Method>(); // for ( final Feature elem : features ) { // if (elem instanceof Method){ // final Method m = (Method)elem; // if ("getGroupedResults".equals(m.getName())){ //NOI18N //not supported // continue; // } // if (m.getName().endsWith("Grouped")){ //NOI18N //not supported // continue; // } // if ( Modifier.isPublic(m.getModifiers()) ){ // methods.add(m); // } // } // } // return new ServiceGeneratorResult(resultClass, // methods.toArray(new Method[methods.size()]), // Util.getServerURL(dataObject.getServerProject(), // dataObject.getConfiguration())); return null; }
/** * Unpack the file to local folder and return a list of derived files * * @param pipelineContext current ingest context * @param archiveFile file to unpack * @return list of unpacked derived files */ void unpack(AbstractFile archiveFile) { String archiveFilePath; try { archiveFilePath = archiveFile.getUniquePath(); } catch (TskCoreException ex) { archiveFilePath = archiveFile.getParentPath() + archiveFile.getName(); } // check if already has derived files, skip try { if (archiveFile.hasChildren()) { // check if local unpacked dir exists if (new File(EmbeddedFileExtractorIngestModule.getUniqueName(archiveFile)).exists()) { logger.log( Level.INFO, "File already has been processed as it has children and local unpacked file, skipping: {0}", archiveFilePath); // NON-NLS return; } } } catch (TskCoreException e) { logger.log( Level.INFO, "Error checking if file already has been processed, skipping: {0}", archiveFilePath); // NON-NLS return; } List<AbstractFile> unpackedFiles = Collections.<AbstractFile>emptyList(); // recursion depth check for zip bomb final long archiveId = archiveFile.getId(); SevenZipExtractor.ArchiveDepthCountTree.Archive parentAr = archiveDepthCountTree.findArchive(archiveId); if (parentAr == null) { parentAr = archiveDepthCountTree.addArchive(null, archiveId); } else if (parentAr.getDepth() == MAX_DEPTH) { String msg = NbBundle.getMessage( this.getClass(), "EmbeddedFileExtractorIngestModule.ArchiveExtractor.unpack.warnMsg.zipBomb", archiveFile.getName()); String details = NbBundle.getMessage( this.getClass(), "EmbeddedFileExtractorIngestModule.ArchiveExtractor.unpack.warnDetails.zipBomb", parentAr.getDepth(), archiveFilePath); // MessageNotifyUtil.Notify.error(msg, details); services.postMessage( IngestMessage.createWarningMessage( EmbeddedFileExtractorModuleFactory.getModuleName(), msg, details)); return; } boolean hasEncrypted = false; boolean fullEncryption = true; ISevenZipInArchive inArchive = null; SevenZipContentReadStream stream = null; final ProgressHandle progress = ProgressHandleFactory.createHandle( NbBundle.getMessage( this.getClass(), "EmbeddedFileExtractorIngestModule.ArchiveExtractor.moduleName")); int processedItems = 0; boolean progressStarted = false; try { stream = new SevenZipContentReadStream(new ReadContentInputStream(archiveFile)); // for RAR files we need to open them explicitly as RAR. Otherwise, if there is a ZIP archive // inside RAR archive // it will be opened incorrectly when using 7zip's built-in auto-detect functionality. // All other archive formats are still opened using 7zip built-in auto-detect functionality. ArchiveFormat options = get7ZipOptions(archiveFile); inArchive = SevenZip.openInArchive(options, stream); int numItems = inArchive.getNumberOfItems(); logger.log( Level.INFO, "Count of items in archive: {0}: {1}", new Object[] {archiveFilePath, numItems}); // NON-NLS progress.start(numItems); progressStarted = true; final ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface(); // setup the archive local root folder final String uniqueArchiveFileName = EmbeddedFileExtractorIngestModule.getUniqueName(archiveFile); final String localRootAbsPath = getLocalRootAbsPath(uniqueArchiveFileName); final File localRoot = new File(localRootAbsPath); if (!localRoot.exists()) { try { localRoot.mkdirs(); } catch (SecurityException e) { logger.log( Level.SEVERE, "Error setting up output path for archive root: {0}", localRootAbsPath); // NON-NLS // bail return; } } // initialize tree hierarchy to keep track of unpacked file structure SevenZipExtractor.UnpackedTree unpackedTree = new SevenZipExtractor.UnpackedTree( moduleDirRelative + "/" + uniqueArchiveFileName, archiveFile); long freeDiskSpace = services.getFreeDiskSpace(); // unpack and process every item in archive int itemNumber = 0; for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) { String pathInArchive = item.getPath(); if (pathInArchive == null || pathInArchive.isEmpty()) { // some formats (.tar.gz) may not be handled correctly -- file in archive has no name/path // handle this for .tar.gz and tgz but assuming the child is tar, // otherwise, unpack using itemNumber as name // TODO this should really be signature based, not extension based String archName = archiveFile.getName(); int dotI = archName.lastIndexOf("."); String useName = null; if (dotI != -1) { String base = archName.substring(0, dotI); String ext = archName.substring(dotI); switch (ext) { case ".gz": // NON-NLS useName = base; break; case ".tgz": // NON-NLS useName = base + ".tar"; // NON-NLS break; } } if (useName == null) { pathInArchive = "/" + archName + "/" + Integer.toString(itemNumber); } else { pathInArchive = "/" + useName; } String msg = NbBundle.getMessage( this.getClass(), "EmbeddedFileExtractorIngestModule.ArchiveExtractor.unpack.unknownPath.msg", archiveFilePath, pathInArchive); logger.log(Level.WARNING, msg); } ++itemNumber; logger.log(Level.INFO, "Extracted item path: {0}", pathInArchive); // NON-NLS // check if possible zip bomb if (isZipBombArchiveItemCheck(archiveFile, item)) { continue; // skip the item } // find this node in the hierarchy, create if needed SevenZipExtractor.UnpackedTree.UnpackedNode unpackedNode = unpackedTree.addNode(pathInArchive); String fileName = unpackedNode.getFileName(); // update progress bar progress.progress(archiveFile.getName() + ": " + fileName, processedItems); final boolean isEncrypted = item.isEncrypted(); final boolean isDir = item.isFolder(); if (isEncrypted) { logger.log( Level.WARNING, "Skipping encrypted file in archive: {0}", pathInArchive); // NON-NLS hasEncrypted = true; continue; } else { fullEncryption = false; } final Long size = item.getSize(); if (size == null) { // If the size property cannot be determined, out-of-disk-space // situations cannot be ascertained. // Hence skip this file. logger.log( Level.WARNING, "Size cannot be determined. Skipping file in archive: {0}", pathInArchive); // NON-NLS continue; } // check if unpacking this file will result in out of disk space // this is additional to zip bomb prevention mechanism if (freeDiskSpace != IngestMonitor.DISK_FREE_SPACE_UNKNOWN && size > 0) { // if known free space and file not empty long newDiskSpace = freeDiskSpace - size; if (newDiskSpace < MIN_FREE_DISK_SPACE) { String msg = NbBundle.getMessage( this.getClass(), "EmbeddedFileExtractorIngestModule.ArchiveExtractor.unpack.notEnoughDiskSpace.msg", archiveFilePath, fileName); String details = NbBundle.getMessage( this.getClass(), "EmbeddedFileExtractorIngestModule.ArchiveExtractor.unpack.notEnoughDiskSpace.details"); // MessageNotifyUtil.Notify.error(msg, details); services.postMessage( IngestMessage.createErrorMessage( EmbeddedFileExtractorModuleFactory.getModuleName(), msg, details)); logger.log( Level.INFO, "Skipping archive item due to insufficient disk space: {0}, {1}", new Object[] {archiveFilePath, fileName}); // NON-NLS logger.log( Level.INFO, "Available disk space: {0}", new Object[] {freeDiskSpace}); // NON-NLS continue; // skip this file } else { // update est. disk space during this archive, so we don't need to poll for every file // extracted freeDiskSpace = newDiskSpace; } } final String uniqueExtractedName = uniqueArchiveFileName + File.separator + (item.getItemIndex() / 1000) + File.separator + item.getItemIndex() + new File(pathInArchive).getName(); // final String localRelPath = unpackDir + File.separator + localFileRelPath; final String localRelPath = moduleDirRelative + File.separator + uniqueExtractedName; final String localAbsPath = moduleDirAbsolute + File.separator + uniqueExtractedName; // create local dirs and empty files before extracted File localFile = new java.io.File(localAbsPath); // cannot rely on files in top-bottom order if (!localFile.exists()) { try { if (isDir) { localFile.mkdirs(); } else { localFile.getParentFile().mkdirs(); try { localFile.createNewFile(); } catch (IOException ex) { logger.log( Level.SEVERE, "Error creating extracted file: " + localFile.getAbsolutePath(), ex); // NON-NLS } } } catch (SecurityException e) { logger.log( Level.SEVERE, "Error setting up output path for unpacked file: {0}", pathInArchive); // NON-NLS // TODO consider bail out / msg to the user } } // skip the rest of this loop if we couldn't create the file if (localFile.exists() == false) { continue; } final Date createTime = item.getCreationTime(); final Date accessTime = item.getLastAccessTime(); final Date writeTime = item.getLastWriteTime(); final long createtime = createTime == null ? 0L : createTime.getTime() / 1000; final long modtime = writeTime == null ? 0L : writeTime.getTime() / 1000; final long accesstime = accessTime == null ? 0L : accessTime.getTime() / 1000; // record derived data in unode, to be traversed later after unpacking the archive unpackedNode.addDerivedInfo( size, !isDir, 0L, createtime, accesstime, modtime, localRelPath); // unpack locally if a file if (!isDir) { SevenZipExtractor.UnpackStream unpackStream = null; try { unpackStream = new SevenZipExtractor.UnpackStream(localAbsPath); item.extractSlow(unpackStream); } catch (Exception e) { // could be something unexpected with this file, move on logger.log( Level.WARNING, "Could not extract file from archive: " + localAbsPath, e); // NON-NLS } finally { if (unpackStream != null) { unpackStream.close(); } } } // update units for progress bar ++processedItems; } // add them to the DB. We wait until the end so that we have the metadata on all of the // intermediate nodes since the order is not guaranteed try { unpackedTree.addDerivedFilesToCase(); unpackedFiles = unpackedTree.getAllFileObjects(); // check if children are archives, update archive depth tracking for (AbstractFile unpackedFile : unpackedFiles) { if (isSevenZipExtractionSupported(unpackedFile)) { archiveDepthCountTree.addArchive(parentAr, unpackedFile.getId()); } } } catch (TskCoreException e) { logger.log( Level.SEVERE, "Error populating complete derived file hierarchy from the unpacked dir structure"); // NON-NLS // TODO decide if anything to cleanup, for now bailing } } catch (SevenZipException ex) { logger.log(Level.SEVERE, "Error unpacking file: " + archiveFile, ex); // NON-NLS // inbox message // print a message if the file is allocated if (archiveFile.isMetaFlagSet(TskData.TSK_FS_META_FLAG_ENUM.ALLOC)) { String msg = NbBundle.getMessage( this.getClass(), "EmbeddedFileExtractorIngestModule.ArchiveExtractor.unpack.errUnpacking.msg", archiveFile.getName()); String details = NbBundle.getMessage( this.getClass(), "EmbeddedFileExtractorIngestModule.ArchiveExtractor.unpack.errUnpacking.details", archiveFilePath, ex.getMessage()); services.postMessage( IngestMessage.createErrorMessage( EmbeddedFileExtractorModuleFactory.getModuleName(), msg, details)); } } finally { if (inArchive != null) { try { inArchive.close(); } catch (SevenZipException e) { logger.log(Level.SEVERE, "Error closing archive: " + archiveFile, e); // NON-NLS } } if (stream != null) { try { stream.close(); } catch (IOException ex) { logger.log( Level.SEVERE, "Error closing stream after unpacking archive: " + archiveFile, ex); // NON-NLS } } // close progress bar if (progressStarted) { progress.finish(); } } // create artifact and send user message if (hasEncrypted) { String encryptionType = fullEncryption ? ENCRYPTION_FULL : ENCRYPTION_FILE_LEVEL; try { BlackboardArtifact artifact = archiveFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_ENCRYPTION_DETECTED); artifact.addAttribute( new BlackboardAttribute( BlackboardAttribute.ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), EmbeddedFileExtractorModuleFactory.getModuleName(), encryptionType)); services.fireModuleDataEvent( new ModuleDataEvent( EmbeddedFileExtractorModuleFactory.getModuleName(), BlackboardArtifact.ARTIFACT_TYPE.TSK_ENCRYPTION_DETECTED)); } catch (TskCoreException ex) { logger.log( Level.SEVERE, "Error creating blackboard artifact for encryption detected for file: " + archiveFilePath, ex); // NON-NLS } String msg = NbBundle.getMessage( this.getClass(), "EmbeddedFileExtractorIngestModule.ArchiveExtractor.unpack.encrFileDetected.msg"); String details = NbBundle.getMessage( this.getClass(), "EmbeddedFileExtractorIngestModule.ArchiveExtractor.unpack.encrFileDetected.details", archiveFile.getName(), EmbeddedFileExtractorModuleFactory.getModuleName()); services.postMessage( IngestMessage.createWarningMessage( EmbeddedFileExtractorModuleFactory.getModuleName(), msg, details)); } // adding unpacked extracted derived files to the job after closing relevant resources. if (!unpackedFiles.isEmpty()) { // currently sending a single event for all new files services.fireModuleContentEvent(new ModuleContentEvent(archiveFile)); context.addFilesToJob(unpackedFiles); } }