Autopsy  4.17.0
Graphical digital forensics platform for The Sleuth Kit and other tools.
ExtractActionHelper.java
Go to the documentation of this file.
1 /*
2  * Autopsy Forensic Browser
3  *
4  * Copyright 2013-2019 Basis Technology Corp.
5  * Contact: carrier <at> sleuthkit <dot> org
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this content except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19 package org.sleuthkit.autopsy.directorytree.actionhelpers;
20 
21 import java.awt.Component;
22 import java.awt.event.ActionEvent;
23 import java.io.File;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.HashSet;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Set;
30 import java.util.concurrent.ExecutionException;
31 import java.util.logging.Level;
32 import javax.swing.JFileChooser;
33 import javax.swing.JOptionPane;
34 import javax.swing.SwingWorker;
35 import org.netbeans.api.progress.ProgressHandle;
36 import org.openide.util.Cancellable;
37 import org.openide.util.NbBundle;
38 import org.openide.util.NbBundle.Messages;
45 import org.sleuthkit.datamodel.AbstractFile;
46 
50 public class ExtractActionHelper {
51 
52  private final Logger logger = Logger.getLogger(ExtractActionHelper.class.getName());
53  private String userDefinedExportPath;
54 
63  public void extract(ActionEvent event, Collection<? extends AbstractFile> selectedFiles) {
64  if (selectedFiles.size() > 1) {
65  extractFiles(event, selectedFiles);
66  } else if (selectedFiles.size() == 1) {
67  AbstractFile source = selectedFiles.iterator().next();
68  if (source.isDir()) {
69  extractFiles(event, selectedFiles);
70  } else {
71  extractFile(event, selectedFiles.iterator().next());
72  }
73  }
74  }
75 
82  @NbBundle.Messages({"ExtractActionHelper.noOpenCase.errMsg=No open case available."})
83  private void extractFile(ActionEvent event, AbstractFile selectedFile) {
84  Case openCase;
85  try {
86  openCase = Case.getCurrentCaseThrows();
87  } catch (NoCurrentCaseException ex) {
88  JOptionPane.showMessageDialog((Component) event.getSource(), Bundle.ExtractActionHelper_noOpenCase_errMsg());
89  logger.log(Level.INFO, "Exception while getting open case.", ex); //NON-NLS
90  return;
91  }
92  JFileChooser fileChooser = new JFileChooser();
93  fileChooser.setCurrentDirectory(new File(getExportDirectory(openCase)));
94  // If there is an attribute name, change the ":". Otherwise the extracted file will be hidden
95  fileChooser.setSelectedFile(new File(FileUtil.escapeFileName(selectedFile.getName())));
96  if (fileChooser.showSaveDialog((Component) event.getSource()) == JFileChooser.APPROVE_OPTION) {
97  updateExportDirectory(fileChooser.getSelectedFile().getParent(), openCase);
98 
99  ArrayList<FileExtractionTask> fileExtractionTasks = new ArrayList<>();
100  fileExtractionTasks.add(new FileExtractionTask(selectedFile, fileChooser.getSelectedFile()));
101  runExtractionTasks(event, fileExtractionTasks, fileChooser.getSelectedFile().getName());
102  }
103  }
104 
111  private void extractFiles(ActionEvent event, Collection<? extends AbstractFile> selectedFiles) {
112  Case openCase;
113  try {
114  openCase = Case.getCurrentCaseThrows();
115  } catch (NoCurrentCaseException ex) {
116  JOptionPane.showMessageDialog((Component) event.getSource(), Bundle.ExtractActionHelper_noOpenCase_errMsg());
117  logger.log(Level.INFO, "Exception while getting open case.", ex); //NON-NLS
118  return;
119  }
120  JFileChooser folderChooser = new JFileChooser();
121  folderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
122  folderChooser.setCurrentDirectory(new File(getExportDirectory(openCase)));
123  if (folderChooser.showSaveDialog((Component) event.getSource()) == JFileChooser.APPROVE_OPTION) {
124  File destinationFolder = folderChooser.getSelectedFile();
125  if (!destinationFolder.exists()) {
126  try {
127  destinationFolder.mkdirs();
128  } catch (Exception ex) {
129  JOptionPane.showMessageDialog((Component) event.getSource(), NbBundle.getMessage(this.getClass(),
130  "ExtractAction.extractFiles.cantCreateFolderErr.msg"));
131  logger.log(Level.INFO, "Unable to create folder(s) for user " + destinationFolder.getAbsolutePath(), ex); //NON-NLS
132  return;
133  }
134  }
135  updateExportDirectory(destinationFolder.getPath(), openCase);
136 
137  /*
138  * get the unique set of files from the list. A user once reported
139  * extraction taking days because it was extracting the same PST
140  * file 20k times. They selected 20k email messages in the tree and
141  * chose to extract them.
142  */
143  Set<AbstractFile> uniqueFiles = new HashSet<>(selectedFiles);
144 
145  // make a task for each file
146  ArrayList<FileExtractionTask> fileExtractionTasks = new ArrayList<>();
147  for (AbstractFile source : uniqueFiles) {
148  // If there is an attribute name, change the ":". Otherwise the extracted file will be hidden
149  fileExtractionTasks.add(new FileExtractionTask(source, new File(destinationFolder, source.getId() + "-" + FileUtil.escapeFileName(source.getName()))));
150  }
151  runExtractionTasks(event, fileExtractionTasks, destinationFolder.getName());
152  }
153  }
154 
162  private String getExportDirectory(Case openCase) {
163  String caseExportPath = openCase.getExportDirectory();
164 
165  if (userDefinedExportPath == null) {
166  return caseExportPath;
167  }
168 
169  File file = new File(userDefinedExportPath);
170  if (file.exists() == false || file.isDirectory() == false) {
171  return caseExportPath;
172  }
173 
174  return userDefinedExportPath;
175  }
176 
186  private void updateExportDirectory(String exportPath, Case openCase) {
187  if (exportPath.equalsIgnoreCase(openCase.getExportDirectory())) {
188  userDefinedExportPath = null;
189  } else {
190  userDefinedExportPath = exportPath;
191  }
192  }
193 
203  private void runExtractionTasks(ActionEvent event, List<FileExtractionTask> fileExtractionTasks, String destName) {
204 
205  // verify all of the sources and destinations are OK
206  for (Iterator<FileExtractionTask> it = fileExtractionTasks.iterator(); it.hasNext();) {
207  FileExtractionTask task = it.next();
208 
209  if (ContentUtils.isDotDirectory(task.source)) {
210  it.remove();
211  continue;
212  }
213 
214  /*
215  * This code assumes that each destination is unique. We previously
216  * satisfied that by adding the unique ID.
217  */
218  if (task.destination.exists()) {
219  if (JOptionPane.showConfirmDialog((Component) event.getSource(),
220  NbBundle.getMessage(this.getClass(), "ExtractActionHelper.confDlg.destFileExist.msg", task.destination.getAbsolutePath()),
221  NbBundle.getMessage(this.getClass(), "ExtractActionHelper.confDlg.destFileExist.title"),
222  JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
223  if (!FileUtil.deleteFileDir(task.destination)) {
224  JOptionPane.showMessageDialog((Component) event.getSource(),
225  NbBundle.getMessage(this.getClass(), "ExtractActionHelper.msgDlg.cantOverwriteFile.msg", task.destination.getAbsolutePath()));
226  it.remove();
227  }
228  } else {
229  it.remove();
230  }
231  }
232  }
233 
234  // launch a thread to do the work
235  if (!fileExtractionTasks.isEmpty()) {
236  try {
237  FileExtracter extracter = new FileExtracter(fileExtractionTasks, destName);
238  extracter.execute();
239  } catch (Exception ex) {
240  logger.log(Level.WARNING, "Unable to start background file extraction thread", ex); //NON-NLS
241  }
242  } else {
244  NbBundle.getMessage(this.getClass(), "ExtractActionHelper.notifyDlg.noFileToExtr.msg"));
245  }
246  }
247 
251  private class FileExtractionTask {
252 
253  AbstractFile source;
254  File destination;
255 
262  FileExtractionTask(AbstractFile source, File destination) {
263  this.source = source;
264  this.destination = destination;
265  }
266  }
267 
271  private class FileExtracter extends SwingWorker<Object, Void> {
272 
273  private final Logger logger = Logger.getLogger(FileExtracter.class.getName());
274  private final String destName;
275  private ProgressHandle progress;
276  private final List<FileExtractionTask> extractionTasks;
277 
285  FileExtracter(List<FileExtractionTask> extractionTasks, String destName) {
286  this.extractionTasks = extractionTasks;
287  this.destName = destName;
288  }
289 
290  @Override
291  @Messages({
292  "# {0} - outputFolderName",
293  "ExtractActionHelper.progress.extracting=Extracting to {0}",
294  "# {0} - fileName",
295  "ExtractActionHelper.progress.fileExtracting=Extracting file: {0}"
296  })
297  protected Object doInBackground() throws Exception {
298  if (extractionTasks.isEmpty()) {
299  return null;
300  }
301 
302  // Setup progress bar.
303  final String displayName = Bundle.ExtractActionHelper_progress_extracting(destName);
304  progress = ProgressHandle.createHandle(displayName, new Cancellable() {
305  @Override
306  public boolean cancel() {
307  if (progress != null) {
308  progress.setDisplayName(
309  NbBundle.getMessage(this.getClass(), "ExtractActionHelper.progress.cancellingExtraction", displayName));
310  }
311  return ExtractActionHelper.FileExtracter.this.cancel(true);
312  }
313  });
314  progress.start();
315  progress.switchToIndeterminate();
316 
317  // Do the extraction tasks.
318  for (FileExtractionTask task : this.extractionTasks) {
319  progress.progress(Bundle.ExtractActionHelper_progress_fileExtracting(task.destination.getName()));
320 
321  ContentUtils.ExtractFscContentVisitor.extract(task.source, task.destination, null, this);
322  }
323 
324  return null;
325  }
326 
327  @Override
328  protected void done() {
329  boolean msgDisplayed = false;
330  try {
331  super.get();
332  } catch (InterruptedException | ExecutionException ex) {
333  logger.log(Level.SEVERE, "Fatal error during file extraction", ex); //NON-NLS
335  NbBundle.getMessage(this.getClass(), "ExtractActionHelper.done.notifyMsg.extractErr", ex.getMessage()));
336  msgDisplayed = true;
337  } finally {
338  progress.finish();
339  if (!this.isCancelled() && !msgDisplayed) {
341  NbBundle.getMessage(this.getClass(), "ExtractActionHelper.done.notifyMsg.fileExtr.text"));
342  }
343  }
344  }
345 
354  /*
355  * private int calculateProgressBarWorkUnits(AbstractFile file) { int
356  * workUnits = 0; if (file.isFile()) { workUnits += file.getSize(); }
357  * else { try { for (Content child : file.getChildren()) { if (child
358  * instanceof AbstractFile) { workUnits +=
359  * calculateProgressBarWorkUnits((AbstractFile) child); } } } catch
360  * (TskCoreException ex) { logger.log(Level.SEVERE, "Could not get
361  * children of content", ex); //NON-NLS } } return workUnits; }
362  */
363  }
364 }
void extractFiles(ActionEvent event, Collection<?extends AbstractFile > selectedFiles)
void runExtractionTasks(ActionEvent event, List< FileExtractionTask > fileExtractionTasks, String destName)
static boolean deleteFileDir(File path)
Definition: FileUtil.java:87
static< T, V > void extract(Content cntnt, java.io.File dest, ProgressHandle progress, SwingWorker< T, V > worker)
void extract(ActionEvent event, Collection<?extends AbstractFile > selectedFiles)
static String escapeFileName(String fileName)
Definition: FileUtil.java:169
synchronized static Logger getLogger(String name)
Definition: Logger.java:124
void extractFile(ActionEvent event, AbstractFile selectedFile)
static boolean isDotDirectory(AbstractFile dir)

Copyright © 2012-2021 Basis Technology. Generated on: Tue Jan 19 2021
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.