Skip to content

Commit

Permalink
SHIBUI-522: refactoring filters controller. Wip
Browse files Browse the repository at this point in the history
  • Loading branch information
dima767 committed Jun 4, 2018
1 parent 857bb53 commit b69c651
Show file tree
Hide file tree
Showing 11 changed files with 94 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public Iterable<MetadataFilter> getAll(@PathVariable String metadataResolverId)
return repository.findAll().iterator().next().getMetadataFilters();
}

@GetMapping("/Filter/{resourceId}")
@GetMapping("/Filters/{resourceId}")
public ResponseEntity<?> getOne(@PathVariable String metadataResolverId, @PathVariable String resourceId) {
// TODO: implement lookup based on metadataResolverId once we have more than one
// TODO: should we check that we found exactly one filter (as in the update method below)? If not, error?
Expand All @@ -57,7 +57,7 @@ public ResponseEntity<?> getOne(@PathVariable String metadataResolverId, @PathVa
.collect(Collectors.toList()).get(0));
}

@PostMapping("/Filter")
@PostMapping("/Filters")
public ResponseEntity<?> create(@PathVariable String metadataResolverId, @RequestBody MetadataFilter createdFilter) {
//TODO: replace with get by metadataResolverId once we have more than one
MetadataResolver metadataResolver = repository.findAll().iterator().next();
Expand All @@ -78,51 +78,48 @@ public ResponseEntity<?> create(@PathVariable String metadataResolverId, @Reques

}

@PutMapping("/Filter/{resourceId}")
public ResponseEntity<?> update(@PathVariable String metadataResolverId, @RequestBody FilterRepresentation filterRepresentation) {
@PutMapping("/Filters/EntityAttributes/{resourceId}")
public ResponseEntity<?> update(@PathVariable String metadataResolverId, @RequestBody EntityAttributesFilter updatedFilter) {
//TODO: replace with get by metadataResolverId once we have more than one
MetadataResolver metadataResolver = repository.findAll().iterator().next();

List<EntityAttributesFilter> filters = (List<EntityAttributesFilter>)(List<?>)
List<MetadataFilter> filters =
metadataResolver.getMetadataFilters().stream()
.filter(eaf -> eaf.getResourceId().equals(filterRepresentation.getId()))
.filter(f -> f.getResourceId().equals(updatedFilter.getResourceId()))
.collect(Collectors.toList());
if (filters.size() != 1) {
// TODO: I don't think this should ever happen, but... if it does...
// do something? throw exception, return error?
LOGGER.warn("More than one filter was found for id {}! This is probably a bad thing.\n" +
"We're going to go ahead and use the first one, but .. look in to this!", filterRepresentation.getId());
"We're going to go ahead and use the first one, but .. look in to this!", updatedFilter.getResourceId());
}

EntityAttributesFilter eaf = filters.get(0);

EntityAttributesFilter filter = EntityAttributesFilter.class.cast(filters.get(0));
// Verify we're the only one attempting to update the filter
if (filterRepresentation.getVersion() != eaf.hashCode()) {
if (updatedFilter.getVersion() != filter.hashCode()) {
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}

// convert our representation so we can get the attributes more easily...
EntityAttributesFilter updatedFilter = filterService.createFilterFromRepresentation(filterRepresentation);
eaf.setName(updatedFilter.getName());
eaf.setFilterEnabled(updatedFilter.isFilterEnabled());
eaf.setEntityAttributesFilterTarget(updatedFilter.getEntityAttributesFilterTarget());
eaf.setAttributes(updatedFilter.getAttributes());
filter.setName(updatedFilter.getName());
filter.setFilterEnabled(updatedFilter.isFilterEnabled());
filter.setEntityAttributesFilterTarget(updatedFilter.getEntityAttributesFilterTarget());
filter.setAttributes(updatedFilter.getAttributes());

MetadataResolver persistedMr = repository.save(metadataResolver);

metadataResolverService.reloadFilters(persistedMr.getName());

return ResponseEntity.ok()
.body(filterService.createRepresentationFromFilter((EntityAttributesFilter)persistedMr.getMetadataFilters().stream()
.filter(filter -> filter.getResourceId().equals(filterRepresentation.getId()))
.collect(Collectors.toList()).get(0)));
.body(persistedMr.getMetadataFilters().stream()
.filter(f -> f.getResourceId().equals(updatedFilter.getResourceId()))
.collect(Collectors.toList()).get(0));
}

private static URI getResourceUriFor(MetadataResolver mr, String filterResourceId) {
return ServletUriComponentsBuilder
.fromCurrentServletMapping().path("/api/MetadataResolver/")
.pathSegment(mr.getResourceId())
.pathSegment("Filter")
.pathSegment("Filters")
.pathSegment(filterResourceId)
.build()
.toUri();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package edu.internet2.tier.shibboleth.admin.ui.domain.filters;

import com.fasterxml.jackson.annotation.JsonIgnore;
import edu.internet2.tier.shibboleth.admin.ui.domain.AbstractAuditable;
import lombok.EqualsAndHashCode;
import org.slf4j.Logger;
Expand Down Expand Up @@ -38,7 +39,7 @@ public List<String> getValue() {
return value;
}

public void setValue(String value) {
public void setSingleValue(String value) {
List<String> values = new ArrayList<>();
values.add(value);
this.value = values;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ class MetadataFiltersControllerTests extends Specification {
def expectedResponseContentType = APPLICATION_JSON_UTF8

when:
def result = mockMvc.perform(get("/api/MetadataResolver/foo/Filter/$expectedResourceId"))
def result = mockMvc.perform(get("/api/MetadataResolver/foo/Filters/$expectedResourceId"))

then:
result.andExpect(expectedHttpResponseStatus)
Expand All @@ -140,19 +140,20 @@ class MetadataFiltersControllerTests extends Specification {

1 * metadataResolverRepository.findAll() >> [metadataResolver]
1 * metadataResolverRepository.save(_) >> metadataResolverWithFilter
1 * mockFilterService.createFilterFromRepresentation(_) >> randomFilter // this is where we want to control the id
1 * mockFilterService.createRepresentationFromFilter(randomFilter) >> filterService.createRepresentationFromFilter(randomFilter)

def expectedMetadataResolverUUID = metadataResolver.getResourceId()
def expectedFilterUUID = randomFilter.getResourceId()
def expectedResponseHeader = 'Location'
def expectedResponseHeaderValue = "/api/MetadataResolver/$expectedMetadataResolverUUID/Filter/$expectedFilterUUID"
def expectedJsonBody = mapper.writeValueAsString(filterService.createRepresentationFromFilter(randomFilter))
def expectedResponseHeaderValue = "/api/MetadataResolver/$expectedMetadataResolverUUID/Filters/$expectedFilterUUID"
def expectedJsonBody = mapper.writeValueAsString(randomFilter)
def postedJsonBody = expectedJsonBody - ~/"id":.*?,/ // remove the "id:<foo>,"
println postedJsonBody
def filter = mapper.readValue(postedJsonBody, MetadataFilter)
println filter

when:
def result = mockMvc.perform(
post('/api/MetadataResolver/foo/Filter')
post('/api/MetadataResolver/foo/Filters')
.contentType(APPLICATION_JSON_UTF8)
.content(postedJsonBody))

Expand All @@ -162,14 +163,14 @@ class MetadataFiltersControllerTests extends Specification {
.andExpect(header().string(expectedResponseHeader, containsString(expectedResponseHeaderValue)))
}

def "FilterController.update updates the target filter as desired"() {
def "FilterController.update updates the target EntityAttributes filter as desired"() {
given:
def randomFilter = testObjectGenerator.entityAttributesFilter()
def updatedFilter = testObjectGenerator.entityAttributesFilter()
updatedFilter.resourceId = randomFilter.resourceId
def updatedFilterRepresentation = filterService.createRepresentationFromFilter(updatedFilter)
updatedFilterRepresentation.setVersion(randomFilter.hashCode())
def postedJsonBody = mapper.writeValueAsString(updatedFilterRepresentation)
updatedFilter.version = randomFilter.hashCode()

def postedJsonBody = mapper.writeValueAsString(updatedFilter)

def originalMetadataResolver = new MetadataResolver()
originalMetadataResolver.setResourceId(randomGenerator.randomId())
Expand All @@ -187,7 +188,7 @@ class MetadataFiltersControllerTests extends Specification {

when:
def result = mockMvc.perform(
put("/api/MetadataResolver/foo/Filter/$filterUUID")
put("/api/MetadataResolver/foo/Filters/EntityAttributes/$filterUUID")
.contentType(APPLICATION_JSON_UTF8)
.content(postedJsonBody))

Expand All @@ -198,7 +199,7 @@ class MetadataFiltersControllerTests extends Specification {
.andExpect(content().json(JsonOutput.toJson(expectedJson), true))
}

def "FilterController.update 409's if the version numbers don't match"() {
def "FilterController.update EntityAttributes filter 409's if the version numbers don't match"() {
given:
def randomFilter = testObjectGenerator.entityAttributesFilter()
def updatedFilter = testObjectGenerator.entityAttributesFilter()
Expand All @@ -217,15 +218,15 @@ class MetadataFiltersControllerTests extends Specification {

when:
def result = mockMvc.perform(
put("/api/MetadataResolver/foo/Filter/$filterUUID")
put("/api/MetadataResolver/foo/Filters/EntityAttributes/$filterUUID")
.contentType(APPLICATION_JSON_UTF8)
.content(postedJsonBody))

then:
result.andExpect(status().is(409))
}

EntityAttributesFilter chooseRandomFilterFromList(List<MetadataFilter> filters) {
EntityAttributesFilter chooseRandomEentityAttributesFilterFromList(List<MetadataFilter> filters) {
filters.get(randomGenerator.randomInt(0, filters.size() - 1))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class EntityAttributesFilterTargetTests extends Specification {
def stringsList = ["one", "two", "three"]

when:
filterTarget.setValue(stringsList)
filterTarget.setSingleValue(stringsList)

then:
filterTarget.value == stringsList
Expand All @@ -27,7 +27,7 @@ class EntityAttributesFilterTargetTests extends Specification {
def expectedList = [someString]

when:
filterTarget.setValue(someString)
filterTarget.setSingleValue(someString)

then:
filterTarget.value.size() == 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,50 @@ class PolymorphicFiltersJacksonHandlingTests extends Specification {

}

def "Deserialization of EntityAttributes filter"() {
given:
def filterJson = """
{
"createdDate" : null,
"modifiedDate" : null,
"createdBy" : null,
"modifiedBy" : null,
"name" : "EntityAttributes",
"resourceId" : "ab3fec19-8544-45d8-9700-289155b42edf",
"filterEnabled" : false,
"version" : 0,
"entityAttributesFilterTarget" : {
"createdDate" : null,
"modifiedDate" : null,
"createdBy" : null,
"modifiedBy" : null,
"entityAttributesFilterTargetType" : "ENTITY",
"value" : [ "GATCCLk32V" ],
"audId" : null
},
"attributeRelease" : [ ],
"relyingPartyOverrides" : {
"signAssertion" : true,
"dontSignResponse" : false,
"turnOffEncryption" : false,
"useSha" : false,
"ignoreAuthenticationMethod" : true,
"omitNotBefore" : false,
"responderId" : null,
"nameIdFormats" : [ "wEPdpaov4a" ],
"authenticationMethods" : [ "FlCgvd4Z60" ]
},
"audId" : null,
"@type" : "EntityAttributes"
}"""

when:
def filter = mapper.readValue(filterJson, MetadataFilter)

then:
filter instanceof EntityAttributesFilter
filter.resourceId == 'ab3fec19-8544-45d8-9700-289155b42edf'
EntityAttributesFilter.class.cast(filter).entityAttributesFilterTarget.entityAttributesFilterTargetType.name() == 'ENTITY'
EntityAttributesFilter.class.cast(filter).entityAttributesFilterTarget.value == ['GATCCLk32V']
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class FileBackedHttpMetadataResolverRepositoryTests extends Specification {
it.metadataFilters.add(new EntityAttributesFilter().with {
it.entityAttributesFilterTarget = new EntityAttributesFilterTarget().with {
it.entityAttributesFilterTargetType = ENTITY
it.setValue(["hola"])
it.setSingleValue(["hola"])
it
}
it
Expand All @@ -70,8 +70,8 @@ class FileBackedHttpMetadataResolverRepositoryTests extends Specification {
item.name == "FileBackedHttpMetadata"
item.metadataFilters.size() == 1
item.metadataFilters[0].entityAttributesFilterTarget.entityAttributesFilterTargetType == ENTITY
item.metadataFilters[0].entityAttributesFilterTarget.value.size() == 1
item.metadataFilters[0].entityAttributesFilterTarget.value.get(0) == "hola"
item.metadataFilters[0].entityAttributesFilterTarget.setSingleValue.size() == 1
item.metadataFilters[0].entityAttributesFilterTarget.setSingleValue.get(0) == "hola"
item.httpMetadataResolverAttributes.connectionRequestTimeout == "PT05"
item.httpMetadataResolverAttributes.disregardTLSCertificate
item.httpMetadataResolverAttributes.httpCaching == memory
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class MetadataResolverRepositoryTest extends Specification {
it.metadataFilters.add(new EntityAttributesFilter().with {
it.entityAttributesFilterTarget = new EntityAttributesFilterTarget().with {
it.entityAttributesFilterTargetType = EntityAttributesFilterTarget.EntityAttributesFilterTargetType.ENTITY
it.setValue(["hola"])
it.setSingleValue(["hola"])
return it
}
return it
Expand All @@ -64,8 +64,8 @@ class MetadataResolverRepositoryTest extends Specification {
item.name == "testme"
item.metadataFilters.size() == 1
item.metadataFilters.get(0).entityAttributesFilterTarget.entityAttributesFilterTargetType == EntityAttributesFilterTarget.EntityAttributesFilterTargetType.ENTITY
item.metadataFilters.get(0).entityAttributesFilterTarget.value.size() == 1
item.metadataFilters.get(0).entityAttributesFilterTarget.value.get(0) == "hola"
item.metadataFilters.get(0).entityAttributesFilterTarget.setSingleValue.size() == 1
item.metadataFilters.get(0).entityAttributesFilterTarget.setSingleValue.get(0) == "hola"
}

def "SHIBUI-553"() {
Expand All @@ -75,7 +75,7 @@ class MetadataResolverRepositoryTest extends Specification {
it.metadataFilters.add(new EntityAttributesFilter().with {
it.entityAttributesFilterTarget = new EntityAttributesFilterTarget().with {
it.entityAttributesFilterTargetType = EntityAttributesFilterTarget.EntityAttributesFilterTargetType.ENTITY
it.setValue(["hola"])
it.setSingleValue(["hola"])
return it
}
return it
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class IncommonJPAMetadataResolverServiceImplTests extends Specification {
mr.metadataFilters.add(new EntityAttributesFilter().with {
it.entityAttributesFilterTarget = new EntityAttributesFilterTarget().with {
it.entityAttributesFilterTargetType = EntityAttributesFilterTarget.EntityAttributesFilterTargetType.ENTITY
it.value = ['https://sp1.example.org']
it.singleValue = ['https://sp1.example.org']
it
}
def attribute = attributeUtility.createAttributeWithArbitraryValues('here', null, 'there')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ class JPAEntityServiceImplTests extends Specification {
result.name == expectedAttributeName
result.attributeValues.size == listOfStrings.size
result.attributeValues.each {
listOfStrings.contains(it.value)
listOfStrings.contains(it.setSingleValue)
it.namespaceURI == expectedNamespaceURI
it.elementLocalName == expectedElementLocalName
it.namespacePrefix == expectedNamespacePrefix
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ class JPAMetadataResolverServiceImplTests extends Specification {
it.metadataFilters.add(new EntityAttributesFilter().with {
it.entityAttributesFilterTarget = new EntityAttributesFilterTarget().with {
it.entityAttributesFilterTargetType = EntityAttributesFilterTarget.EntityAttributesFilterTargetType.ENTITY
it.setValue(['http://test.scaldingspoon.org/test1'])
it.setSingleValue(['http://test.scaldingspoon.org/test1'])
return it
}
it.attributes = entityService.getAttributeListFromAttributeReleaseList(['testme'])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ class TestObjectGenerator {
EntityAttributesFilterTarget buildEntityAttributesFilterTarget() {
EntityAttributesFilterTarget entityAttributesFilterTarget = new EntityAttributesFilterTarget()

entityAttributesFilterTarget.setValue(generator.randomStringList())
entityAttributesFilterTarget.setSingleValue(generator.randomStringList())
entityAttributesFilterTarget.setEntityAttributesFilterTargetType(randomFilterTargetType())

return entityAttributesFilterTarget
Expand Down Expand Up @@ -212,7 +212,7 @@ class TestObjectGenerator {
/**
* This method takes a type and a size and builds a List of that size containing objects of that type. This is
* intended to be used with things that extend LocalizedName such as {@link OrganizationName}, {@link OrganizationDisplayName},
* or with {@link OrganizationURL}s (really, a class that has a setValue() method).
* or with {@link OrganizationURL}s (really, a class that has a setSingleValue() method).
*
* @param type the type of list to generate
* @param listSize the number of instances of that type to generate and add to the list
Expand Down

0 comments on commit b69c651

Please sign in to comment.