Commit 2244f15e authored by Noel Alonso's avatar Noel Alonso
Browse files

Añade parámetro al consulta fijada + añade tests

En el controlador se establece el usuario que ha realizado la petición
para restringir la búsqueda. Se modifica tests para comprobar cambios
parent 2aeb9b70
Loading
Loading
Loading
Loading
+86 −2
Original line number Diff line number Diff line
package es.redmic.viewlib.usersettings.controller;

import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;

import org.mapstruct.factory.Mappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

/*-
@@ -27,11 +33,22 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.kafka.annotation.KafkaHandler;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import es.redmic.exception.common.ExceptionType;
import es.redmic.exception.databinding.DTONotValidException;
import es.redmic.models.es.common.dto.ElasticSearchDTO;
import es.redmic.models.es.common.dto.EventApplicationResult;
import es.redmic.models.es.common.dto.JSONCollectionDTO;
import es.redmic.models.es.common.dto.SuperDTO;
import es.redmic.models.es.common.query.dto.SimpleQueryDTO;
import es.redmic.restlib.config.UserService;
import es.redmic.usersettingslib.dto.SettingsDTO;
import es.redmic.usersettingslib.events.SettingsEventFactory;
import es.redmic.usersettingslib.events.SettingsEventTypes;
@@ -41,7 +58,7 @@ import es.redmic.usersettingslib.events.deselect.DeselectEvent;
import es.redmic.usersettingslib.events.save.SaveSettingsEvent;
import es.redmic.usersettingslib.events.select.SelectEvent;
import es.redmic.usersettingslib.model.Settings;
import es.redmic.viewlib.data.controller.DataController;
import es.redmic.viewlib.common.controller.RController;
import es.redmic.viewlib.usersettings.mapper.SettingsESMapper;
import es.redmic.viewlib.usersettings.service.SelectionService;

@@ -49,11 +66,14 @@ import es.redmic.viewlib.usersettings.service.SelectionService;
@ConditionalOnProperty(name = "redmic.user-settings.enabled", havingValue = "true")
@RequestMapping(value = "${controller.mapping.SETTINGS}")
@KafkaListener(topics = "${broker.topic.settings}")
public class SelectionController extends DataController<Settings, SettingsDTO, SimpleQueryDTO> {
public class SelectionController extends RController<Settings, SettingsDTO, SimpleQueryDTO> {

	@Value("${broker.topic.settings}")
	private String settings_topic;

	@Autowired
	UserService userService;

	SelectionService service;

	public SelectionController(SelectionService service) {
@@ -186,4 +206,68 @@ public class SelectionController extends DataController<Settings, SettingsDTO, S
	@KafkaHandler(isDefault = true)
	public void listenDefualt(Object event) {
	}

	// REST

	@RequestMapping(value = "", method = RequestMethod.GET)
	@ResponseBody
	public SuperDTO _search(@RequestParam(required = false, value = "fields") String[] fields,
			@RequestParam(required = false, value = "text") String text,
			@RequestParam(required = false, value = "from") Integer from,
			@RequestParam(required = false, value = "size") Integer size) {

		Map<String, Object> newFixedQuery = new HashMap<String, Object>();
		newFixedQuery.put("userId", userService.getUserId());

		return new ElasticSearchDTO(service.find(fields, text, from, size, newFixedQuery, fieldsExcludedOnQuery));
	}

	@RequestMapping(value = "/_search", method = RequestMethod.POST)
	@ResponseBody
	public SuperDTO _advancedSearch(@Valid @RequestBody SimpleQueryDTO queryDTO, BindingResult bindingResult) {

		if (bindingResult != null && bindingResult.hasErrors())
			throw new DTONotValidException(bindingResult);

		Map<String, Object> newFixedQuery = new HashMap<String, Object>();
		newFixedQuery.put("userId", userService.getUserId());

		return new ElasticSearchDTO(service.find(queryDTO, newFixedQuery, fieldsExcludedOnQuery));
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public SuperDTO _get(@PathVariable("id") String id) {

		Map<String, Object> newFixedQuery = new HashMap<String, Object>();
		newFixedQuery.put("userId", userService.getUserId());
		newFixedQuery.put("id", id);

		JSONCollectionDTO result = service.find(new SimpleQueryDTO(), newFixedQuery, fieldsExcludedOnQuery);

		if (result.getTotal() == 1)
			return new ElasticSearchDTO(result.getData().get(0), 1);
		return new ElasticSearchDTO(null, 0);
	}

	@RequestMapping(value = "/_suggest", method = RequestMethod.GET)
	@ResponseBody
	public SuperDTO _suggest(@RequestParam(required = false, value = "fields") String[] fields,
			@RequestParam("text") String text, @RequestParam(required = false, value = "size") Integer size) {

		Map<String, Object> newFixedQuery = new HashMap<String, Object>();
		newFixedQuery.put("userId", userService.getUserId());

		return new ElasticSearchDTO(service.suggest(fields, text, size, newFixedQuery, fieldsExcludedOnQuery));
	}

	@RequestMapping(value = "/_suggest", method = RequestMethod.POST)
	@ResponseBody
	public SuperDTO _advancedSuggest(@Valid @RequestBody SimpleQueryDTO queryDTO, BindingResult bindingResult) {

		Map<String, Object> newFixedQuery = new HashMap<String, Object>();
		newFixedQuery.put("userId", userService.getUserId());

		return new ElasticSearchDTO(service.suggest(queryDTO, newFixedQuery, fieldsExcludedOnQuery));
	}
}
+47 −59
Original line number Diff line number Diff line
@@ -10,7 +10,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.Arrays;
import java.util.UUID;

import org.junit.After;
import org.junit.Before;
@@ -21,7 +21,6 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import es.redmic.models.es.common.query.dto.MgetDTO;
import es.redmic.models.es.common.query.dto.SimpleQueryDTO;
import es.redmic.testutils.documentation.DocumentationViewBaseTest;
import es.redmic.usersettingslib.dto.SettingsDTO;
@@ -60,7 +59,15 @@ public class SettingsControllerBase extends DocumentationViewBaseTest {
	@Autowired
	SettingsRepository repository;

	SettingsDTO settings = new SettingsDTO();
	SettingsDTO settings;

	SettingsDTO settingsWork;

	SettingsDTO settingsOtherService;

	SettingsDTO settingsOtherUser;

	SettingsDTO settingsUserNotLoggedIn;

	@Override
	@Before
@@ -68,8 +75,28 @@ public class SettingsControllerBase extends DocumentationViewBaseTest {

		settings = SettingsDataUtil.getSettingsDTO();

		settingsWork = SettingsDataUtil.getSettingsDTO(UUID.randomUUID().toString());
		settingsWork.setName(null);

		settingsOtherService = SettingsDataUtil.getSettingsDTO(UUID.randomUUID().toString());
		settingsOtherService.setService("prueba");

		settingsOtherUser = SettingsDataUtil.getSettingsDTO(UUID.randomUUID().toString());
		settingsOtherUser.setUserId("999");

		settingsUserNotLoggedIn = SettingsDataUtil.getSettingsDTO(UUID.randomUUID().toString());
		settingsUserNotLoggedIn.setUserId("1");

		repository.save(Mappers.getMapper(SettingsESMapper.class).map(settings));

		repository.save(Mappers.getMapper(SettingsESMapper.class).map(settingsWork));

		repository.save(Mappers.getMapper(SettingsESMapper.class).map(settingsOtherService));

		repository.save(Mappers.getMapper(SettingsESMapper.class).map(settingsOtherUser));

		repository.save(Mappers.getMapper(SettingsESMapper.class).map(settingsUserNotLoggedIn));

		// @formatter:off
		
		mockMvc = MockMvcBuilders
@@ -85,6 +112,10 @@ public class SettingsControllerBase extends DocumentationViewBaseTest {
	@After
	public void clean() {
		repository.delete(settings.getId());
		repository.delete(settingsWork.getId());
		repository.delete(settingsOtherService.getId());
		repository.delete(settingsOtherUser.getId());
		repository.delete(settingsUserNotLoggedIn.getId());
	}

	@Test
@@ -92,12 +123,12 @@ public class SettingsControllerBase extends DocumentationViewBaseTest {

		// @formatter:off
		
		this.mockMvc.perform(get(SETTINGS_PATH + "/" + settings.getId())
		this.mockMvc.perform(get(SETTINGS_PATH + "/" + settingsUserNotLoggedIn.getId())
				.accept(MediaType.APPLICATION_JSON))
			.andExpect(status().isOk())
			.andExpect(jsonPath("$.success", is(true)))
			.andExpect(jsonPath("$.body", notNullValue()))
			.andExpect(jsonPath("$.body.id", is(settings.getId())));
			.andExpect(jsonPath("$.body.id", is(settingsUserNotLoggedIn.getId())));
		
		// @formatter:on
	}
@@ -106,7 +137,7 @@ public class SettingsControllerBase extends DocumentationViewBaseTest {
	public void searchSettingsPost_Return200_WhenSearchIsCorrect() throws Exception {

		SimpleQueryDTO dataQuery = new SimpleQueryDTO();
		dataQuery.setSize(1);
		dataQuery.setSize(10);

		// @formatter:off
		
@@ -129,7 +160,7 @@ public class SettingsControllerBase extends DocumentationViewBaseTest {
	public void searchSettingsPost_ReturnUnauthorized_IfUserIsNotLoggedIn() throws Exception {

		SimpleQueryDTO dataQuery = new SimpleQueryDTO();
		dataQuery.setSize(1);
		dataQuery.setSize(10);

		// @formatter:off
		
@@ -152,7 +183,7 @@ public class SettingsControllerBase extends DocumentationViewBaseTest {
					.param("fields", "{name}")
					.param("text", settings.getName())
					.param("from", "0")
					.param("size", "1")
					.param("size", "10")
					.header("Authorization", "Bearer " + getTokenOAGUser())
					.accept(MediaType.APPLICATION_JSON))
				.andExpect(status().isOk())
@@ -175,56 +206,13 @@ public class SettingsControllerBase extends DocumentationViewBaseTest {
				.param("fields", "{name}")
				.param("text", settings.getName())
				.param("from", "0")
				.param("size", "1")
				.param("size", "10")
				.accept(MediaType.APPLICATION_JSON))
				.andExpect(status().isUnauthorized());
		
		// @formatter:on
	}

	@Test
	public void mgetSettings_Return200_WhenSettingsExists() throws Exception {

		MgetDTO mgetQuery = new MgetDTO();
		mgetQuery.setIds(Arrays.asList(settings.getId()));
		mgetQuery.setFields(Arrays.asList("id"));

		// @formatter:off
		
		this.mockMvc
			.perform(post(SETTINGS_PATH + "/_mget")
					.header("Authorization", "Bearer " + getTokenOAGUser())
					.content(mapper.writeValueAsString(mgetQuery))
					.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
				.andExpect(status().isOk())
				.andExpect(jsonPath("$.success", is(true)))
				.andExpect(jsonPath("$.body.data", notNullValue()))
				.andExpect(jsonPath("$.body.data[0]", notNullValue()))
				.andExpect(jsonPath("$.body.data[0].id", is(settings.getId())))
				.andExpect(jsonPath("$.body.data.length()", is(1)))
					.andDo(getMgetRequestDescription());
		
		// @formatter:on
	}

	@Test
	public void mgetSettings_ReturnUnauthorized_IfUserIsNotLoggedIn() throws Exception {

		MgetDTO mgetQuery = new MgetDTO();
		mgetQuery.setIds(Arrays.asList(settings.getId()));
		mgetQuery.setFields(Arrays.asList("id"));

		// @formatter:off
		
		this.mockMvc
			.perform(post(SETTINGS_PATH + "/_mget")
					.content(mapper.writeValueAsString(mgetQuery))
					.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
				.andExpect(status().isUnauthorized());
		
		// @formatter:on
	}

	@Test
	public void suggestSettingsQueryString_Return200_WhenSuggestIsCorrect() throws Exception {

@@ -234,7 +222,7 @@ public class SettingsControllerBase extends DocumentationViewBaseTest {
			.perform(get(SETTINGS_PATH + "/_suggest")
					.param("fields", new String[] { "name" })
					.param("text", settings.getName())
					.param("size", "1")
					.param("size", "10")
						.header("Authorization", "Bearer " + getTokenOAGUser())
						.accept(MediaType.APPLICATION_JSON))
				.andExpect(status().isOk())
@@ -252,7 +240,7 @@ public class SettingsControllerBase extends DocumentationViewBaseTest {
	public void suggestSettingsQueryString_ReturnUnauthorized_IfUserIsNotLoggedIn() throws Exception {

		SimpleQueryDTO dataQuery = new SimpleQueryDTO();
		dataQuery.setSize(1);
		dataQuery.setSize(10);

		// @formatter:off
		
@@ -260,7 +248,7 @@ public class SettingsControllerBase extends DocumentationViewBaseTest {
			.perform(get(SETTINGS_PATH + "/_suggest")
				.param("fields", new String[] { "name" })
				.param("text", settings.getName())
				.param("size", "1")
				.param("size", "10")
					.accept(MediaType.APPLICATION_JSON))
				.andExpect(status().isUnauthorized());
		
@@ -271,8 +259,8 @@ public class SettingsControllerBase extends DocumentationViewBaseTest {
	public void suggestSettingsPost_Return200_WhenSuggestIsCorrect() throws Exception {

		SimpleQueryDTO dataQuery = new SimpleQueryDTO();
		dataQuery.setSize(1);
		dataQuery.createSimpleQueryDTOFromSuggestQueryParams(new String[] { "name" }, settings.getName(), 1);
		dataQuery.setSize(10);
		dataQuery.createSimpleQueryDTOFromSuggestQueryParams(new String[] { "name" }, settings.getName(), 10);

		// @formatter:off
		
@@ -296,8 +284,8 @@ public class SettingsControllerBase extends DocumentationViewBaseTest {
	public void suggestSettingsPost_ReturnUnauthorized_IfUserIsNotLoggedIn() throws Exception {

		SimpleQueryDTO dataQuery = new SimpleQueryDTO();
		dataQuery.setSize(1);
		dataQuery.createSimpleQueryDTOFromSuggestQueryParams(new String[] { "name" }, settings.getName(), 1);
		dataQuery.setSize(10);
		dataQuery.createSimpleQueryDTOFromSuggestQueryParams(new String[] { "name" }, settings.getName(), 10);

		// @formatter:off