use of com.haulmont.cuba.core.global.FileStorageException in project cuba by cuba-platform.
the class FileUploadController method upload.
@RequestMapping(value = "/api/upload", method = RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
UserSession userSession = getSession(request, response);
if (userSession == null)
return;
AppContext.setSecurityContext(new SecurityContext(userSession));
try {
InputStream is = request.getInputStream();
if (is == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
FileDescriptor fd = getFileDescriptor(request, response);
if (fd == null)
return;
try {
uploadToMiddleware(userSession, is, fd);
saveFileDescriptor(fd);
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter writer = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8));
writer.write(fd.getId().toString());
writer.close();
} catch (FileStorageException e) {
log.error("Unable to upload file", e);
response.sendError(e.getType().getHttpStatus());
} finally {
IOUtils.closeQuietly(is);
}
} finally {
AppContext.setSecurityContext(null);
}
}
use of com.haulmont.cuba.core.global.FileStorageException in project cuba by cuba-platform.
the class FileUploadController method uploadToMiddleware.
protected void uploadToMiddleware(UserSession userSession, InputStream is, FileDescriptor fd) throws FileStorageException, InterruptedIOException {
Object context = serverSelector.initContext();
String selectedUrl = serverSelector.getUrl(context);
if (selectedUrl == null) {
throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName());
}
while (true) {
String url = selectedUrl + CORE_FILE_UPLOAD_CONTEXT + "?s=" + userSession.getId() + "&f=" + fd.toUrlParam();
HttpPost method = new HttpPost(url);
InputStreamEntity entity = new InputStreamEntity(is, -1);
method.setEntity(entity);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse coreResponse = client.execute(method);
int statusCode = coreResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
break;
} else {
log.debug("Unable to upload file to " + url + "\n" + coreResponse.getStatusLine());
selectedUrl = failAndGetNextUrl(context);
if (selectedUrl == null)
throw new FileStorageException(FileStorageException.Type.fromHttpStatus(statusCode), fd.getName());
}
} catch (InterruptedIOException e) {
log.trace("Uploading has been interrupted");
throw e;
} catch (IOException e) {
log.debug("Unable to upload file to " + url + "\n" + e);
selectedUrl = failAndGetNextUrl(context);
if (selectedUrl == null)
throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName(), e);
} finally {
client.getConnectionManager().shutdown();
}
}
}
use of com.haulmont.cuba.core.global.FileStorageException in project cuba by cuba-platform.
the class AmazonS3FileStorage method removeFile.
@Override
public void removeFile(FileDescriptor fileDescr) throws FileStorageException {
URL amazonUrl = getAmazonUrl(fileDescr);
// for a simple DELETE, we have no body so supply the precomputed 'empty' hash
Map<String, String> headers = new HashMap<>();
headers.put("x-amz-content-sha256", AWS4SignerBase.EMPTY_BODY_SHA256);
String authorization = createAuthorizationHeader(amazonUrl, "DELETE", headers);
headers.put("Authorization", authorization);
HttpUtils.HttpResponse httpResponse = HttpUtils.invokeHttpRequest(amazonUrl, "DELETE", headers, null);
if (!httpResponse.isStatusOk()) {
String message = String.format("Could not remove file %s. %s", getFileName(fileDescr), getInputStreamContent(httpResponse));
throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, message);
}
}
use of com.haulmont.cuba.core.global.FileStorageException in project cuba by cuba-platform.
the class WebFileMultiUploadField method initComponent.
protected void initComponent() {
CubaFileUpload impl = createComponent();
impl.setMultiSelect(true);
Messages messages = AppBeans.get(Messages.NAME);
impl.setProgressWindowCaption(messages.getMainMessage("upload.uploadingProgressTitle"));
impl.setUnableToUploadFileMessage(messages.getMainMessage("upload.unableToUploadFile"));
impl.setCancelButtonCaption(messages.getMainMessage("upload.cancel"));
impl.setCaption(messages.getMainMessage("upload.submit"));
impl.setDropZonePrompt(messages.getMainMessage("upload.dropZonePrompt"));
impl.setDescription(null);
Configuration configuration = AppBeans.get(Configuration.NAME);
final int maxUploadSizeMb = configuration.getConfig(ClientConfig.class).getMaxUploadSizeMb();
final int maxSizeBytes = maxUploadSizeMb * BYTES_IN_MEGABYTE;
impl.setFileSizeLimit(maxSizeBytes);
impl.setReceiver((fileName, MIMEType) -> {
FileOutputStream outputStream;
try {
FileUploadingAPI.FileInfo fileInfo = fileUploading.createFile();
tempFileId = fileInfo.getId();
File tmpFile = fileInfo.getFile();
outputStream = new FileOutputStream(tmpFile);
} catch (Exception e) {
throw new RuntimeException("Unable to receive file", e);
}
return outputStream;
});
impl.addStartedListener(event -> fireFileUploadStart(event.getFileName(), event.getContentLength()));
impl.addQueueUploadFinishedListener(event -> fireQueueUploadComplete());
impl.addSucceededListener(event -> {
files.put(tempFileId, event.getFileName());
fireFileUploadFinish(event.getFileName(), event.getContentLength());
});
impl.addFailedListener(event -> {
try {
// close and remove temp file
fileUploading.deleteFile(tempFileId);
tempFileId = null;
} catch (Exception e) {
if (e instanceof FileStorageException) {
FileStorageException fse = (FileStorageException) e;
if (fse.getType() != FileStorageException.Type.FILE_NOT_FOUND) {
LoggerFactory.getLogger(WebFileMultiUploadField.class).warn("Could not remove temp file {} after broken uploading", tempFileId);
}
}
LoggerFactory.getLogger(WebFileMultiUploadField.class).warn("Error while delete temp file {}", tempFileId);
}
fireFileUploadError(event.getFileName(), event.getContentLength(), event.getReason());
});
impl.addFileSizeLimitExceededListener(e -> {
String warningMsg = messages.formatMessage(WebFileMultiUploadField.class, "multiupload.filesizeLimitExceed", e.getFileName(), getFileSizeLimitString());
getFrame().showNotification(warningMsg, Frame.NotificationType.WARNING);
});
impl.addFileExtensionNotAllowedListener(e -> {
String warningMsg = messages.formatMainMessage("upload.fileIncorrectExtension.message", e.getFileName());
getFrame().showNotification(warningMsg, Frame.NotificationType.WARNING);
});
component = impl;
}
use of com.haulmont.cuba.core.global.FileStorageException in project cuba by cuba-platform.
the class WebFileUploadField method initOldUploadButton.
protected void initOldUploadButton() {
uploadButton = createOldComponent();
final CubaUpload impl = (CubaUpload) uploadButton;
impl.setButtonCaption(messages.getMainMessage("upload.submit"));
impl.setDescription(null);
impl.setReceiver((fileName1, MIMEType) -> {
FileOutputStream outputStream;
try {
tempFileId = fileUploading.createEmptyFile();
File tmpFile = fileUploading.getFile(tempFileId);
// noinspection ConstantConditions
outputStream = new FileOutputStream(tmpFile);
} catch (Exception e) {
throw new RuntimeException("Unable to receive file", e);
}
return outputStream;
});
// Set single click upload functional
impl.setImmediate(true);
impl.addStartedListener(event -> {
if (event.getContentLength() > getActualFileSizeLimit()) {
impl.interruptUpload();
String warningMsg = messages.formatMainMessage("upload.fileTooBig.message", event.getFilename(), getFileSizeLimitString());
getFrame().showNotification(warningMsg, NotificationType.WARNING);
} else if (hasInvalidExtensionOld(event.getFilename())) {
impl.interruptUpload();
String warningMsg = messages.formatMainMessage("upload.fileIncorrectExtension.message", event.getFilename());
getFrame().showNotification(warningMsg, NotificationType.WARNING);
} else {
fireFileUploadStart(event.getFilename(), event.getContentLength());
}
});
impl.addFinishedListener(event -> fireFileUploadFinish(event.getFilename(), event.getLength()));
impl.addSucceededListener(event -> {
fileName = event.getFilename();
fileId = tempFileId;
saveFile(getFileDescriptor());
component.setFileNameButtonCaption(fileName);
fireFileUploadSucceed(event.getFilename(), event.getLength());
});
impl.addFailedListener(event -> {
try {
fileUploading.deleteFile(tempFileId);
tempFileId = null;
} catch (Exception e) {
if (e instanceof FileStorageException) {
FileStorageException fse = (FileStorageException) e;
if (fse.getType() != FileStorageException.Type.FILE_NOT_FOUND)
log.warn(String.format("Could not remove temp file %s after broken uploading", tempFileId));
}
log.warn(String.format("Error while delete temp file %s", tempFileId));
}
fireFileUploadError(event.getFilename(), event.getLength(), event.getReason());
});
}
Aggregations