com.sippnex.fileblade.services.FilebladeItemService Maven / Gradle / Ivy
package com.sippnex.fileblade.services;
import com.sippnex.fileblade.entities.Directory;
import com.sippnex.fileblade.entities.File;
import com.sippnex.fileblade.entities.FilebladeItem;
import com.sippnex.fileblade.repositories.FilebladeItemRepository;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
@Service
public class FilebladeItemService {
final FilebladeItemRepository filebladeItemRepository;
public FilebladeItemService(FilebladeItemRepository filebladeItemRepository) {
this.filebladeItemRepository = filebladeItemRepository;
}
public FilebladeItem save(FilebladeItem filebladeItem) {
if(this.isUniquePath(filebladeItem)) {
return (FilebladeItem)this.filebladeItemRepository.save(filebladeItem);
} else {
System.out.println("Error creating file-blade-item: item with the same path already exists!");
return filebladeItem;
}
}
public Optional findFileByPath(String path) {
List pathElements = new ArrayList<>(Arrays.asList(path.split("\\+")));
if(pathElements.size() > 0 && pathElements.get(0).equals("")) {
pathElements.remove(0);
}
if(pathElements.size() == 0) {
return Optional.empty();
}
Optional optionalRootItem = this.filebladeItemRepository.findRootItemByName(pathElements.get(0).toLowerCase());
if(!optionalRootItem.isPresent()) {
return Optional.empty();
}
FilebladeItem rootItem = optionalRootItem.get();
if(rootItem instanceof File) {
return Optional.of((File)rootItem);
}
pathElements.remove(0);
if (pathElements.size() == 0) {
return Optional.empty();
}
Directory currentDirectory = (Directory)rootItem;
FilebladeItem nextChildItem = null;
do {
for(FilebladeItem childItem: currentDirectory.getItems()) {
if(childItem.getName().toLowerCase().equals(pathElements.get(0).toLowerCase())) {
nextChildItem = childItem;
}
}
if(nextChildItem instanceof File) {
return Optional.of((File)nextChildItem);
} else if(nextChildItem instanceof Directory) {
currentDirectory = (Directory)nextChildItem;
pathElements.remove(0);
}
} while(nextChildItem != null);
return Optional.empty();
}
public Optional findById(Long id) {
return this.filebladeItemRepository.findById(id);
}
public FilebladeItem findByName(String name) {
return this.filebladeItemRepository.findByName(name);
}
public List findRootItems() {
return this.filebladeItemRepository.findRootItems();
}
public void deleteById(Long id) {
this.filebladeItemRepository.deleteById(id);
}
private boolean isUniquePath(FilebladeItem filebladeItem) {
List neighbourItems;
if(filebladeItem.getParentDirectory() != null) {
neighbourItems = filebladeItem.getParentDirectory().getItems();
} else {
neighbourItems = filebladeItemRepository.findRootItems();
}
for(FilebladeItem neighbourItem: neighbourItems) {
if(neighbourItem.getName().toLowerCase().equals(filebladeItem.getName().toLowerCase())) {
return false;
}
}
return true;
}
}