Commit 302150be authored by Noel Alonso's avatar Noel Alonso
Browse files

Añade componentes para realizar consultas

parent e4deca50
Loading
Loading
Loading
Loading
+131 −0
Original line number Diff line number Diff line
package es.redmic.atlasview.controller.category;

/*-
 * #%L
 * Atlas-query-endpoint
 * %%
 * Copyright (C) 2019 REDMIC Project / Server
 * %%
 * 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.
 * #L%
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaHandler;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import es.redmic.atlaslib.dto.category.CategoryDTO;
import es.redmic.atlaslib.events.category.CategoryEventFactory;
import es.redmic.atlaslib.events.category.CategoryEventTypes;
import es.redmic.atlaslib.events.category.create.CreateCategoryConfirmedEvent;
import es.redmic.atlaslib.events.category.create.CreateCategoryEvent;
import es.redmic.atlaslib.events.category.delete.DeleteCategoryConfirmedEvent;
import es.redmic.atlaslib.events.category.delete.DeleteCategoryEvent;
import es.redmic.atlaslib.events.category.update.UpdateCategoryConfirmedEvent;
import es.redmic.atlaslib.events.category.update.UpdateCategoryEvent;
import es.redmic.atlasview.config.MapperScanBean;
import es.redmic.atlasview.model.category.Category;
import es.redmic.atlasview.service.category.CategoryESService;
import es.redmic.exception.common.ExceptionType;
import es.redmic.models.es.common.dto.EventApplicationResult;
import es.redmic.models.es.common.query.dto.SimpleQueryDTO;
import es.redmic.viewlib.data.controller.DataController;

@Controller
@RequestMapping(value = "${controller.mapping.CATEGORY}")
@KafkaListener(topics = "${broker.topic.category}")
public class CategoryController extends DataController<Category, CategoryDTO, SimpleQueryDTO> {

	@Value("${broker.topic.category}")
	private String category_topic;

	@Autowired
	protected MapperScanBean mapper;

	CategoryESService service;

	public CategoryController(CategoryESService service) {
		super(service);
		this.service = service;
	}

	@KafkaHandler
	public void listen(CreateCategoryEvent event) {

		EventApplicationResult result = null;

		try {
			result = service.save(mapper.getMapperFacade().map(event.getCategory(), Category.class));
		} catch (Exception e) {
			publishFailedEvent(CategoryEventFactory.getEvent(event, CategoryEventTypes.CREATE_FAILED,
					ExceptionType.INTERNAL_EXCEPTION.name(), null), category_topic);
			return;
		}

		if (result.isSuccess()) {
			publishConfirmedEvent(new CreateCategoryConfirmedEvent().buildFrom(event), category_topic);
		} else {
			publishFailedEvent(CategoryEventFactory.getEvent(event, CategoryEventTypes.CREATE_FAILED,
					result.getExeptionType(), result.getExceptionArguments()), category_topic);
		}
	}

	@KafkaHandler
	public void listen(UpdateCategoryEvent event) {

		EventApplicationResult result = null;

		try {
			result = service.update(mapper.getMapperFacade().map(event.getCategory(), Category.class));
		} catch (Exception e) {
			publishFailedEvent(CategoryEventFactory.getEvent(event, CategoryEventTypes.UPDATE_FAILED,
					ExceptionType.INTERNAL_EXCEPTION.name(), null), category_topic);
			return;
		}

		if (result.isSuccess()) {
			publishConfirmedEvent(new UpdateCategoryConfirmedEvent().buildFrom(event), category_topic);
		} else {
			publishFailedEvent(CategoryEventFactory.getEvent(event, CategoryEventTypes.UPDATE_FAILED,
					result.getExeptionType(), result.getExceptionArguments()), category_topic);
		}
	}

	@KafkaHandler
	public void listen(DeleteCategoryEvent event) {

		EventApplicationResult result = null;

		try {
			result = service.delete(event.getAggregateId());
		} catch (Exception e) {
			publishFailedEvent(CategoryEventFactory.getEvent(event, CategoryEventTypes.DELETE_FAILED,
					ExceptionType.INTERNAL_EXCEPTION.name(), null), category_topic);
			return;
		}

		if (result.isSuccess()) {
			publishConfirmedEvent(new DeleteCategoryConfirmedEvent().buildFrom(event), category_topic);
		} else {
			publishFailedEvent(CategoryEventFactory.getEvent(event, CategoryEventTypes.DELETE_FAILED,
					result.getExeptionType(), result.getExceptionArguments()), category_topic);
		}
	}

	@KafkaHandler(isDefault = true)
	public void listenDefualt(Object event) {
	}
}
+140 −0
Original line number Diff line number Diff line
package es.redmic.atlasview.repository.category;

/*-
 * #%L
 * Atlas-query-endpoint
 * %%
 * Copyright (C) 2019 REDMIC Project / Server
 * %%
 * 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.
 * #L%
 */

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.elasticsearch.action.search.MultiSearchRequest;
import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.MultiSearchResponse.Item;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Repository;

import es.redmic.atlasview.model.category.Category;
import es.redmic.elasticsearchlib.data.repository.RWDataESRepository;
import es.redmic.exception.common.ExceptionType;
import es.redmic.exception.elasticsearch.ESQueryException;
import es.redmic.models.es.common.dto.EventApplicationResult;
import es.redmic.models.es.common.query.dto.SimpleQueryDTO;
import es.redmic.viewlib.data.repository.IDataRepository;

@Repository
public class CategoryESRepository extends RWDataESRepository<Category, SimpleQueryDTO>
		implements IDataRepository<Category, SimpleQueryDTO> {

	private static String[] INDEX = { "category" };
	private static String TYPE = "_doc";

	// @formatter:off
	
	private final String ID_PROPERTY = "id";
	// @formatter:on

	public CategoryESRepository() {
		super(INDEX, TYPE);
	}

	@Override
	protected EventApplicationResult checkInsertConstraintsFulfilled(Category modelToIndex) {

		QueryBuilder idTerm = QueryBuilders.termQuery(ID_PROPERTY, modelToIndex.getId());

		MultiSearchRequest request = new MultiSearchRequest();

		SearchSourceBuilder requestBuilderId = new SearchSourceBuilder().query(idTerm).size(1);

		request.add(new SearchRequest().indices(getIndex()).source(requestBuilderId));

		MultiSearchResponse sr;
		try {
			sr = ESProvider.getClient().msearch(request, RequestOptions.DEFAULT);
		} catch (IOException e) {
			e.printStackTrace();
			throw new ESQueryException();
		}

		Map<String, String> arguments = new HashMap<>();

		Item[] responses = sr.getResponses();

		if (responses != null && responses[0].getResponse().getHits().getTotalHits() > 0) {
			arguments.put(ID_PROPERTY, modelToIndex.getId());
		}

		if (arguments.size() > 0) {
			return new EventApplicationResult(ExceptionType.ES_INSERT_DOCUMENT.toString(), arguments);
		}

		return new EventApplicationResult(true);
	}

	@Override
	protected EventApplicationResult checkUpdateConstraintsFulfilled(Category modelToIndex) {
		// @formatter:off
		
		BoolQueryBuilder idTerm = QueryBuilders.boolQuery()
				.mustNot(QueryBuilders.termQuery(ID_PROPERTY, modelToIndex.getId()));
		
		MultiSearchRequest request = new MultiSearchRequest();
		
		SearchSourceBuilder requestBuilderId = new SearchSourceBuilder().query(idTerm).size(1);
		
		request.add(new SearchRequest().indices(getIndex()).source(requestBuilderId));
		
		// @formatter:on

		MultiSearchResponse sr;
		try {
			sr = ESProvider.getClient().msearch(request, RequestOptions.DEFAULT);
		} catch (IOException e) {
			e.printStackTrace();
			throw new ESQueryException();
		}

		Map<String, String> arguments = new HashMap<>();

		Item[] responses = sr.getResponses();

		if (responses != null && responses[0].getResponse().getHits().getTotalHits() > 0) {
			arguments.put(ID_PROPERTY, modelToIndex.getId().toString());
		}

		if (arguments.size() > 0) {
			return new EventApplicationResult(ExceptionType.ES_UPDATE_DOCUMENT.toString(), arguments);
		}

		return new EventApplicationResult(true);
	}

	@Override
	protected EventApplicationResult checkDeleteConstraintsFulfilled(String modelToIndexId) {

		// TODO: mirar si tiene hijos
		return new EventApplicationResult(true);
	}
}
+39 −0
Original line number Diff line number Diff line
package es.redmic.atlasview.service.category;

/*-
 * #%L
 * Atlas-query-endpoint
 * %%
 * Copyright (C) 2019 REDMIC Project / Server
 * %%
 * 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.
 * #L%
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import es.redmic.atlaslib.dto.category.CategoryDTO;
import es.redmic.atlasview.model.category.Category;
import es.redmic.atlasview.repository.category.CategoryESRepository;
import es.redmic.models.es.common.query.dto.SimpleQueryDTO;
import es.redmic.viewlib.data.service.RWDataService;

@Service
public class CategoryESService extends RWDataService<Category, CategoryDTO, SimpleQueryDTO> {

	@Autowired
	public CategoryESService(CategoryESRepository repository) {
		super(repository);
	}
}
+49 −0
Original line number Diff line number Diff line
{
	"settings": {
		"analysis": {
			"analyzer": {
				"lower_analyzer": {
					"type": "custom",
					"tokenizer": "standard",
					"filter": ["lowercase", "asciifolding"]
				},
				"autocomplete": {
					"type": "custom",
					"tokenizer": "whitespace",
					"filter": ["lowercase", "asciifolding", "nGram_filter"]
				}
			},
			"tokenizer": {},
			"filter": {
				"nGram_filter": {
					"type": "nGram",
					"min_gram": 2,
					"max_gram": 20
				}
			}
		}
	},
	"mappings": {
		"_doc": {
			"_all": {
				"enabled": false
			},
			"dynamic": false,
			"properties": {
				"id": {
					"type": "keyword"
				},
				"name": {
					"type": "keyword",
					"fields": {
						"suggest": {
							"type": "text",
							"analyzer": "autocomplete",
							"search_analyzer": "lower_analyzer"
						}
					}
				}
			}
		}
	}
}
 No newline at end of file