Commit d8bceb1c authored by Kostis Trantzas's avatar Kostis Trantzas
Browse files

Merge branch...

Merge branch '111-resourcespecification-list-by-category-and-by-name-category-and-version' into 'develop'

fix for #111

See merge request !112
parents fa57a5b8 d231d12d
Loading
Loading
Loading
Loading
Loading
+2
Changes for src/main/java/org/etsi/osl/tmf/rcm634/api/ResourceSpecificationApi.java: 2 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -26,6 +26,7 @@ package org.etsi.osl.tmf.rcm634.api;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import com.fasterxml.jackson.databind.JsonNode;
@@ -158,6 +159,7 @@ public interface ResourceSpecificationApi {
    default ResponseEntity<List<ResourceSpecification>> listResourceSpecification(@Parameter(description = "Comma-separated properties to be provided in response") @Valid @RequestParam(value = "fields", required = false) String fields
,@Parameter(description = "Requested index for start of resources to be provided in response") @Valid @RequestParam(value = "offset", required = false) Integer offset
,@Parameter(description = "Requested number of resources to be provided in response") @Valid @RequestParam(value = "limit", required = false) Integer limit
,@Parameter(description = "Any other query parameter is an exact-match filter on the column of the same name (e.g. name, category, version)", hidden = true) @RequestParam Map<String, String> allParams
) {
        if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) {
            if (getAcceptHeader().get().contains("application/json")) {
+11 −13
Changes for src/main/java/org/etsi/osl/tmf/rcm634/api/ResourceSpecificationApiController.java: 11 added lines, 13 removed lines.
Original line number Diff line number Diff line
@@ -24,7 +24,9 @@ import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import com.fasterxml.jackson.databind.JsonNode;
@@ -153,21 +155,17 @@ public class ResourceSpecificationApiController implements ResourceSpecification
	public ResponseEntity<List<ResourceSpecification>> listResourceSpecification(
			@Parameter(description = "Comma-separated properties to be provided in response") @Valid @RequestParam(value = "fields", required = false) String fields,
			@Parameter(description = "Requested index for start of resources to be provided in response") @Valid @RequestParam(value = "offset", required = false) Integer offset,
			@Parameter(description = "Requested number of resources to be provided in response") @Valid @RequestParam(value = "limit", required = false) Integer limit) {
			@Parameter(description = "Requested number of resources to be provided in response") @Valid @RequestParam(value = "limit", required = false) Integer limit,
			@Parameter(description = "Any other query parameter is an exact-match filter on the column of the same name (e.g. name, category, version)", hidden = true) @RequestParam Map<String, String> allParams) {

		try {
			if ((fields == null) ) {

				String myfields = "lastUpdate,lifecycleStatus";
				return new ResponseEntity<List<ResourceSpecification>>(resourceSpecificationRepoService.findAll(myfields),
						HttpStatus.OK);
			} else {

				return new ResponseEntity<List<ResourceSpecification>>(resourceSpecificationRepoService.findAll(fields),
						HttpStatus.OK);
			}
			

			String myfields = ( fields == null ) ? "lastUpdate,lifecycleStatus" : fields;
			Map<String, String> filters = new LinkedHashMap<>( allParams );
			filters.keySet().removeAll( List.of( "fields", "offset", "limit" ) );
			return new ResponseEntity<List<ResourceSpecification>>(
					resourceSpecificationRepoService.findAll(myfields, offset, limit, filters), HttpStatus.OK);
		} catch (IllegalArgumentException e) {
			return new ResponseEntity<List<ResourceSpecification>>(HttpStatus.BAD_REQUEST);
		} catch (Exception e) {
			log.error("Couldn't serialize response for content type application/json", e);
			return new ResponseEntity<List<ResourceSpecification>>(HttpStatus.INTERNAL_SERVER_ERROR);
+40 −5
Changes for src/main/java/org/etsi/osl/tmf/rcm634/reposervices/ResourceSpecificationRepoService.java: 40 added lines, 5 removed lines.
Original line number Diff line number Diff line
@@ -97,6 +97,10 @@ public class ResourceSpecificationRepoService {

	private SessionFactory sessionFactory;

	/** Default and maximum page size for paged queries such as {@link #findAll(String, Integer, Integer, Map)}. */
	public static final int DEFAULT_LIMIT = 25;
	public static final int MAX_LIMIT = 1000;

	private static final String METADATADIR = System.getProperty("user.home") + File.separator + ".attachments"
			+ File.separator + "metadata" + File.separator;

@@ -229,7 +233,14 @@ public class ResourceSpecificationRepoService {
	}
	
	
	public List findAll(@Valid String fields) {
	/**
	 * Lists resource specifications as lean maps, optionally filtered by column and paged.
	 * {@code filters} maps a ResSpec column name to the value it must equal exactly (all are ANDed).
	 * An unknown column or a value of the wrong type fails with an {@link IllegalArgumentException}.
	 * Paging applies only when {@code offset} or {@code limit} is given: offset is the index of the first
	 * result (not a page number), a null/non-positive limit defaults to {@link #DEFAULT_LIMIT}, capped at {@link #MAX_LIMIT}.
	 */
	public List findAll(@Valid String fields, Integer offset, Integer limit, Map<String, String> filters) {
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		List<ResourceSpecification> alist = null;
@@ -247,19 +258,43 @@ public class ResourceSpecificationRepoService {
			if (fields != null) {
				String[] field = fields.split(",");
				for (String f : field) {
					f = f.trim();
					if (!f.matches("[A-Za-z0-9_]+")) {
						throw new IllegalArgumentException("Invalid field name: " + f);
					}
					sql += ", s." + f + " as " + f ;
				}

			}
			sql += " FROM ResSpec s";

			List<String> conditions = new ArrayList<>();
			if (filters != null) {
				for (String column : filters.keySet()) {
					if (!column.matches("[A-Za-z0-9_]+")) {
						throw new IllegalArgumentException("Invalid filter name: " + column);
					}
					conditions.add("s." + column + " = :" + column);
				}
			}
			if (!conditions.isEmpty()) {
				sql += " WHERE " + String.join(" AND ", conditions);
			}

			sql += " ORDER BY s.name";
			
			sql += " ORDER BY s.name, s.uuid";

			org.hibernate.query.Query<?> query = session.createQuery(sql);
			if (filters != null) {
				for (Map.Entry<String, String> filter : filters.entrySet()) {
					query.setParameter(filter.getKey(), filter.getValue());
				}
			}
			if (offset != null || limit != null) {
				query.setFirstResult(( offset == null || offset < 0 ) ? 0 : offset);
				query.setMaxResults(( limit == null || limit <= 0 ) ? DEFAULT_LIMIT : Math.min( limit, MAX_LIMIT ));
			}

			List<Object> mapaEntity = session
				    .createQuery(sql )
			List<Object> mapaEntity = query
				    .setResultTransformer( new ResultTransformer() {
						
						@Override
+150
Changes for src/test/java/org/etsi/osl/services/api/rcm634/ResourceSpecificationListFilterPaginationTest.java: 150 added lines, 0 removed lines.
Original line number Diff line number Diff line
package org.etsi.osl.services.api.rcm634;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
import org.etsi.osl.services.api.BaseIT;
import org.etsi.osl.tmf.rcm634.model.ResourceSpecificationCreate;
import org.etsi.osl.tmf.rcm634.model.ResourceSpecification;
import org.etsi.osl.tmf.rcm634.reposervices.ResourceSpecificationRepoService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

public class ResourceSpecificationListFilterPaginationTest extends BaseIT {

    private static final String URL = "/resourceCatalogManagement/v4/resourceSpecification";
    private static final String CATEGORY = "PagCat";

    @Autowired
    private MockMvc mvc;

    @Autowired
    private ResourceSpecificationRepoService resourceSpecificationRepoService;

    private final List<String> createdUuids = new ArrayList<>();

    @BeforeEach
    public void setup() {
        // created out of name order on purpose, to check ordering by name
        for (String name : new String[] { "spec-c", "spec-a", "spec-e", "spec-b", "spec-d" }) {
            createdUuids.add(createSpec(name, CATEGORY, "1.0"));
        }
        createdUuids.add(createSpec("spec-a", CATEGORY, "2.0"));
        createdUuids.add(createSpec("spec-other", "OtherPagCat", "1.0"));
    }

    @AfterEach
    public void cleanup() {
        for (String uuid : createdUuids) {
            resourceSpecificationRepoService.deleteByUuid(uuid);
        }
        createdUuids.clear();
    }

    private String createSpec(String name, String category, String version) {
        ResourceSpecificationCreate spec = new ResourceSpecificationCreate();
        spec.setName(name);
        spec.setCategory(category);
        spec.setVersion(version);
        ResourceSpecification created = resourceSpecificationRepoService.addLogicalResourceSpecification(spec);
        return created.getUuid();
    }

    @Test
    @WithMockUser(authorities = { "ROLE_ADMIN" })
    public void testFilterByCategoryOrderedByName() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get(URL).param("category", CATEGORY))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(6)))
                .andExpect(jsonPath("$[0].name", is("spec-a")))
                .andExpect(jsonPath("$[5].name", is("spec-e")));
    }

    @Test
    @WithMockUser(authorities = { "ROLE_ADMIN" })
    public void testFilterByNameCategoryVersion() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get(URL)
                .param("name", "spec-a").param("category", CATEGORY).param("version", "2.0"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(1)))
                .andExpect(jsonPath("$[0].version", is("2.0")));

        mvc.perform(MockMvcRequestBuilders.get(URL).param("name", "spec-a").param("category", CATEGORY))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(2)));
    }

    @Test
    @WithMockUser(authorities = { "ROLE_ADMIN" })
    public void testUnknownFilterValueReturnsEmpty() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get(URL).param("category", "NoSuchCat"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(0)));
    }

    @Test
    @WithMockUser(authorities = { "ROLE_ADMIN" })
    public void testUnfilteredReturnsAllWithoutPaging() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get(URL))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.length()", greaterThanOrEqualTo(7)));
    }

    @Test
    @WithMockUser(authorities = { "ROLE_ADMIN" })
    public void testOffsetAndLimit() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get(URL).param("category", CATEGORY).param("version", "1.0")
                .param("offset", "2").param("limit", "2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(2)))
                .andExpect(jsonPath("$[0].name", is("spec-c")))
                .andExpect(jsonPath("$[1].name", is("spec-d")));
    }

    @Test
    @WithMockUser(authorities = { "ROLE_ADMIN" })
    public void testOffsetBeyondEndReturnsEmpty() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get(URL).param("category", CATEGORY).param("offset", "10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(0)));
    }

    @Test
    @WithMockUser(authorities = { "ROLE_ADMIN" })
    public void testOversizedAndInvalidLimitAreHandled() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get(URL).param("category", CATEGORY).param("limit", "5000"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(6)));

        mvc.perform(MockMvcRequestBuilders.get(URL).param("category", CATEGORY).param("offset", "-3").param("limit", "0"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(6)));
    }

    @Test
    @WithMockUser(authorities = { "ROLE_ADMIN" })
    public void testAnyColumnIsAFilterAndUnknownColumnIsBadRequest() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get(URL).param("name", "spec-b").param("lifecycleStatus", "NoSuchStatus"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(0)));

        mvc.perform(MockMvcRequestBuilders.get(URL).param("noSuchColumn", "x"))
                .andExpect(status().isBadRequest());
    }

    @Test
    @WithMockUser(authorities = { "ROLE_ADMIN" })
    public void testInvalidFieldNameIsBadRequest() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get(URL).param("fields", "name from ResSpec where 1=1 --"))
                .andExpect(status().isBadRequest());
    }
}