Search in sources :

Example 1 with Attachment

use of org.phoebus.logbook.Attachment in project phoebus by ControlSystemStudio.

the class AttachmentsPreviewController method initialize.

@FXML
public void initialize() {
    attachmentListView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    attachmentListView.setCellFactory(view -> new AttachmentRow());
    attachmentListView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<>() {

        /**
         * Shows preview of selected attachment.
         * @param observable
         * @param oldValue
         * @param newValue
         */
        @Override
        public void changed(ObservableValue<? extends Attachment> observable, Attachment oldValue, Attachment newValue) {
            selectedAttachment.set(newValue);
            showPreview();
        }
    });
    attachmentListView.setOnMouseClicked(me -> {
        if (me.getClickCount() == 2) {
            Attachment attachment = attachmentListView.getSelectionModel().getSelectedItem();
            if (!attachment.getContentType().startsWith("image")) {
                // First try to open the file with an internal Phoebus app
                AppResourceDescriptor defaultApp = ApplicationLauncherService.findApplication(attachment.getFile().toURI(), true, null);
                if (defaultApp != null) {
                    defaultApp.create(attachment.getFile().toURI());
                    return;
                }
                // If not internal apps are found look for external apps
                String fileName = attachment.getFile().getName();
                String[] parts = fileName.split("\\.");
                if (parts.length == 1 || !ApplicationService.getExtensionsHandledByExternalApp().contains(parts[parts.length - 1])) {
                    // If there is no app configured for the file type, show an error message and return.
                    ExceptionDetailsErrorDialog.openError(Messages.PreviewOpenErrorTitle, Messages.PreviewOpenErrorBody, null);
                    return;
                }
            }
            ApplicationLauncherService.openFile(attachment.getFile(), false, null);
        }
    });
    attachmentListView.getSelectionModel().getSelectedItems().addListener(new ListChangeListener<>() {

        /**
         * Notifies listeners of list selection change.
         * @param change
         */
        @Override
        public void onChanged(Change<? extends Attachment> change) {
            selectedAttachments.setAll(change.getList());
            listSelectionChangeListeners.stream().forEach(l -> l.onChanged(change));
        }
    });
    attachmentListView.setOnContextMenuRequested((e) -> {
        ContextMenu contextMenu = new ContextMenu();
        MenuItem menuItem = new MenuItem(Messages.DownloadSelected);
        menuItem.setOnAction(actionEvent -> downloadSelectedAttachments());
        menuItem.disableProperty().bind(Bindings.createBooleanBinding(() -> selectedAttachments.isEmpty(), selectedAttachments));
        contextMenu.getItems().add(menuItem);
        URI selectedResource = !selectedAttachments.isEmpty() ? selectedAttachments.get(0).getFile().toURI() : null;
        if (selectedResource != null) {
            contextMenu.getItems().add(new SeparatorMenuItem());
            final List<AppResourceDescriptor> applications = ApplicationService.getApplications(selectedResource);
            applications.forEach(app -> {
                MenuItem appMenuItem = new MenuItem(app.getDisplayName());
                appMenuItem.setGraphic(ImageCache.getImageView(app.getIconURL()));
                appMenuItem.setOnAction(actionEvent -> app.create(selectedResource));
                contextMenu.getItems().add(appMenuItem);
            });
        }
        attachmentListView.setContextMenu(contextMenu);
    });
    imagePreview.fitWidthProperty().bind(previewPane.widthProperty());
    imagePreview.fitHeightProperty().bind(previewPane.heightProperty());
    imagePreview.hoverProperty().addListener((event) -> {
        if (((ReadOnlyBooleanProperty) event).get()) {
            splitPane.getScene().setCursor(Cursor.HAND);
        } else {
            splitPane.getScene().setCursor(Cursor.DEFAULT);
        }
    });
    imagePreview.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
        if (selectedAttachment.get() != null && selectedAttachment.get().getContentType().startsWith("image")) {
            ApplicationLauncherService.openFile(selectedAttachment.get().getFile(), false, null);
        }
        event.consume();
    });
}
Also used : JobManager(org.phoebus.framework.jobs.JobManager) javafx.scene.control(javafx.scene.control) MouseEvent(javafx.scene.input.MouseEvent) ReadOnlyBooleanProperty(javafx.beans.property.ReadOnlyBooleanProperty) FXCollections(javafx.collections.FXCollections) StackPane(javafx.scene.layout.StackPane) Bindings(javafx.beans.binding.Bindings) ApplicationService(org.phoebus.framework.workbench.ApplicationService) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) ListChangeListener(javafx.collections.ListChangeListener) ApplicationLauncherService(org.phoebus.ui.application.ApplicationLauncherService) ImageIO(javax.imageio.ImageIO) URI(java.net.URI) Attachment(org.phoebus.logbook.Attachment) GridPane(javafx.scene.layout.GridPane) DirectoryChooser(javafx.stage.DirectoryChooser) ImageCache(org.phoebus.ui.javafx.ImageCache) BufferedImage(java.awt.image.BufferedImage) Files(java.nio.file.Files) IOException(java.io.IOException) Logger(java.util.logging.Logger) File(java.io.File) FXML(javafx.fxml.FXML) Cursor(javafx.scene.Cursor) List(java.util.List) SimpleObjectProperty(javafx.beans.property.SimpleObjectProperty) ImageView(javafx.scene.image.ImageView) SwingFXUtils(javafx.embed.swing.SwingFXUtils) AppResourceDescriptor(org.phoebus.framework.spi.AppResourceDescriptor) ObservableValue(javafx.beans.value.ObservableValue) ObservableList(javafx.collections.ObservableList) ChangeListener(javafx.beans.value.ChangeListener) Image(javafx.scene.image.Image) AttachmentsViewController(org.phoebus.logbook.olog.ui.write.AttachmentsViewController) ExceptionDetailsErrorDialog(org.phoebus.ui.dialog.ExceptionDetailsErrorDialog) Attachment(org.phoebus.logbook.Attachment) URI(java.net.URI) AppResourceDescriptor(org.phoebus.framework.spi.AppResourceDescriptor) ReadOnlyBooleanProperty(javafx.beans.property.ReadOnlyBooleanProperty) FXML(javafx.fxml.FXML)

Example 2 with Attachment

use of org.phoebus.logbook.Attachment in project phoebus by ControlSystemStudio.

the class SendLogbookAction method submitLogEntry.

private void submitLogEntry(final Node parent, final String title, final String body, final File image_file) {
    LogEntryBuilder logEntryBuilder = new LogEntryBuilder();
    if (title != null)
        logEntryBuilder.title(title);
    if (body != null)
        logEntryBuilder.appendDescription(body);
    if (image_file != null) {
        try {
            final Attachment attachment = AttachmentImpl.of(image_file, "image", false);
            logEntryBuilder.attach(attachment);
        } catch (FileNotFoundException ex) {
            logger.log(Level.WARNING, "Cannot attach " + image_file, ex);
        }
    }
    final LogEntryModel model = new LogEntryModel(logEntryBuilder.createdDate(Instant.now()).build());
    new LogEntryEditorStage(parent, model, null).show();
}
Also used : LogEntryModel(org.phoebus.logbook.ui.write.LogEntryModel) FileNotFoundException(java.io.FileNotFoundException) LogEntryBuilder(org.phoebus.logbook.LogEntryImpl.LogEntryBuilder) Attachment(org.phoebus.logbook.Attachment) LogEntryEditorStage(org.phoebus.logbook.ui.write.LogEntryEditorStage)

Example 3 with Attachment

use of org.phoebus.logbook.Attachment in project phoebus by ControlSystemStudio.

the class LogEntryDisplayDemo method start.

@Override
public void start(Stage primaryStage) throws Exception {
    primaryStage.setTitle("LogEntry Display demo");
    BorderPane root;
    ResourceBundle resourceBundle = NLS.getMessages(Messages.class);
    FXMLLoader loader = new FXMLLoader();
    loader.setResources(resourceBundle);
    loader.setLocation(this.getClass().getResource("LogEntryDisplay.fxml"));
    loader.setControllerFactory(clazz -> {
        try {
            if (clazz.isAssignableFrom(LogEntryTableViewController.class)) {
                return clazz.getConstructor(LogClient.class).newInstance(getLogClient());
            } else if (clazz.isAssignableFrom(AdvancedSearchViewController.class)) {
                return clazz.getConstructor(LogClient.class).newInstance(getLogClient());
            } else if (clazz.isAssignableFrom(LogPropertiesController.class)) {
                return clazz.getConstructor().newInstance();
            } else if (clazz.isAssignableFrom(AttachmentsPreviewController.class)) {
                return clazz.getConstructor().newInstance();
            } else if (clazz.isAssignableFrom(LogEntryCellController.class)) {
                return clazz.getConstructor().newInstance();
            } else if (clazz.isAssignableFrom(LogEntryDisplayController.class)) {
                return clazz.getConstructor(LogClient.class).newInstance(getLogClient());
            } else if (clazz.isAssignableFrom(MergedLogEntryDisplayController.class)) {
                return clazz.getConstructor(LogClient.class).newInstance(getLogClient());
            } else if (clazz.isAssignableFrom(SingleLogEntryDisplayController.class)) {
                return clazz.getConstructor(LogClient.class).newInstance(getLogClient());
            } else {
                throw new RuntimeException("No controller for class " + clazz.getName());
            }
        } catch (Exception e) {
            Logger.getLogger(LogEntryEditorStage.class.getName()).log(Level.SEVERE, "Failed to construct controller for log calendar view", e);
        }
        return null;
    });
    loader.load();
    LogEntryDisplayController controller = loader.getController();
    root = loader.getRoot();
    primaryStage.setScene(new Scene(root, 400, 400));
    primaryStage.show();
    // Every few seconds add a new log entry
    ex.schedule(() -> {
        OlogLog ologLog = new OlogLog(1L);
        ologLog.setDescription("Fast correctors for the vertical orbit have glitched to near saturation. Archiver shows there have been several episodes the past 24 hrs. Appears that FOFB in vertical plane might have momentary bad BPM reading.");
        ologLog.setCreatedDate(Instant.now());
        runLater(() -> {
            controller.setLogEntry(ologLog);
        });
    }, 2, TimeUnit.SECONDS);
    ex.schedule(() -> {
        Set<Tag> tags = new HashSet<Tag>();
        tags.add(TagImpl.of("tag1", "active"));
        tags.add(TagImpl.of("tag2", "active"));
        Set<Logbook> logbooks = new HashSet<Logbook>();
        logbooks.add(LogbookImpl.of("logbook1", "active"));
        logbooks.add(LogbookImpl.of("logbook2", "active"));
        LogEntry logEntry = controller.getLogEntry();
        runLater(() -> {
            OlogLog anotherLog = new OlogLog(2L);
            anotherLog.setDescription(controller.getLogEntry().getDescription());
            anotherLog.setCreatedDate(controller.getLogEntry().getCreatedDate());
            anotherLog.setTags(tags);
            anotherLog.setLogbooks(logbooks);
            controller.setLogEntry(anotherLog);
        });
    }, 2, TimeUnit.SECONDS);
    ex.schedule(() -> {
        Set<Tag> tags = new HashSet<Tag>();
        tags.add(TagImpl.of("tag1", "active"));
        tags.add(TagImpl.of("tag2", "active"));
        Set<Logbook> logbooks = new HashSet<Logbook>();
        logbooks.add(LogbookImpl.of("logbook1", "active"));
        logbooks.add(LogbookImpl.of("logbook2", "active"));
        Map<String, String> tracAttributes = new HashMap<>();
        tracAttributes.put("id", "1234");
        tracAttributes.put("URL", "https://trac.epics.org/tickets/1234");
        Property track = PropertyImpl.of("Track", tracAttributes);
        Map<String, String> experimentAttributes = new HashMap<>();
        experimentAttributes.put("id", "1234");
        experimentAttributes.put("type", "XPD xray diffraction");
        experimentAttributes.put("scan-id", "6789");
        Property experimentProperty = PropertyImpl.of("Experiment", experimentAttributes);
        runLater(() -> {
            OlogLog ologLog = new OlogLog(3L);
            ologLog.setCreatedDate(Instant.now());
            ologLog.setTitle("A report on the orbit studies");
            ologLog.setDescription("Fast correctors for the vertical orbit have glitched to near saturation. Archiver shows there have been several episodes the past 24 hrs. Appears that FOFB in vertical plane might have momentary bad BPM reading.");
            ologLog.setTags(new HashSet(Arrays.asList(TagImpl.of("Orbit", "active"), TagImpl.of("Studies", "active"))));
            ologLog.setLogbooks(new HashSet(Arrays.asList(LogbookImpl.of("Operations", "active"))));
            ologLog.setProperties(Arrays.asList(track, experimentProperty));
            List<Attachment> attachments = new ArrayList<>();
            OlogAttachment attachment1 = new OlogAttachment("image_1.png");
            attachment1.setFileName("image_1.png");
            attachment1.setContentType("image");
            OlogAttachment attachment2 = new OlogAttachment("file_phoebus.txt");
            attachment2.setFileName("file_phoebus.txt");
            attachment2.setContentType("text");
            attachments.add(attachment1);
            attachments.add(attachment2);
            ologLog.setAttachments(attachments);
            controller.setLogEntry(ologLog);
        });
    }, 2, TimeUnit.SECONDS);
}
Also used : BorderPane(javafx.scene.layout.BorderPane) LogClient(org.phoebus.logbook.LogClient) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) OlogAttachment(org.phoebus.olog.es.api.model.OlogAttachment) Attachment(org.phoebus.logbook.Attachment) OlogLog(org.phoebus.olog.es.api.model.OlogLog) FXMLLoader(javafx.fxml.FXMLLoader) Logbook(org.phoebus.logbook.Logbook) OlogAttachment(org.phoebus.olog.es.api.model.OlogAttachment) Property(org.phoebus.logbook.Property) LogEntry(org.phoebus.logbook.LogEntry) HashSet(java.util.HashSet) LogEntryEditorStage(org.phoebus.logbook.olog.ui.write.LogEntryEditorStage) Scene(javafx.scene.Scene) LogbookException(org.phoebus.logbook.LogbookException) ResourceBundle(java.util.ResourceBundle) Tag(org.phoebus.logbook.Tag)

Example 4 with Attachment

use of org.phoebus.logbook.Attachment in project phoebus by ControlSystemStudio.

the class SingleLogEntryDisplayController method fetchAttachments.

/**
 * Retrieves the actual attachments from the remote service and copies them to temporary files. The idea is that attachments
 * should be retrieved when user requests to see the details, not in connection to a log entry search.
 * @return A {@link Collection} of {@link Attachment}s holding the attachment content.
 */
private void fetchAttachments() {
    JobManager.schedule("Fetch attachment data", monitor -> {
        Collection<Attachment> attachments = logEntry.getAttachments().stream().filter((attachment) -> {
            return attachment.getName() != null && !attachment.getName().isEmpty();
        }).map((attachment) -> {
            OlogAttachment fileAttachment = new OlogAttachment();
            fileAttachment.setContentType(attachment.getContentType());
            fileAttachment.setThumbnail(false);
            fileAttachment.setFileName(attachment.getName());
            try {
                Path temp = Files.createTempFile("phoebus", attachment.getName());
                Files.copy(logClient.getAttachment(logEntry.getId(), attachment.getName()), temp, StandardCopyOption.REPLACE_EXISTING);
                fileAttachment.setFile(temp.toFile());
                temp.toFile().deleteOnExit();
            } catch (LogbookException | IOException e) {
                Logger.getLogger(SingleLogEntryDisplayController.class.getName()).log(Level.WARNING, "Failed to retrieve attachment " + fileAttachment.getFileName(), e);
            }
            return fileAttachment;
        }).collect(Collectors.toList());
        // // TODO: to allow the UI to be used by non Olog log services commenting out the cast to OlogLog,
        // // the model will not be updated.
        // // Update the log entry attachments object
        // ((OlogLog)logEntry).setAttachments(attachments);
        // // Update UI
        // Platform.runLater(() -> attachmentsPreviewController
        // .setAttachments(FXCollections.observableArrayList(logEntry.getAttachments())));
        // Update UI
        Platform.runLater(() -> attachmentsPreviewController.setAttachments(FXCollections.observableArrayList(attachments)));
    });
}
Also used : Button(javafx.scene.control.Button) LogEntry(org.phoebus.logbook.LogEntry) OlogAttachment(org.phoebus.olog.es.api.model.OlogAttachment) WebEngine(javafx.scene.web.WebEngine) JobManager(org.phoebus.framework.jobs.JobManager) Arrays(java.util.Arrays) FXCollections(javafx.collections.FXCollections) VBox(javafx.scene.layout.VBox) StandardCopyOption(java.nio.file.StandardCopyOption) Level(java.util.logging.Level) Property(org.phoebus.logbook.Property) Attachment(org.phoebus.logbook.Attachment) Path(java.nio.file.Path) LogbookException(org.phoebus.logbook.LogbookException) SECONDS_FORMAT(org.phoebus.util.time.TimestampFormats.SECONDS_FORMAT) WebView(javafx.scene.web.WebView) Logbook(org.phoebus.logbook.Logbook) ImageCache(org.phoebus.ui.javafx.ImageCache) Label(javafx.scene.control.Label) TitledPane(javafx.scene.control.TitledPane) Files(java.nio.file.Files) Collection(java.util.Collection) Tag(org.phoebus.logbook.Tag) IOException(java.io.IOException) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Platform(javafx.application.Platform) FXML(javafx.fxml.FXML) List(java.util.List) Clipboard(javafx.scene.input.Clipboard) ImageView(javafx.scene.image.ImageView) ObservableList(javafx.collections.ObservableList) ClipboardContent(javafx.scene.input.ClipboardContent) OlogLog(org.phoebus.olog.es.api.model.OlogLog) Image(javafx.scene.image.Image) LogClient(org.phoebus.logbook.LogClient) Path(java.nio.file.Path) OlogAttachment(org.phoebus.olog.es.api.model.OlogAttachment) OlogAttachment(org.phoebus.olog.es.api.model.OlogAttachment) Attachment(org.phoebus.logbook.Attachment)

Example 5 with Attachment

use of org.phoebus.logbook.Attachment in project phoebus by ControlSystemStudio.

the class LogPropertiesEditorDemo method getDummyLogClient.

private LogClient getDummyLogClient() {
    return new LogClient() {

        @Override
        public LogEntry set(LogEntry log) throws LogbookException {
            return null;
        }

        @Override
        public LogEntry getLog(Long logId) {
            return null;
        }

        @Override
        public Collection<Attachment> listAttachments(Long logId) {
            return null;
        }

        @Override
        public List<LogEntry> findLogs(Map<String, String> map) {
            return null;
        }

        @Override
        public Collection<LogEntry> listLogs() {
            return null;
        }

        @Override
        public Collection<Property> listProperties() {
            Map<String, String> experimentAttributes = new HashMap<>();
            experimentAttributes.put("id", "1234");
            experimentAttributes.put("type", "XPD xray diffraction");
            experimentAttributes.put("scan-id", "6789");
            Property experimentProperty = PropertyImpl.of("Experiment", experimentAttributes);
            return Arrays.asList(experimentProperty);
        }
    };
}
Also used : LogClient(org.phoebus.logbook.LogClient) Attachment(org.phoebus.logbook.Attachment) Property(org.phoebus.logbook.Property) LogEntry(org.phoebus.logbook.LogEntry)

Aggregations

Attachment (org.phoebus.logbook.Attachment)7 ArrayList (java.util.ArrayList)3 LogClient (org.phoebus.logbook.LogClient)3 LogEntry (org.phoebus.logbook.LogEntry)3 Property (org.phoebus.logbook.Property)3 OlogLog (org.phoebus.olog.es.api.model.OlogLog)3 FileNotFoundException (java.io.FileNotFoundException)2 IOException (java.io.IOException)2 Files (java.nio.file.Files)2 List (java.util.List)2 Level (java.util.logging.Level)2 Logger (java.util.logging.Logger)2 FXCollections (javafx.collections.FXCollections)2 ObservableList (javafx.collections.ObservableList)2 FXML (javafx.fxml.FXML)2 Image (javafx.scene.image.Image)2 ImageView (javafx.scene.image.ImageView)2 JobManager (org.phoebus.framework.jobs.JobManager)2 Logbook (org.phoebus.logbook.Logbook)2 LogbookException (org.phoebus.logbook.LogbookException)2