KPIReadController.java

/*
 * Copyright 2018 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.genesys.server.api.v1;

import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.genesys.server.api.Pagination;
import org.genesys.server.model.kpi.Execution;
import org.genesys.server.model.kpi.Observation;
import org.genesys.server.service.KPIService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.querydsl.core.Tuple;

import io.swagger.annotations.Api;

/**
 * @author Maxym Borodenko
 */
@RestController("kpiReadApi1")
@RequestMapping(value = { KPIController.CONTROLLER_URL })
@PreAuthorize("isAuthenticated()")
@Api(tags = { "kpi" })
public class KPIReadController {

	@Autowired
	private KPIService kpiService;
	
	@Autowired
	private ObjectMapper objectMapper;

	/**
	 * List names of executions for which observations are available
	 *
	 * @return the list of execution names
	 */
	@GetMapping(value="/observations")
	public List<String> listExecutions() {
		return kpiService.listExecutions().stream().map(ex -> ex.getName()).collect(Collectors.toList());
	}

	@PostMapping(value="/observations/{executionName}", params = { "date" })
	public ArrayNode observations(@PathVariable final String executionName,
			@RequestParam(value="date", required = true) @DateTimeFormat(pattern="yyyyMMdd") final LocalDate date,
			@RequestBody(required = false) final Map<String, Set<String>> keys) {

		ArrayNode l = objectMapper.createArrayNode();
		Execution execution = kpiService.getExecution(executionName);
		kpiService.filterObservations(execution, date, keys).forEach(observation -> {
			l.add(toMap(observation));
		});
		return l;
	}
	
	@PostMapping(value="/observations/range/{executionName}")
	public Page<Object> observations2(@PathVariable final String executionName, @RequestParam(value = "days", required = false) final Integer days,
			@RequestParam(value = "from", required = false) @DateTimeFormat(pattern = "yyyyMMdd") LocalDate from,
			@RequestParam(value = "to", required = false) @DateTimeFormat(pattern = "yyyyMMdd") LocalDate to, final Pagination pagination, @RequestBody(required = false) final Map<String, Set<String>> keys) {

		Execution execution = kpiService.getExecution(executionName);
		
		if (days != null) {
			LocalDate startDate = LocalDate.now();
			if (to != null) {
				startDate = to;
			} else {
				to = startDate;
			}
			startDate = startDate.minusDays(days);
			from = startDate;
		}

		
		Page<Tuple> observations = kpiService.listObservations(execution, from, to, keys, pagination.toPageRequest(1000, 1000, Direction.DESC, "id"));
		return observations.map(tuple -> toMap(tuple));
	}
	
	private ObjectNode toMap(Tuple observation) {
		ObjectNode m = toMap(observation.get(1, Observation.class));
		m.put("timestamp", observation.get(0, LocalDate.class).atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli());
		return m;
	}

	private ObjectNode toMap(Observation observation) {
		ObjectNode m=objectMapper.createObjectNode();
		m.put("value", observation.getValue());
		m.put("stdDev", observation.getStdDev());
		ObjectNode dims = m.putObject("dimensions");
		observation.getDimensions().forEach(dim -> {
			dims.put(dim.getName(), dim.getValue());
		});
		return m;
	}
}