Search in sources :

Example 1 with OlogLog

use of org.phoebus.olog.es.api.model.OlogLog in project phoebus by ControlSystemStudio.

the class OlogClient method save.

/**
 * Calls the back-end service to persist the log entry.
 *
 * @param log       The log entry to save.
 * @param inReplyTo If non-null, this save operation will treat the <code>log</code> parameter as a reply to
 *                  the log entry represented by <code>inReplyTo</code>.
 * @return The saved log entry.
 * @throws LogbookException E.g. due to invalid log entry data.
 */
private LogEntry save(LogEntry log, LogEntry inReplyTo) throws LogbookException {
    ClientResponse clientResponse;
    try {
        MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
        queryParams.putSingle("markup", "commonmark");
        if (inReplyTo != null) {
            queryParams.putSingle("inReplyTo", Long.toString(inReplyTo.getId()));
        }
        clientResponse = service.path("logs").queryParams(queryParams).type(MediaType.APPLICATION_JSON).header(OLOG_CLIENT_INFO_HEADER, CLIENT_INFO).accept(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_JSON).put(ClientResponse.class, OlogObjectMappers.logEntrySerializer.writeValueAsString(log));
        if (clientResponse.getStatus() < 300) {
            OlogLog createdLog = OlogObjectMappers.logEntryDeserializer.readValue(clientResponse.getEntityInputStream(), OlogLog.class);
            log.getAttachments().stream().forEach(attachment -> {
                FormDataMultiPart form = new FormDataMultiPart();
                // Add id only if it is set, otherwise Jersey will complain and cause the submission to fail.
                if (attachment.getId() != null && !attachment.getId().isEmpty()) {
                    form.bodyPart(new FormDataBodyPart("id", attachment.getId()));
                }
                form.bodyPart(new FileDataBodyPart("file", attachment.getFile()));
                form.bodyPart(new FormDataBodyPart("filename", attachment.getName()));
                form.bodyPart(new FormDataBodyPart("fileMetadataDescription", attachment.getContentType()));
                ClientResponse attachmentResponse = service.path("logs").path("attachments").path(String.valueOf(createdLog.getId())).type(MediaType.MULTIPART_FORM_DATA).accept(MediaType.APPLICATION_XML).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, form);
                if (attachmentResponse.getStatus() > 300) {
                    // TODO failed to add attachments
                    logger.log(Level.SEVERE, "Failed to submit attachment(s), HTTP status: " + attachmentResponse.getStatus());
                }
            });
            clientResponse = service.path("logs").path(String.valueOf(createdLog.getId())).type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
            return OlogObjectMappers.logEntryDeserializer.readValue(clientResponse.getEntityInputStream(), OlogLog.class);
        } else if (clientResponse.getStatus() == 401) {
            logger.log(Level.SEVERE, "Submission of log entry returned HTTP status, invalid credentials");
            throw new LogbookException(Messages.SubmissionFailedInvalidCredentials);
        } else {
            logger.log(Level.SEVERE, "Submission of log entry returned HTTP status" + clientResponse.getStatus());
            throw new LogbookException(MessageFormat.format(Messages.SubmissionFailedWithHttpStatus, clientResponse.getStatus()));
        }
    } catch (UniformInterfaceException | ClientHandlerException | IOException e) {
        logger.log(Level.SEVERE, "Failed to submit log entry, got client exception", e);
        throw new LogbookException(e);
    }
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) ClientHandlerException(com.sun.jersey.api.client.ClientHandlerException) MultivaluedMapImpl(com.sun.jersey.core.util.MultivaluedMapImpl) IOException(java.io.IOException) OlogLog(org.phoebus.olog.es.api.model.OlogLog) UniformInterfaceException(com.sun.jersey.api.client.UniformInterfaceException) FormDataBodyPart(com.sun.jersey.multipart.FormDataBodyPart) FormDataMultiPart(com.sun.jersey.multipart.FormDataMultiPart) LogbookException(org.phoebus.logbook.LogbookException) FileDataBodyPart(com.sun.jersey.multipart.file.FileDataBodyPart)

Example 2 with OlogLog

use of org.phoebus.olog.es.api.model.OlogLog in project phoebus by ControlSystemStudio.

the class LogEntryEditorController method submit.

@FXML
public void submit() {
    submissionInProgress.set(true);
    JobManager.schedule("Submit Log Entry", monitor -> {
        OlogLog ologLog = new OlogLog();
        ologLog.setTitle(fieldsViewController.getTitle());
        ologLog.setDescription(fieldsViewController.getDescription());
        ologLog.setLevel(fieldsViewController.getSelectedLevel());
        ologLog.setLogbooks(fieldsViewController.getSelectedLogbooks());
        ologLog.setTags(fieldsViewController.getSelectedTags());
        ologLog.setAttachments(attachmentsViewController.getAttachments());
        ologLog.setProperties(logPropertiesEditorController.getProperties());
        LogClient logClient = logFactory.getLogClient(new SimpleAuthenticationToken(fieldsViewController.getUsernameProperty(), fieldsViewController.getPasswordProperty()));
        LogEntry result;
        try {
            if (replyTo == null) {
                result = logClient.set(ologLog);
            } else {
                result = logClient.reply(ologLog, replyTo);
            }
            if (result != null) {
                if (completionHandler != null) {
                    completionHandler.handleResult(result);
                }
                // Set username and password in secure store if submission of log entry completes successfully
                if (LogbookUIPreferences.save_credentials) {
                    // Get the SecureStore. Store username and password.
                    try {
                        SecureStore store = new SecureStore();
                        ScopedAuthenticationToken scopedAuthenticationToken = new ScopedAuthenticationToken(LogService.AUTHENTICATION_SCOPE, fieldsViewController.getUsernameProperty(), fieldsViewController.getPasswordProperty());
                        store.setScopedAuthentication(scopedAuthenticationToken);
                    } catch (Exception ex) {
                        logger.log(Level.WARNING, "Secure Store file not found.", ex);
                    }
                }
                attachmentsViewController.deleteTemporaryFiles();
                // This will close the editor
                Platform.runLater(() -> cancel());
            }
        } catch (LogbookException e) {
            logger.log(Level.WARNING, "Unable to submit log entry", e);
            Platform.runLater(() -> {
                if (e.getCause() != null && e.getCause().getMessage() != null) {
                    completionMessageLabel.textProperty().setValue(e.getCause().getMessage());
                } else if (e.getMessage() != null) {
                    completionMessageLabel.textProperty().setValue(e.getMessage());
                } else {
                    completionMessageLabel.textProperty().setValue(org.phoebus.logbook.Messages.SubmissionFailed);
                }
            });
        }
        submissionInProgress.set(false);
    });
}
Also used : LogClient(org.phoebus.logbook.LogClient) ScopedAuthenticationToken(org.phoebus.security.tokens.ScopedAuthenticationToken) LogbookException(org.phoebus.logbook.LogbookException) OlogLog(org.phoebus.olog.es.api.model.OlogLog) SecureStore(org.phoebus.security.store.SecureStore) LogEntry(org.phoebus.logbook.LogEntry) LogbookException(org.phoebus.logbook.LogbookException) ExecutionException(java.util.concurrent.ExecutionException) SimpleAuthenticationToken(org.phoebus.security.tokens.SimpleAuthenticationToken) FXML(javafx.fxml.FXML)

Example 3 with OlogLog

use of org.phoebus.olog.es.api.model.OlogLog 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 OlogLog

use of org.phoebus.olog.es.api.model.OlogLog in project phoebus by ControlSystemStudio.

the class LogEntryEditorStageDemo method start.

@Override
public void start(Stage primaryStage) throws Exception {
    StackPane root = new StackPane();
    Scene scene = new Scene(root);
    primaryStage.setScene(scene);
    new LogEntryEditorStage(root, new OlogLog()).show();
}
Also used : LogEntryEditorStage(org.phoebus.logbook.olog.ui.write.LogEntryEditorStage) Scene(javafx.scene.Scene) OlogLog(org.phoebus.olog.es.api.model.OlogLog) StackPane(javafx.scene.layout.StackPane)

Example 5 with OlogLog

use of org.phoebus.olog.es.api.model.OlogLog 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)

Aggregations

OlogLog (org.phoebus.olog.es.api.model.OlogLog)8 LogEntry (org.phoebus.logbook.LogEntry)4 LogbookException (org.phoebus.logbook.LogbookException)4 LogEntryEditorStage (org.phoebus.logbook.olog.ui.write.LogEntryEditorStage)4 FXML (javafx.fxml.FXML)3 Attachment (org.phoebus.logbook.Attachment)3 LogClient (org.phoebus.logbook.LogClient)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 Scene (javafx.scene.Scene)2 Logbook (org.phoebus.logbook.Logbook)2 Property (org.phoebus.logbook.Property)2 Tag (org.phoebus.logbook.Tag)2 OlogAttachment (org.phoebus.olog.es.api.model.OlogAttachment)2 ClientHandlerException (com.sun.jersey.api.client.ClientHandlerException)1 ClientResponse (com.sun.jersey.api.client.ClientResponse)1 UniformInterfaceException (com.sun.jersey.api.client.UniformInterfaceException)1 MultivaluedMapImpl (com.sun.jersey.core.util.MultivaluedMapImpl)1 FormDataBodyPart (com.sun.jersey.multipart.FormDataBodyPart)1 FormDataMultiPart (com.sun.jersey.multipart.FormDataMultiPart)1