Search in sources :

Example 6 with LogbookException

use of org.phoebus.logbook.LogbookException 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 7 with LogbookException

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

the class ElogApi method search.

/**
 * Searches the logbook and returns the message ids.
 *
 * @param search_term
 * @param {@link ElogEntry}
 */
public List<ElogEntry> search(Map<String, String> search_term) throws LogbookException {
    Map<String, Object> params = new HashMap<>();
    params.put("mode", "summary");
    params.put("reverse", "1");
    // number of returned results...
    params.put("npp", 20);
    params.putAll(search_term);
    Map<String, Object> cookies = new HashMap<>();
    cookies.put("unm", this.username);
    cookies.put("upwd", this.password);
    Response<String> resp = Requests.get(this.url).cookies(cookies).params(params).followRedirect(false).verify(false).send().toTextResponse();
    validateResponse(resp);
    List<ElogEntry> entries = new ArrayList<>();
    try {
        TagNode tagNode = new HtmlCleaner().clean(resp.body());
        org.w3c.dom.Document doc = new DomSerializer(new CleanerProperties()).createDOM(tagNode);
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList msgIds = (NodeList) xpath.evaluate("(//tr/td[@class=\"list1\" or @class=\"list2\"][1])/a/@href", doc, XPathConstants.NODESET);
        for (int i = 0; i < msgIds.getLength(); i++) {
            String msgIdStr = msgIds.item(i).getNodeValue();
            entries.add(read(Long.valueOf(msgIdStr.substring(msgIdStr.lastIndexOf('/') + 1))));
        }
    } catch (XPathExpressionException | ParserConfigurationException e) {
        throw new LogbookException("could not parse the elog response", e);
    }
    return entries;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) HtmlCleaner(org.htmlcleaner.HtmlCleaner) DomSerializer(org.htmlcleaner.DomSerializer) CleanerProperties(org.htmlcleaner.CleanerProperties) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) LogbookException(org.phoebus.logbook.LogbookException) TagNode(org.htmlcleaner.TagNode)

Example 8 with LogbookException

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

the class ElogApi method getMessages.

/**
 * Get a list of all messages on logbook
 */
public List<ElogEntry> getMessages() throws LogbookException {
    Map<String, Object> cookies = new HashMap<>();
    cookies.put("unm", this.username);
    cookies.put("upwd", this.password);
    Response<String> resp = Requests.get(this.url + "page?mode=summary").cookies(cookies).followRedirect(false).verify(false).send().toTextResponse();
    validateResponse(resp);
    List<ElogEntry> entries = new ArrayList<>();
    try {
        TagNode tagNode = new HtmlCleaner().clean(resp.body());
        org.w3c.dom.Document doc = new DomSerializer(new CleanerProperties()).createDOM(tagNode);
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList msgIds = (NodeList) xpath.evaluate("(//tr/td[@class=\"list1\" or @class=\"list2\"][1])/a/@href", doc, XPathConstants.NODESET);
        for (int i = 0; i < msgIds.getLength(); i++) {
            String msgIdStr = msgIds.item(i).getNodeValue();
            entries.add(read(Long.valueOf(msgIdStr.substring(msgIdStr.lastIndexOf('/') + 1))));
        }
    } catch (XPathExpressionException | ParserConfigurationException e) {
        throw new LogbookException("could not parse the elog response", e);
    }
    return entries;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) HtmlCleaner(org.htmlcleaner.HtmlCleaner) DomSerializer(org.htmlcleaner.DomSerializer) CleanerProperties(org.htmlcleaner.CleanerProperties) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) LogbookException(org.phoebus.logbook.LogbookException) TagNode(org.htmlcleaner.TagNode)

Example 9 with LogbookException

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

the class ElogApi method getCategories.

/**
 * Get list of available categories
 *
 * @return Collection<String>
 */
public Collection<String> getCategories() throws LogbookException {
    Map<String, Object> cookies = new HashMap<>();
    cookies.put("unm", this.username);
    cookies.put("upwd", this.password);
    Response<String> resp = Requests.get(this.url + "?cmd=new").cookies(cookies).followRedirect(false).verify(false).send().toTextResponse();
    // validateResponse( resp );
    // validateResponse does not work here, as the response body contains
    // "form name=form1"....
    int statuscode = resp.statusCode();
    if (statuscode != 200 && statuscode != 302) {
        final Pattern pattern = Pattern.compile("<td.*?class=\"errormsg\".*?>(.*?)</td>");
        Matcher m = pattern.matcher(resp.body());
        if (m.matches()) {
            String err = m.group();
            throw new LogbookException("Rejected because of: " + err);
        } else {
            throw new LogbookException("Rejected because of unknown error.");
        }
    } else {
        String location = resp.getHeader("Location");
        if (location != null && !location.isEmpty()) {
            if (location.contains("has moved")) {
                throw new LogbookException("Logbook server has moved to another location.");
            } else if (location.contains("fail")) {
                throw new LogbookException("Failed to submit log entry, invalid credentials.");
            }
        }
    }
    List<String> categories = new ArrayList<>();
    try {
        TagNode tagNode = new HtmlCleaner().clean(resp.body());
        org.w3c.dom.Document doc = new DomSerializer(new CleanerProperties()).createDOM(tagNode);
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList catnodes = (NodeList) xpath.evaluate("//tr/td[@class=\"attribvalue\"]/select[@name=\"Category\"]/option/@value", doc, XPathConstants.NODESET);
        for (int i = 0; i < catnodes.getLength(); i++) {
            String c = catnodes.item(i).getNodeValue();
            if (!c.isEmpty()) {
                categories.add(c);
            }
        }
    } catch (XPathExpressionException | ParserConfigurationException e) {
        throw new LogbookException("could not parse the elog response", e);
    }
    return categories;
}
Also used : XPath(javax.xml.xpath.XPath) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) HtmlCleaner(org.htmlcleaner.HtmlCleaner) DomSerializer(org.htmlcleaner.DomSerializer) CleanerProperties(org.htmlcleaner.CleanerProperties) LogbookException(org.phoebus.logbook.LogbookException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TagNode(org.htmlcleaner.TagNode)

Example 10 with LogbookException

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

the class ElogApi method validateResponse.

/**
 * Validate response of the request.
 *
 * @param resp
 * @return id of new message
 */
private long validateResponse(Response<String> resp) throws LogbookException {
    int statuscode = resp.statusCode();
    String body = resp.body();
    long msgId = -1;
    if (statuscode != 200 && statuscode != 302) {
        final Pattern pattern = Pattern.compile("<td.*?class=\"errormsg\".*?>(.*?)</td>");
        Matcher m = pattern.matcher(body);
        if (m.matches()) {
            String err = m.group();
            throw new LogbookException("Rejected because of: " + err);
        } else {
            throw new LogbookException("Rejected because of unknown error.");
        }
    } else {
        String location = resp.getHeader("Location");
        if (location != null && !location.isEmpty()) {
            if (location.contains("has moved")) {
                throw new LogbookException("Logbook server has moved to another location.");
            } else if (location.contains("fail")) {
                throw new LogbookException("Failed to submit log entry, invalid credentials.");
            } else {
                URI loc = URI.create(location);
                String[] path = loc.getPath().split("/");
                msgId = Integer.parseInt(path[path.length - 1]);
            }
        }
        if (body.contains("form name=form1") || body.contains("type=password")) {
            throw new LogbookException("Failed to submit log entry, invalid credentials.");
        }
    }
    return msgId;
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) LogbookException(org.phoebus.logbook.LogbookException) URI(java.net.URI)

Aggregations

LogbookException (org.phoebus.logbook.LogbookException)11 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)4 XPath (javax.xml.xpath.XPath)4 XPathExpressionException (javax.xml.xpath.XPathExpressionException)4 CleanerProperties (org.htmlcleaner.CleanerProperties)4 DomSerializer (org.htmlcleaner.DomSerializer)4 HtmlCleaner (org.htmlcleaner.HtmlCleaner)4 TagNode (org.htmlcleaner.TagNode)4 NodeList (org.w3c.dom.NodeList)4 Matcher (java.util.regex.Matcher)3 Pattern (java.util.regex.Pattern)3 Property (org.phoebus.logbook.Property)3 OlogLog (org.phoebus.olog.es.api.model.OlogLog)3 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 FXML (javafx.fxml.FXML)2 Test (org.junit.Test)2 LogClient (org.phoebus.logbook.LogClient)2 LogEntry (org.phoebus.logbook.LogEntry)2 ClientHandlerException (com.sun.jersey.api.client.ClientHandlerException)1