Commit c3c72d19 authored by Matija Obreza's avatar Matija Obreza

Repository API v1

- Files
- Folders
- Image galleries
parent 9cf1082a
......@@ -21,6 +21,7 @@ import javax.servlet.http.HttpServletRequest;
import org.genesys.catalog.exceptions.InvalidApiUsageException;
import org.genesys.catalog.exceptions.NotFoundElement;
import org.genesys.filerepository.FileRepositoryException;
import org.genesys.filerepository.NoSuchRepositoryFileException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -130,7 +131,7 @@ public class ApiExceptionHandler {
* @return the api error
*/
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
@ExceptionHandler({ InvalidApiUsageException.class, ConcurrencyFailureException.class })
@ExceptionHandler({ InvalidApiUsageException.class, ConcurrencyFailureException.class, FileRepositoryException.class })
@ResponseBody
public ApiError<Exception> handleInvalidApiUsage(final Exception e, final HttpServletRequest request) {
LOG.warn("{} for {} {}", e.getMessage(), request.getMethod(), request.getRequestURL()); //, e);
......
/*
* Copyright 2018 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys2.server.api.v1;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.genesys.blocks.model.JsonViews;
import org.genesys.catalog.exceptions.NotFoundElement;
import org.genesys.filerepository.FolderNotEmptyException;
import org.genesys.filerepository.InvalidRepositoryFileDataException;
import org.genesys.filerepository.InvalidRepositoryPathException;
import org.genesys.filerepository.NoSuchRepositoryFileException;
import org.genesys.filerepository.NoSuchRepositoryFolderException;
import org.genesys.filerepository.model.ImageGallery;
import org.genesys.filerepository.model.RepositoryFile;
import org.genesys.filerepository.model.RepositoryFolder;
import org.genesys.filerepository.service.ImageGalleryService;
import org.genesys.filerepository.service.RepositoryService;
import org.genesys2.server.api.ApiBaseController;
import org.genesys2.spring.ResourceNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;
import com.fasterxml.jackson.annotation.JsonView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
/**
* @author Matija Obreza
*/
@RestController("repositoryApi1")
@RequestMapping(RepositoryController.CONTROLLER_URL)
@PreAuthorize("isAuthenticated()")
@Api(tags = { "repository" })
public class RepositoryController {
/** The Constant API_BASE. */
protected static final String CONTROLLER_URL = ApiBaseController.APIv1_BASE + "/repository";
private static final Logger LOG = LoggerFactory.getLogger(RepositoryController.class);
/** The repository service. */
@Autowired
protected RepositoryService repositoryService;
@Autowired
private ImageGalleryService imagegalleryService;
/**
* Gets the file.
*
* @param fileUuid the file uuid
* @return the file
* @throws NoSuchRepositoryFileException the no such repository file exception
* @throws IOException Signals that an I/O exception has occurred.
*/
@GetMapping(value = "/file/{fileUuid}")
public RepositoryFile getFile(@PathVariable("fileUuid") final UUID fileUuid) throws NoSuchRepositoryFileException, IOException {
return repositoryService.getFile(fileUuid);
}
/**
* Update file.
*
* @param fileUuid the file uuid
* @param version the version
* @param metadata the metadata
* @return the repository file
* @throws NoSuchRepositoryFileException the no such repository file exception
* @throws IOException Signals that an I/O exception has occurred.
*/
@PutMapping(value = "/file")
public RepositoryFile updateFile(@RequestBody final RepositoryFile metadata) throws NoSuchRepositoryFileException, IOException {
return repositoryService.updateMetadata(metadata);
}
/**
* Removes the file.
*
* @param fileUuid the file uuid
* @return the repository file
* @throws NoSuchRepositoryFileException the no such repository file exception
* @throws IOException Signals that an I/O exception has occurred.
*/
@DeleteMapping(value = "/file/{fileUuid}")
public RepositoryFile removeFile(@PathVariable("fileUuid") final UUID fileUuid) throws NoSuchRepositoryFileException, IOException {
return repositoryService.removeFile(repositoryService.getFile(fileUuid));
}
/**
* Upload file to specified folder.
*
* @param file the file
* @param request the request
* @return repository file metadata
* @throws InvalidRepositoryPathException the invalid repository path exception
* @throws InvalidRepositoryFileDataException the invalid repository file data
* exception
* @throws IOException Signals that an I/O exception has occurred.
* @throws NotFoundElement the not found element
*/
@PostMapping(value = "/upload/**")
public RepositoryFile uploadFile(@RequestParam("file") final MultipartFile file, final HttpServletRequest request) throws InvalidRepositoryPathException,
InvalidRepositoryFileDataException, IOException {
final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/upload").length());
Path repositoryPath = Paths.get(folderPath);
LOG.info("Upload file {} to path {}", file.getOriginalFilename(), repositoryPath);
return repositoryService.addFile(repositoryPath, file.getOriginalFilename(), file.getContentType(), file.getBytes(), null);
}
/**
* Download file.
*
* @param fileUuid the file uuid
* @param response the response
* @throws NoSuchRepositoryFileException the no such repository file exception
* @throws IOException Signals that an I/O exception has occurred.
*/
@GetMapping(value = "/download/{fileUuid}")
public void downloadFile(@PathVariable("fileUuid") final UUID fileUuid, final HttpServletResponse response) throws NoSuchRepositoryFileException, IOException {
final RepositoryFile repositoryFile = repositoryService.getFile(fileUuid);
response.setHeader(HttpHeaders.CACHE_CONTROL, "max-age=86400, s-maxage=86400, public, no-transform");
response.setHeader(HttpHeaders.PRAGMA, "");
response.setDateHeader(HttpHeaders.LAST_MODIFIED, repositoryFile.getLastModifiedDate().getTime());
response.setContentType(repositoryFile.getContentType());
response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", repositoryFile.getOriginalFilename()));
final byte[] data = repositoryService.getFileBytes(repositoryFile);
if (data != null) {
response.setContentLength(data.length);
response.getOutputStream().write(data);
}
response.flushBuffer();
}
/**
* Move specified file to the specified full file path (folder + new
* originalFilename).
*
* @param fileUuid file UUID
* @param fullPath full folder path + new orignalFilename
* @return the repository file
* @throws InvalidRepositoryPathException the invalid repository path exception
* @throws InvalidRepositoryFileDataException the invalid repository file data
* exception
* @throws NoSuchRepositoryFileException the no such repository file exception
*/
@PostMapping(value = "/file/{fileUuid}/move", consumes = MediaType.TEXT_PLAIN_VALUE)
public RepositoryFile moveAndRenameFile(@PathVariable("fileUuid") final UUID fileUuid, @RequestBody(required = true) String fullPath) throws InvalidRepositoryPathException,
InvalidRepositoryFileDataException, NoSuchRepositoryFileException {
return repositoryService.moveAndRenameFile(repositoryService.getFile(fileUuid), Paths.get(fullPath));
}
/**
* Rename folder.
*
* @param folderUuid the folder uuid
* @param fullPath the full path
* @return the folder details
* @throws InvalidRepositoryPathException the invalid repository path exception
*/
@PostMapping(value = "/folder/{folderUuid}/rename", consumes = MediaType.TEXT_PLAIN_VALUE)
@JsonView(JsonViews.Protected.class)
public FolderDetails renameFolder(@PathVariable("folderUuid") final UUID folderUuid, @RequestBody(required = true) String fullPath) throws InvalidRepositoryPathException {
RepositoryFolder folder = repositoryService.getFolder(folderUuid);
if (folder == null) {
throw new ResourceNotFoundException("No folder with uuid=" + folderUuid);
}
return folderDetails(repositoryService.renamePath(folder.getFolderPath(), Paths.get(fullPath)).getFolderPath());
}
/**
* Update folder title and description
*
* @param request the request
* @return the folder
* @throws InvalidRepositoryPathException the invalid repository path exception
* @throws NoSuchRepositoryFolderException
*/
@PutMapping("/folder")
@ApiOperation(nickname = "updateFolder", value = "Update folder title and description")
@JsonView(JsonViews.Protected.class)
public FolderDetails updateFolder(@RequestBody(required = true) RepositoryFolder folder) throws InvalidRepositoryPathException, NoSuchRepositoryFolderException {
folder = repositoryService.updateFolder(folder);
return folderDetails(folder.getFolderPath());
}
/**
* Gets folder details at specified path.
*
* @param request the request
* @return the folder
* @throws InvalidRepositoryPathException the invalid repository path exception
*/
@GetMapping("/folder/**")
@ApiOperation(nickname = "getFolder", value = "Get folder details by folder path")
@JsonView(JsonViews.Protected.class)
public FolderDetails getFolder(@ApiParam(name = "path", type = "java.lang.String") final HttpServletRequest request) throws InvalidRepositoryPathException {
final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/folder").length());
return folderDetails(Paths.get(folderPath));
}
/**
* Gets folder details at specified path.
*
* @param request the request
* @return the deleted folder
* @throws InvalidRepositoryPathException the invalid repository path exception
* @throws FolderNotEmptyException
*/
@DeleteMapping("/folder/**")
@ApiOperation(nickname = "deleteFolder", value = "Delete folder")
@JsonView(JsonViews.Protected.class)
public RepositoryFolder deleteFolder(@ApiParam(name = "path", type = "java.lang.String") final HttpServletRequest request) throws InvalidRepositoryPathException,
FolderNotEmptyException {
final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/folder").length());
RepositoryFolder folder = repositoryService.getFolder(Paths.get(folderPath));
repositoryService.deleteFolder(Paths.get(folderPath));
return folder;
}
/**
* Folder details.
*
* @param path the path
* @return the folder details
* @throws InvalidRepositoryPathException the invalid repository path exception
*/
private FolderDetails folderDetails(final Path path) throws InvalidRepositoryPathException {
FolderDetails fd = new FolderDetails();
fd.folder = repositoryService.getFolder(path);
fd.subFolders = repositoryService.getFolders(path);
if (fd.folder == null && !path.toAbsolutePath().toString().equals("/")) {
throw new ResourceNotFoundException("No such folder");
}
fd.files = repositoryService.getFiles(path);
fd.gallery = imagegalleryService.loadImageGallery(path);
return fd;
}
/**
* Get image gallery.
*
* @param request the request
* @return the gallery
* @throws InvalidRepositoryPathException the invalid repository path exception
*/
@GetMapping("/gallery/**")
@JsonView(JsonViews.Root.class)
public ImageGallery getGallery(final HttpServletRequest request) throws InvalidRepositoryPathException {
final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/gallery").length());
return imagegalleryService.loadImageGallery(Paths.get(folderPath));
}
/**
* Creates the gallery.
*
* @param request the request
* @param imageGallery the image gallery
* @return the image gallery
* @throws InvalidRepositoryPathException the invalid repository path exception
*/
@PostMapping("/gallery/**")
@JsonView(JsonViews.Root.class)
public ImageGallery createGallery(final HttpServletRequest request, @RequestBody ImageGallery imageGallery) throws InvalidRepositoryPathException {
final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/gallery").length());
return imagegalleryService.createImageGallery(Paths.get(folderPath), imageGallery.getTitle(), imageGallery.getDescription());
}
/**
* Update gallery information
*
* @param imageGallery the image gallery
* @return the image gallery
* @throws InvalidRepositoryPathException the invalid repository path exception
*/
@PutMapping("/gallery")
@JsonView(JsonViews.Root.class)
public ImageGallery updateGallery(@RequestBody ImageGallery imageGallery) throws InvalidRepositoryPathException {
return imagegalleryService.updateImageGalery(imageGallery, imageGallery.getTitle(), imageGallery.getDescription());
}
/**
* Creates the gallery.
*
* @param request the request
* @param imageGallery the image gallery
* @return the image gallery
* @throws InvalidRepositoryPathException the invalid repository path exception
*/
@DeleteMapping("/gallery/**")
@JsonView(JsonViews.Root.class)
public ImageGallery removeGallery(final HttpServletRequest request) throws InvalidRepositoryPathException {
final String folderPath = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).substring((CONTROLLER_URL + "/gallery").length());
ImageGallery imageGallery = imagegalleryService.loadImageGallery(Paths.get(folderPath));
imagegalleryService.removeGallery(imageGallery);
return imageGallery;
}
/**
* The Class FolderDetails.
*/
public static class FolderDetails {
/** The folder itself (may be null for /). */
public RepositoryFolder folder;
/** Subfolders */
public List<RepositoryFolder> subFolders;
/** The files. */
public List<RepositoryFile> files;
/** The gallery. */
public ImageGallery gallery;
}
}
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