use of org.hisp.dhis.fileresource.FileResource in project dhis2-core by dhis2.
the class SaveDocumentAction method uploadFile.
private FileResource uploadFile(File file, String fileName, String contentType) throws IOException {
log.info("Uploading file '" + fileName + "' to document " + name + ".");
byte[] bytes = FileUtils.readFileToByteArray(file);
FileResource fileResource = new FileResource(fileName, contentType, bytes.length, ByteSource.wrap(bytes).hash(Hashing.md5()).toString(), FileResourceDomain.DOCUMENT);
fileResourceService.saveFileResource(fileResource, bytes);
log.info("Upload complete.");
return fileResource;
}
use of org.hisp.dhis.fileresource.FileResource in project dhis2-core by dhis2.
the class DataValueController method getDataValueFile.
// ---------------------------------------------------------------------
// GET file
// ---------------------------------------------------------------------
@RequestMapping(value = "/files", method = RequestMethod.GET)
public void getDataValueFile(@RequestParam String de, @RequestParam(required = false) String co, @RequestParam(required = false) String cc, @RequestParam(required = false) String cp, @RequestParam String pe, @RequestParam String ou, HttpServletResponse response, HttpServletRequest request) throws WebMessageException {
// ---------------------------------------------------------------------
// Input validation
// ---------------------------------------------------------------------
DataElement dataElement = getAndValidateDataElement(de);
if (!dataElement.isFileType()) {
throw new WebMessageException(WebMessageUtils.conflict("DataElement must be of type file"));
}
DataElementCategoryOptionCombo categoryOptionCombo = getAndValidateCategoryOptionCombo(co, false);
DataElementCategoryOptionCombo attributeOptionCombo = getAndValidateAttributeOptionCombo(cc, cp);
Period period = getAndValidatePeriod(pe);
OrganisationUnit organisationUnit = getAndValidateOrganisationUnit(ou);
// ---------------------------------------------------------------------
// Get data value
// ---------------------------------------------------------------------
DataValue dataValue = dataValueService.getDataValue(dataElement, period, organisationUnit, categoryOptionCombo, attributeOptionCombo);
if (dataValue == null) {
throw new WebMessageException(WebMessageUtils.conflict("Data value does not exist"));
}
// ---------------------------------------------------------------------
// Get file resource
// ---------------------------------------------------------------------
String uid = dataValue.getValue();
FileResource fileResource = fileResourceService.getFileResource(uid);
if (fileResource == null || fileResource.getDomain() != FileResourceDomain.DATA_VALUE) {
throw new WebMessageException(WebMessageUtils.notFound("A data value file resource with id " + uid + " does not exist."));
}
FileResourceStorageStatus storageStatus = fileResource.getStorageStatus();
if (storageStatus != FileResourceStorageStatus.STORED) {
// Special case:
// The FileResource exists and has been tied to this DataValue, however, the underlying file
// content is still not stored to the (most likely external) file store provider.
// HTTP 409, for lack of a more suitable status code
WebMessage webMessage = WebMessageUtils.conflict("The content is being processed and is not available yet. Try again later.", "The content requested is in transit to the file store and will be available at a later time.");
webMessage.setResponse(new FileResourceWebMessageResponse(fileResource));
throw new WebMessageException(webMessage);
}
ByteSource content = fileResourceService.getFileResourceContent(fileResource);
if (content == null) {
throw new WebMessageException(WebMessageUtils.notFound("The referenced file could not be found"));
}
// ---------------------------------------------------------------------
// Attempt to build signed URL request for content and redirect
// ---------------------------------------------------------------------
URI signedGetUri = fileResourceService.getSignedGetFileResourceContentUri(uid);
if (signedGetUri != null) {
response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
response.setHeader(HttpHeaders.LOCATION, signedGetUri.toASCIIString());
return;
}
// ---------------------------------------------------------------------
// Build response and return
// ---------------------------------------------------------------------
response.setContentType(fileResource.getContentType());
response.setContentLength(new Long(fileResource.getContentLength()).intValue());
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "filename=" + fileResource.getName());
// ---------------------------------------------------------------------
// Request signing is not available, stream content back to client
// ---------------------------------------------------------------------
InputStream inputStream = null;
try {
inputStream = content.openStream();
IOUtils.copy(inputStream, response.getOutputStream());
} catch (IOException e) {
throw new WebMessageException(WebMessageUtils.error("Failed fetching the file from storage", "There was an exception when trying to fetch the file from the storage backend. " + "Depending on the provider the root cause could be network or file system related."));
} finally {
IOUtils.closeQuietly(inputStream);
}
}
use of org.hisp.dhis.fileresource.FileResource in project dhis2-core by dhis2.
the class ExternalFileResourceController method getExternalFileResource.
/**
* Returns a file associated with the externalFileResource resolved from the accessToken.
* <p>
* Only files contained in externalFileResources with a valid accessToken, expiration date null or in the future
* are files allowed to be served trough this endpoint.
*
* @param accessToken a unique string that resolves to a given externalFileResource
* @param response
* @throws WebMessageException
*/
@RequestMapping(value = "/{accessToken}", method = RequestMethod.GET)
public void getExternalFileResource(@PathVariable String accessToken, HttpServletResponse response) throws WebMessageException {
ExternalFileResource externalFileResource = externalFileResourceService.getExternalFileResourceByAccessToken(accessToken);
if (externalFileResource == null) {
throw new WebMessageException(WebMessageUtils.notFound("No file found with key '" + accessToken + "'"));
}
if (externalFileResource.getExpires() != null && externalFileResource.getExpires().before(new Date())) {
throw new WebMessageException(WebMessageUtils.createWebMessage("The key you requested has expired", Status.WARNING, HttpStatus.GONE));
}
FileResource fileResource = externalFileResource.getFileResource();
// ---------------------------------------------------------------------
// Attempt to build signed URL request for content and redirect
// ---------------------------------------------------------------------
URI signedGetUri = fileResourceService.getSignedGetFileResourceContentUri(fileResource.getUid());
if (signedGetUri != null) {
response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
response.setHeader(HttpHeaders.LOCATION, signedGetUri.toASCIIString());
return;
}
// ---------------------------------------------------------------------
// Build response and return
// ---------------------------------------------------------------------
response.setContentType(fileResource.getContentType());
response.setContentLength(new Long(fileResource.getContentLength()).intValue());
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "filename=" + fileResource.getName());
// ---------------------------------------------------------------------
// Request signing is not available, stream content back to client
// ---------------------------------------------------------------------
InputStream inputStream = null;
try {
inputStream = fileResourceService.getFileResourceContent(fileResource).openStream();
IOUtils.copy(inputStream, response.getOutputStream());
} catch (IOException e) {
throw new WebMessageException(WebMessageUtils.error("Failed fetching the file from storage", "There was an exception when trying to fetch the file from the storage backend. " + "Depending on the provider the root cause could be network or file system related."));
} finally {
IOUtils.closeQuietly(inputStream);
}
}
use of org.hisp.dhis.fileresource.FileResource in project dhis2-core by dhis2.
the class FileResourceController method saveFileResource.
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public WebMessage saveFileResource(@RequestParam MultipartFile file) throws WebMessageException, IOException {
String filename = StringUtils.defaultIfBlank(FilenameUtils.getName(file.getOriginalFilename()), DEFAULT_FILENAME);
String contentType = file.getContentType();
contentType = isValidContentType(contentType) ? contentType : DEFAULT_CONTENT_TYPE;
long contentLength = file.getSize();
if (contentLength <= 0) {
throw new WebMessageException(WebMessageUtils.conflict("Could not read file or file is empty."));
}
ByteSource bytes = new MultipartFileByteSource(file);
String contentMd5 = bytes.hash(Hashing.md5()).toString();
FileResource fileResource = new FileResource(filename, contentType, contentLength, contentMd5, FileResourceDomain.DATA_VALUE);
fileResource.setAssigned(false);
fileResource.setCreated(new Date());
fileResource.setUser(currentUserService.getCurrentUser());
File tmpFile = toTempFile(file);
String uid = fileResourceService.saveFileResource(fileResource, tmpFile);
if (uid == null) {
throw new WebMessageException(WebMessageUtils.error("Saving the file failed."));
}
WebMessage webMessage = new WebMessage(Status.OK, HttpStatus.ACCEPTED);
webMessage.setResponse(new FileResourceWebMessageResponse(fileResource));
return webMessage;
}
use of org.hisp.dhis.fileresource.FileResource in project dhis2-core by dhis2.
the class DefaultDocumentService method deleteFileFromDocument.
@Override
public void deleteFileFromDocument(Document document) {
FileResource fileResource = document.getFileResource();
// Remove reference to fileResource from document to avoid db constraint exception
document.setFileResource(null);
documentStore.save(document);
// Delete file
fileResourceService.deleteFileResource(fileResource.getUid());
}
Aggregations