Skip to content
This repository was archived by the owner on Apr 5, 2024. It is now read-only.

Commit 62212c2

Browse files
FF-394 - Added create new folder endpoint (#117)
* Added create new folder endpoint * Unit Tests * Fixed a bug with the calculation of paths * FF-426 add Integration tests for new folder Co-authored-by: qvalentin <[email protected]>
1 parent 85d7bb8 commit 62212c2

File tree

10 files changed

+297
-3
lines changed

10 files changed

+297
-3
lines changed

pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
</parent>
1111
<groupId>de.filefighter</groupId>
1212
<artifactId>rest</artifactId>
13-
<version>0.0.9</version>
13+
<version>0.1.0</version>
1414
<name>RestApi</name>
1515
<description>RestApi for FileFighter</description>
1616

src/main/java/de/filefighter/rest/domain/filesystem/business/FileSystemUploadService.java

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import de.filefighter.rest.domain.common.exceptions.RequestDidntMeetFormalRequirementsException;
66
import de.filefighter.rest.domain.filesystem.data.InteractionType;
77
import de.filefighter.rest.domain.filesystem.data.dto.FileSystemItem;
8+
import de.filefighter.rest.domain.filesystem.data.dto.upload.CreateNewFolder;
89
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUpload;
910
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUploadPreflightResponse;
1011
import de.filefighter.rest.domain.filesystem.data.dto.upload.PreflightResponse;
@@ -386,4 +387,75 @@ public PreflightResponse handlePreflightEntity(String absolutePath, String curre
386387
}
387388
}
388389
}
390+
391+
public FileSystemItem createNewFolder(long parentId, CreateNewFolder newFolderRequest, User authenticatedUser) {
392+
FileSystemEntity parent = fileSystemRepository.findByFileSystemId(parentId);
393+
if (null == parent)
394+
throw new FileSystemItemCouldNotBeUploadedException("Could not find parent entity or you are not allowed to see it.");
395+
396+
if (!fileSystemHelperService.userIsAllowedToInteractWithFileSystemEntity(parent, authenticatedUser, InteractionType.READ))
397+
throw new FileSystemItemCouldNotBeUploadedException("Could not find parent entity or you are not allowed to see it.");
398+
399+
if (!fileSystemHelperService.userIsAllowedToInteractWithFileSystemEntity(parent, authenticatedUser, InteractionType.CHANGE))
400+
throw new FileSystemItemCouldNotBeUploadedException("You dont have write permissions in that directory.");
401+
402+
// check for already existing folder.
403+
List<FileSystemEntity> children = fileSystemHelperService.getFolderContentsOfEntityAndPermissions(parent, authenticatedUser, false, false);
404+
Optional<FileSystemEntity> entityWithSameName = children.stream().filter(child -> child.getName().equalsIgnoreCase(newFolderRequest.getName())).findFirst();
405+
if (entityWithSameName.isPresent())
406+
throw new FileSystemItemCouldNotBeUploadedException("A Entity with the same name already exists in this directory.");
407+
408+
long timeStamp = fileSystemHelperService.getCurrentTimeStamp();
409+
410+
String dbPath;
411+
if (parent.getPath().equals("/")) {
412+
dbPath = parent.getPath() + newFolderRequest.getName().toLowerCase();
413+
} else {
414+
dbPath = parent.getPath() + "/" + newFolderRequest.getName().toLowerCase();
415+
}
416+
417+
FileSystemEntity newFolder = FileSystemEntity.builder()
418+
.path(dbPath)
419+
.name(newFolderRequest.getName())
420+
.fileSystemId(idGenerationService.consumeNext())
421+
.ownerId(parent.getOwnerId())
422+
.editableForUserIds(parent.getEditableForUserIds())
423+
.editableFoGroupIds(parent.getEditableFoGroupIds())
424+
.visibleForGroupIds(parent.getVisibleForGroupIds())
425+
.visibleForUserIds(parent.getVisibleForUserIds())
426+
.size(0)
427+
.typeId(FileSystemType.FOLDER.getId())
428+
.isFile(false)
429+
.lastUpdatedBy(authenticatedUser.getUserId())
430+
.lastUpdated(timeStamp)
431+
.build();
432+
433+
fileSystemRepository.insert(newFolder);
434+
435+
// add folder to children of parent.
436+
long[] childrenWithNewFolder = fileSystemHelperService.addLongToLongArray(parent.getItemIds(), newFolder.getFileSystemId());
437+
Query query = new Query().addCriteria(Criteria.where("fileSystemId").is(parent.getFileSystemId()));
438+
Update update = new Update().set("itemIds", childrenWithNewFolder);
439+
mongoTemplate.findAndModify(query, update, FileSystemEntity.class);
440+
441+
// update timestamps.
442+
fileSystemHelperService.recursivlyUpdateTimeStamps(parent, authenticatedUser, timeStamp);
443+
444+
User owner;
445+
try {
446+
owner = userBusinessService.findUserById(parent.getOwnerId());
447+
} catch (UserNotFoundException ex) {
448+
throw new FileFighterDataException("Could not find the owner of the entity with id: " + parentId);
449+
}
450+
451+
StringBuilder absolutePathBuilder = new StringBuilder("/").append(owner.getUsername());
452+
if (parent.getPath().equals("/")) {
453+
absolutePathBuilder.append(parent.getPath());
454+
} else {
455+
absolutePathBuilder.append(parent.getPath()).append("/");
456+
}
457+
absolutePathBuilder.append(newFolderRequest.getName().toLowerCase());
458+
459+
return fileSystemHelperService.createDTO(newFolder, authenticatedUser, absolutePathBuilder.toString());
460+
}
389461
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package de.filefighter.rest.domain.filesystem.data.dto.upload;
2+
3+
import com.fasterxml.jackson.annotation.JsonCreator;
4+
import com.fasterxml.jackson.annotation.JsonProperty;
5+
import lombok.Builder;
6+
import lombok.Getter;
7+
import lombok.ToString;
8+
9+
@Builder
10+
@ToString
11+
@Getter
12+
public class CreateNewFolder {
13+
private final String name;
14+
15+
@JsonCreator
16+
public CreateNewFolder(@JsonProperty("name") String name) {
17+
this.name = name;
18+
}
19+
}

src/main/java/de/filefighter/rest/domain/filesystem/rest/FileSystemRestController.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import de.filefighter.rest.domain.common.Pair;
44
import de.filefighter.rest.domain.filesystem.data.dto.FileSystemItem;
55
import de.filefighter.rest.domain.filesystem.data.dto.FileSystemItemUpdate;
6+
import de.filefighter.rest.domain.filesystem.data.dto.upload.CreateNewFolder;
67
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUpload;
78
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUploadPreflightResponse;
89
import io.swagger.v3.oas.annotations.tags.Tag;
@@ -66,6 +67,16 @@ public ResponseEntity<List<FileSystemItem>> downloadFileOrFolder(
6667
return fileSystemRestService.downloadFileSystemEntity(ids, new Pair<>(cookieValue, accessToken));
6768
}
6869

70+
@PostMapping(FS_BASE_URI + "{fsItemId}/folder/create")
71+
public ResponseEntity<FileSystemItem> createNewFolder(
72+
@PathVariable long fsItemId,
73+
@RequestBody CreateNewFolder newFolder,
74+
@RequestHeader(value = "Authorization") String accessToken) {
75+
76+
log.info("Tried creating new Folder {}", newFolder);
77+
return fileSystemRestService.createNewFolder(fsItemId, newFolder, accessToken);
78+
}
79+
6980
@PostMapping(FS_BASE_URI + "{fsItemId}/upload")
7081
public ResponseEntity<List<FileSystemItem>> uploadFileOrFolder(
7182
@PathVariable long fsItemId,

src/main/java/de/filefighter/rest/domain/filesystem/rest/FileSystemRestService.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import de.filefighter.rest.domain.filesystem.business.FileSystemUploadService;
99
import de.filefighter.rest.domain.filesystem.data.dto.FileSystemItem;
1010
import de.filefighter.rest.domain.filesystem.data.dto.FileSystemItemUpdate;
11+
import de.filefighter.rest.domain.filesystem.data.dto.upload.CreateNewFolder;
1112
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUpload;
1213
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUploadPreflightResponse;
1314
import de.filefighter.rest.domain.user.data.dto.User;
@@ -61,6 +62,16 @@ public ResponseEntity<List<FileSystemItem>> downloadFileSystemEntity(List<Long>
6162
return new ResponseEntity<>(listStringPair.getFirst(), responseHeaders, HttpStatus.OK);
6263
}
6364

65+
@Override
66+
public ResponseEntity<FileSystemItem> createNewFolder(long parentId, CreateNewFolder newFolder, String accessToken) {
67+
User authenticatedUser = authenticationService.bearerAuthenticationWithAccessToken(accessToken);
68+
String sanitizedName = inputSanitizerService.sanitizeString(newFolder.getName());
69+
newFolder = CreateNewFolder.builder().name(sanitizedName).build();
70+
71+
FileSystemItem folderItem = fileSystemUploadService.createNewFolder(parentId, newFolder, authenticatedUser);
72+
return new ResponseEntity<>(folderItem, HttpStatus.CREATED);
73+
}
74+
6475
@Override
6576
public ResponseEntity<List<FileSystemItem>> uploadFileSystemItemWithAccessToken(long rootItemId, FileSystemUpload fileSystemUpload, String accessToken) {
6677
User authenticatedUser = authenticationService.bearerAuthenticationWithAccessToken(accessToken);

src/main/java/de/filefighter/rest/domain/filesystem/rest/FileSystemRestServiceInterface.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import de.filefighter.rest.domain.common.Pair;
44
import de.filefighter.rest.domain.filesystem.data.dto.FileSystemItem;
55
import de.filefighter.rest.domain.filesystem.data.dto.FileSystemItemUpdate;
6+
import de.filefighter.rest.domain.filesystem.data.dto.upload.CreateNewFolder;
67
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUpload;
78
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUploadPreflightResponse;
89
import org.springframework.http.ResponseEntity;
@@ -25,4 +26,6 @@ public interface FileSystemRestServiceInterface {
2526
ResponseEntity<List<FileSystemItem>> deleteFileSystemItemWithIdAndAccessToken(long fsItemId, String accessToken);
2627

2728
ResponseEntity<List<FileSystemItem>> downloadFileSystemEntity(List<Long> fsItemIds, Pair<String, String> authPair);
29+
30+
ResponseEntity<FileSystemItem> createNewFolder(long parentId, CreateNewFolder newFolder, String accessToken);
2831
}

src/main/resources/application.properties

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,6 @@ spring.data.mongodb.host=localhost
1616
spring.data.mongodb.port=20000
1717
spring.data.mongodb.auto-index-creation=true
1818
#------------------- Custom -----------------------
19-
filefighter.version=0.0.9
20-
filefighter.date=18.05.2021
19+
filefighter.version=0.1.0
20+
filefighter.date=22.05.2021
2121
filefighter.disable-password-check=false

src/test/java/de/filefighter/rest/cucumber/FileSystemUploadSteps.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import com.fasterxml.jackson.databind.ObjectMapper;
66
import com.fasterxml.jackson.databind.node.ArrayNode;
77
import de.filefighter.rest.RestApplicationIntegrationTest;
8+
import de.filefighter.rest.domain.filesystem.data.dto.upload.CreateNewFolder;
89
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUpload;
910
import de.filefighter.rest.domain.filesystem.data.dto.upload.PreflightResponse;
1011
import io.cucumber.java.en.Then;
@@ -110,4 +111,21 @@ public void theUserWithTokenWantsToUploadAFileWithTheNamePathMimeTypeAndSizeToTh
110111

111112
executeRestApiCall(HttpMethod.POST, url, header, jsonBody);
112113
}
114+
115+
@When("the user with token {string} wants to create a folder with name {string} in the the folder with the id {long}")
116+
public void theUserWithTokenWantsToCreateAFolderWithNameInTheTheFolderWithTheId(String accessToken, String name, long parentId ) throws JsonProcessingException {
117+
118+
String authHeaderString = AUTHORIZATION_BEARER_PREFIX + accessToken;
119+
String url = BASE_API_URI + FS_BASE_URI + parentId + "/folder/create";
120+
121+
HashMap<String, String> header = new HashMap<>();
122+
header.put("Authorization", authHeaderString);
123+
124+
String jsonBody = objectMapper.writeValueAsString(CreateNewFolder.builder()
125+
.name(name)
126+
.build());
127+
128+
executeRestApiCall(HttpMethod.POST, url, header, jsonBody);
129+
130+
}
113131
}
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package de.filefighter.rest.domain.filesystem.business;
2+
3+
import de.filefighter.rest.domain.common.InputSanitizerService;
4+
import de.filefighter.rest.domain.filesystem.data.InteractionType;
5+
import de.filefighter.rest.domain.filesystem.data.dto.FileSystemItem;
6+
import de.filefighter.rest.domain.filesystem.data.dto.upload.CreateNewFolder;
7+
import de.filefighter.rest.domain.filesystem.data.persistence.FileSystemEntity;
8+
import de.filefighter.rest.domain.filesystem.data.persistence.FileSystemRepository;
9+
import de.filefighter.rest.domain.filesystem.exceptions.FileSystemItemCouldNotBeUploadedException;
10+
import de.filefighter.rest.domain.filesystem.type.FileSystemTypeRepository;
11+
import de.filefighter.rest.domain.user.business.UserBusinessService;
12+
import de.filefighter.rest.domain.user.data.dto.User;
13+
import org.junit.jupiter.api.Test;
14+
import org.springframework.data.mongodb.core.MongoTemplate;
15+
16+
import java.util.Collections;
17+
18+
import static org.junit.jupiter.api.Assertions.assertEquals;
19+
import static org.junit.jupiter.api.Assertions.assertThrows;
20+
import static org.mockito.ArgumentMatchers.any;
21+
import static org.mockito.ArgumentMatchers.eq;
22+
import static org.mockito.Mockito.mock;
23+
import static org.mockito.Mockito.when;
24+
25+
class FileSystemUploadServiceUnitTest {
26+
27+
private final FileSystemRepository fileSystemRepositoryMock = mock(FileSystemRepository.class);
28+
private final FileSystemHelperService fileSystemHelperServiceMock = mock(FileSystemHelperService.class);
29+
private final InputSanitizerService inputSanitizerServiceMock = mock(InputSanitizerService.class);
30+
private final MongoTemplate mongoTemplateMock = mock(MongoTemplate.class);
31+
private final FileSystemTypeRepository fileSystemTypeRepositoryMock = mock(FileSystemTypeRepository.class);
32+
private final UserBusinessService userBusinessServiceMock = mock(UserBusinessService.class);
33+
private final IdGenerationService idGenerationServiceMock = mock(IdGenerationService.class);
34+
35+
private final FileSystemUploadService fileSystemUploadService = new FileSystemUploadService(fileSystemRepositoryMock, fileSystemHelperServiceMock, inputSanitizerServiceMock, fileSystemTypeRepositoryMock, mongoTemplateMock, userBusinessServiceMock, idGenerationServiceMock);
36+
37+
@Test
38+
void createNewFolderThrows() {
39+
long parentId = 420;
40+
String folderName = "Kevin";
41+
CreateNewFolder createNewFolder = new CreateNewFolder(folderName);
42+
User autheticatedUser = User.builder().build();
43+
44+
FileSystemItemCouldNotBeUploadedException ex = assertThrows(FileSystemItemCouldNotBeUploadedException.class,
45+
() -> fileSystemUploadService.createNewFolder(parentId, createNewFolder, autheticatedUser));
46+
assertEquals(FileSystemItemCouldNotBeUploadedException.getErrorMessagePrefix() + " Could not find parent entity or you are not allowed to see it.", ex.getMessage());
47+
48+
FileSystemEntity parent = FileSystemEntity.builder().build();
49+
when(fileSystemRepositoryMock.findByFileSystemId(parentId)).thenReturn(parent);
50+
51+
ex = assertThrows(FileSystemItemCouldNotBeUploadedException.class,
52+
() -> fileSystemUploadService.createNewFolder(parentId, createNewFolder, autheticatedUser));
53+
assertEquals(FileSystemItemCouldNotBeUploadedException.getErrorMessagePrefix() + " Could not find parent entity or you are not allowed to see it.", ex.getMessage());
54+
55+
when(fileSystemHelperServiceMock.userIsAllowedToInteractWithFileSystemEntity(parent, autheticatedUser, InteractionType.READ)).thenReturn(true);
56+
57+
ex = assertThrows(FileSystemItemCouldNotBeUploadedException.class,
58+
() -> fileSystemUploadService.createNewFolder(parentId, createNewFolder, autheticatedUser));
59+
assertEquals(FileSystemItemCouldNotBeUploadedException.getErrorMessagePrefix() + " You dont have write permissions in that directory.", ex.getMessage());
60+
61+
when(fileSystemHelperServiceMock.userIsAllowedToInteractWithFileSystemEntity(parent, autheticatedUser, InteractionType.CHANGE)).thenReturn(true);
62+
when(fileSystemHelperServiceMock.getFolderContentsOfEntityAndPermissions(parent, autheticatedUser, false, false)).thenReturn(Collections.singletonList(FileSystemEntity.builder().name(folderName.toUpperCase()).build()));
63+
64+
ex = assertThrows(FileSystemItemCouldNotBeUploadedException.class,
65+
() -> fileSystemUploadService.createNewFolder(parentId, createNewFolder, autheticatedUser));
66+
assertEquals(FileSystemItemCouldNotBeUploadedException.getErrorMessagePrefix() + " A Entity with the same name already exists in this directory.", ex.getMessage());
67+
}
68+
69+
@Test
70+
void createNewFolderWorks() {
71+
long parentId = 420;
72+
String folderName = "Kevin";
73+
CreateNewFolder createNewFolder = new CreateNewFolder(folderName);
74+
long userId = 420;
75+
User autheticatedUser = User.builder().build();
76+
77+
FileSystemEntity parent = FileSystemEntity.builder().path("/parent").ownerId(userId).build();
78+
when(fileSystemRepositoryMock.findByFileSystemId(parentId)).thenReturn(parent);
79+
when(fileSystemHelperServiceMock.userIsAllowedToInteractWithFileSystemEntity(parent, autheticatedUser, InteractionType.READ)).thenReturn(true);
80+
when(fileSystemHelperServiceMock.userIsAllowedToInteractWithFileSystemEntity(parent, autheticatedUser, InteractionType.CHANGE)).thenReturn(true);
81+
when(fileSystemHelperServiceMock.getFolderContentsOfEntityAndPermissions(parent, autheticatedUser, false, false)).thenReturn(Collections.singletonList(FileSystemEntity.builder().name("a name").build()));
82+
when(userBusinessServiceMock.findUserById(userId)).thenReturn(User.builder().username(folderName).build());
83+
84+
FileSystemItem item = FileSystemItem.builder().build();
85+
String path = "/" + folderName + "/parent/" + folderName.toLowerCase();
86+
when(fileSystemHelperServiceMock.createDTO(any(), eq(autheticatedUser), eq(path))).thenReturn(item);
87+
88+
FileSystemItem actual = fileSystemUploadService.createNewFolder(parentId, createNewFolder, autheticatedUser);
89+
assertEquals(item, actual);
90+
}
91+
}

0 commit comments

Comments
 (0)