Search in sources :

Example 1 with FileStorageException

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);
    }
}
Also used : UserSession(com.haulmont.cuba.security.global.UserSession) SecurityContext(com.haulmont.cuba.core.sys.SecurityContext) FileStorageException(com.haulmont.cuba.core.global.FileStorageException) FileDescriptor(com.haulmont.cuba.core.entity.FileDescriptor) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with FileStorageException

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();
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) FileStorageException(com.haulmont.cuba.core.global.FileStorageException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) InputStreamEntity(org.apache.http.entity.InputStreamEntity)

Example 3 with FileStorageException

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);
    }
}
Also used : HttpUtils(com.haulmont.cuba.core.app.filestorage.amazon.util.HttpUtils) HashMap(java.util.HashMap) FileStorageException(com.haulmont.cuba.core.global.FileStorageException) URL(java.net.URL)

Example 4 with FileStorageException

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;
}
Also used : Messages(com.haulmont.cuba.core.global.Messages) Configuration(com.haulmont.cuba.core.global.Configuration) FileStorageException(com.haulmont.cuba.core.global.FileStorageException) FileStorageException(com.haulmont.cuba.core.global.FileStorageException) IOException(java.io.IOException) CubaFileUpload(com.haulmont.cuba.web.toolkit.ui.CubaFileUpload) FileUploadingAPI(com.haulmont.cuba.gui.upload.FileUploadingAPI) FileOutputStream(java.io.FileOutputStream) ClientConfig(com.haulmont.cuba.client.ClientConfig) File(java.io.File)

Example 5 with FileStorageException

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());
    });
}
Also used : CubaUpload(com.haulmont.cuba.web.toolkit.ui.CubaUpload) FileStorageException(com.haulmont.cuba.core.global.FileStorageException) FileStorageException(com.haulmont.cuba.core.global.FileStorageException)

Aggregations

FileStorageException (com.haulmont.cuba.core.global.FileStorageException)23 FileDescriptor (com.haulmont.cuba.core.entity.FileDescriptor)9 IOException (java.io.IOException)5 InputStream (java.io.InputStream)5 File (java.io.File)4 HttpUtils (com.haulmont.cuba.core.app.filestorage.amazon.util.HttpUtils)3 SecurityContext (com.haulmont.cuba.core.sys.SecurityContext)3 FileUploadingAPI (com.haulmont.cuba.gui.upload.FileUploadingAPI)3 UserSession (com.haulmont.cuba.security.global.UserSession)3 URL (java.net.URL)3 HashMap (java.util.HashMap)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 ClientConfig (com.haulmont.cuba.client.ClientConfig)2 Transaction (com.haulmont.cuba.core.Transaction)2 Configuration (com.haulmont.cuba.core.global.Configuration)2 Messages (com.haulmont.cuba.core.global.Messages)2 Notifications (com.haulmont.cuba.gui.Notifications)2 CubaFileUpload (com.haulmont.cuba.web.toolkit.ui.CubaFileUpload)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 FileOutputStream (java.io.FileOutputStream)2