From c99a9a59979ccf76f3fe70349b236ffef8509362 Mon Sep 17 00:00:00 2001 From: alainbodiguel Date: Thu, 11 Jan 2024 11:51:16 +0100 Subject: [PATCH] Add public dashboard to list --- .../server/core/PersistenceService.java | 17 +- .../FileSystemPersistenceServiceImpl.java | 101 ++----- ...GoogleFirestorePersistenceServiceImpl.java | 194 +++---------- .../impl/HibernatePersistenceServiceImpl.java | 122 +++------ .../persistence/model/DataWithLinks.java | 10 + .../rest/PersistenceRestService.java | 128 --------- .../arlas/persistence/rest/PersistenceIT.java | 256 +++++++++--------- pom.xml | 2 +- 8 files changed, 240 insertions(+), 590 deletions(-) diff --git a/arlas-persistence-core/src/main/java/io/arlas/persistence/server/core/PersistenceService.java b/arlas-persistence-core/src/main/java/io/arlas/persistence/server/core/PersistenceService.java index 71fb319..eab2596 100644 --- a/arlas-persistence-core/src/main/java/io/arlas/persistence/server/core/PersistenceService.java +++ b/arlas-persistence-core/src/main/java/io/arlas/persistence/server/core/PersistenceService.java @@ -18,18 +18,19 @@ */ package io.arlas.persistence.server.core; +import io.arlas.commons.exceptions.ArlasException; import io.arlas.filter.core.IdentityParam; import io.arlas.persistence.server.exceptions.ForbiddenException; import io.arlas.persistence.server.model.Data; import io.arlas.persistence.server.utils.SortOrder; -import io.arlas.commons.exceptions.ArlasException; import org.apache.commons.lang3.tuple.Pair; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; -import java.util.stream.Collectors; + +import static io.arlas.filter.config.TechnicalRoles.GROUP_PUBLIC; public interface PersistenceService { @@ -40,10 +41,6 @@ Pair> list(String zone, Integer page, SortOrder order) throws ArlasException; - Data get(String zone, - String key, - IdentityParam identityParam) throws ArlasException; - Data getById(String id, IdentityParam identityParam) throws ArlasException; @@ -65,10 +62,6 @@ Data update(String id, Data deleteById(String id, IdentityParam identityParam) throws ArlasException; - Data delete(String zone, - String key, - IdentityParam identityParam) throws ArlasException; - static List getGroupsForZone(String zone, IdentityParam identityParam) { return identityParam.groups; @@ -96,7 +89,9 @@ static void checkReadersWritersGroups(String zone, IdentityParam identityParam, isShareableGroup(readersList, zone, identityParam); } - + static boolean isPublic(Data data) { + return data.getDocReaders().contains(GROUP_PUBLIC) || data.getDocWriters().contains(GROUP_PUBLIC); + } static boolean isReaderOnData(IdentityParam idp, Data data) { return (idp.isAnonymous || idp.organisation.contains(data.getDocOrganization())) && diff --git a/arlas-persistence-core/src/main/java/io/arlas/persistence/server/impl/FileSystemPersistenceServiceImpl.java b/arlas-persistence-core/src/main/java/io/arlas/persistence/server/impl/FileSystemPersistenceServiceImpl.java index 0a6aaff..77fee59 100644 --- a/arlas-persistence-core/src/main/java/io/arlas/persistence/server/impl/FileSystemPersistenceServiceImpl.java +++ b/arlas-persistence-core/src/main/java/io/arlas/persistence/server/impl/FileSystemPersistenceServiceImpl.java @@ -55,10 +55,17 @@ public FileSystemPersistenceServiceImpl(String localFolder) { @Override public Pair> list(String zone, IdentityParam identityParam, Integer size, Integer page, SortOrder order) throws ArlasException { List fileWrappers = new ArrayList<>(); - List orgs = identityParam.isAnonymous ? List.of(".*") : identityParam.organisation; for (String org : identityParam.organisation) { fileWrappers.addAll(getByFilenameFilter(prefixFilter(zone, org), identityParam, true)); } + if (!identityParam.isAnonymous) { + // add public from other orgs + List pub = getByFilenameFilter(prefixFilter(zone, ""), null,false); + fileWrappers.addAll(pub.stream() + .filter(f -> PersistenceService.isPublic(f.data)) + .filter(f -> !identityParam.organisation.contains(f.data.getDocOrganization())) + .toList()); + } Stream rawlist = fileWrappers.stream().map(fw -> fw.data); List list; if (order.equals(SortOrder.DESC)) { @@ -72,22 +79,6 @@ public Pair> list(String zone, IdentityParam identityParam, Int (page - 1) * size > list.size() ? Collections.emptyList() : list.subList((page - 1) * size, Math.min(list.size(), page * size))); } - @Override - public Data get(String zone, String key, IdentityParam identityParam) throws ArlasException { - Optional fw = getByZoneKeyOrga(zone, key, identityParam); - if (fw.isPresent()) { - if (PersistenceService.isReaderOnData(identityParam, fw.get().data) || - PersistenceService.isWriterOnData(identityParam, fw.get().data)) { - return fw.get().data; - } else { - throw new ForbiddenException("You are not authorized to view this resource"); - } - } else { - throw new NotFoundException("Data with zone " + zone + " and key " + key + " not found."); - } - } - - @Override public Data getById(String id, IdentityParam identityParam) throws ArlasException { List list = getByFilenameFilter(suffixFilter(id), identityParam, false); if (list.size() == 1) { @@ -107,26 +98,21 @@ public Data create(String zone, String key, IdentityParam identityParam, Set data = getByZoneKeyOrga(zone, key, identityParam); - if (data.isPresent()) { - throw new ArlasException("A resource with zone " + zone + " and key " + key + " already exists."); - } else { - PersistenceService.checkReadersWritersGroups(zone, identityParam, readers,writers); - Data newData = new Data(UUIDHelper.generateUUID().toString(), - key, - zone, - value, - identityParam.userId, - identityParam.organisation.get(0), - new ArrayList<>(writers), - new ArrayList<>(readers), - new Date()); - try (FileOutputStream fos = new FileOutputStream(storageFolder.concat(getFileName(newData)))) { - objectMapper.writeValue(fos, newData); - return newData; - } catch (IOException e) { - throw new ArlasException("An error occur in writing file: " + e.getMessage()); - } + PersistenceService.checkReadersWritersGroups(zone, identityParam, readers,writers); + Data newData = new Data(UUIDHelper.generateUUID().toString(), + key, + zone, + value, + identityParam.userId, + identityParam.organisation.get(0), + new ArrayList<>(writers), + new ArrayList<>(readers), + new Date()); + try (FileOutputStream fos = new FileOutputStream(storageFolder.concat(getFileName(newData)))) { + objectMapper.writeValue(fos, newData); + return newData; + } catch (IOException e) { + throw new ArlasException("An error occur in writing file: " + e.getMessage()); } } @@ -138,13 +124,6 @@ public Data update(String id, String key, IdentityParam identityParam, Set alreadyExisting = getByZoneKeyOrga(zone, key, identityParam); - if (alreadyExisting.isPresent()) { - throw new ArlasException("A resource with zone " + zone + " and key " + key + " already exists."); - } - } data.setDocKey(Optional.ofNullable(key).orElse(data.getDocKey())); Set readersToUpdate = Optional.ofNullable(readers).orElse(new HashSet<>(data.getDocReaders())); Set writersToUpdate = Optional.ofNullable(writers).orElse(new HashSet<>(data.getDocWriters())); @@ -189,27 +168,8 @@ public Data deleteById(String id, IdentityParam identityParam) throws ArlasExcep } } - @Override - public Data delete(String zone, String key, IdentityParam identityParam) throws ArlasException { - Optional fw = getByZoneKeyOrga(zone, key, identityParam); - if (fw.isPresent()) { - if (PersistenceService.isWriterOnData(identityParam, fw.get().data)) { - try { - fw.get().file.delete(); - } catch (Exception e) { - throw new ArlasException("Could not delete data: " + e.getMessage()); - } - return fw.get().data; - } else { - throw new ForbiddenException("You are not authorized to delete this resource"); - } - } else { - throw new NotFoundException("Data with zone " + zone + " and key " + key + " not found."); - } - } - private String getFileName(Data data){ - // zone_org_userid_key_id + // zone_org_key_userid_id return String.join("_", data.getDocZone(), data.getDocOrganization(), @@ -218,16 +178,9 @@ private String getFileName(Data data){ data.getId()); } - private Optional getByZoneKeyOrga(String zone, String key, IdentityParam identityParam) throws ArlasException { - List list = new ArrayList<>(); - for (String org : identityParam.organisation) { - list.addAll(getByFilenameFilter(prefixFilter(zone, org, key), identityParam, false)); - } - return list.size() > 0 ? Optional.of(list.get(0)) : Optional.empty(); - } - - private Predicate prefixFilter(String... prefix) { - return p -> p.getFileName().toString().startsWith(String.join("_", prefix).concat("_")); + private Predicate prefixFilter(String zone, String org) { + String prefix = org.isBlank() ? zone + "_" : zone + "_" + org + "_"; + return p -> p.getFileName().toString().startsWith(prefix); } private Predicate suffixFilter(String suffix) { diff --git a/arlas-persistence-core/src/main/java/io/arlas/persistence/server/impl/GoogleFirestorePersistenceServiceImpl.java b/arlas-persistence-core/src/main/java/io/arlas/persistence/server/impl/GoogleFirestorePersistenceServiceImpl.java index 00b34b1..d9f656f 100644 --- a/arlas-persistence-core/src/main/java/io/arlas/persistence/server/impl/GoogleFirestorePersistenceServiceImpl.java +++ b/arlas-persistence-core/src/main/java/io/arlas/persistence/server/impl/GoogleFirestorePersistenceServiceImpl.java @@ -44,6 +44,8 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import static io.arlas.filter.config.TechnicalRoles.GROUP_PUBLIC; + public class GoogleFirestorePersistenceServiceImpl implements PersistenceService { protected static Logger LOGGER = LoggerFactory.getLogger(GoogleFirestorePersistenceServiceImpl.class); @@ -57,31 +59,6 @@ public GoogleFirestorePersistenceServiceImpl(String collection) throws ArlasExce LOGGER.info("Creating indices for collection " + collection); try (FirestoreAdminClient firestoreAdminClient = FirestoreAdminClient.create()) { String parent = CollectionGroupName.of(db.getOptions().getProjectId(), db.getOptions().getDatabaseId(), collection).toString(); - try { - firestoreAdminClient.createIndexAsync(parent, Index.newBuilder() - .addFields(Index.IndexField.newBuilder().setFieldPath(Data.keyColumn).setOrder(Index.IndexField.Order.ASCENDING).build()) - .addFields(Index.IndexField.newBuilder().setFieldPath(Data.zoneColumn).setOrder(Index.IndexField.Order.ASCENDING).build()) - .addFields(Index.IndexField.newBuilder().setFieldPath(Data.lastUpdateDateColumn).setOrder(Index.IndexField.Order.ASCENDING).build()) - .setQueryScope(Index.QueryScope.COLLECTION) - .build()).get(); - } catch (AlreadyExistsException e) { - LOGGER.debug("Firestore index1 was already created"); - } catch (Exception e) { - LOGGER.error("Could not create Firestore index1, it will need to be created manually", e); - } - - try { - firestoreAdminClient.createIndexAsync(parent, Index.newBuilder() - .addFields(Index.IndexField.newBuilder().setFieldPath(Data.keyColumn).setOrder(Index.IndexField.Order.ASCENDING).build()) - .addFields(Index.IndexField.newBuilder().setFieldPath(Data.zoneColumn).setOrder(Index.IndexField.Order.ASCENDING).build()) - .addFields(Index.IndexField.newBuilder().setFieldPath(Data.lastUpdateDateColumn).setOrder(Index.IndexField.Order.DESCENDING).build()) - .setQueryScope(Index.QueryScope.COLLECTION) - .build()).get(); - } catch (AlreadyExistsException e) { - LOGGER.debug("Firestore index2 was already created"); - } catch (Exception e) { - LOGGER.error("Could not create Firestore index2, it will need to be created manually", e); - } try { firestoreAdminClient.createIndexAsync(parent, Index.newBuilder() @@ -163,28 +140,37 @@ private Data toData(String id, DocumentSnapshot d) throws NotFoundException { @Override public Pair> list(String zone, IdentityParam identityParam, Integer size, Integer page, SortOrder order) throws ArlasException { List entities = new ArrayList<>(identityParam.groups); - entities.addAll(Stream.of(identityParam.userId).toList()); + entities.add(identityParam.userId); try { - if (identityParam.isAnonymous) { - return Pair.of( - (long) db.collection(this.collection) - .whereEqualTo(Data.zoneColumn, zone) - .whereArrayContainsAny(Data.docEntitiesColumn, entities) - .get() - .get() - .size(), + return Pair.of( + (long) db.collection(this.collection) + .whereEqualTo(Data.zoneColumn, zone) + .where(Filter.or( + Filter.arrayContainsAny(Data.docEntitiesColumn, GROUP_PUBLIC), + Filter.and( + Filter.inArray(Data.organizationColumn, identityParam.organisation), + Filter.arrayContainsAny(Data.docEntitiesColumn, entities) + ))) + .get() + .get() + .size(), - db.collection(this.collection) - .whereEqualTo(Data.zoneColumn, zone) - .whereArrayContainsAny(Data.docEntitiesColumn, entities) - .orderBy(Data.lastUpdateDateColumn, order == SortOrder.ASC ? Query.Direction.ASCENDING : Query.Direction.DESCENDING) - .limit(size) - .offset((page - 1) * size) - .get() - .get() - .getDocuments() - .stream() - .map(d -> { + db.collection(this.collection) + .whereEqualTo(Data.zoneColumn, zone) + .where(Filter.or( + Filter.arrayContainsAny(Data.docEntitiesColumn, GROUP_PUBLIC), + Filter.and( + Filter.inArray(Data.organizationColumn, identityParam.organisation), + Filter.arrayContainsAny(Data.docEntitiesColumn, entities) + ))) + .orderBy(Data.lastUpdateDateColumn, order == SortOrder.ASC ? Query.Direction.ASCENDING : Query.Direction.DESCENDING) + .limit(size) + .offset((page - 1) * size) + .get() + .get() + .getDocuments() + .stream() + .map(d -> { try { return toData(d.getId(), d); } catch (NotFoundException e) { //can't happen in this case @@ -193,37 +179,6 @@ public Pair> list(String zone, IdentityParam identityParam, Int }) .filter(Objects::nonNull) .collect(Collectors.toList())); - } else { - return Pair.of( - (long) db.collection(this.collection) - .whereEqualTo(Data.zoneColumn, zone) - .whereIn(Data.organizationColumn, identityParam.organisation) - .whereArrayContainsAny(Data.docEntitiesColumn, entities) - .get() - .get() - .size(), - - db.collection(this.collection) - .whereEqualTo(Data.zoneColumn, zone) - .whereIn(Data.organizationColumn, identityParam.organisation) - .whereArrayContainsAny(Data.docEntitiesColumn, entities) - .orderBy(Data.lastUpdateDateColumn, order == SortOrder.ASC ? Query.Direction.ASCENDING : Query.Direction.DESCENDING) - .limit(size) - .offset((page - 1) * size) - .get() - .get() - .getDocuments() - .stream() - .map(d -> { - try { - return toData(d.getId(), d); - } catch (NotFoundException e) { //can't happen in this case - return null; - } - }) - .filter(Objects::nonNull) - .collect(Collectors.toList())); - } } catch (FailedPreconditionException e) { LOGGER.error(e.getMessage()); // happens when index is missing throw new ArlasException("Error listing document: " + e.getMessage()); @@ -232,22 +187,6 @@ public Pair> list(String zone, IdentityParam identityParam, Int } } - @Override - public Data get(String zone, String key, IdentityParam identityParam) throws ArlasException { - Optional data = getByZoneKeyOrga(zone, key, identityParam.organisation); - if (data.isPresent()) { - if (PersistenceService.isReaderOnData(identityParam, data.get()) || - PersistenceService.isWriterOnData(identityParam, data.get())) { - return data - .orElseThrow(() -> new NotFoundException("Data with zone " + zone + " and key " + key + " not found.")); - } else { - throw new ForbiddenException("You are not authorized to get this resource"); - } - } else { - throw new NotFoundException("Data with zone " + zone + " and key " +key +" not found."); - } - } - @Override public Data getById(String id, IdentityParam identityParam) throws ArlasException { Data data = getById(id); @@ -265,23 +204,18 @@ public Data create(String zone, String key, IdentityParam identityParam, Set data = getByZoneKeyOrga(zone, key, identityParam.organisation); - if (data.isPresent()) { - throw new ArlasException("A resource with zone " + zone + " and key " + key + " already exists."); - } else { - PersistenceService.checkReadersWritersGroups(zone, identityParam, readers,writers); - DocumentReference docRef = db.collection(collection).document(); - Set entities = new HashSet<>(); - entities.addAll(writers); - entities.addAll(readers); - entities.addAll(Stream.of(identityParam.userId).collect(Collectors.toSet())); - Data newData = new Data(docRef.getId(), key, zone, value, identityParam.userId, - identityParam.organisation.get(0), new ArrayList<>(writers), new ArrayList<>(readers), - new ArrayList<>(entities), new Date()); - Timestamp result = docRef.create(newData).get().getUpdateTime(); - LOGGER.debug("Created doc " + docRef.getId() + " at " + result); - return newData; - } + PersistenceService.checkReadersWritersGroups(zone, identityParam, readers,writers); + DocumentReference docRef = db.collection(collection).document(); + Set entities = new HashSet<>(); + entities.addAll(writers); + entities.addAll(readers); + entities.addAll(Stream.of(identityParam.userId).collect(Collectors.toSet())); + Data newData = new Data(docRef.getId(), key, zone, value, identityParam.userId, + identityParam.organisation.get(0), new ArrayList<>(writers), new ArrayList<>(readers), + new ArrayList<>(entities), new Date()); + Timestamp result = docRef.create(newData).get().getUpdateTime(); + LOGGER.debug("Created doc " + docRef.getId() + " at " + result); + return newData; } catch (InterruptedException | ExecutionException e) { throw new ArlasException("Error creating document", e); } @@ -297,13 +231,6 @@ public Data update(String id, String key, IdentityParam identityParam, Set alreadyExisting = getByZoneKeyOrga(zone, key, List.of(data.getDocOrganization())); - if (alreadyExisting.isPresent()) { - throw new ArlasException("A resource with zone " + zone + " and key " + key + " already exists."); - } - } DocumentReference docRef = db.collection(collection).document(id); Data newData = toData(id, docRef.get().get()); newData.setDocKey(Optional.ofNullable(key).orElse(data.getDocKey())); @@ -338,41 +265,6 @@ public Data deleteById(String id, IdentityParam identityParam) throws ArlasExcep return deleteData(data, identityParam); } - @Override - public Data delete(String zone, String key, IdentityParam identityParam) throws ArlasException { - Optional data = getByZoneKeyOrga(zone, key, identityParam.organisation); - if (data.isPresent()) { - return deleteData(data.get(), identityParam); - } else { - throw new NotFoundException("Data with zone " + zone + " and key " + key + " not found."); - } - } - - private Optional getByZoneKeyOrga(String zone, String key, List organization) throws ArlasException { - - try { - return db.collection(this.collection) - .whereEqualTo(Data.zoneColumn, zone) - .whereEqualTo(Data.keyColumn, key) - .whereIn(Data.organizationColumn, organization) - .limit(1) - .get().get() - .getDocuments() - .stream() - .map(d -> { - try { - return toData(d.getId(), d); - } catch (NotFoundException e) { //can't happen in this case - return null; - } - }) - .filter(Objects::nonNull) - .findFirst(); - } catch (InterruptedException | ExecutionException e) { - throw new ArlasException("Error listing document: " + e.getMessage()); - } - } - private Data getById(String id) throws ArlasException { try { return toData(id, db.collection(collection).document(id).get().get()); diff --git a/arlas-persistence-core/src/main/java/io/arlas/persistence/server/impl/HibernatePersistenceServiceImpl.java b/arlas-persistence-core/src/main/java/io/arlas/persistence/server/impl/HibernatePersistenceServiceImpl.java index 07dd5db..5e58d9a 100644 --- a/arlas-persistence-core/src/main/java/io/arlas/persistence/server/impl/HibernatePersistenceServiceImpl.java +++ b/arlas-persistence-core/src/main/java/io/arlas/persistence/server/impl/HibernatePersistenceServiceImpl.java @@ -36,6 +36,8 @@ import java.util.*; import java.util.stream.Collectors; +import static io.arlas.filter.config.TechnicalRoles.GROUP_PUBLIC; + public class HibernatePersistenceServiceImpl extends AbstractDAO implements PersistenceService { public HibernatePersistenceServiceImpl(SessionFactory factory) { @@ -43,56 +45,30 @@ public HibernatePersistenceServiceImpl(SessionFactory factory) { } @Override - public Pair list(String zone, IdentityParam identityParam, Integer size, Integer page, SortOrder order) { - - Query qCount = currentSession().createQuery("SELECT count(ud) FROM Data ud " - + " where ud." + Data.zoneColumn + "=:zone" - + (identityParam.isAnonymous ? "" : " and ud." + Data.organizationColumn + " in :organization") - + " and " + - "( " + - "ud." + Data.ownerColumn + "=:userId " - + "or " + getGroupsRequest(identityParam.groups) + ")" - , Long.class) - .setParameter("zone", zone); - if (!identityParam.isAnonymous) { - qCount.setParameter("organization", identityParam.organisation); - } - Long totalCount = qCount.setParameter("userId", identityParam.userId).uniqueResult(); - - Query query = currentSession().createQuery(" from Data ud " - + " where ud." + Data.zoneColumn + "=:zone" - + (identityParam.isAnonymous ? "" : " and ud." + Data.organizationColumn + " in :organization") - + " and " + - "( " + - "ud." + Data.ownerColumn + "=:userId " + - "or" + getGroupsRequest(identityParam.groups) + ")" + - " order by ud." + Data.lastUpdateDateColumn + " " + order.toString(), Data.class) - .setParameter("zone", zone); - if (!identityParam.isAnonymous) { - query.setParameter("organization", identityParam.organisation); - } - query.setParameter("userId", identityParam.userId) + public Pair> list(String zone, IdentityParam identityParam, Integer size, Integer page, SortOrder order) { + String from = " from Data ud " + + " where ud." + Data.zoneColumn + "=:zone" + + " and (ud." + Data.organizationColumn + " in :organization" + + " and (ud." + Data.ownerColumn + "=:userId" + + " or " + getGroupsRequest(identityParam.groups) + "))" + + " or (" + getGroupsRequest(List.of(GROUP_PUBLIC)) + ")"; + + Long totalCount = currentSession().createQuery("SELECT count(ud) " + from, Long.class) + .setParameter("zone", zone) + .setParameter("organization", identityParam.organisation) + .setParameter("userId", identityParam.userId) + .uniqueResult(); + + Query query = currentSession().createQuery(from + + " order by ud." + Data.lastUpdateDateColumn + " " + order.toString(), Data.class) + .setParameter("zone", zone) + .setParameter("organization", identityParam.organisation) + .setParameter("userId", identityParam.userId) .setMaxResults(size) .setFirstResult((page - 1) * size); return Pair.of(totalCount, list(query)); } - @Override - public Data get(String zone, String key, IdentityParam identityParam) throws ArlasException { - Optional data = getByZoneKeyOrga(zone, key, identityParam.organisation); - if (data.isPresent()) { - if (PersistenceService.isReaderOnData(identityParam, data.get()) || - PersistenceService.isWriterOnData(identityParam, data.get())) { - return data - .orElseThrow(() -> new NotFoundException("Data with zone " + zone + " and key " + key + " not found.")); - } else { - throw new ForbiddenException("You are not authorized to get this resource."); - } - } else { - throw new NotFoundException("Data with zone " + zone + " and key " +key +" not found."); - } - } - @Override public Data getById(String id, IdentityParam identityParam) throws ArlasException { Data data = getById(id); @@ -109,22 +85,17 @@ public Data create(String zone, String key, IdentityParam identityParam, Set data = getByZoneKeyOrga(zone, key, identityParam.organisation); - if (data.isPresent()) { - throw new ArlasException("A resource with zone " + zone + " and key " + key + " already exists."); - } else { - PersistenceService.checkReadersWritersGroups(zone, identityParam, readers,writers); - Data newData = new Data(UUIDHelper.generateUUID().toString(), - key, - zone, - value, - identityParam.userId, - identityParam.organisation.get(0), - new ArrayList<>(writers), - new ArrayList<>(readers), - new Date()); - return persist(newData); - } + PersistenceService.checkReadersWritersGroups(zone, identityParam, readers, writers); + Data newData = new Data(UUIDHelper.generateUUID().toString(), + key, + zone, + value, + identityParam.userId, + identityParam.organisation.get(0), + new ArrayList<>(writers), + new ArrayList<>(readers), + new Date()); + return persist(newData); } @Override @@ -136,13 +107,6 @@ public Data update(String id, String key, IdentityParam identityParam, Set alreadyExisting = getByZoneKeyOrga(zone, key, List.of(data.getDocOrganization())); - if (alreadyExisting.isPresent()) { - throw new ArlasException("A resource with zone " + zone + " and key " + key + " already exists."); - } - } data.setDocKey(Optional.ofNullable(key).orElse(data.getDocKey())); Set readersToUpdate = Optional.ofNullable(readers).orElse(new HashSet<>(data.getDocReaders())); Set writersToUpdate = Optional.ofNullable(writers).orElse(new HashSet<>(data.getDocWriters())); @@ -165,33 +129,11 @@ public Data deleteById(String id, IdentityParam identityParam) throws ArlasExcep return deleteData(data, identityParam); } - @Override - public Data delete(String zone, String key, IdentityParam identityParam) throws ArlasException { - Optional data = getByZoneKeyOrga(zone, key, identityParam.organisation); - if (data.isPresent()) { - return deleteData(data.get(), identityParam); - } else { - throw new NotFoundException("Data with zone " + zone + " and key " +key +" not found."); - } - } - private Data getById(String id) throws ArlasException { return Optional.ofNullable(get(id)) .orElseThrow(() -> new NotFoundException("Data with id " + id + " not found.")); } - private Optional getByZoneKeyOrga(String zone, String key, List organization) { - Data data = currentSession().createQuery("from Data ud" - + " where ud." + Data.zoneColumn + "=:zone" - + " and ud." + Data.keyColumn + "=:key" - + " and ud." + Data.organizationColumn + " in :organization", Data.class) - .setParameter("zone", zone) - .setParameter("key", key) - .setParameter("organization", organization) - .uniqueResult(); - return Optional.ofNullable(data); - } - private Data deleteData(Data data, IdentityParam identityParam) throws ForbiddenException { if (PersistenceService.isWriterOnData(identityParam, data)) { currentSession().delete(data); diff --git a/arlas-persistence-rest/src/main/java/io/arlas/persistence/model/DataWithLinks.java b/arlas-persistence-rest/src/main/java/io/arlas/persistence/model/DataWithLinks.java index 96dfdf9..9a0bc62 100644 --- a/arlas-persistence-rest/src/main/java/io/arlas/persistence/model/DataWithLinks.java +++ b/arlas-persistence-rest/src/main/java/io/arlas/persistence/model/DataWithLinks.java @@ -29,6 +29,7 @@ import java.util.Map; import java.util.Optional; +import static io.arlas.filter.config.TechnicalRoles.GROUP_PUBLIC; import static io.arlas.persistence.server.core.PersistenceService.intersect; @JsonSnakeCase @@ -40,7 +41,11 @@ public class DataWithLinks extends Data { @JsonProperty("updatable") public boolean updatable; + @JsonProperty("ispublic") + public boolean isPublic; + public DataWithLinks(Data data, IdentityParam identityParam) { + this.setDocOrganization(data.getDocOrganization()); this.setDocZone(data.getDocZone()); this.setDocKey(data.getDocKey()); this.setLastUpdateDate(data.getLastUpdateDate()); @@ -50,12 +55,17 @@ public DataWithLinks(Data data, IdentityParam identityParam) { this.setDocOwner(data.getDocOwner()); this.setDocReaders(data.getDocReaders()); this.setDocWriters(data.getDocWriters()); + this.setPublic(data.getDocEntities().contains(GROUP_PUBLIC)); } public void setUpdatable(boolean updatable) { this.updatable = updatable; } + public void setPublic(boolean isPublic) { + this.isPublic = isPublic; + } + public DataWithLinks withLinks(Map links) { this.links = links; return this; diff --git a/arlas-persistence-rest/src/main/java/io/arlas/persistence/rest/PersistenceRestService.java b/arlas-persistence-rest/src/main/java/io/arlas/persistence/rest/PersistenceRestService.java index c66685f..3fd3060 100644 --- a/arlas-persistence-rest/src/main/java/io/arlas/persistence/rest/PersistenceRestService.java +++ b/arlas-persistence-rest/src/main/java/io/arlas/persistence/rest/PersistenceRestService.java @@ -127,91 +127,6 @@ public Response list( persistenceService.list(zone, identityparam, size, page, order), uriInfo, page, size, order, identityparam)); } - @Timed - @Path("resource/{zone}/{key}") - @GET - @Produces(UTF8JSON) - @Consumes(UTF8JSON) - @ApiOperation( - value = Documentation.GET_FROM_KEY_ZONE_OPERATION, - produces = UTF8JSON, - notes = Documentation.GET_FROM_KEY_ZONE_OPERATION, - consumes = UTF8JSON - ) - @ApiResponses(value = {@ApiResponse(code = 200, message = "Successful operation", response = DataWithLinks.class), - @ApiResponse(code = 404, message = "Key or zone not found.", response = Error.class), - @ApiResponse(code = 500, message = "Arlas Persistence Error.", response = Error.class)}) - - @UnitOfWork - public Response getByKey( - @Context UriInfo uriInfo, - @Context HttpHeaders headers, - - @ApiParam(name = "zone", value = Documentation.ZONE, - defaultValue = "pref", - required = true) - @PathParam(value = "zone") String zone, - - @ApiParam(name = "key", value = Documentation.KEY, - required = true) - @PathParam(value = "key") String key, - - // -------------------------------------------------------- - // ----------------------- FORM ----------------------- - // -------------------------------------------------------- - @ApiParam(name = "pretty", value = Documentation.FORM_PRETTY, - defaultValue = "false") - @QueryParam(value = "pretty") Boolean pretty - ) throws ArlasException { - IdentityParam identityparam = getIdentityParam(headers); - DataWithLinks dataWithLinks = new DataWithLinks(persistenceService.get(zone, key, identityparam), identityparam); - return ResponseFormatter.getResultResponse(halService.dataWithLinks(dataWithLinks, uriInfo, identityparam)); - } - - @Timed - @Path("resource/exists/{zone}/{key}") - @GET - @Produces(UTF8JSON) - @Consumes(UTF8JSON) - @ApiOperation( - value = Documentation.EXISTS_FROM_KEY_ZONE_OPERATION, - produces = UTF8JSON, - notes = Documentation.EXISTS_FROM_KEY_ZONE_OPERATION, - consumes = UTF8JSON - ) - @ApiResponses(value = {@ApiResponse(code = 200, message = "Successful operation", response = Exists.class), - @ApiResponse(code = 500, message = "Arlas Persistence Error.", response = Error.class)}) - - @UnitOfWork - public Response existsByKey( - @Context UriInfo uriInfo, - @Context HttpHeaders headers, - - @ApiParam(name = "zone", value = Documentation.ZONE, - defaultValue = "pref", - required = true) - @PathParam(value = "zone") String zone, - - @ApiParam(name = "key", value = Documentation.KEY, - required = true) - @PathParam(value = "key") String key, - - // -------------------------------------------------------- - // ----------------------- FORM ----------------------- - // -------------------------------------------------------- - @ApiParam(name = "pretty", value = Documentation.FORM_PRETTY, - defaultValue = "false") - @QueryParam(value = "pretty") Boolean pretty - ) throws ArlasException { - IdentityParam identityparam = getIdentityParam(headers); - try { - persistenceService.get(zone, key, identityparam); - return Response.ok(new Exists(true)).build(); - } catch (NotFoundException e) { - return Response.ok(new Exists(false)).build(); - } - } - @Timed @Path("resource/id/{id}") @GET @@ -487,49 +402,6 @@ public Response deleteById( .build(); } - @Timed - @Path("resource/{zone}/{key}") - @DELETE - @Produces(UTF8JSON) - @Consumes(UTF8JSON) - @ApiOperation( - value = Documentation.DELETE_OPERATION, - produces = UTF8JSON, - notes = Documentation.DELETE_OPERATION, - consumes = UTF8JSON - ) - @ApiResponses(value = {@ApiResponse(code = 202, message = "Successful operation", response = DataWithLinks.class), - @ApiResponse(code = 404, message = "Zone or key not found.", response = Error.class), - @ApiResponse(code = 500, message = "Arlas Server Error.", response = Error.class)}) - - @UnitOfWork - public Response delete( - @Context HttpHeaders headers, - @Context UriInfo uriInfo, - - @ApiParam(name = "zone", value = Documentation.ZONE, - defaultValue = "pref", - required = true) - @PathParam(value = "zone") String zone, - - @ApiParam(name = "key", value = Documentation.KEY, - required = true) - @PathParam(value = "key") String key, - - // -------------------------------------------------------- - // ----------------------- FORM ----------------------- - // -------------------------------------------------------- - @ApiParam(name = "pretty", value = Documentation.FORM_PRETTY, - defaultValue = "false") - @QueryParam(value = "pretty") Boolean pretty - ) throws ArlasException { - IdentityParam identityparam = getIdentityParam(headers); - DataWithLinks dataWithLinks = new DataWithLinks(persistenceService.delete(zone,key,identityparam),identityparam); - return Response.accepted().entity(halService.dataWithLinks(dataWithLinks, uriInfo,identityparam)) - .type("application/json") - .build(); - } - private IdentityParam getIdentityParam(HttpHeaders headers) { IdentityParam idp = new IdentityParam(configuration, headers); LOGGER.info("User='" + idp.userId + "' / Org='" + idp.organisation + "' / Groups='" + idp.groups + "'"); diff --git a/arlas-persistence-tests/src/test/java/io/arlas/persistence/rest/PersistenceIT.java b/arlas-persistence-tests/src/test/java/io/arlas/persistence/rest/PersistenceIT.java index 9a7eb29..22b8323 100644 --- a/arlas-persistence-tests/src/test/java/io/arlas/persistence/rest/PersistenceIT.java +++ b/arlas-persistence-tests/src/test/java/io/arlas/persistence/rest/PersistenceIT.java @@ -30,6 +30,7 @@ import java.util.*; +import static io.restassured.RestAssured.delete; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; @@ -57,14 +58,14 @@ public class PersistenceIT { private static final String dataZone; private static String id; - private static String idBis; + private static final List idBis = new ArrayList<>(); static { admin = new UserIdentity("admin", String.join(",", ALL, TECHNICAL, SALES, ADMIN, PUBLIC), "company1"); technical = new UserIdentity("technical", String.join(",",ALL, TECHNICAL, PUBLIC), "company1"); commercial = new UserIdentity("commercial", String.join(",",ALL, SALES, PUBLIC), "company1"); otherCompany = new UserIdentity("other", String.join(",",ALL2, SALES2, PUBLIC), "company2"); - anonymous = new UserIdentity("anonymous", "", ""); + anonymous = new UserIdentity("anonymous", PUBLIC, ""); publicProfile = new UserIdentity("public", String.join(",", PUBLIC), "company1"); @@ -105,38 +106,12 @@ public void test02PostData() { .then().statusCode(201) .body("doc_value", equalTo("{\"age\":1}")) .extract().jsonPath().get("id"); - idBis = createData(technical, "myFirstDocumentBis", Collections.EMPTY_LIST, Collections.EMPTY_LIST) - .then().statusCode(201) - .body("doc_value", equalTo("{\"age\":1}")) - .extract().jsonPath().get("id"); } - @Test - public void test02PostPutDataKeyAlreadyExist() { - createData(technical, "myFirstDocument", Collections.EMPTY_LIST, Collections.EMPTY_LIST) - .then().statusCode(500); - Long currentDate = getData(technical, "myFirstDocument") - .then().statusCode(200) - .contentType(ContentType.JSON) - .extract().jsonPath().get("last_update_date"); - updateData(technical,"myFirstDocumentBis",id,currentDate,Collections.EMPTY_LIST, Collections.EMPTY_LIST) - .then().statusCode(500); - Long currentDateBis = getData(technical, "myFirstDocumentBis") - .then().statusCode(200) - .contentType(ContentType.JSON) - .extract().jsonPath().get("last_update_date"); - updateData(technical,"myFirstDocumentBis",idBis,currentDateBis,Collections.EMPTY_LIST, Collections.EMPTY_LIST) - .then().statusCode(201); - givenForUser(technical) - .contentType("application/json") - .delete(arlasAppPath.concat("resource/id/") + idBis) - .then().statusCode(202) - .body("id", equalTo(idBis)); - } @Test public void test03GetData() { - getData(technical, "myFirstDocument") + getData(technical, id) .then().statusCode(200) .contentType(ContentType.JSON) .body("doc_value", equalTo("{\"age\":1}")) @@ -145,8 +120,8 @@ public void test03GetData() { } @Test - public void test04PutData() { - Long currentDate = getData(technical, "myFirstDocument") + public void test04UpdateData() { + Long currentDate = getData(technical, id) .then().statusCode(200) .contentType(ContentType.JSON) .extract().jsonPath().get("last_update_date"); @@ -159,7 +134,7 @@ public void test04PutData() { .then().statusCode(201) .body("doc_value", equalTo("{\"age\":2}")); - getData(technical, "myFirstDocument") + getData(technical, id) .then().statusCode(200) .contentType(ContentType.JSON) .body("doc_value", equalTo("{\"age\":2}")) @@ -169,27 +144,22 @@ public void test04PutData() { @Test public void test05DeleteData() { - givenForUser(technical) - .contentType("application/json") - .delete(arlasAppPath.concat("resource/id/") + id) - .then().statusCode(202) - .body("id", equalTo(id)); - - getData(technical, "myFirstDocument") - .then().statusCode(404); + deleteData(technical, id); + getData(technical, id).then().statusCode(404); } @Test public void test06ListWithPagination() { for (int i = 0; i < 7; i++) { - givenForUser(technical) + idBis.add(givenForUser(technical) .pathParam("zone", dataZone) .pathParam("key", "document".concat(String.valueOf(i))) .contentType("application/json") .body(generateData(i)) .post(arlasAppPath.concat("resource/{zone}/{key}")) .then().statusCode(201) - .body("doc_value", equalTo("{\"age\":" + i + "}")); + .body("doc_value", equalTo("{\"age\":" + i + "}")) + .extract().jsonPath().get("id")); } givenForUser(technical) @@ -208,30 +178,23 @@ public void test06ListWithPagination() { } @Test - public void test07DeleteAllByZoneKey() { - for (int i = 0; i < 7; i++) { - givenForUser(technical) - .pathParam("zone", dataZone) - .pathParam("key", "document".concat(String.valueOf(i))) - .contentType("application/json") - .delete(arlasAppPath.concat("resource/{zone}/{key}")) - .then().statusCode(202); - - getData(technical, "document".concat(String.valueOf(i))) - .then().statusCode(404); + public void test07DeleteAllById() { + for (String i : idBis) { + deleteData(technical, i); + getData(technical, i).then().statusCode(404); } - } @Test public void test08PostWithWriteAccess() { - id = createData(admin, "myFirstRestrictedDocument", Collections.EMPTY_LIST, Collections.singletonList(SALES)) + id = createData(admin, "myFirstRestrictedDocument", Collections.EMPTY_LIST, List.of(SALES)) .then().statusCode(201) .body("doc_value", equalTo("{\"age\":1}")) .extract().jsonPath().get("id"); listEmpty(technical); listEmpty(otherCompany); + listEmpty(anonymous); givenForUser(commercial) .pathParam("zone", dataZone) .param("order", "asc") @@ -244,9 +207,9 @@ public void test08PostWithWriteAccess() { .body("count", equalTo(1)) .body("total", equalTo(1)); - getData(technical, "myFirstRestrictedDocument").then().statusCode(403); - getData(otherCompany, "myFirstRestrictedDocument").then().statusCode(404); - getData(commercial, "myFirstRestrictedDocument").then().statusCode(200).contentType(ContentType.JSON) + getData(technical, id).then().statusCode(403); + getData(otherCompany, id).then().statusCode(403); + getData(commercial, id).then().statusCode(200).contentType(ContentType.JSON) .body("updatable", equalTo(true)); @@ -254,12 +217,13 @@ public void test08PostWithWriteAccess() { @Test public void test09PostWithReadWriteAccess() { - id = createData(admin, "mySecondRestrictedDocument", Collections.singletonList(TECHNICAL), Collections.singletonList(SALES)) + id = createData(admin, "mySecondRestrictedDocument", List.of(TECHNICAL), List.of(SALES)) .then().statusCode(201) .body("doc_value", equalTo("{\"age\":1}")) .extract().jsonPath().get("id"); listEmpty(otherCompany); + listEmpty(anonymous); givenForUser(commercial) .pathParam("zone", dataZone) .param("order", "asc") @@ -284,19 +248,17 @@ public void test09PostWithReadWriteAccess() { .body("count", equalTo(1)) .body("total", equalTo(1)); - getData(technical, "mySecondRestrictedDocument").then().statusCode(200).contentType(ContentType.JSON) + getData(technical, id).then().statusCode(200).contentType(ContentType.JSON) .body("updatable", equalTo(false)); - getData(otherCompany, "mySecondRestrictedDocument").then().statusCode(404); - getData(commercial, "mySecondRestrictedDocument").then().statusCode(200).contentType(ContentType.JSON) + getData(otherCompany, id).then().statusCode(403); + getData(commercial, id).then().statusCode(200).contentType(ContentType.JSON) .body("updatable", equalTo(true)); - - } @Test public void test10UpdateWithJustReadAccess() { - Long currentDate = getData(technical, "mySecondRestrictedDocument") + Long currentDate = getData(technical, id) .then().statusCode(200) .contentType(ContentType.JSON) .extract().jsonPath().get("last_update_date"); @@ -313,7 +275,7 @@ public void test10UpdateWithJustReadAccess() { @Test public void test11UpdateWithJustWriteAccess() { - Long currentDate = getData(commercial, "mySecondRestrictedDocument") + Long currentDate = getData(commercial, id) .then().statusCode(200) .contentType(ContentType.JSON) .extract().jsonPath().get("last_update_date"); @@ -322,8 +284,8 @@ public void test11UpdateWithJustWriteAccess() { .contentType("application/json") .body(generateData(3)) .param("last_update", currentDate) - .queryParam("readers", Collections.singletonList(PUBLIC)) - .queryParam("writers", Collections.singletonList(SALES)) + .queryParam("readers", List.of(PUBLIC)) + .queryParam("writers", List.of(SALES)) .put(arlasAppPath.concat("resource/id/") + id) .then().statusCode(201) .body("doc_value", equalTo("{\"age\":3}")); @@ -332,12 +294,12 @@ public void test11UpdateWithJustWriteAccess() { @Test public void test12UpdateConflicts() { - Long currentDateCommercial = getData(commercial, "mySecondRestrictedDocument") + Long currentDateCommercial = getData(commercial, id) .then().statusCode(200) .contentType(ContentType.JSON) .extract().jsonPath().get("last_update_date"); - Long currentDateAdmin = getData(admin, "mySecondRestrictedDocument") + Long currentDateAdmin = getData(admin, id) .then().statusCode(200) .contentType(ContentType.JSON) .extract().jsonPath().get("last_update_date"); @@ -347,8 +309,8 @@ public void test12UpdateConflicts() { .contentType("application/json") .body(generateData(4)) .param("last_update", currentDateCommercial) - .queryParam("readers", Collections.singletonList(PUBLIC)) - .queryParam("writers", Collections.singletonList(SALES)) + .queryParam("readers", List.of(PUBLIC)) + .queryParam("writers", List.of(SALES)) .put(arlasAppPath.concat("resource/id/") + id) .then().statusCode(201) .body("doc_value", equalTo("{\"age\":4}")); @@ -357,8 +319,8 @@ public void test12UpdateConflicts() { .contentType("application/json") .body(generateData(5)) .param("last_update", currentDateAdmin) - .queryParam("readers", Collections.singletonList(PUBLIC)) - .queryParam("writers", Collections.singletonList(ADMIN)) + .queryParam("readers", List.of(PUBLIC)) + .queryParam("writers", List.of(ADMIN)) .put(arlasAppPath.concat("resource/id/") + id) .then().statusCode(409); } @@ -374,53 +336,45 @@ public void test13DeleteWithJustReadAccess() { @Test public void test14DeleteWithJustWriteAccess() { - - givenForUser(commercial) - .contentType("application/json") - .delete(arlasAppPath.concat("resource/id/") + id) - .then().statusCode(202) - .body("id", equalTo(id)); - - getData(commercial, "mySecondRestrictedDocument") - .then().statusCode(404); + deleteData(commercial, id); + getData(commercial, id).then().statusCode(404); } @Test public void test15CreateOtherOrganisation() { - id = createData(otherCompany, "mySecondRestrictedDocument", Collections.singletonList(PUBLIC), Collections.singletonList(PUBLIC)) + id = createData(otherCompany, "mySecondRestrictedDocument", List.of(PUBLIC), List.of(PUBLIC)) .then().statusCode(201) .body("doc_value", equalTo("{\"age\":1}")) .extract().jsonPath().get("id"); - - createData(otherCompany, "mySecondRestrictedDocument", Collections.singletonList(TECHNICAL), Collections.singletonList(SALES)) - .then().statusCode(500); - + deleteData(otherCompany, id); } @Test public void test16CreateWithoutHeader() { - given() + String idanon = given() .pathParam("key", "key") .pathParam("zone", "zone") .contentType("application/json") .body(generateData(1)) .post(arlasAppPath.concat("resource/{zone}/{key}")) .then().statusCode(201) - .body("doc_value", equalTo("{\"age\":1}")); + .body("doc_value", equalTo("{\"age\":1}")) + .extract().jsonPath().get("id"); - //return anonymous data + //return anonymous data given() - .pathParam("zone", "zone") - .pathParam("key", "key") + .pathParam("id", idanon) .when() - .get(arlasAppPath.concat("resource/{zone}/{key}")).then() + .get(arlasAppPath.concat("resource/id/{id}")).then() .statusCode(200) .body("doc_value", equalTo("{\"age\":1}")); + + deleteData(anonymous, idanon); } @Test public void test17GetGroups() { - List groups = given().header(userHeader, admin.userId) + List groups = given().header(userHeader, admin.userId) .header(groupsHeader, admin.groups) .header(organizationHeader, admin.organization) .pathParam("zone", dataZone) @@ -435,45 +389,87 @@ public void test17GetGroups() { @Test public void test18PostData() { - createData(technical, "myNewDocument", Collections.EMPTY_LIST, Collections.singletonList("group/private")) + createData(technical, "myNewDocument", Collections.EMPTY_LIST, List.of("group/private")) .then().statusCode(403); - createData(technical, "myNewDocument2", Collections.EMPTY_LIST, Arrays.asList("group/private",TECHNICAL)) - .then().statusCode(201); + String id2 = createData(technical, "myNewDocument2", Collections.EMPTY_LIST, Arrays.asList("group/private", TECHNICAL)) + .then().statusCode(201) + .extract().jsonPath().get("id"); + deleteData(technical, id2); } + @Test public void test19PostData() { - createData(technical, "myNewDocument", Collections.singletonList("group/private"),Collections.EMPTY_LIST) + createData(technical, "myNewDocument", List.of("group/private"), Collections.EMPTY_LIST) .then().statusCode(403); } + @Test public void test20ExistsNot() { givenForUser(technical) - .pathParam("zone", dataZone) - .pathParam("key", "foo") + .pathParam("id", "foo") .when() - .get(arlasAppPath.concat("resource/exists/{zone}/{key}")) + .get(arlasAppPath.concat("resource/exists/id/{id}")) .then().statusCode(200) .contentType(ContentType.JSON) .body("exists", equalTo(false)); } @Test - public void test21ExistsByKey() { - createData(technical, "foo", Collections.EMPTY_LIST, Collections.EMPTY_LIST) + public void test21ListWithPublic() { + String id1 = createData(technical, "privateDocument", List.of(TECHNICAL), Collections.EMPTY_LIST) .then().statusCode(201) - .body("doc_value", equalTo("{\"age\":1}")); + .extract().jsonPath().get("id"); + + String id2 = createData(technical, "publicDocument1", List.of(PUBLIC), Collections.EMPTY_LIST) + .then().statusCode(201) + .extract().jsonPath().get("id"); + + String id3 = createData(otherCompany, "publicDocument2", List.of(PUBLIC), Collections.EMPTY_LIST) + .then().statusCode(201) + .extract().jsonPath().get("id"); givenForUser(technical) .pathParam("zone", dataZone) - .pathParam("key", "foo") + .param("order", "asc") + .param("size", "10") + .param("page", "1") .when() - .get(arlasAppPath.concat("resource/exists/{zone}/{key}")) + .get(arlasAppPath.concat("resources/{zone}")) .then().statusCode(200) .contentType(ContentType.JSON) - .body("exists", equalTo(true)); - } + .body("count", equalTo(3)) + .body("total", equalTo(3)); + + givenForUser(otherCompany) + .pathParam("zone", dataZone) + .param("order", "asc") + .param("size", "10") + .param("page", "1") + .when() + .get(arlasAppPath.concat("resources/{zone}")) + .then().statusCode(200) + .contentType(ContentType.JSON) + .body("count", equalTo(2)) + .body("total", equalTo(2)); + + givenForUser(anonymous) + .pathParam("zone", dataZone) + .param("order", "asc") + .param("size", "10") + .param("page", "1") + .when() + .get(arlasAppPath.concat("resources/{zone}")) + .then().statusCode(200) + .contentType(ContentType.JSON) + .body("count", equalTo(2)) + .body("total", equalTo(2)); + deleteData(technical, id1); + deleteData(technical, id2); + deleteData(otherCompany, id3); + } + protected RequestSpecification givenForUser(UserIdentity userIdentity) { return given().header(userHeader, userIdentity.userId) .header(groupsHeader, userIdentity.groups) @@ -492,39 +488,20 @@ protected Response createData(UserIdentity userIdentity, String key, List readers, List writers) { - RequestSpecification request = givenForUser(userIdentity) - .pathParam("id", id); - - if(!readers.isEmpty()) - request=request.queryParam("readers", readers); - if(!writers.isEmpty()) - request=request.queryParam("writers", writers); - request=request.queryParam("key", key); - return - request - .contentType("application/json") - .body(generateData(2)) - .param("last_update", currentDate) - .put(arlasAppPath.concat("resource/id/{id}")); - } - - protected Response getData(UserIdentity userIdentity, String key) { + protected Response getData(UserIdentity userIdentity, String id) { return givenForUser(userIdentity) - .pathParam("zone", dataZone) - .pathParam("key", key) + .pathParam("id", id) .when() - .get(arlasAppPath.concat("resource/{zone}/{key}")); + .get(arlasAppPath.concat("resource/id/{id}")); } @@ -541,4 +518,13 @@ protected void listEmpty(UserIdentity userIdentity) { .body("count", equalTo(0)) .body("total", equalTo(0)); } + + protected void deleteData(UserIdentity userIdentity, String id) { + givenForUser(userIdentity) + .contentType("application/json") + .delete(arlasAppPath.concat("resource/id/") + id) + .then().statusCode(202) + .body("id", equalTo(id)); + + } } \ No newline at end of file diff --git a/pom.xml b/pom.xml index b22477c..a22c2c9 100644 --- a/pom.xml +++ b/pom.xml @@ -27,7 +27,7 @@ 2.1.10 42.7.1 3.5.2 - 26.28.0 + 26.29.0 2.15.2