Autopsy  4.7.0
Graphical digital forensics platform for The Sleuth Kit and other tools.
AdHocSearchChildFactory.java
Go to the documentation of this file.
1 /*
2  * Autopsy Forensic Browser
3  *
4  * Copyright 2011-2018 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.keywordsearch;
20 
21 import java.awt.EventQueue;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.Collection;
25 import java.util.HashMap;
26 import java.util.LinkedHashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.concurrent.CancellationException;
30 import java.util.concurrent.ExecutionException;
31 import java.util.logging.Level;
32 import java.util.stream.Collectors;
33 import java.util.stream.Stream;
34 import javax.swing.SwingWorker;
35 import org.netbeans.api.progress.ProgressHandle;
36 import org.openide.nodes.ChildFactory;
37 import org.openide.nodes.Children;
38 import org.openide.nodes.Node;
39 import org.openide.util.NbBundle;
40 import org.openide.util.lookup.Lookups;
52 import org.sleuthkit.datamodel.AbstractFile;
53 import org.sleuthkit.datamodel.BlackboardArtifact;
54 import org.sleuthkit.datamodel.BlackboardAttribute;
55 import static org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE.TSK_KEYWORD;
56 import static org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW;
57 import static org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE.TSK_KEYWORD_REGEXP;
58 import org.sleuthkit.datamodel.Content;
59 import org.sleuthkit.datamodel.SleuthkitCase;
60 import org.sleuthkit.datamodel.TskCoreException;
61 
69 class AdHocSearchChildFactory extends ChildFactory<KeyValue> {
70 
71  private static final Logger logger = Logger.getLogger(AdHocSearchChildFactory.class.getName());
72 
73  //common properties (superset of all Node properties) to be displayed as columns
74  static final List<String> COMMON_PROPERTIES
75  = Stream.concat(
76  Stream.of(
77  TSK_KEYWORD,
78  TSK_KEYWORD_REGEXP,
79  TSK_KEYWORD_PREVIEW)
80  .map(BlackboardAttribute.ATTRIBUTE_TYPE::getDisplayName),
81  Arrays.stream(AbstractAbstractFileNode.AbstractFilePropertyType.values())
82  .map(Object::toString))
83  .collect(Collectors.toList());
84 
85  private final Collection<AdHocQueryRequest> queryRequests;
86 
87  AdHocSearchChildFactory(Collection<AdHocQueryRequest> queryRequests) {
88  this.queryRequests = queryRequests;
89  }
90 
98  @Override
99  protected boolean createKeys(List<KeyValue> toPopulate) {
100 
101  for (AdHocQueryRequest queryRequest : queryRequests) {
105  if (!queryRequest.getQuery().validate()) {
106  //TODO mark the particular query node RED
107  break;
108  }
109 
110  //JMTODO: It looks like this map is not actually used for anything...
111  Map<String, Object> map = queryRequest.getProperties();
112  /*
113  * make sure all common properties are displayed as columns (since
114  * we are doing lazy child Node load we need to preinitialize
115  * properties when sending parent Node)
116  */
117  COMMON_PROPERTIES.stream()
118  .forEach((propertyType) -> map.put(propertyType, ""));
119  map.put(TSK_KEYWORD.getDisplayName(), queryRequest.getQueryString());
120  map.put(TSK_KEYWORD_REGEXP.getDisplayName(), !queryRequest.getQuery().isLiteral());
121 
122  createFlatKeys(queryRequest.getQuery(), toPopulate);
123  }
124 
125  return true;
126  }
127 
135  @NbBundle.Messages({"KeywordSearchResultFactory.query.exception.msg=Could not perform the query "})
136  private boolean createFlatKeys(KeywordSearchQuery queryRequest, List<KeyValue> toPopulate) {
137 
141  QueryResults queryResults;
142  try {
143  queryResults = queryRequest.performQuery();
144  } catch (KeywordSearchModuleException | NoOpenCoreException ex) {
145  logger.log(Level.SEVERE, "Could not perform the query " + queryRequest.getQueryString(), ex); //NON-NLS
146  MessageNotifyUtil.Notify.error(Bundle.KeywordSearchResultFactory_query_exception_msg() + queryRequest.getQueryString(), ex.getCause().getMessage());
147  return false;
148  }
149  SleuthkitCase tskCase;
150  try {
151  tskCase = Case.getCurrentCaseThrows().getSleuthkitCase();
152  } catch (NoCurrentCaseException ex) {
153  logger.log(Level.SEVERE, "There was no case open.", ex); //NON-NLS
154  return false;
155  }
156 
157  int hitNumber = 0;
158  List<KeywordHitKey> tempList = new ArrayList<>();
159  for (KeywordHit hit : getOneHitPerObject(queryResults)) {
160 
164  Map<String, Object> properties = new LinkedHashMap<>();
165  Content content;
166  String contentName;
167  try {
168  content = tskCase.getContentById(hit.getContentID());
169  if (content == null) {
170  logger.log(Level.SEVERE, "There was a error getting content by id."); //NON-NLS
171  return false;
172  }
173  } catch (TskCoreException ex) {
174  logger.log(Level.SEVERE, "There was a error getting content by id.", ex); //NON-NLS
175  return false;
176  }
177 
178  contentName = content.getName();
179  if (content instanceof AbstractFile) {
180  AbstractFsContentNode.fillPropertyMap(properties, (AbstractFile) content);
181  } else {
182  properties.put(LOCATION.toString(), contentName);
183  }
184 
188  if (hit.hasSnippet()) {
189  properties.put(TSK_KEYWORD_PREVIEW.getDisplayName(), hit.getSnippet());
190  }
191 
192  String hitName;
193  BlackboardArtifact artifact = null;
194  if (hit.isArtifactHit()) {
195  try {
196  artifact = tskCase.getBlackboardArtifact(hit.getArtifactID().get());
197  hitName = artifact.getDisplayName() + " Artifact"; //NON-NLS
198  } catch (TskCoreException ex) {
199  logger.log(Level.SEVERE, "Error getting blckboard artifact by id", ex);
200  return false;
201  }
202  } else {
203  hitName = contentName;
204  }
205  hitNumber++;
206  tempList.add(new KeywordHitKey(hitName, properties, hitNumber, hit.getSolrObjectId(), content, artifact, queryRequest, queryResults));
207 
208  }
209 
210  if (hitNumber == 0) {
211  toPopulate.add(new KeyValue("This KeyValue Is Empty", 0));
212  } else {
213  // Add all the nodes to toPopulate at once. Minimizes node creation
214  // EDT threads, which can slow and/or hang the UI on large queries.
215  toPopulate.addAll(tempList);
216  }
217 
218  //write to bb
219  //cannot reuse snippet in BlackboardResultWriter
220  //because for regex searches in UI we compress results by showing a content per regex once (even if multiple term hits)
221  //whereas in bb we write every hit per content separately
222  new BlackboardResultWriter(queryResults, queryRequest.getKeywordList().getName()).execute();
223 
224  return true;
225  }
226 
236  Collection<KeywordHit> getOneHitPerObject(QueryResults queryResults) {
237  HashMap<Long, KeywordHit> hits = new HashMap<>();
238  for (Keyword keyWord : queryResults.getKeywords()) {
239  for (KeywordHit hit : queryResults.getResults(keyWord)) {
240  // add hit with lowest SolrObjectID-Chunk-ID combination.
241  if (!hits.containsKey(hit.getSolrObjectId())) {
242  hits.put(hit.getSolrObjectId(), hit);
243  } else if (hit.getChunkId() < hits.get(hit.getSolrObjectId()).getChunkId()) {
244  hits.put(hit.getSolrObjectId(), hit);
245  }
246  }
247  }
248  return hits.values();
249  }
250 
251  @NbBundle.Messages({"KeywordSearchResultFactory.createNodeForKey.noResultsFound.text=No results found."})
252  @Override
253  protected Node createNodeForKey(KeyValue key) {
254  Node resultNode;
255 
256  if (key instanceof KeywordHitKey) {
257  AdHocQueryResult adHocQueryResult = new AdHocQueryResult((KeywordHitKey) key);
258 
263  ArrayList<Object> lookups = new ArrayList<>();
264  lookups.add(adHocQueryResult);
265  if (((KeywordHitKey) key).getContent() != null) {
266  lookups.add(((KeywordHitKey) key).getContent());
267  }
268  if (((KeywordHitKey) key).getArtifact() != null) {
269  lookups.add(((KeywordHitKey) key).getArtifact());
270  }
271 
272  Node kvNode = new KeyValueNode(key, Children.LEAF, Lookups.fixed(lookups.toArray()));
273 
274  //wrap in KeywordSearchFilterNode for the markup content, might need to override FilterNode for more customization
275  resultNode = new AdHocSearchFilterNode(kvNode);
276  } else {
277  resultNode = new EmptyNode("This Node Is Empty");
278  resultNode.setDisplayName(NbBundle.getMessage(this.getClass(), "KeywordSearchResultFactory.createNodeForKey.noResultsFound.text"));
279  }
280 
281  return resultNode;
282 
283  }
284 
289  final class AdHocQueryResult {
290 
291  private final long solrObjectId;
292  private final QueryResults results;
293 
301  AdHocQueryResult(KeywordHitKey key) {
302  this.solrObjectId = key.getSolrObjectId();
303  this.results = key.getHits();
304  }
305 
312  long getSolrObjectId() {
313  return solrObjectId;
314  }
315 
321  QueryResults getResults() {
322  return results;
323  }
324  }
325 
330  class KeywordHitKey extends KeyValue {
331 
332  private final long solrObjectId;
333 
334  private final Content content;
335  private final BlackboardArtifact artifact;
336  private final QueryResults hits;
337  private final KeywordSearchQuery query;
338 
353  KeywordHitKey(String name, Map<String, Object> map, int id, long solrObjectId, Content content, BlackboardArtifact artifact, KeywordSearchQuery query, QueryResults hits) {
354  super(name, map, id);
355  this.solrObjectId = solrObjectId;
356  this.content = content;
357  this.artifact = artifact;
358 
359  this.hits = hits;
360  this.query = query;
361  }
362 
363  Content getContent() {
364  return content;
365  }
366 
367  BlackboardArtifact getArtifact() {
368  return artifact;
369  }
370 
371  long getSolrObjectId() {
372  return solrObjectId;
373  }
374 
375  QueryResults getHits() {
376  return hits;
377  }
378 
379  KeywordSearchQuery getQuery() {
380  return query;
381  }
382  }
383 
388  static class BlackboardResultWriter extends SwingWorker<Void, Void> {
389 
390  private static final List<BlackboardResultWriter> WRITERS = new ArrayList<>();
391  private ProgressHandle progress;
392  private final KeywordSearchQuery query;
393  private final QueryResults hits;
394  private static final int QUERY_DISPLAY_LEN = 40;
395 
396  BlackboardResultWriter(QueryResults hits, String listName) {
397  this.hits = hits;
398  this.query = hits.getQuery();
399  }
400 
401  protected void finalizeWorker() {
402  deregisterWriter(this);
403  EventQueue.invokeLater(progress::finish);
404  }
405 
406  @Override
407  protected Void doInBackground() throws Exception {
408  registerWriter(this); //register (synchronized on class) outside of writerLock to prevent deadlock
409  final String queryStr = query.getQueryString();
410  final String queryDisp = queryStr.length() > QUERY_DISPLAY_LEN ? queryStr.substring(0, QUERY_DISPLAY_LEN - 1) + " ..." : queryStr;
411  try {
412  progress = ProgressHandle.createHandle(NbBundle.getMessage(this.getClass(), "KeywordSearchResultFactory.progress.saving", queryDisp), () -> BlackboardResultWriter.this.cancel(true));
413  hits.process(progress, null, this, false);
414  } finally {
415  finalizeWorker();
416  }
417  return null;
418  }
419 
420  @Override
421  protected void done() {
422  try {
423  get();
424  } catch (InterruptedException | CancellationException ex) {
425  logger.log(Level.WARNING, "User cancelled writing of ad hoc search query results for '{0}' to the blackboard", query.getQueryString()); //NON-NLS
426  } catch (ExecutionException ex) {
427  logger.log(Level.SEVERE, "Error writing of ad hoc search query results for " + query.getQueryString() + " to the blackboard", ex); //NON-NLS
428  }
429  }
430 
431  private static synchronized void registerWriter(BlackboardResultWriter writer) {
432  WRITERS.add(writer);
433  }
434 
435  private static synchronized void deregisterWriter(BlackboardResultWriter writer) {
436  WRITERS.remove(writer);
437  }
438 
439  static synchronized void stopAllWriters() {
440  for (BlackboardResultWriter w : WRITERS) {
441  w.cancel(true);
442  WRITERS.remove(w);
443  }
444  }
445  }
446 }

Copyright © 2012-2016 Basis Technology. Generated on: Mon Jun 18 2018
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.