19 package org.sleuthkit.datamodel;
21 import com.google.common.annotations.Beta;
22 import com.google.common.collect.ImmutableList;
23 import com.google.common.collect.ImmutableMap;
24 import java.sql.PreparedStatement;
25 import java.sql.ResultSet;
26 import java.sql.SQLException;
27 import java.sql.Statement;
28 import java.sql.Types;
29 import java.time.Instant;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.List;
37 import java.util.Objects;
38 import java.util.Optional;
40 import java.util.logging.Level;
41 import java.util.logging.Logger;
42 import java.util.stream.Collectors;
43 import java.util.stream.Stream;
44 import org.joda.time.DateTimeZone;
45 import org.joda.time.Interval;
58 private static final Logger logger = Logger.getLogger(
TimelineManager.class.getName());
63 private static final ImmutableList<TimelineEventType> ROOT_CATEGORY_AND_FILESYSTEM_TYPES
80 private static final ImmutableList<TimelineEventType> PREDEFINED_EVENT_TYPES
90 .map(artType -> artType.getTypeID())
91 .collect(Collectors.toSet());
99 private static final Long MAX_TIMESTAMP_TO_ADD = Instant.now().getEpochSecond() + 394200000;
104 private final Map<Long, TimelineEventType> eventTypeIDMap =
new HashMap<>();
116 this.caseDB = caseDB;
118 List<TimelineEventType> fullList =
new ArrayList<>();
119 fullList.addAll(ROOT_CATEGORY_AND_FILESYSTEM_TYPES);
120 fullList.addAll(PREDEFINED_EVENT_TYPES);
123 try (
final CaseDbConnection con = caseDB.getConnection();
124 final PreparedStatement pStatement = con.prepareStatement(
125 insertOrIgnore(
" INTO tsk_event_types(event_type_id, display_name, super_type_id) VALUES (?, ?, ?)"),
126 Statement.NO_GENERATED_KEYS)) {
128 pStatement.setLong(1, type.getTypeID());
129 pStatement.setString(2, escapeSingleQuotes(type.getDisplayName()));
130 if (type != type.getParent()) {
131 pStatement.setLong(3, type.getParent().getTypeID());
133 pStatement.setNull(3, java.sql.Types.INTEGER);
136 con.executeUpdate(pStatement);
137 eventTypeIDMap.put(type.getTypeID(), type);
139 }
catch (SQLException ex) {
140 throw new TskCoreException(
"Failed to initialize timeline event types", ex);
158 if (eventIDs.isEmpty()) {
161 final String query =
"SELECT Min(time) as minTime, Max(time) as maxTime FROM tsk_events WHERE event_id IN (" + buildCSVString(eventIDs) +
")";
163 try (CaseDbConnection con = caseDB.getConnection();
164 Statement stmt = con.createStatement();
165 ResultSet results = stmt.executeQuery(query);) {
166 if (results.next()) {
167 return new Interval(results.getLong(
"minTime") * 1000, (results.getLong(
"maxTime") + 1) * 1000, DateTimeZone.UTC);
169 }
catch (SQLException ex) {
170 throw new TskCoreException(
"Error executing get spanning interval query: " + query, ex);
190 long start = timeRange.getStartMillis() / 1000;
191 long end = timeRange.getEndMillis() / 1000;
192 String sqlWhere = getSQLWhere(filter);
193 String augmentedEventsTablesSQL = getAugmentedEventsTablesSQL(filter);
194 String queryString =
" SELECT (SELECT Max(time) FROM " + augmentedEventsTablesSQL
195 +
" WHERE time <=" + start +
" AND " + sqlWhere +
") AS start,"
196 +
" (SELECT Min(time) FROM " + augmentedEventsTablesSQL
197 +
" WHERE time >= " + end +
" AND " + sqlWhere +
") AS end";
199 try (CaseDbConnection con = caseDB.getConnection();
200 Statement stmt = con.createStatement();
201 ResultSet results = stmt.executeQuery(queryString);) {
203 if (results.next()) {
204 long start2 = results.getLong(
"start");
205 long end2 = results.getLong(
"end");
210 return new Interval(start2 * 1000, (end2 + 1) * 1000, timeZone);
212 }
catch (SQLException ex) {
230 String sql =
"SELECT * FROM " + getAugmentedEventsTablesSQL(
false) +
" WHERE event_id = " + eventID;
232 try (CaseDbConnection con = caseDB.getConnection();
233 Statement stmt = con.createStatement();) {
234 try (ResultSet results = stmt.executeQuery(sql);) {
235 if (results.next()) {
236 int typeID = results.getInt(
"event_type_id");
239 results.getLong(
"data_source_obj_id"),
240 results.getLong(
"content_obj_id"),
241 results.getLong(
"artifact_id"),
242 results.getLong(
"time"),
243 type, results.getString(
"full_description"),
244 results.getString(
"med_description"),
245 results.getString(
"short_description"),
246 intToBoolean(results.getInt(
"hash_hit")),
247 intToBoolean(results.getInt(
"tagged")));
250 }
catch (SQLException sqlEx) {
270 Long startTime = timeRange.getStartMillis() / 1000;
271 Long endTime = timeRange.getEndMillis() / 1000;
273 if (Objects.equals(startTime, endTime)) {
277 ArrayList<Long> resultIDs =
new ArrayList<>();
279 String query =
"SELECT tsk_events.event_id AS event_id FROM " + getAugmentedEventsTablesSQL(filter)
280 +
" WHERE time >= " + startTime +
" AND time <" + endTime +
" AND " + getSQLWhere(filter) +
" ORDER BY time ASC";
282 try (CaseDbConnection con = caseDB.getConnection();
283 Statement stmt = con.createStatement();
284 ResultSet results = stmt.executeQuery(query);) {
285 while (results.next()) {
286 resultIDs.add(results.getLong(
"event_id"));
289 }
catch (SQLException sqlEx) {
290 throw new TskCoreException(
"Error while executing query " + query, sqlEx);
308 try (CaseDbConnection con = caseDB.getConnection();
309 Statement stms = con.createStatement();
310 ResultSet results = stms.executeQuery(STATEMENTS.GET_MAX_TIME.getSQL());) {
311 if (results.next()) {
312 return results.getLong(
"max");
314 }
catch (SQLException ex) {
315 throw new TskCoreException(
"Error while executing query " + STATEMENTS.GET_MAX_TIME.getSQL(), ex);
332 try (CaseDbConnection con = caseDB.getConnection();
333 Statement stms = con.createStatement();
334 ResultSet results = stms.executeQuery(STATEMENTS.GET_MIN_TIME.getSQL());) {
335 if (results.next()) {
336 return results.getLong(
"min");
338 }
catch (SQLException ex) {
339 throw new TskCoreException(
"Error while executing query " + STATEMENTS.GET_MAX_TIME.getSQL(), ex);
355 return Optional.ofNullable(eventTypeIDMap.get(eventTypeID));
364 return ImmutableList.copyOf(eventTypeIDMap.values());
367 private String insertOrIgnore(String query) {
370 return " INSERT " + query +
" ON CONFLICT DO NOTHING ";
372 return " INSERT OR IGNORE " + query;
374 throw new UnsupportedOperationException(
"Unsupported DB type: " + caseDB.
getDatabaseType().name());
381 private enum STATEMENTS {
383 GET_MAX_TIME(
"SELECT Max(time) AS max FROM tsk_events"),
384 GET_MIN_TIME(
"SELECT Min(time) AS min FROM tsk_events");
386 private final String sql;
388 private STATEMENTS(String sql) {
408 ArrayList<Long> eventIDs =
new ArrayList<>();
411 =
"SELECT event_id FROM tsk_events "
412 +
" LEFT JOIN tsk_event_descriptions on ( tsk_events.event_description_id = tsk_event_descriptions.event_description_id ) "
413 +
" WHERE artifact_id = " + artifact.getArtifactID();
415 try (CaseDbConnection con = caseDB.getConnection();
416 Statement stmt = con.createStatement();
417 ResultSet results = stmt.executeQuery(query);) {
418 while (results.next()) {
419 eventIDs.add(results.getLong(
"event_id"));
421 }
catch (SQLException ex) {
422 throw new TskCoreException(
"Error executing getEventIDsForArtifact query.", ex);
444 try (CaseDbConnection conn = caseDB.getConnection()) {
445 return getEventAndDescriptionIDs(conn, content.getId(), includeDerivedArtifacts).keySet();
469 private Long addEventDescription(
long dataSourceObjId,
long fileObjId, Long artifactID,
470 String fullDescription, String medDescription, String shortDescription,
471 boolean hasHashHits,
boolean tagged, CaseDbConnection connection)
throws TskCoreException, DuplicateException {
472 String tableValuesClause
473 =
"tsk_event_descriptions ( "
474 +
"data_source_obj_id, content_obj_id, artifact_id, "
475 +
" full_description, med_description, short_description, "
476 +
" hash_hit, tagged "
478 +
"(?, ?, ?, ?, ?, ?, ?, ?)";
480 String insertDescriptionSql = getSqlIgnoreConflict(tableValuesClause);
484 PreparedStatement insertDescriptionStmt = connection.getPreparedStatement(insertDescriptionSql, PreparedStatement.RETURN_GENERATED_KEYS);
485 insertDescriptionStmt.clearParameters();
486 insertDescriptionStmt.setLong(1, dataSourceObjId);
487 insertDescriptionStmt.setLong(2, fileObjId);
489 if (artifactID == null) {
490 insertDescriptionStmt.setNull(3, Types.INTEGER);
492 insertDescriptionStmt.setLong(3, artifactID);
495 insertDescriptionStmt.setString(4, fullDescription);
496 insertDescriptionStmt.setString(5, medDescription);
497 insertDescriptionStmt.setString(6, shortDescription);
498 insertDescriptionStmt.setInt(7, booleanToInt(hasHashHits));
499 insertDescriptionStmt.setInt(8, booleanToInt(tagged));
500 int row = insertDescriptionStmt.executeUpdate();
507 try (ResultSet generatedKeys = insertDescriptionStmt.getGeneratedKeys()) {
508 if (generatedKeys.next()) {
509 return generatedKeys.getLong(1);
514 }
catch (SQLException ex) {
515 throw new TskCoreException(
"Failed to insert event description.", ex);
534 private Long getEventDescription(
long dataSourceObjId,
long fileObjId, Long artifactID,
535 String fullDescription, CaseDbConnection connection)
throws TskCoreException {
537 String query =
"SELECT event_description_id FROM tsk_event_descriptions "
538 +
"WHERE data_source_obj_id = " + dataSourceObjId
539 +
" AND content_obj_id = " + fileObjId
540 +
" AND artifact_id " + (artifactID != null ?
" = " + artifactID :
"IS null")
541 +
" AND full_description " + (fullDescription != null ?
"= '"
542 + SleuthkitCase.escapeSingleQuotes(fullDescription) +
"'" :
"IS null");
545 try (ResultSet resultSet = connection.createStatement().executeQuery(query)) {
547 if (resultSet.next()) {
548 long id = resultSet.getLong(1);
551 }
catch (SQLException ex) {
552 throw new TskCoreException(String.format(
"Failed to get description, dataSource=%d, fileObjId=%d, artifactId=%d", dataSourceObjId, fileObjId, artifactID), ex);
560 Collection<TimelineEvent> addEventsForNewFile(AbstractFile file, CaseDbConnection connection)
throws TskCoreException {
561 Set<TimelineEvent> events = addEventsForNewFileQuiet(file, connection);
563 .map(TimelineEventAddedEvent::new)
564 .forEach(caseDB::fireTSKEvent);
583 Set<TimelineEvent> addEventsForNewFileQuiet(AbstractFile file, CaseDbConnection connection)
throws TskCoreException {
585 Map<TimelineEventType, Long> timeMap = ImmutableMap.of(TimelineEventType.FILE_CREATED, file.getCrtime(),
586 TimelineEventType.FILE_ACCESSED, file.getAtime(),
587 TimelineEventType.FILE_CHANGED, file.getCtime(),
588 TimelineEventType.FILE_MODIFIED, file.getMtime());
594 if (Collections.max(timeMap.values()) <= 0) {
595 return Collections.emptySet();
598 String description = file.getParentPath() + file.getName();
599 long fileObjId = file.getId();
600 Set<TimelineEvent> events =
new HashSet<>();
603 Long descriptionID = addEventDescription(file.getDataSourceObjectId(), fileObjId, null,
604 description, null, null,
false,
false, connection);
606 if(descriptionID == null) {
607 descriptionID = getEventDescription(file.getDataSourceObjectId(), fileObjId, null, description, connection);
609 if(descriptionID != null) {
610 for (Map.Entry<TimelineEventType, Long> timeEntry : timeMap.entrySet()) {
611 Long time = timeEntry.getValue();
612 if (time > 0 && time < MAX_TIMESTAMP_TO_ADD) {
613 TimelineEventType type = timeEntry.getKey();
614 long eventID = addEventWithExistingDescription(time, type, descriptionID, connection);
621 events.add(
new TimelineEvent(eventID, descriptionID, fileObjId, null, time, type,
622 description, null, null,
false,
false));
624 if (time >= MAX_TIMESTAMP_TO_ADD) {
625 logger.log(Level.WARNING, String.format(
"Date/Time discarded from Timeline for %s for file %s with Id %d", timeEntry.getKey().getDisplayName(), file.getParentPath() + file.getName(), file.getId()));
630 throw new TskCoreException(String.format(
"Failed to get event description for file id = %d", fileObjId));
632 }
catch (DuplicateException dupEx) {
633 logger.log(Level.SEVERE,
"Attempt to make file event duplicate.", dupEx);
654 Set<TimelineEvent> addArtifactEvents(BlackboardArtifact artifact)
throws TskCoreException {
655 Set<TimelineEvent> newEvents =
new HashSet<>();
662 if (artifact.getArtifactTypeID() == TSK_TL_EVENT.getTypeID()) {
663 TimelineEventType eventType;
664 BlackboardAttribute attribute = artifact.getAttribute(
new BlackboardAttribute.Type(TSK_TL_EVENT_TYPE));
665 if (attribute == null) {
666 eventType = TimelineEventType.OTHER;
668 long eventTypeID = attribute.getValueLong();
669 eventType = eventTypeIDMap.getOrDefault(eventTypeID, TimelineEventType.OTHER);
674 addArtifactEvent(((TimelineEventArtifactTypeImpl) TimelineEventType.OTHER).makeEventDescription(artifact), eventType, artifact)
675 .ifPresent(newEvents::add);
676 }
catch (DuplicateException ex) {
677 logger.log(Level.SEVERE, getDuplicateExceptionMessage(artifact,
"Attempt to make a timeline event artifact duplicate"), ex);
684 Set<TimelineEventArtifactTypeImpl> eventTypesForArtifact = eventTypeIDMap.values().stream()
685 .filter(TimelineEventArtifactTypeImpl.class::isInstance)
686 .map(TimelineEventArtifactTypeImpl.class::cast)
687 .filter(eventType -> eventType.getArtifactTypeID() == artifact.getArtifactTypeID())
688 .collect(Collectors.toSet());
690 boolean duplicateExists =
false;
691 for (TimelineEventArtifactTypeImpl eventType : eventTypesForArtifact) {
693 addArtifactEvent(eventType.makeEventDescription(artifact), eventType, artifact)
694 .ifPresent(newEvents::add);
695 }
catch (DuplicateException ex) {
696 duplicateExists =
true;
697 logger.log(Level.SEVERE, getDuplicateExceptionMessage(artifact,
"Attempt to make artifact event duplicate"), ex);
702 if (!duplicateExists && newEvents.isEmpty()) {
704 addOtherEventDesc(artifact).ifPresent(newEvents::add);
705 }
catch (DuplicateException ex) {
706 logger.log(Level.SEVERE, getDuplicateExceptionMessage(artifact,
"Attempt to make 'other' artifact event duplicate"), ex);
711 .map(TimelineEventAddedEvent::new)
712 .forEach(caseDB::fireTSKEvent);
728 private String getDuplicateExceptionMessage(BlackboardArtifact artifact, String error) {
729 String artifactIDStr = null;
730 String sourceStr = null;
732 if (artifact != null) {
733 artifactIDStr = Long.toString(artifact.getId());
736 sourceStr = artifact.getAttributes().stream()
737 .filter(attr -> attr != null && attr.getSources() != null && !attr.getSources().isEmpty())
738 .map(attr -> String.join(
",", attr.getSources()))
741 }
catch (TskCoreException ex) {
742 logger.log(Level.WARNING, String.format(
"Could not fetch artifacts for artifact id: %d.", artifact.getId()), ex);
746 artifactIDStr = (artifactIDStr == null) ?
"<null>" : artifactIDStr;
747 sourceStr = (sourceStr == null) ?
"<null>" : sourceStr;
749 return String.format(
"%s (artifactID=%s, Source=%s).", error, artifactIDStr, sourceStr);
763 private Optional<TimelineEvent> addOtherEventDesc(BlackboardArtifact artifact)
throws TskCoreException, DuplicateException {
764 if (artifact == null) {
765 return Optional.empty();
768 Long timeVal = artifact.getAttributes().stream()
769 .filter((attr) -> attr.getAttributeType().getValueType() == BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.DATETIME)
770 .map(attr -> attr.getValueLong())
774 if (timeVal == null) {
775 return Optional.empty();
778 String description = String.format(
"%s: %d", artifact.getDisplayName(), artifact.getId());
780 TimelineEventDescriptionWithTime evtWDesc =
new TimelineEventDescriptionWithTime(timeVal, description, description, description);
782 TimelineEventType evtType = (ARTIFACT_TYPE_IDS.contains(artifact.getArtifactTypeID()))
783 ? TimelineEventType.OTHER
784 : TimelineEventType.USER_CREATED;
786 return addArtifactEvent(evtWDesc, evtType, artifact);
802 private Optional<TimelineEvent> addArtifactEvent(TimelineEventDescriptionWithTime eventPayload,
803 TimelineEventType eventType, BlackboardArtifact artifact)
throws TskCoreException, DuplicateException {
805 if (eventPayload == null) {
806 return Optional.empty();
808 long time = eventPayload.getTime();
810 if (time <= 0 || time >= MAX_TIMESTAMP_TO_ADD) {
811 if (time >= MAX_TIMESTAMP_TO_ADD) {
812 logger.log(Level.WARNING, String.format(
"Date/Time discarded from Timeline for %s for artifact %s with id %d", artifact.getDisplayName(), eventPayload.getDescription(TimelineLevelOfDetail.HIGH), artifact.getId()));
814 return Optional.empty();
816 String fullDescription = eventPayload.getDescription(TimelineLevelOfDetail.HIGH);
817 String medDescription = eventPayload.getDescription(TimelineLevelOfDetail.MEDIUM);
818 String shortDescription = eventPayload.getDescription(TimelineLevelOfDetail.LOW);
819 long artifactID = artifact.getArtifactID();
820 long fileObjId = artifact.getObjectID();
821 Long dataSourceObjectID = artifact.getDataSourceObjectID();
823 if(dataSourceObjectID == null) {
824 logger.log(Level.SEVERE, String.format(
"Failed to create timeline event for artifact (%d), artifact data source was null"), artifact.getId());
825 return Optional.empty();
829 boolean hasHashHits =
false;
832 hasHashHits = isNotEmpty(file.getHashSetNames());
838 try (CaseDbConnection connection = caseDB.getConnection();) {
840 Long descriptionID = addEventDescription(dataSourceObjectID, fileObjId, artifactID,
841 fullDescription, medDescription, shortDescription,
842 hasHashHits, tagged, connection);
844 if(descriptionID == null) {
845 descriptionID = getEventDescription(dataSourceObjectID, fileObjId, artifactID,
846 fullDescription, connection);
849 if(descriptionID != null) {
850 long eventID = addEventWithExistingDescription(time, eventType, descriptionID, connection);
852 event =
new TimelineEvent(eventID, dataSourceObjectID, fileObjId, artifactID,
853 time, eventType, fullDescription, medDescription, shortDescription,
854 hasHashHits, tagged);
856 throw new TskCoreException(String.format(
"Failed to get event description for file id = %d, artifactId %d", fileObjId, artifactID));
862 return Optional.of(event);
865 private long addEventWithExistingDescription(Long time, TimelineEventType type,
long descriptionID, CaseDbConnection connection)
throws TskCoreException, DuplicateException {
866 String tableValuesClause
867 =
"tsk_events ( event_type_id, event_description_id , time) VALUES (?, ?, ?)";
869 String insertEventSql = getSqlIgnoreConflict(tableValuesClause);
873 PreparedStatement insertRowStmt = connection.getPreparedStatement(insertEventSql, Statement.RETURN_GENERATED_KEYS);
874 insertRowStmt.clearParameters();
875 insertRowStmt.setLong(1, type.getTypeID());
876 insertRowStmt.setLong(2, descriptionID);
877 insertRowStmt.setLong(3, time);
878 int row = insertRowStmt.executeUpdate();
881 throw new DuplicateException(String.format(
"An event already exists in the event table for this item [time: %s, type: %s, description: %d].",
882 time == null ?
"<null>" : Long.toString(time),
883 type == null ?
"<null>" : type.toString(),
887 try (ResultSet generatedKeys = insertRowStmt.getGeneratedKeys();) {
888 if (generatedKeys.next()) {
889 return generatedKeys.getLong(1);
891 throw new DuplicateException(String.format(
"An event already exists in the event table for this item [time: %s, type: %s, description: %d].",
892 time == null ?
"<null>" : Long.toString(time),
893 type == null ?
"<null>" : type.toString(),
897 }
catch (SQLException ex) {
898 throw new TskCoreException(
"Failed to insert event for existing description.", ex);
904 private Map<Long, Long> getEventAndDescriptionIDs(CaseDbConnection conn,
long contentObjID,
boolean includeArtifacts)
throws TskCoreException {
905 return getEventAndDescriptionIDsHelper(conn, contentObjID, (includeArtifacts ?
"" :
" AND artifact_id IS NULL"));
908 private Map<Long, Long> getEventAndDescriptionIDs(CaseDbConnection conn,
long contentObjID, Long artifactID)
throws TskCoreException {
909 return getEventAndDescriptionIDsHelper(conn, contentObjID,
" AND artifact_id = " + artifactID);
912 private Map<Long, Long> getEventAndDescriptionIDsHelper(CaseDbConnection con,
long fileObjID, String artifactClause)
throws TskCoreException {
914 Map<Long, Long> eventIDToDescriptionIDs =
new HashMap<>();
915 String sql =
"SELECT event_id, tsk_events.event_description_id"
916 +
" FROM tsk_events "
917 +
" LEFT JOIN tsk_event_descriptions ON ( tsk_events.event_description_id = tsk_event_descriptions.event_description_id )"
918 +
" WHERE content_obj_id = " + fileObjID
920 try (Statement selectStmt = con.createStatement(); ResultSet executeQuery = selectStmt.executeQuery(sql);) {
921 while (executeQuery.next()) {
922 eventIDToDescriptionIDs.put(executeQuery.getLong(
"event_id"), executeQuery.getLong(
"event_description_id"));
924 }
catch (SQLException ex) {
925 throw new TskCoreException(
"Error getting event description ids for object id = " + fileObjID, ex);
927 return eventIDToDescriptionIDs;
949 try (CaseDbConnection conn = caseDB.getConnection()) {
950 Map<Long, Long> eventIDs = getEventAndDescriptionIDs(conn, content.getId(),
false);
951 updateEventSourceTaggedFlag(conn, eventIDs.values(), 1);
952 return eventIDs.keySet();
978 try (CaseDbConnection conn = caseDB.getConnection()) {
980 Map<Long, Long> eventIDs = getEventAndDescriptionIDs(conn, content.getId(),
false);
981 updateEventSourceTaggedFlag(conn, eventIDs.values(), 0);
982 return eventIDs.keySet();
984 return Collections.emptySet();
1004 try (CaseDbConnection conn = caseDB.getConnection()) {
1005 Map<Long, Long> eventIDs = getEventAndDescriptionIDs(conn, artifact.getObjectID(), artifact.getArtifactID());
1006 updateEventSourceTaggedFlag(conn, eventIDs.values(), 1);
1007 return eventIDs.keySet();
1027 try (CaseDbConnection conn = caseDB.getConnection()) {
1029 Map<Long, Long> eventIDs = getEventAndDescriptionIDs(conn, artifact.getObjectID(), artifact.getArtifactID());
1030 updateEventSourceTaggedFlag(conn, eventIDs.values(), 0);
1031 return eventIDs.keySet();
1033 return Collections.emptySet();
1040 private void updateEventSourceTaggedFlag(CaseDbConnection conn, Collection<Long> eventDescriptionIDs,
int flagValue)
throws TskCoreException {
1041 if (eventDescriptionIDs.isEmpty()) {
1045 String sql =
"UPDATE tsk_event_descriptions SET tagged = " + flagValue +
" WHERE event_description_id IN (" + buildCSVString(eventDescriptionIDs) +
")";
1046 try (Statement updateStatement = conn.createStatement()) {
1047 updateStatement.executeUpdate(sql);
1048 }
catch (SQLException ex) {
1049 throw new TskCoreException(
"Error marking content events tagged: " + sql, ex);
1069 try (CaseDbConnection con = caseDB.getConnection(); Statement updateStatement = con.createStatement();) {
1070 Map<Long, Long> eventIDs = getEventAndDescriptionIDs(con, content.getId(),
true);
1071 if (!eventIDs.isEmpty()) {
1072 String sql =
"UPDATE tsk_event_descriptions SET hash_hit = 1" +
" WHERE event_description_id IN (" + buildCSVString(eventIDs.values()) +
")";
1074 updateStatement.executeUpdate(sql);
1075 return eventIDs.keySet();
1076 }
catch (SQLException ex) {
1077 throw new TskCoreException(
"Error setting hash_hit of events.", ex);
1080 return eventIDs.keySet();
1082 }
catch (SQLException ex) {
1083 throw new TskCoreException(
"Error setting hash_hit of events.", ex);
1113 long adjustedEndTime = Objects.equals(startTime, endTime) ? endTime + 1 : endTime;
1117 String queryString =
"SELECT count(DISTINCT tsk_events.event_id) AS count, " + typeColumn
1118 +
" FROM " + getAugmentedEventsTablesSQL(filter)
1119 +
" WHERE time >= " + startTime +
" AND time < " + adjustedEndTime +
" AND " + getSQLWhere(filter)
1120 +
" GROUP BY " + typeColumn;
1123 try (CaseDbConnection con = caseDB.getConnection();
1124 Statement stmt = con.createStatement();
1125 ResultSet results = stmt.executeQuery(queryString);) {
1126 Map<TimelineEventType, Long> typeMap =
new HashMap<>();
1127 while (results.next()) {
1128 int eventTypeID = results.getInt(typeColumn);
1130 .orElseThrow(() -> newEventTypeMappingException(eventTypeID));
1132 typeMap.put(eventType, results.getLong(
"count"));
1135 }
catch (SQLException ex) {
1136 throw new TskCoreException(
"Error getting count of events from db: " + queryString, ex);
1142 private static TskCoreException newEventTypeMappingException(
int eventTypeID) {
1143 return new TskCoreException(
"Error mapping event type id " + eventTypeID +
" to EventType.");
1159 static private String getAugmentedEventsTablesSQL(TimelineFilter.RootFilter filter) {
1160 TimelineFilter.FileTypesFilter fileTypesFitler = filter.getFileTypesFilter();
1161 boolean needsMimeTypes = fileTypesFitler != null && fileTypesFitler.hasSubFilters();
1163 return getAugmentedEventsTablesSQL(needsMimeTypes);
1180 static private String getAugmentedEventsTablesSQL(
boolean needMimeTypes) {
1193 return "( SELECT event_id, time, tsk_event_descriptions.data_source_obj_id, content_obj_id, artifact_id, "
1194 +
" full_description, med_description, short_description, tsk_events.event_type_id, super_type_id,"
1195 +
" hash_hit, tagged "
1196 + (needMimeTypes ?
", mime_type" :
"")
1197 +
" FROM tsk_events "
1198 +
" JOIN tsk_event_descriptions ON ( tsk_event_descriptions.event_description_id = tsk_events.event_description_id)"
1199 +
" JOIN tsk_event_types ON (tsk_events.event_type_id = tsk_event_types.event_type_id ) "
1200 + (needMimeTypes ?
" LEFT OUTER JOIN tsk_files "
1201 +
" ON (tsk_event_descriptions.content_obj_id = tsk_files.obj_id)"
1203 +
") AS tsk_events";
1213 private static int booleanToInt(
boolean value) {
1214 return value ? 1 : 0;
1217 private static boolean intToBoolean(
int value) {
1234 List<TimelineEvent> events =
new ArrayList<>();
1236 Long startTime = timeRange.getStartMillis() / 1000;
1237 Long endTime = timeRange.getEndMillis() / 1000;
1239 if (Objects.equals(startTime, endTime)) {
1243 if (filter == null) {
1247 if (endTime < startTime) {
1252 String querySql =
"SELECT time, content_obj_id, data_source_obj_id, artifact_id, "
1256 +
" event_type_id, super_type_id, "
1257 +
" full_description, med_description, short_description "
1258 +
" FROM " + getAugmentedEventsTablesSQL(filter)
1259 +
" WHERE time >= " + startTime +
" AND time < " + endTime +
" AND " + getSQLWhere(filter)
1263 try (CaseDbConnection con = caseDB.getConnection();
1264 Statement stmt = con.createStatement();
1265 ResultSet resultSet = stmt.executeQuery(querySql);) {
1267 while (resultSet.next()) {
1268 int eventTypeID = resultSet.getInt(
"event_type_id");
1270 ->
new TskCoreException(
"Error mapping event type id " + eventTypeID +
"to EventType."));
1273 resultSet.getLong(
"event_id"),
1274 resultSet.getLong(
"data_source_obj_id"),
1275 resultSet.getLong(
"content_obj_id"),
1276 resultSet.getLong(
"artifact_id"),
1277 resultSet.getLong(
"time"),
1279 resultSet.getString(
"full_description"),
1280 resultSet.getString(
"med_description"),
1281 resultSet.getString(
"short_description"),
1282 resultSet.getInt(
"hash_hit") != 0,
1283 resultSet.getInt(
"tagged") != 0);
1288 }
catch (SQLException ex) {
1289 throw new TskCoreException(
"Error getting events from db: " + querySql, ex);
1304 private static String typeColumnHelper(
final boolean useSubTypes) {
1305 return useSubTypes ?
"event_type_id" :
"super_type_id";
1316 String getSQLWhere(TimelineFilter.RootFilter filter) {
1319 if (filter == null) {
1320 return getTrueLiteral();
1322 result = filter.getSQLWhere(
this);
1339 private String getSqlIgnoreConflict(String insertTableValues)
throws TskCoreException {
1342 return "INSERT INTO " + insertTableValues +
" ON CONFLICT DO NOTHING";
1344 return "INSERT OR IGNORE INTO " + insertTableValues;
1346 throw new TskCoreException(
"Unknown DB Type: " + caseDB.
getDatabaseType().name());
1350 private String getTrueLiteral() {
1357 throw new UnsupportedOperationException(
"Unsupported DB type: " + caseDB.
getDatabaseType().name());
1375 this.addedEvent = event;
1382 private static class DuplicateException
extends Exception {
1384 private static final long serialVersionUID = 1L;
1391 DuplicateException(String message) {
List< Long > getEventIDs(Interval timeRange, TimelineFilter.RootFilter filter)
TimelineEvent getAddedEvent()
TimelineEvent getEventById(long eventID)
ImmutableList< TimelineEventType > getEventTypes()
Interval getSpanningInterval(Interval timeRange, TimelineFilter.RootFilter filter, DateTimeZone timeZone)
Set< Long > getEventIDsForContent(Content content, boolean includeDerivedArtifacts)
TimelineEventType FILE_ACCESSED
Interval getSpanningInterval(Collection< Long > eventIDs)
Set< Long > updateEventsForContentTagAdded(Content content)
List< BlackboardArtifactTag > getBlackboardArtifactTagsByArtifact(BlackboardArtifact artifact)
SortedSet<?extends TimelineEventType > getChildren()
Set< Long > updateEventsForContentTagDeleted(Content content)
Set< Long > updateEventsForHashSetHit(Content content)
TimelineEventType WEB_ACTIVITY
AbstractFile getAbstractFileById(long id)
TimelineEventType FILE_MODIFIED
void releaseSingleUserCaseReadLock()
TimelineEventType MISC_TYPES
static String escapeSingleQuotes(String text)
Set< Long > updateEventsForArtifactTagDeleted(BlackboardArtifact artifact)
void acquireSingleUserCaseWriteLock()
void releaseSingleUserCaseWriteLock()
TimelineEventType FILE_CREATED
TimelineEventType FILE_SYSTEM
Map< TimelineEventType, Long > countEventsByType(Long startTime, Long endTime, TimelineFilter.RootFilter filter, TimelineEventType.HierarchyLevel typeHierachyLevel)
List< Long > getEventIDsForArtifact(BlackboardArtifact artifact)
TimelineEventType ROOT_EVENT_TYPE
List< TimelineEvent > getEvents(Interval timeRange, TimelineFilter.RootFilter filter)
TimelineEventType CUSTOM_TYPES
void acquireSingleUserCaseReadLock()
List< ContentTag > getContentTagsByContent(Content content)
Optional< TimelineEventType > getEventType(long eventTypeID)
TimelineEventType FILE_CHANGED
Set< Long > updateEventsForArtifactTagAdded(BlackboardArtifact artifact)