Commit 37a77638 authored by Matija Obreza's avatar Matija Obreza

Fix: Descriptor#image tests stuck

parent cb60773c
......@@ -225,7 +225,7 @@ public class Descriptor extends UuidModel implements SelfCleaning, Publishable,
@Size(max = 2)
private String lang;
@OneToOne(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }, optional = true, orphanRemoval = true)
@OneToOne(fetch = FetchType.LAZY, cascade = { }, optional = true, orphanRemoval = false)
@JoinColumn(name = "imageId", unique = true)
private RepositoryImage image;
......@@ -243,6 +243,13 @@ public class Descriptor extends UuidModel implements SelfCleaning, Publishable,
private void preupdate() {
trimStringsToNull();
}
@PreRemove
private void preventRemoveWithImage() {
if (image != null) {
throw new DataIntegrityViolationException("Refusing to delete Descriptor with image");
}
}
/**
* Owner is the ACL parent object for the descriptor
......
......@@ -151,7 +151,7 @@ public class DescriptorServiceImpl implements DescriptorService {
LOG.debug("searchMatching: {}", new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(input));
} catch (IOException e) {
}
List<Predicate> searches = Lists.newArrayList();
// version + title
searches.add(descriptor.versionTag.eq(input.getVersionTag()).and(descriptor.title.eq(input.getTitle())));
......@@ -171,7 +171,7 @@ public class DescriptorServiceImpl implements DescriptorService {
// uom
searches.add(descriptor.dataType.eq(input.getDataType()).and(descriptor.uom.eq(input.getUom())));
}
final Predicate predicate = descriptor.crop.eq(input.getCrop()).andAnyOf(searches.toArray(EMPTY_PREDICATE_ARRAY));
List<Descriptor> matches = new ArrayList<>();
descriptorRepository.findAll(predicate).forEach(match -> matches.add(lazyLoad(match)));
......@@ -181,39 +181,34 @@ public class DescriptorServiceImpl implements DescriptorService {
@Override
@Transactional
@PreAuthorize("hasRole('ADMINISTRATOR') or hasPermission(#descriptor, 'write')")
public Descriptor updateImage(Descriptor descriptor, final MultipartFile file, final RepositoryImage imageMetadata) throws IOException,
InvalidRepositoryPathException, InvalidRepositoryFileDataException, NoSuchRepositoryFileException {
public Descriptor updateImage(Descriptor descriptor, final MultipartFile file, final RepositoryImage imageMetadata) throws IOException, InvalidRepositoryPathException,
InvalidRepositoryFileDataException, NoSuchRepositoryFileException {
descriptor = descriptorRepository.findByUuidAndVersion(descriptor.getUuid(), descriptor.getVersion());
if (descriptor.isPublished()) {
throw new InvalidApiUsageException("Cannot modify a published Descriptor.");
}
if (! file.getContentType().startsWith("image/")) {
if (!file.getContentType().startsWith("image/")) {
throw new InvalidApiUsageException("Invalid image type: " + file.getContentType() + " is not permitted.");
}
RepositoryImage repositoryImage = descriptor.getImage();
if (repositoryImage == null) {
String originalFilename = file.getOriginalFilename();
String ext = "";
if (originalFilename != null) {
int dotIndex = originalFilename.lastIndexOf(".");
ext = dotIndex > 0 ? originalFilename.substring(dotIndex) : "";
}
repositoryImage = repositoryService.addImage(getRepositoryImageFolder(descriptor),
descriptor.getUuid().toString() + ext, file.getContentType(), file.getBytes(), imageMetadata);
descriptor.setImage(repositoryImage);
if (repositoryImage != null) {
descriptor = removeImage(descriptor);
}
return lazyLoad(descriptorRepository.save(descriptor));
String originalFilename = file.getOriginalFilename();
String ext = "";
if (originalFilename != null) {
int dotIndex = originalFilename.lastIndexOf(".");
ext = dotIndex > 0 ? originalFilename.substring(dotIndex) : "";
}
String imageName = repositoryImage.getOriginalFilename();
descriptor = removeImage(descriptor);
RepositoryImage newImage = repositoryService.addImage(getRepositoryImageFolder(descriptor),
imageName, file.getContentType(), file.getBytes(), imageMetadata);
descriptor.setImage(newImage);
repositoryImage = repositoryService.addImage(getRepositoryImageFolder(descriptor), descriptor.getUuid().toString() + ext, file.getContentType(), file.getBytes(),
imageMetadata);
descriptor.setImage(repositoryImage);
return lazyLoad(descriptorRepository.save(descriptor));
}
......@@ -363,7 +358,7 @@ public class DescriptorServiceImpl implements DescriptorService {
return new PageImpl<>(res.getContent(), page, res.getTotalElements());
}
}
@Override
@PreAuthorize("isAuthenticated()")
public Page<Descriptor> listAccessibleDescriptors(DescriptorFilter descriptorFilter, Pageable page) {
......@@ -372,7 +367,8 @@ public class DescriptorServiceImpl implements DescriptorService {
} else {
final HashSet<Long> partners = new HashSet<>(securityUtils.listObjectIdentityIdsForCurrentUser(Partner.class, BasePermission.WRITE));
Pageable markdownSortPageRequest = JPAUtils.toMarkdownSort(page, "title");
Page<Descriptor> res = descriptorRepository.findAll(QDescriptor.descriptor.state.in(PublishState.PUBLISHED).or(descriptor.owner.id.in(partners)).and(descriptorFilter.buildPredicate()), markdownSortPageRequest);
Page<Descriptor> res = descriptorRepository.findAll(QDescriptor.descriptor.state.in(PublishState.PUBLISHED).or(descriptor.owner.id.in(partners)).and(descriptorFilter
.buildPredicate()), markdownSortPageRequest);
return new PageImpl<>(res.getContent(), page, res.getTotalElements());
}
}
......@@ -387,7 +383,8 @@ public class DescriptorServiceImpl implements DescriptorService {
if (descriptorFilter.isFulltextQuery()) {
res = elasticsearchService.findAll(Descriptor.class, descriptorFilter, page);
} else {
res = descriptorRepository.findAll(new BooleanBuilder().and(descriptorFilter.buildPredicate()).and(QDescriptor.descriptor.state.in(PublishState.PUBLISHED)), markdownSortPageRequest);
res = descriptorRepository.findAll(new BooleanBuilder().and(descriptorFilter.buildPredicate()).and(QDescriptor.descriptor.state.in(PublishState.PUBLISHED)),
markdownSortPageRequest);
}
return new PageImpl<>(res.getContent(), page, res.getTotalElements());
}
......@@ -400,6 +397,16 @@ public class DescriptorServiceImpl implements DescriptorService {
@PreAuthorize("hasRole('ADMINISTRATOR') or hasPermission(#descriptor, 'delete')")
public Descriptor removeDescriptor(final Descriptor descriptor) {
final Descriptor loadedDescriptor = reloadDescriptor(descriptor);
if (loadedDescriptor.isPublished()) {
throw new InvalidApiUsageException("Cannot remove a published descriptor");
}
if (loadedDescriptor.getImage() != null) {
try {
repositoryService.removeFile(loadedDescriptor.getImage());
} catch (NoSuchRepositoryFileException | IOException e) {
LOG.warn("Descriptor file not found");
}
}
descriptorRepository.delete(loadedDescriptor);
return loadedDescriptor;
}
......@@ -614,11 +621,10 @@ public class DescriptorServiceImpl implements DescriptorService {
@Override
public void exportDescriptors(DescriptorFilter filter, OutputStream outputStream) throws IOException {
List<Descriptor> descriptors = (List<Descriptor>) descriptorRepository
.findAll(filter.buildPredicate());
List<Descriptor> descriptors = (List<Descriptor>) descriptorRepository.findAll(filter.buildPredicate());
downloadService.writeXlsxDescriptor(descriptors, outputStream);
}
}
@Override
public long countDescriptors(DescriptorFilter filter) {
......
......@@ -365,7 +365,7 @@ public class DatasetServiceTest extends AbstractDatasetServiceTest {
assertThat(savedDataset.getDescriptors(), contains(descriptor2));
}
@Test(expected = DataIntegrityViolationException.class)
@Test(expected = InvalidApiUsageException.class)
public void testCannotDeleteDescriptor() {
testAddDescriptorToDataset();
DatasetFilter filter = new DatasetFilter();
......
......@@ -63,7 +63,8 @@ public class DescriptorServiceTest extends CatalogServiceTest {
descriptorListRepository.deleteAll();
descriptorRepository.deleteAll();
partnerRepository.deleteAll();
assertThat(descriptorRepository.count(), is(0l));
assertThat(descriptorListRepository.count(), is(0l));
super.cleanup();
}
......
......@@ -17,16 +17,13 @@
package org.genesys.test.server.api.v1;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import java.util.UUID;
import org.genesys.blocks.model.filters.StringFilter;
import org.genesys.filerepository.model.RepositoryImage;
import org.genesys2.server.api.v1.DescriptorController;
import org.genesys.catalog.model.Partner;
import org.genesys.catalog.model.filters.DescriptorFilter;
import org.genesys.catalog.model.filters.PartnerFilter;
......@@ -36,12 +33,13 @@ import org.genesys.catalog.model.traits.Descriptor.DataType;
import org.genesys.catalog.model.vocab.VocabularyTerm;
import org.genesys.catalog.persistence.traits.DescriptorRepository;
import org.genesys.catalog.service.DescriptorService;
import org.genesys.filerepository.model.RepositoryImage;
import org.genesys.test.base.AbstractApiTest;
import org.genesys.test.base.WithMockOAuth2Authentication;
import org.genesys2.server.api.v1.DescriptorController;
import org.genesys2.server.model.PublishState;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
......@@ -233,6 +231,8 @@ public class DescriptorControllerTest extends AbstractApiTest {
.andExpect(jsonPath("$.image", not(nullValue())))
.andExpect(jsonPath("$.image.description", is(imageMetadata.getDescription())));
/*@formatter:on*/
descriptorService.removeImage(descriptorService.getDescriptor(descriptor.getUuid())); // remove image
}
@Test
......@@ -275,6 +275,8 @@ public class DescriptorControllerTest extends AbstractApiTest {
.andExpect(jsonPath("$.image", not(nullValue())))
.andExpect(jsonPath("$.image.description", is(newRepositoryImage.getDescription())));
/*@formatter:on*/
descriptorService.removeImage(descriptorService.getDescriptor(descriptor.getUuid())); // remove image
}
@Test
......@@ -303,8 +305,10 @@ public class DescriptorControllerTest extends AbstractApiTest {
.andExpect(jsonPath("$.uuid", is(descriptor.getUuid().toString())))
.andExpect(jsonPath("$.image", nullValue()));
/*@formatter:on*/
descriptorService.removeImage(descriptorService.getDescriptor(descriptor.getUuid())); // remove image
}
@Test
@WithMockOAuth2Authentication(roles = { "ADMINISTRATOR" }, scopes = { "write" })
public void invalidImageTypeTest() throws Exception {
......@@ -318,6 +322,8 @@ public class DescriptorControllerTest extends AbstractApiTest {
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));
/*@formatter:on*/
assertThat(descriptorService.getDescriptor(descriptor.getUuid()).getImage(), nullValue());
}
@Test
......
......@@ -134,6 +134,8 @@ public class DescriptorListControllerTest extends AbstractApiTest {
.andExpect(jsonPath("$.descriptors[0].image.description", is(imageMetadata.getDescription())))
.andDo(document("contract-roles-get"));
/*@formatter:on*/
descriptorService.removeImage(descriptor); // ensure image is removed
}
@Test
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment