simplify locking in DrawableTagsManager.java by making the backing tagsManager final

This commit is contained in:
millmanorama 2018-09-03 17:31:14 +02:00
parent 31903d04d8
commit a37b8dc743
5 changed files with 261 additions and 332 deletions

View File

@ -60,6 +60,7 @@ import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.netbeans.api.progress.ProgressHandle;
import org.openide.util.Cancellable;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.Case.CaseType;
@ -123,7 +124,7 @@ public final class ImageGalleryController {
private final GroupManager groupManager = new GroupManager(this);
private final HashSetManager hashSetManager = new HashSetManager();
private final CategoryManager categoryManager = new CategoryManager(this);
private final DrawableTagsManager tagsManager = new DrawableTagsManager(null);
private DrawableTagsManager tagsManager;
private Runnable showTree;
private Toolbar toolbar;
@ -144,7 +145,11 @@ public final class ImageGalleryController {
public static synchronized ImageGalleryController getDefault() {
if (instance == null) {
try {
instance = new ImageGalleryController();
} catch (NoClassDefFoundError error) {
Exceptions.printStackTrace(error);
}
}
return instance;
}
@ -232,12 +237,7 @@ public final class ImageGalleryController {
}
});
groupManager.getAnalyzedGroups().addListener((Observable o) -> {
//analyzed groups is confined to JFX thread
if (Case.isCaseOpen()) {
checkForGroups();
}
});
groupManager.getAnalyzedGroups().addListener((Observable o) -> checkForGroups());
viewState().addListener((Observable observable) -> {
//when the viewed group changes, clear the selection and the undo/redo history
@ -291,7 +291,6 @@ public final class ImageGalleryController {
* GroupManager and remove blocking progress spinners if there are. If there
* aren't, add a blocking progress spinner with appropriate message.
*/
@ThreadConfined(type = ThreadConfined.ThreadType.JFX)
@NbBundle.Messages({"ImageGalleryController.noGroupsDlg.msg1=No groups are fully analyzed; but listening to ingest is disabled. "
+ " No groups will be available until ingest is finished and listening is re-enabled.",
"ImageGalleryController.noGroupsDlg.msg2=No groups are fully analyzed yet, but ingest is still ongoing. Please Wait.",
@ -303,15 +302,16 @@ public final class ImageGalleryController {
+ " the current Group By setting resulted in no groups, "
+ "or no groups are fully analyzed but ingest is not running."})
synchronized private void checkForGroups() {
if (Case.isCaseOpen()) {
if (groupManager.getAnalyzedGroups().isEmpty()) {
if (IngestManager.getInstance().isIngestRunning()) {
if (listeningEnabled.not().get()) {
replaceNotification(fullUIStackPane,
new NoGroupsDialog(Bundle.ImageGalleryController_noGroupsDlg_msg1()));
} else {
replaceNotification(fullUIStackPane,
if (listeningEnabled.get()) {
replaceNotification(centralStackPane,
new NoGroupsDialog(Bundle.ImageGalleryController_noGroupsDlg_msg2(),
new ProgressIndicator()));
} else {
replaceNotification(fullUIStackPane,
new NoGroupsDialog(Bundle.ImageGalleryController_noGroupsDlg_msg1()));
}
} else if (dbTaskQueueSize.get() > 0) {
@ -321,27 +321,27 @@ public final class ImageGalleryController {
} else if (db != null) {
try {
if (db.countAllFiles() <= 0) {
// there are no files in db
if (listeningEnabled.not().get()) {
replaceNotification(fullUIStackPane,
new NoGroupsDialog(Bundle.ImageGalleryController_noGroupsDlg_msg4()));
} else {
if (listeningEnabled.get()) {
replaceNotification(fullUIStackPane,
new NoGroupsDialog(Bundle.ImageGalleryController_noGroupsDlg_msg5()));
} else {
replaceNotification(fullUIStackPane,
new NoGroupsDialog(Bundle.ImageGalleryController_noGroupsDlg_msg4()));
}
}
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error counting files in drawable db.", ex);
}
} else if (!groupManager.isRegrouping()) {
} else if (false == groupManager.isRegrouping()) {
replaceNotification(centralStackPane,
new NoGroupsDialog(Bundle.ImageGalleryController_noGroupsDlg_msg6()));
}
} else {
clearNotification();
Platform.runLater(this::clearNotification);
}
}
}
@ -357,22 +357,25 @@ public final class ImageGalleryController {
}
}
@ThreadConfined(type = ThreadConfined.ThreadType.JFX)
private void replaceNotification(StackPane stackPane, Node newNode) {
Platform.runLater(() -> {
clearNotification();
infoOverlay = new StackPane(infoOverLayBackground, newNode);
if (stackPane != null) {
stackPane.getChildren().add(infoOverlay);
}
});
}
/**
* configure the controller for a specific case.
*
* @param theNewCase the case to configure the controller for
*
* @throws org.sleuthkit.datamodel.TskCoreException
*/
public synchronized void setCase(Case theNewCase) {
public synchronized void setCase(Case theNewCase) throws TskCoreException {
if (null == theNewCase) {
reset();
} else {
@ -385,10 +388,15 @@ public final class ImageGalleryController {
// if we add this line icons are made as files are analyzed rather than on demand.
// db.addUpdatedFileListener(IconCache.getDefault());
historyManager.clear();
groupManager.setDB(db);
groupManager.reset();
hashSetManager.setDb(db);
categoryManager.setDb(db);
tagsManager.setAutopsyTagsManager(theNewCase.getServices().getTagsManager());
if (tagsManager != null) {
tagsManager.unregisterListener(groupManager);
tagsManager.unregisterListener(categoryManager);
}
tagsManager = new DrawableTagsManager(theNewCase.getServices().getTagsManager());
tagsManager.registerListener(groupManager);
tagsManager.registerListener(categoryManager);
shutDownDBExecutor();
@ -416,10 +424,11 @@ public final class ImageGalleryController {
setListeningEnabled(false);
ThumbnailCache.getDefault().clearCache();
historyManager.clear();
groupManager.clear();
tagsManager.clearFollowUpTagName();
groupManager.reset();
tagsManager.unregisterListener(groupManager);
tagsManager.unregisterListener(categoryManager);
tagsManager = null;
shutDownDBExecutor();
if (toolbar != null) {
@ -854,6 +863,9 @@ public final class ImageGalleryController {
taskDB.commitTransaction(drawableDbTransaction, true);
} catch (TskCoreException ex) {
if (null != drawableDbTransaction) {
taskDB.rollbackTransaction(drawableDbTransaction);
}
if (null != caseDbTransaction) {
try {
caseDbTransaction.rollback();
@ -861,9 +873,6 @@ public final class ImageGalleryController {
logger.log(Level.SEVERE, "Error in trying to rollback transaction", ex2); //NON-NLS
}
}
if (null != drawableDbTransaction) {
taskDB.rollbackTransaction(drawableDbTransaction);
}
progressHandle.progress(Bundle.BulkTask_stopCopy_status());
logger.log(Level.WARNING, "Stopping copy to drawable db task. Failed to transfer all database contents", ex); //NON-NLS
@ -1065,8 +1074,13 @@ public final class ImageGalleryController {
//close window, reset everything
SwingUtilities.invokeLater(ImageGalleryTopComponent::closeTopComponent);
reset();
} else { // a new case has been opened
} else {
try {
// a new case has been opened
setCase(newCase); //connect db, groupmanager, start worker thread
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error changing case in ImageGallery.", ex);
}
}
break;
case DATA_SOURCE_ADDED:

View File

@ -1,7 +1,7 @@
/*
* Autopsy Forensic Browser
*
* Copyright 2013-16 Basis Technology Corp.
* Copyright 2013-18 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
@ -18,25 +18,24 @@
*/
package org.sleuthkit.autopsy.imagegallery.datamodel;
import org.sleuthkit.autopsy.datamodel.DhsImageCategory;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.stream.Collectors;
import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javax.annotation.Nonnull;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.casemodule.events.ContentTagAddedEvent;
import org.sleuthkit.autopsy.casemodule.events.ContentTagDeletedEvent;
import org.sleuthkit.autopsy.casemodule.services.TagsManager;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.datamodel.DhsImageCategory;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.ContentTag;
import org.sleuthkit.datamodel.TagName;
@ -44,39 +43,40 @@ import org.sleuthkit.datamodel.TskCoreException;
/**
* Manages Tags, Tagging, and the relationship between Categories and Tags in
* the autopsy Db. Delegates some work to the backing {@link TagsManager}.
* the autopsy Db. Delegates some work to the backing autopsy TagsManager.
*/
@NbBundle.Messages({"DrawableTagsManager.followUp=Follow Up",
"DrawableTagsManager.bookMark=Bookmark"})
public class DrawableTagsManager {
public final class DrawableTagsManager {
private static final Logger LOGGER = Logger.getLogger(DrawableTagsManager.class.getName());
private static final Logger logger = Logger.getLogger(DrawableTagsManager.class.getName());
private static Image FOLLOW_UP_IMAGE;
private static Image BOOKMARK_IMAGE;
private static final Image FOLLOW_UP_IMAGE = new Image("/org/sleuthkit/autopsy/imagegallery/images/flag_red.png");
private static final Image BOOKMARK_IMAGE = new Image("/org/sleuthkit/autopsy/images/star-bookmark-icon-16.png");
final private Object autopsyTagsManagerLock = new Object();
private TagsManager autopsyTagsManager;
private final TagsManager autopsyTagsManager;
/** The tag name corresponding to the "built-in" tag "Follow Up" */
private final TagName followUpTagName;
private final TagName bookmarkTagName;
/**
* Used to distribute {@link TagsChangeEvent}s
*/
private final EventBus tagsEventBus = new AsyncEventBus(
private final EventBus tagsEventBus
= new AsyncEventBus(
Executors.newSingleThreadExecutor(
new BasicThreadFactory.Builder().namingPattern("Tags Event Bus").uncaughtExceptionHandler((Thread t, Throwable e) -> { //NON-NLS
LOGGER.log(Level.SEVERE, "uncaught exception in event bus handler", e); //NON-NLS
}).build()
));
new BasicThreadFactory.Builder()
.namingPattern("Tags Event Bus")//NON-NLS
.uncaughtExceptionHandler((Thread t, Throwable e) -> {
logger.log(Level.SEVERE, "Uncaught exception in DrawableTagsManager event bus handler.", e); //NON-NLS
})
.build()));
/**
* The tag name corresponding to the "built-in" tag "Follow Up"
*/
private TagName followUpTagName;
private TagName bookmarkTagName;
public DrawableTagsManager(TagsManager autopsyTagsManager) {
public DrawableTagsManager(TagsManager autopsyTagsManager) throws TskCoreException {
this.autopsyTagsManager = autopsyTagsManager;
followUpTagName = getTagName(NbBundle.getMessage(DrawableTagsManager.class, "DrawableTagsManager.followUp"));
bookmarkTagName = getTagName(NbBundle.getMessage(DrawableTagsManager.class, "DrawableTagsManager.bookMark"));
}
/**
@ -106,72 +106,37 @@ public class DrawableTagsManager {
}
/**
* assign a new TagsManager to back this one, ie when the current case
* changes
* Get the follow up TagName.
*
* @param autopsyTagsManager
* @return The follow up TagName.
*/
public void setAutopsyTagsManager(TagsManager autopsyTagsManager) {
synchronized (autopsyTagsManagerLock) {
this.autopsyTagsManager = autopsyTagsManager;
clearFollowUpTagName();
}
}
/**
* Use when closing a case to make sure everything is re-initialized in the
* next case.
*/
public void clearFollowUpTagName() {
synchronized (autopsyTagsManagerLock) {
followUpTagName = null;
}
}
/**
* get the (cached) follow up TagName
*
* @return
*
* @throws TskCoreException
*/
public TagName getFollowUpTagName() throws TskCoreException {
synchronized (autopsyTagsManagerLock) {
if (Objects.isNull(followUpTagName)) {
followUpTagName = getTagName(NbBundle.getMessage(DrawableTagsManager.class, "DrawableTagsManager.followUp"));
}
public TagName getFollowUpTagName() {
return followUpTagName;
}
}
private Object getBookmarkTagName() throws TskCoreException {
synchronized (autopsyTagsManagerLock) {
if (Objects.isNull(bookmarkTagName)) {
bookmarkTagName = getTagName(NbBundle.getMessage(DrawableTagsManager.class, "DrawableTagsManager.bookMark"));
}
return bookmarkTagName;
}
}
/**
* get all the TagNames that are not categories
* Get the bookmark TagName.
*
* @return all the TagNames that are not categories, in alphabetical order
* @return The bookmark TagName.
*/
private TagName getBookmarkTagName() throws TskCoreException {
return bookmarkTagName;
}
/**
* Get all the TagNames that are not categories
*
* @return All the TagNames that are not categories, in alphabetical order
* by displayName, or, an empty set if there was an exception
* looking them up from the db.
*/
@Nonnull
public List<TagName> getNonCategoryTagNames() {
synchronized (autopsyTagsManagerLock) {
try {
return autopsyTagsManager.getAllTagNames().stream()
.filter(CategoryManager::isNotCategoryTagName)
.distinct().sorted()
.collect(Collectors.toList());
} catch (TskCoreException | IllegalStateException ex) {
LOGGER.log(Level.WARNING, "couldn't access case", ex); //NON-NLS
}
} catch (TskCoreException tskCoreException) {
return Collections.emptyList();
}
}
@ -187,10 +152,8 @@ public class DrawableTagsManager {
* @throws TskCoreException if there was an error reading from the db
*/
public List<ContentTag> getContentTags(Content content) throws TskCoreException {
synchronized (autopsyTagsManagerLock) {
return autopsyTagsManager.getContentTagsByContent(content);
}
}
/**
* Gets content tags by DrawableFile.
@ -207,7 +170,6 @@ public class DrawableTagsManager {
}
public TagName getTagName(String displayName) throws TskCoreException {
synchronized (autopsyTagsManagerLock) {
try {
TagName returnTagName = autopsyTagsManager.getDisplayNamesToTagNamesMap().get(displayName);
if (returnTagName != null) {
@ -223,75 +185,50 @@ public class DrawableTagsManager {
throw new TskCoreException("Tag name exists but an error occured in retrieving it", ex);
}
} catch (NullPointerException | IllegalStateException ex) {
LOGGER.log(Level.SEVERE, "Case was closed out from underneath", ex); //NON-NLS
logger.log(Level.SEVERE, "Case was closed out from underneath", ex); //NON-NLS
throw new TskCoreException("Case was closed out from underneath", ex);
}
}
}
public TagName getTagName(DhsImageCategory cat) {
try {
return getTagName(cat.getDisplayName());
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error getting tag for Category: " + cat.getDisplayName(), ex);
return null;
}
}
public ContentTag addContentTag(DrawableFile file, TagName tagName, String comment) throws TskCoreException {
synchronized (autopsyTagsManagerLock) {
return autopsyTagsManager.addContentTag(file.getAbstractFile(), tagName, comment);
}
}
public List<ContentTag> getContentTagsByTagName(TagName t) throws TskCoreException {
synchronized (autopsyTagsManagerLock) {
return autopsyTagsManager.getContentTagsByTagName(t);
}
}
public List<TagName> getAllTagNames() throws TskCoreException {
synchronized (autopsyTagsManagerLock) {
return autopsyTagsManager.getAllTagNames();
}
}
public List<TagName> getTagNamesInUse() throws TskCoreException {
synchronized (autopsyTagsManagerLock) {
return autopsyTagsManager.getTagNamesInUse();
}
}
public void deleteContentTag(ContentTag ct) throws TskCoreException {
synchronized (autopsyTagsManagerLock) {
autopsyTagsManager.deleteContentTag(ct);
}
}
public Node getGraphic(TagName tagname) {
try {
if (tagname.equals(getFollowUpTagName())) {
return new ImageView(getFollowUpImage());
return new ImageView(FOLLOW_UP_IMAGE);
} else if (tagname.equals(getBookmarkTagName())) {
return new ImageView(getBookmarkImage());
return new ImageView(BOOKMARK_IMAGE);
}
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Failed to get \"Follow Up\" or \"Bookmark\"tag name from db.", ex);
logger.log(Level.SEVERE, "Failed to get \"Follow Up\" or \"Bookmark\"tag name from db.", ex);
}
return DrawableAttribute.TAGS.getGraphicForValue(tagname);
}
synchronized private static Image getFollowUpImage() {
if (FOLLOW_UP_IMAGE == null) {
FOLLOW_UP_IMAGE = new Image("/org/sleuthkit/autopsy/imagegallery/images/flag_red.png");
}
return FOLLOW_UP_IMAGE;
}
synchronized private static Image getBookmarkImage() {
if (BOOKMARK_IMAGE == null) {
BOOKMARK_IMAGE = new Image("/org/sleuthkit/autopsy/images/star-bookmark-icon-16.png");
}
return BOOKMARK_IMAGE;
}
}

View File

@ -231,7 +231,7 @@ public class GroupManager {
}
}
synchronized public void clear() {
synchronized public void reset() {
if (groupByTask != null) {
groupByTask.cancel(true);

View File

@ -190,7 +190,7 @@ public abstract class DrawableTileBase extends DrawableUIBase {
menuItems.add(AddTagAction.getTagMenu(getController()));
final Collection<AbstractFile> selectedFilesList = new HashSet<>(Utilities.actionsGlobalContext().lookupAll(AbstractFile.class));
if(selectedFilesList.size() == 1) {
if (selectedFilesList.size() == 1) {
menuItems.add(DeleteTagAction.getTagMenu(getController()));
}
@ -243,32 +243,24 @@ public abstract class DrawableTileBase extends DrawableUIBase {
protected abstract String getTextForLabel();
protected void initialize() {
followUpToggle.setOnAction(actionEvent -> {
getFile().ifPresent(file -> {
followUpToggle.setOnAction(
actionEvent -> getFile().ifPresent(
file -> {
if (followUpToggle.isSelected() == true) {
try {
selectionModel.clearAndSelect(file.getId());
new AddTagAction(getController(), getController().getTagsManager().getFollowUpTagName(), selectionModel.getSelected()).handle(actionEvent);
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Failed to add Follow Up tag. Could not load TagName.", ex); //NON-NLS
}
} else {
new DeleteFollowUpTagAction(getController(), file).handle(actionEvent);
}
});
});
})
);
}
protected boolean hasFollowUp() {
if (getFileID().isPresent()) {
try {
TagName followUpTagName = getController().getTagsManager().getFollowUpTagName();
TagName followUpTagName = getController().getTagsManager().getFollowUpTagName(); //NON-NLS
return DrawableAttribute.TAGS.getValue(getFile().get()).stream()
.anyMatch(followUpTagName::equals);
} catch (TskCoreException ex) {
LOGGER.log(Level.WARNING, "failed to get follow up tag name ", ex); //NON-NLS
return true;
}
} else {
return false;
}
@ -342,8 +334,7 @@ public abstract class DrawableTileBase extends DrawableUIBase {
@Override
public void handleTagAdded(ContentTagAddedEvent evt) {
getFileID().ifPresent(fileID -> {
try {
final TagName followUpTagName = getController().getTagsManager().getFollowUpTagName();
final TagName followUpTagName = getController().getTagsManager().getFollowUpTagName(); //NON-NLS
final ContentTag addedTag = evt.getAddedTag();
if (fileID == addedTag.getContent().getId()
&& addedTag.getName().equals(followUpTagName)) {
@ -352,9 +343,6 @@ public abstract class DrawableTileBase extends DrawableUIBase {
followUpToggle.setSelected(true);
});
}
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Failed to get followup tag name. Unable to update follow up status for file. ", ex); //NON-NLS
}
});
}
@ -362,16 +350,12 @@ public abstract class DrawableTileBase extends DrawableUIBase {
@Override
public void handleTagDeleted(ContentTagDeletedEvent evt) {
getFileID().ifPresent(fileID -> {
try {
final TagName followUpTagName = getController().getTagsManager().getFollowUpTagName();
final TagName followUpTagName = getController().getTagsManager().getFollowUpTagName(); //NON-NLS
final ContentTagDeletedEvent.DeletedContentTagInfo deletedTagInfo = evt.getDeletedTagInfo();
if (fileID == deletedTagInfo.getContentID()
&& deletedTagInfo.getName().equals(followUpTagName)) {
updateFollowUpIcon();
}
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Failed to get followup tag name. Unable to update follow up status for file. ", ex); //NON-NLS
}
});
}

View File

@ -427,14 +427,10 @@ public class GroupPane extends BorderPane {
tagSelectedSplitMenu.disableProperty().bind(isSelectionEmpty);
Platform.runLater(() -> {
try {
TagSelectedFilesAction followUpSelectedACtion = new TagSelectedFilesAction(controller.getTagsManager().getFollowUpTagName(), controller);
TagSelectedFilesAction followUpSelectedACtion = new TagSelectedFilesAction(controller.getTagsManager().getFollowUpTagName(), controller); //NON-NLS
tagSelectedSplitMenu.setText(followUpSelectedACtion.getText());
tagSelectedSplitMenu.setGraphic(followUpSelectedACtion.getGraphic());
tagSelectedSplitMenu.setOnAction(followUpSelectedACtion);
} catch (TskCoreException tskCoreException) {
LOGGER.log(Level.WARNING, "failed to load FollowUpTagName", tskCoreException); //NON-NLS
}
tagSelectedSplitMenu.showingProperty().addListener(showing -> {
if (tagSelectedSplitMenu.isShowing()) {
List<MenuItem> selTagMenues = Lists.transform(controller.getTagsManager().getNonCategoryTagNames(),
@ -832,11 +828,9 @@ public class GroupPane extends BorderPane {
private ContextMenu buildContextMenu() {
ArrayList<MenuItem> menuItems = new ArrayList<>();
menuItems.add(CategorizeAction.getCategoriesMenu(controller));
menuItems.add(AddTagAction.getTagMenu(controller));
Collection<? extends ContextMenuActionsProvider> menuProviders = Lookup.getDefault().lookupAll(ContextMenuActionsProvider.class);
for (ContextMenuActionsProvider provider : menuProviders) {