Added auto assign distribution set to target filter query feature

Signed-off-by: Dominik Herbst <dominik.herbst@bosch-si.com>
This commit is contained in:
Dominik Herbst
2016-09-01 10:19:55 +02:00
parent 93d509fbcd
commit 03e2ee81b8
54 changed files with 2922 additions and 1115 deletions

View File

@@ -23,6 +23,7 @@ import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtTargetAssignmentR
import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModule;
import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleAssigment;
import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget;
import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQuery;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetRestApi;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.DeploymentManagement;
@@ -32,12 +33,14 @@ import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.SystemManagement;
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
import org.eclipse.hawkbit.repository.TargetManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.eclipse.hawkbit.repository.model.TargetWithActionType;
import org.eclipse.hawkbit.security.SystemSecurityContext;
import org.slf4j.Logger;
@@ -66,6 +69,9 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
@Autowired
private TargetManagement targetManagement;
@Autowired
private TargetFilterQueryManagement targetFilterQueryManagement;
@Autowired
private DeploymentManagement deployManagament;
@@ -223,6 +229,37 @@ public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi {
HttpStatus.OK);
}
@Override
public ResponseEntity<PagedList<MgmtTargetFilterQuery>> getAutoAssignTargetFilterQueries(
@PathVariable("distributionSetId") Long distributionSetId,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) int pagingOffsetParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) int pagingLimitParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) String rsqlParam) {
// check if distribution set exists otherwise throw exception
// immediately
DistributionSet distributionSet = findDistributionSetWithExceptionIfNotFound(distributionSetId);
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTargetSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Page<TargetFilterQuery> targetFilterQueries;
if (rsqlParam != null) {
targetFilterQueries = this.targetFilterQueryManagement.findTargetFilterQueryByAutoAssignDS(pageable,
distributionSet, rsqlParam);
} else {
targetFilterQueries = this.targetFilterQueryManagement.findTargetFilterQueryByAutoAssignDS(pageable,
distributionSet);
}
return new ResponseEntity<>(
new PagedList<>(MgmtTargetFilterQueryMapper.toResponse(targetFilterQueries.getContent()),
targetFilterQueries.getTotalElements()),
HttpStatus.OK);
}
@Override
public ResponseEntity<MgmtTargetAssignmentResponseBody> createAssignedTarget(
@PathVariable("distributionSetId") final Long distributionSetId,

View File

@@ -0,0 +1,95 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
* <p>
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQuery;
import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQueryRequestBody;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetFilterQueryRestApi;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
/**
* A mapper which maps repository model to RESTful model representation and
* back.
*
*/
public final class MgmtTargetFilterQueryMapper {
private MgmtTargetFilterQueryMapper() {
// Utility class
}
/**
* Create a response for targets.
*
* @param filters
* list of targets
* @return the response
*/
public static List<MgmtTargetFilterQuery> toResponse(final Iterable<TargetFilterQuery> filters) {
final List<MgmtTargetFilterQuery> mappedList = new ArrayList<>();
if (filters != null) {
for (final TargetFilterQuery filter : filters) {
final MgmtTargetFilterQuery response = toResponse(filter);
mappedList.add(response);
}
}
return mappedList;
}
/**
* Create a response for target.
*
* @param filter
* the target
* @return the response
*/
public static MgmtTargetFilterQuery toResponse(final TargetFilterQuery filter) {
if (filter == null) {
return null;
}
final MgmtTargetFilterQuery targetRest = new MgmtTargetFilterQuery();
targetRest.setFilterId(filter.getId());
targetRest.setName(filter.getName());
targetRest.setQuery(filter.getQuery());
targetRest.setCreatedBy(filter.getCreatedBy());
targetRest.setLastModifiedBy(filter.getLastModifiedBy());
targetRest.setCreatedAt(filter.getCreatedAt());
targetRest.setLastModifiedAt(filter.getLastModifiedAt());
DistributionSet distributionSet = filter.getAutoAssignDistributionSet();
if (distributionSet != null) {
targetRest.setAutoAssignDistributionSet(distributionSet.getId());
}
targetRest.add(linkTo(methodOn(MgmtTargetFilterQueryRestApi.class).getFilter(filter.getId())).withRel("self"));
targetRest.add(linkTo(methodOn(MgmtTargetFilterQueryRestApi.class).postAssignedDistributionSet(filter.getId(),null)).withRel("autoAssignDS"));
return targetRest;
}
static TargetFilterQuery fromRequest(final EntityFactory entityFactory,
final MgmtTargetFilterQueryRequestBody filterRest) {
final TargetFilterQuery filter = entityFactory.generateTargetFilterQuery();
filter.setName(filterRest.getName());
filter.setQuery(filterRest.getQuery());
return filter;
}
}

View File

@@ -0,0 +1,180 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
* <p>
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import java.util.List;
import org.eclipse.hawkbit.mgmt.json.model.MgmtId;
import org.eclipse.hawkbit.mgmt.json.model.PagedList;
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet;
import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQuery;
import org.eclipse.hawkbit.mgmt.json.model.targetfilter.MgmtTargetFilterQueryRequestBody;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetFilterQueryRestApi;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.EntityFactory;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* REST Resource handling target CRUD operations.
*/
@RestController
public class MgmtTargetFilterQueryResource implements MgmtTargetFilterQueryRestApi {
private static final Logger LOG = LoggerFactory.getLogger(MgmtTargetFilterQueryResource.class);
@Autowired
private TargetFilterQueryManagement filterManagement;
@Autowired
private DistributionSetManagement distributionSetManagement;
@Autowired
private EntityFactory entityFactory;
@Override
public ResponseEntity<MgmtTargetFilterQuery> getFilter(@PathVariable("filterId") Long filterId) {
final TargetFilterQuery findTarget = findFilterWithExceptionIfNotFound(filterId);
// to single response include poll status
final MgmtTargetFilterQuery response = MgmtTargetFilterQueryMapper.toResponse(findTarget);
return new ResponseEntity<>(response, HttpStatus.OK);
}
@Override
public ResponseEntity<PagedList<MgmtTargetFilterQuery>> getFilters(
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) int pagingOffsetParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) int pagingLimitParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) String sortParam,
@RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) String rsqlParam) {
final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam);
final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam);
final Sort sorting = PagingUtility.sanitizeTargetSortParam(sortParam);
final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting);
final Slice<TargetFilterQuery> findTargetFiltersAll;
final Long countTargetsAll;
if (rsqlParam != null) {
final Page<TargetFilterQuery> findFilterPage = this.filterManagement
.findTargetFilterQueryByFilter(pageable, rsqlParam);
countTargetsAll = findFilterPage.getTotalElements();
findTargetFiltersAll = findFilterPage;
} else {
findTargetFiltersAll = this.filterManagement.findAllTargetFilterQuery(pageable);
countTargetsAll = this.filterManagement.countAllTargetFilterQuery();
}
final List<MgmtTargetFilterQuery> rest = MgmtTargetFilterQueryMapper
.toResponse(findTargetFiltersAll.getContent());
return new ResponseEntity<>(new PagedList<MgmtTargetFilterQuery>(rest, countTargetsAll), HttpStatus.OK);
}
@Override
public ResponseEntity<MgmtTargetFilterQuery> createFilter(@RequestBody MgmtTargetFilterQueryRequestBody filter) {
final TargetFilterQuery createdTarget = this.filterManagement
.createTargetFilterQuery(MgmtTargetFilterQueryMapper.fromRequest(entityFactory, filter));
return new ResponseEntity<>(MgmtTargetFilterQueryMapper.toResponse(createdTarget), HttpStatus.CREATED);
}
@Override
public ResponseEntity<MgmtTargetFilterQuery> updateFilter(@PathVariable("filterId") Long filterId,
@RequestBody MgmtTargetFilterQueryRequestBody targetFilterRest) {
final TargetFilterQuery existingFilter = findFilterWithExceptionIfNotFound(filterId);
LOG.debug("updating target filter query {}", existingFilter.getId());
if (targetFilterRest.getName() != null) {
existingFilter.setName(targetFilterRest.getName());
}
if (targetFilterRest.getQuery() != null) {
existingFilter.setQuery(targetFilterRest.getQuery());
}
final TargetFilterQuery updateFilter = this.filterManagement.updateTargetFilterQuery(existingFilter);
return new ResponseEntity<>(MgmtTargetFilterQueryMapper.toResponse(updateFilter), HttpStatus.OK);
}
@Override
public ResponseEntity<Void> deleteFilter(@PathVariable("filterId") Long filterId) {
final TargetFilterQuery filter = findFilterWithExceptionIfNotFound(filterId);
this.filterManagement.deleteTargetFilterQuery(filter.getId());
LOG.debug("{} target filter query deleted, return status {}", filterId, HttpStatus.OK);
return new ResponseEntity<>(HttpStatus.OK);
}
@Override
public ResponseEntity<MgmtTargetFilterQuery> postAssignedDistributionSet(@PathVariable("filterId") Long filterId,
@RequestBody MgmtId dsId) {
final TargetFilterQuery filter = findFilterWithExceptionIfNotFound(filterId);
DistributionSet distributionSet;
distributionSet = distributionSetManagement.findDistributionSetById(dsId.getId());
if (distributionSet == null) {
throw new EntityNotFoundException("DistributionSet with Id {" + dsId + "} does not exist");
}
filter.setAutoAssignDistributionSet(distributionSet);
final TargetFilterQuery updateFilter = this.filterManagement.updateTargetFilterQuery(filter);
return new ResponseEntity<>(MgmtTargetFilterQueryMapper.toResponse(updateFilter), HttpStatus.OK);
}
@Override
public ResponseEntity<MgmtDistributionSet> getAssignedDistributionSet(@PathVariable("filterId") Long filterId) {
final TargetFilterQuery filter = findFilterWithExceptionIfNotFound(filterId);
DistributionSet autoAssignDistributionSet = filter.getAutoAssignDistributionSet();
MgmtDistributionSet distributionSetRest = MgmtDistributionSetMapper.toResponse(autoAssignDistributionSet);
final HttpStatus retStatus;
if (distributionSetRest == null) {
retStatus = HttpStatus.NO_CONTENT;
} else {
retStatus = HttpStatus.OK;
}
return new ResponseEntity<>(distributionSetRest, retStatus);
}
@Override
public ResponseEntity<Void> deleteAssignedDistributionSet(@PathVariable("filterId") Long filterId) {
final TargetFilterQuery filter = findFilterWithExceptionIfNotFound(filterId);
filter.setAutoAssignDistributionSet(null);
this.filterManagement.updateTargetFilterQuery(filter);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
private TargetFilterQuery findFilterWithExceptionIfNotFound(final Long filterId) {
final TargetFilterQuery filter = this.filterManagement.findTargetFilterQueryById(filterId);
if (filter == null) {
throw new EntityNotFoundException("TargetFilterQuery with Id {" + filterId + "} does not exist");
}
return filter;
}
}

View File

@@ -30,11 +30,8 @@ import java.util.Set;
import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.*;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.test.util.TestdataFactory;
import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
@@ -297,6 +294,25 @@ public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest
.andExpect(jsonPath("$.content[0].controllerId", equalTo(knownTargetId)));
}
@Test
@Description("Ensures that target filters with auto assign DS are returned as persisted in the repository.")
public void getAutoAssignTargetFiltersOfDistributionSet() throws Exception {
// prepare distribution set
final String knownFilterName = "a";
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
final TargetFilterQuery tfq = targetFilterQueryManagement
.createTargetFilterQuery(entityFactory.generateTargetFilterQuery(knownFilterName, "x==y", createdDs));
// create some dummy targets which are not assigned or installed
targetFilterQueryManagement.createTargetFilterQuery(entityFactory.generateTargetFilterQuery("b", "x==y"));
targetFilterQueryManagement.createTargetFilterQuery(entityFactory.generateTargetFilterQuery("c", "x==y"));
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId()
+ "/autoAssignTargetFilters")).andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(1)))
.andExpect(jsonPath("$.content[0].name", equalTo(knownFilterName)));
}
@Test
@Description("Ensures that DS in repository are listed with proper paging properties.")
public void getDistributionSetsWithoutAddtionalRequestParameters() throws Exception {

View File

@@ -0,0 +1,362 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import static com.google.common.collect.Lists.newArrayList;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import java.util.*;
import java.util.stream.Collectors;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
import org.eclipse.hawkbit.repository.model.*;
import org.eclipse.hawkbit.repository.model.Action.ActionType;
import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest;
import org.eclipse.hawkbit.rest.exception.MessageNotReadableException;
import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
import org.eclipse.hawkbit.rest.util.JsonBuilder;
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
import org.json.JSONObject;
import org.junit.Test;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Slice;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import com.jayway.jsonpath.JsonPath;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
/**
* Spring MVC Tests against the MgmtTargetResource.
*
*/
@Features("Component Tests - Management API")
@Stories("Target Filter Query Resource")
public class MgmtTargetFilterQueryResourceTest extends AbstractRestIntegrationTest {
private static final String TARGET_DESCRIPTION_TEST = "created in test";
private static final String JSON_PATH_ROOT = "$";
// fields, attributes
private static final String JSON_PATH_FIELD_ID = ".id";
private static final String JSON_PATH_FIELD_NAME = ".name";
private static final String JSON_PATH_FIELD_QUERY = ".query";
private static final String JSON_PATH_FIELD_CONTENT = ".content";
private static final String JSON_PATH_FIELD_SIZE = ".size";
private static final String JSON_PATH_FIELD_TOTAL = ".total";
private static final String JSON_PATH_FIELD_AUTO_ASSIGN_DS = ".autoAssignDistributionSet";
// target
// $.field
static final String JSON_PATH_PAGED_LIST_CONTENT = JSON_PATH_ROOT + JSON_PATH_FIELD_CONTENT;
static final String JSON_PATH_PAGED_LIST_SIZE = JSON_PATH_ROOT + JSON_PATH_FIELD_SIZE;
static final String JSON_PATH_PAGED_LIST_TOTAL = JSON_PATH_ROOT + JSON_PATH_FIELD_TOTAL;
private static final String JSON_PATH_NAME = JSON_PATH_ROOT + JSON_PATH_FIELD_NAME;
private static final String JSON_PATH_ID = JSON_PATH_ROOT + JSON_PATH_FIELD_ID;
private static final String JSON_PATH_QUERY = JSON_PATH_ROOT + JSON_PATH_FIELD_QUERY;
private static final String JSON_PATH_AUTO_ASSIGN_DS = JSON_PATH_ROOT + JSON_PATH_FIELD_AUTO_ASSIGN_DS;
@Test
@Description("Ensures that deletion is executed if permitted.")
public void deleteTargetFilterQueryReturnsOK() throws Exception {
final String filterName = "filter_01";
TargetFilterQuery filterQuery = createSingleTargetFilterQuery(filterName, "name=test_01");
mvc.perform(delete(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + filterQuery.getId()))
.andExpect(status().isOk());
TargetFilterQuery tfq = targetFilterQueryManagement.findTargetFilterQueryById(filterQuery.getId());
assertThat(tfq).isNull();
}
@Test
@Description("Ensures that deletion is refused with not found if target does not exist.")
public void deleteTargetWhichDoesNotExistsLeadsToEntityNotFound() throws Exception {
final String notExistingId = "4395";
mvc.perform(delete(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + notExistingId))
.andExpect(status().isNotFound());
}
@Test
@Description("Ensures that update is refused with not found if target does not exist.")
public void updateTargetWhichDoesNotExistsLeadsToEntityNotFound() throws Exception {
final String notExistingId = "4395";
mvc.perform(put(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + notExistingId).content("{}")
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound());
}
@Test
@Description("Ensures that update request is reflected by repository.")
public void updateTargetFilterQueryQuery() throws Exception {
final String filterName = "filter_02";
final String filterQuery = "name=test_02";
final String filterQuery2 = "name=test_02_changed";
final String body = new JSONObject().put("query", filterQuery2).toString();
// prepare
TargetFilterQuery tfq = createSingleTargetFilterQuery(filterName, filterQuery);
mvc.perform(put(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId()).content(body)
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("$.id", equalTo(tfq.getId().intValue())))
.andExpect(jsonPath("$.query", equalTo(filterQuery2)))
.andExpect(jsonPath("$.name", equalTo(filterName)));
TargetFilterQuery tfqCheck = targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId());
assertThat(tfqCheck.getQuery()).isEqualTo(filterQuery2);
assertThat(tfqCheck.getName()).isEqualTo(filterName);
}
@Test
@Description("Ensures that update request is reflected by repository.")
public void updateTargetFilterQueryName() throws Exception {
final String filterName = "filter_03";
final String filterName2 = "filter_03_changed";
final String filterQuery = "name=test_03";
final String body = new JSONObject().put("name", filterName2).toString();
// prepare
TargetFilterQuery tfq = entityFactory.generateTargetFilterQuery();
tfq.setName(filterName);
tfq.setQuery(filterQuery);
tfq = targetFilterQueryManagement.createTargetFilterQuery(tfq);
mvc.perform(put(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId()).content(body)
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("$.id", equalTo(tfq.getId().intValue())))
.andExpect(jsonPath("$.query", equalTo(filterQuery)))
.andExpect(jsonPath("$.name", equalTo(filterName2)));
TargetFilterQuery tfqCheck = targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId());
assertThat(tfqCheck.getQuery()).isEqualTo(filterQuery);
assertThat(tfqCheck.getName()).isEqualTo(filterName2);
}
@Test
@Description("Ensures that request returns list of filters in defined format.")
public void getTargetFilterQueryWithoutAdditionalRequestParameters() throws Exception {
final int knownTargetAmount = 3;
final String idA = "a";
final String idB = "b";
final String idC = "c";
final String testQuery = "name=test";
createSingleTargetFilterQuery(idA, testQuery);
createSingleTargetFilterQuery(idB, testQuery);
createSingleTargetFilterQuery(idC, testQuery);
mvc.perform(get(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING)).andExpect(status().isOk())
.andDo(MockMvcResultPrinter.print())
.andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(knownTargetAmount)))
.andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(knownTargetAmount)))
.andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(knownTargetAmount)))
// idA
.andExpect(jsonPath("$.content.[?(@.name==" + idA + ")].name", contains(idA)))
.andExpect(jsonPath("$.content.[?(@.name==" + idA + ")].query", contains(testQuery)))
// idB
.andExpect(jsonPath("$.content.[?(@.name==" + idB + ")].name", contains(idB)))
.andExpect(jsonPath("$.content.[?(@.name==" + idB + ")].query", contains(testQuery)))
// idC
.andExpect(jsonPath("$.content.[?(@.name==" + idC + ")].name", contains(idC)))
.andExpect(jsonPath("$.content.[?(@.name==" + idC + ")].query", contains(testQuery)));
}
@Test
@Description("Ensures that request returns list of filters in defined format in size reduced by given limit parameter.")
public void getTargetWithPagingLimitRequestParameter() throws Exception {
final int limitSize = 1;
final int knownTargetAmount = 3;
final String idA = "a";
final String idB = "b";
final String idC = "c";
final String testQuery = "name=test";
createSingleTargetFilterQuery(idA, testQuery);
createSingleTargetFilterQuery(idB, testQuery);
createSingleTargetFilterQuery(idC, testQuery);
mvc.perform(get(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING)
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)))
.andExpect(status().isOk()).andDo(MockMvcResultPrinter.print())
.andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(knownTargetAmount)))
.andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize)))
.andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize)))
// idA
.andExpect(jsonPath("$.content.[?(@.name==" + idA + ")].name", contains(idA)))
.andExpect(jsonPath("$.content.[?(@.name==" + idA + ")].query", contains(testQuery)));
}
@Test
@Description("Ensures that request returns list of filters in defined format in size reduced by given limit and offset parameter.")
public void getTargetWithPagingLimitAndOffsetRequestParameter() throws Exception {
final int knownTargetAmount = 5;
final int offsetParam = 2;
final int expectedSize = knownTargetAmount - offsetParam;
final String idC = "c";
final String idD = "d";
final String idE = "e";
final String testQuery = "name=test";
createSingleTargetFilterQuery("a", testQuery);
createSingleTargetFilterQuery("b", testQuery);
createSingleTargetFilterQuery(idC, testQuery);
createSingleTargetFilterQuery(idD, testQuery);
createSingleTargetFilterQuery(idE, testQuery);
mvc.perform(get(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING)
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam))
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(knownTargetAmount)))
.andExpect(status().isOk()).andDo(MockMvcResultPrinter.print())
.andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(knownTargetAmount)))
.andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize)))
.andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize)))
// idA
.andExpect(jsonPath("$.content.[?(@.name==" + idC + ")].name", contains(idC)))
.andExpect(jsonPath("$.content.[?(@.name==" + idC + ")].query", contains(testQuery)))
// idB
.andExpect(jsonPath("$.content.[?(@.name==" + idD + ")].name", contains(idD)))
.andExpect(jsonPath("$.content.[?(@.name==" + idD + ")].query", contains(testQuery)))
// idC
.andExpect(jsonPath("$.content.[?(@.name==" + idE + ")].name", contains(idE)))
.andExpect(jsonPath("$.content.[?(@.name==" + idE + ")].query", contains(testQuery)));
}
@Test
public void getSingleTarget() throws Exception {
// create first a target which can be retrieved by rest interface
final String knownQuery = "name=test01";
final String knownName = "someName";
final TargetFilterQuery tfq = createSingleTargetFilterQuery(knownName, knownQuery);
final String hrefPrefix = "http://localhost"+MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING+"/" + tfq.getId();
// test
mvc.perform(get(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(JSON_PATH_NAME, equalTo(knownName)))
.andExpect(jsonPath(JSON_PATH_QUERY, equalTo(knownQuery)))
.andExpect(jsonPath("$._links.self.href", equalTo(hrefPrefix)))
.andExpect(jsonPath("$._links.autoAssignDS.href", equalTo(hrefPrefix + "/autoAssignDS")));
}
@Test
public void getSingleTargetNoExistsResponseNotFound() throws Exception {
final String targetIdNotExists = "546546";
// test
final MvcResult mvcResult = mvc
.perform(get(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + targetIdNotExists))
.andExpect(status().isNotFound()).andReturn();
// verify response json exception message
final ExceptionInfo exceptionInfo = ResourceUtility
.convertException(mvcResult.getResponse().getContentAsString());
assertThat(exceptionInfo.getErrorCode()).isEqualTo(SpServerError.SP_REPO_ENTITY_NOT_EXISTS.getKey());
}
@Test
public void createTargetFilterQueryWithBadPayloadBadRequest() throws Exception {
final String notJson = "abc";
final MvcResult mvcResult = mvc
.perform(post(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING).content(notJson)
.contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn();
assertThat(targetFilterQueryManagement.countAllTargetFilterQuery()).isEqualTo(0);
// verify response json exception message
final ExceptionInfo exceptionInfo = ResourceUtility
.convertException(mvcResult.getResponse().getContentAsString());
assertThat(exceptionInfo.getExceptionClass()).isEqualTo(MessageNotReadableException.class.getName());
assertThat(exceptionInfo.getErrorCode()).isEqualTo(SpServerError.SP_REST_BODY_NOT_READABLE.getKey());
}
@Test
public void setAutoAssignDistributionSetToTargetFilterQuery() throws Exception {
final String knownQuery = "name=test05";
final String knownName = "filter05";
final DistributionSet set = testdataFactory.createDistributionSet("one");
final TargetFilterQuery tfq = createSingleTargetFilterQuery(knownName, knownQuery);
mvc.perform(post(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/"+tfq.getId()+"/autoAssignDS")
.content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).getAutoAssignDistributionSet()).isEqualTo(set);
final String hrefPrefix = "http://localhost"+MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING+"/" + tfq.getId();
mvc.perform(get(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/" + tfq.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(JSON_PATH_NAME, equalTo(knownName)))
.andExpect(jsonPath(JSON_PATH_QUERY, equalTo(knownQuery)))
.andExpect(jsonPath(JSON_PATH_AUTO_ASSIGN_DS, equalTo(set.getId().intValue())))
.andExpect(jsonPath("$._links.self.href", equalTo(hrefPrefix)))
.andExpect(jsonPath("$._links.autoAssignDS.href", equalTo(hrefPrefix + "/autoAssignDS")));
}
@Test
public void deleteAutoAssignDistributionSetOfTargetFilterQuery() throws Exception {
final String knownQuery = "name=test06";
final String knownName = "filter06";
final String dsName = "testDS";
final DistributionSet set = testdataFactory.createDistributionSet(dsName);
TargetFilterQuery tfq = entityFactory.generateTargetFilterQuery();
tfq.setName(knownName);
tfq.setQuery(knownQuery);
tfq.setAutoAssignDistributionSet(set);
tfq = targetFilterQueryManagement.createTargetFilterQuery(tfq);
assertThat(targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).getAutoAssignDistributionSet())
.isEqualTo(set);
mvc.perform(get(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/"+tfq.getId()+"/autoAssignDS"))
.andExpect(status().isOk())
.andExpect(jsonPath(JSON_PATH_NAME, equalTo(dsName)));
mvc.perform(delete(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/"+tfq.getId()+"/autoAssignDS"))
.andExpect(status().isNoContent());
assertThat(targetFilterQueryManagement.findTargetFilterQueryById(tfq.getId()).getAutoAssignDistributionSet())
.isNull();
mvc.perform(get(MgmtRestConstants.TARGET_FILTER_V1_REQUEST_MAPPING + "/"+tfq.getId()+"/autoAssignDS"))
.andExpect(status().isNoContent());
}
private TargetFilterQuery createSingleTargetFilterQuery(final String name, final String query) {
final TargetFilterQuery target = entityFactory.generateTargetFilterQuery();
target.setName(name);
target.setQuery(query);
return targetFilterQueryManagement.createTargetFilterQuery(target);
}
}