Search in sources :

Example 1 with Property

use of org.phoebus.olog.entity.Property in project phoebus-olog by Olog.

the class LogResource method groupLogEntries.

@SuppressWarnings("unused")
@PostMapping(value = "/group")
public void groupLogEntries(@RequestBody List<Long> logEntryIds) {
    logger.log(Level.INFO, "Grouping log entries: " + logEntryIds.stream().map(id -> Long.toString(id)).collect(Collectors.joining(",")));
    Property existingLogEntryGroupProperty = null;
    List<Log> logs = new ArrayList<>();
    // the same group. If not, throw exception.
    synchronized (logGroupSyncObject) {
        for (Long id : logEntryIds) {
            Optional<Log> log = null;
            try {
                log = logRepository.findById(Long.toString(id));
            } catch (ResponseStatusException exception) {
                throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Log id " + id + " not found");
            }
            Property logEntryGroupProperty = LogEntryGroupHelper.getLogEntryGroupProperty(log.get());
            if (logEntryGroupProperty != null && existingLogEntryGroupProperty != null && !logEntryGroupProperty.getAttribute(LogEntryGroupHelper.ATTRIBUTE_ID).equals(existingLogEntryGroupProperty.getAttribute(LogEntryGroupHelper.ATTRIBUTE_ID))) {
                logger.log(Level.INFO, "Grouping not allowed due to conflicting log entry groups.");
                throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cannot group: at least two entries already contained in different groups");
            }
            if (logEntryGroupProperty != null) {
                existingLogEntryGroupProperty = logEntryGroupProperty;
            }
            logs.add(log.get());
        }
        final Property logEntryGroupProperty;
        // If no existing log entry group was found, create a new.
        if (existingLogEntryGroupProperty == null) {
            logEntryGroupProperty = LogEntryGroupHelper.createNewLogEntryProperty();
        } else {
            logEntryGroupProperty = existingLogEntryGroupProperty;
        }
        // Now update the log entries by adding the log group property. Except for those that already have it.
        logs.forEach(log -> {
            if (LogEntryGroupHelper.getLogEntryGroupProperty(log) == null) {
                log.getProperties().add(logEntryGroupProperty);
                logRepository.update(log);
            }
        });
    }
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) Autowired(org.springframework.beans.factory.annotation.Autowired) MarkupCleaner(org.phoebus.olog.entity.preprocess.MarkupCleaner) RequestPart(org.springframework.web.bind.annotation.RequestPart) Valid(javax.validation.Valid) TimeParser(org.phoebus.util.time.TimeParser) PutMapping(org.springframework.web.bind.annotation.PutMapping) InputStreamResource(org.springframework.core.io.InputStreamResource) TaskExecutor(org.springframework.core.task.TaskExecutor) Resource(org.springframework.core.io.Resource) PostMapping(org.springframework.web.bind.annotation.PostMapping) ResponseStatusException(org.springframework.web.server.ResponseStatusException) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) Set(java.util.Set) Instant(java.time.Instant) Logger(java.util.logging.Logger) RestController(org.springframework.web.bind.annotation.RestController) Collectors(java.util.stream.Collectors) LOG_RESOURCE_URI(org.phoebus.olog.OlogResourceDescriptors.LOG_RESOURCE_URI) LogPropertyProvider(org.phoebus.olog.entity.preprocess.LogPropertyProvider) List(java.util.List) Principal(java.security.Principal) Optional(java.util.Optional) RequestHeader(org.springframework.web.bind.annotation.RequestHeader) Property(org.phoebus.olog.entity.Property) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) CompletableFuture(java.util.concurrent.CompletableFuture) Log(org.phoebus.olog.entity.Log) CollectionUtils(org.apache.commons.collections4.CollectionUtils) LogEntryGroupHelper(org.phoebus.olog.entity.LogEntryGroupHelper) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) RequestBody(org.springframework.web.bind.annotation.RequestBody) HashSet(java.util.HashSet) ContentDisposition(org.springframework.http.ContentDisposition) GetMapping(org.springframework.web.bind.annotation.GetMapping) TemporalAmount(java.time.temporal.TemporalAmount) ExecutorService(java.util.concurrent.ExecutorService) LogEntryNotifier(org.phoebus.olog.notification.LogEntryNotifier) Tag(org.phoebus.olog.entity.Tag) MultiValueMap(org.springframework.util.MultiValueMap) IOException(java.io.IOException) Attachment(org.phoebus.olog.entity.Attachment) TimeUnit(java.util.concurrent.TimeUnit) HttpStatus(org.springframework.http.HttpStatus) SearchResult(org.phoebus.olog.entity.SearchResult) AuthenticationPrincipal(org.springframework.security.core.annotation.AuthenticationPrincipal) MultipartFile(org.springframework.web.multipart.MultipartFile) ResponseEntity(org.springframework.http.ResponseEntity) MILLI_FORMAT(org.phoebus.util.time.TimestampFormats.MILLI_FORMAT) Log(org.phoebus.olog.entity.Log) ArrayList(java.util.ArrayList) Property(org.phoebus.olog.entity.Property) ResponseStatusException(org.springframework.web.server.ResponseStatusException) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 2 with Property

use of org.phoebus.olog.entity.Property in project phoebus-olog by Olog.

the class PropertyRepository method deleteById.

@Override
public void deleteById(String propertyName) {
    try {
        UpdateResponse response = client.update(new UpdateRequest(ES_PROPERTY_INDEX, ES_PROPERTY_TYPE, propertyName).doc(jsonBuilder().startObject().field("state", State.Inactive).endObject()).setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT);
        if (response.getResult().equals(Result.UPDATED)) {
            BytesReference ref = client.get(new GetRequest(ES_PROPERTY_INDEX, ES_PROPERTY_TYPE, response.getId()), RequestOptions.DEFAULT).getSourceAsBytesRef();
            Property deletedProperty = mapper.readValue(ref.streamInput(), Property.class);
            logger.log(Level.INFO, "Deleted property " + deletedProperty.toLogger());
        }
    } catch (DocumentMissingException e) {
        logger.log(Level.SEVERE, "Failed to delete property: " + propertyName + " because it does not exist", e);
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Failed to delete property: " + propertyName + " because it does not exist");
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Failed to delete property: " + propertyName, e);
        throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to delete property: " + propertyName);
    }
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) UpdateResponse(org.elasticsearch.action.update.UpdateResponse) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) MultiGetRequest(org.elasticsearch.action.get.MultiGetRequest) GetRequest(org.elasticsearch.action.get.GetRequest) DocumentMissingException(org.elasticsearch.index.engine.DocumentMissingException) Property(org.phoebus.olog.entity.Property) ResponseStatusException(org.springframework.web.server.ResponseStatusException) ResponseStatusException(org.springframework.web.server.ResponseStatusException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) DocumentMissingException(org.elasticsearch.index.engine.DocumentMissingException)

Example 3 with Property

use of org.phoebus.olog.entity.Property in project phoebus-olog by Olog.

the class PropertyRepository method findAllById.

@Override
public Iterable<Property> findAllById(Iterable<String> propertyNames) {
    MultiGetRequest request = new MultiGetRequest();
    for (String propertyName : propertyNames) {
        request.add(new MultiGetRequest.Item(ES_PROPERTY_INDEX, ES_PROPERTY_TYPE, propertyName));
    }
    try {
        List<Property> foundProperties = new ArrayList<Property>();
        MultiGetResponse response = client.mget(request, RequestOptions.DEFAULT);
        for (MultiGetItemResponse multiGetItemResponse : response) {
            if (!multiGetItemResponse.isFailed()) {
                GetResponse res = multiGetItemResponse.getResponse();
                StreamInput str = res.getSourceAsBytesRef().streamInput();
                foundProperties.add(mapper.readValue(str, Property.class));
            }
        }
        return foundProperties;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Failed to find properties: " + propertyNames, e);
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Failed to find properties: " + propertyNames);
    }
}
Also used : MultiGetResponse(org.elasticsearch.action.get.MultiGetResponse) MultiGetItemResponse(org.elasticsearch.action.get.MultiGetItemResponse) ArrayList(java.util.ArrayList) StreamInput(org.elasticsearch.common.io.stream.StreamInput) Property(org.phoebus.olog.entity.Property) GetResponse(org.elasticsearch.action.get.GetResponse) MultiGetResponse(org.elasticsearch.action.get.MultiGetResponse) ResponseStatusException(org.springframework.web.server.ResponseStatusException) ResponseStatusException(org.springframework.web.server.ResponseStatusException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) DocumentMissingException(org.elasticsearch.index.engine.DocumentMissingException) MultiGetRequest(org.elasticsearch.action.get.MultiGetRequest)

Example 4 with Property

use of org.phoebus.olog.entity.Property in project phoebus-olog by Olog.

the class PropertyRepository method deleteAttribute.

public void deleteAttribute(String propertyName, String attributeName) {
    try {
        Property property = findById(propertyName).get();
        if (property != null) {
            property.setAttributes(property.getAttributes().stream().map(p -> {
                if (p.getName().equals(attributeName)) {
                    p.setState(State.Inactive);
                }
                return p;
            }).collect(Collectors.toSet()));
        }
        UpdateResponse response = client.update(new UpdateRequest(ES_PROPERTY_INDEX, ES_PROPERTY_TYPE, propertyName).doc(mapper.writeValueAsBytes(property), XContentType.JSON).setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT);
        if (response.getResult().equals(Result.UPDATED)) {
            BytesReference ref = client.get(new GetRequest(ES_PROPERTY_INDEX, ES_PROPERTY_TYPE, response.getId()), RequestOptions.DEFAULT).getSourceAsBytesRef();
            Property deletedProperty = mapper.readValue(ref.streamInput(), Property.class);
            logger.log(Level.INFO, "Deleted property attribute" + deletedProperty.toLogger());
        }
    } catch (DocumentMissingException e) {
        logger.log(Level.SEVERE, propertyName + " Does not exist and thus cannot be deleted");
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) UpdateResponse(org.elasticsearch.action.update.UpdateResponse) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) MultiGetRequest(org.elasticsearch.action.get.MultiGetRequest) GetRequest(org.elasticsearch.action.get.GetRequest) DocumentMissingException(org.elasticsearch.index.engine.DocumentMissingException) Property(org.phoebus.olog.entity.Property) ResponseStatusException(org.springframework.web.server.ResponseStatusException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) DocumentMissingException(org.elasticsearch.index.engine.DocumentMissingException)

Example 5 with Property

use of org.phoebus.olog.entity.Property in project phoebus-olog by Olog.

the class PropertiesResourceTest method testFindById.

@Test
public void testFindById() throws Exception {
    when(propertyRepository.findById("property1")).thenReturn(Optional.of(property1));
    MockHttpServletRequestBuilder request = get("/" + OlogResourceDescriptors.PROPERTY_RESOURCE_URI + "/property1");
    MvcResult result = mockMvc.perform(request).andExpect(status().isOk()).andReturn();
    Property property = objectMapper.readValue(result.getResponse().getContentAsString(), Property.class);
    assertEquals("property1", property.getName());
    verify(propertyRepository, times(1)).findById("property1");
    reset(propertyRepository);
}
Also used : MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) MvcResult(org.springframework.test.web.servlet.MvcResult) Property(org.phoebus.olog.entity.Property) Test(org.junit.Test) WebMvcTest(org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest)

Aggregations

Property (org.phoebus.olog.entity.Property)26 IOException (java.io.IOException)12 Test (org.junit.Test)12 WebMvcTest (org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest)9 MockHttpServletRequestBuilder (org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder)9 Log (org.phoebus.olog.entity.Log)8 Attribute (org.phoebus.olog.entity.Attribute)7 ResponseStatusException (org.springframework.web.server.ResponseStatusException)7 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)5 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)5 GetRequest (org.elasticsearch.action.get.GetRequest)5 DocumentMissingException (org.elasticsearch.index.engine.DocumentMissingException)5 MvcResult (org.springframework.test.web.servlet.MvcResult)5 MultiGetRequest (org.elasticsearch.action.get.MultiGetRequest)4 BytesReference (org.elasticsearch.common.bytes.BytesReference)4 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 List (java.util.List)3 IndexRequest (org.elasticsearch.action.index.IndexRequest)3 IndexResponse (org.elasticsearch.action.index.IndexResponse)3