Example usage for org.springframework.web.multipart.support DefaultMultipartHttpServletRequest getFile

List of usage examples for org.springframework.web.multipart.support DefaultMultipartHttpServletRequest getFile

Introduction

In this page you can find the example usage for org.springframework.web.multipart.support DefaultMultipartHttpServletRequest getFile.

Prototype

@Override
    public MultipartFile getFile(String name) 

Source Link

Usage

From source file:com.jaspersoft.jasperserver.rest.RESTUtils.java

/**
 * Extract the attachments from the request and put the in the list of
 * input attachments of the service.//from  w w  w .j  a  v a2s  .  c  o  m
 *
 * The method returns the currenst HttpServletRequest if the message is not
 * multipart, otherwise it returns a MultipartHttpServletRequest
 *
 *
 * @param service
 * @param hRequest
 */
public static HttpServletRequest extractAttachments(LegacyRunReportService service,
        HttpServletRequest hRequest) {
    //Check whether we're dealing with a multipart request
    MultipartResolver resolver = new CommonsMultipartResolver();

    // handles the PUT multipart requests
    if (isMultipartContent(hRequest) && hRequest.getContentLength() != -1) {
        MultipartHttpServletRequest mreq = resolver.resolveMultipart(hRequest);
        if (mreq != null && mreq.getFileMap().size() != 0) {
            Iterator iterator = mreq.getFileNames();
            String fieldName = null;
            while (iterator.hasNext()) {
                fieldName = (String) iterator.next();
                MultipartFile file = mreq.getFile(fieldName);
                if (file != null) {
                    DataSource ds = new MultipartFileDataSource(file);
                    service.getInputAttachments().put(fieldName, ds);
                }
            }
            if (log.isDebugEnabled()) {
                log.debug(service.getInputAttachments().size() + " attachments were extracted from the PUT");
            }
            return mreq;
        }
        // handles the POST multipart requests
        else {
            if (hRequest instanceof DefaultMultipartHttpServletRequest) {
                DefaultMultipartHttpServletRequest dmServletRequest = (DefaultMultipartHttpServletRequest) hRequest;

                Iterator iterator = ((DefaultMultipartHttpServletRequest) hRequest).getFileNames();
                String fieldName = null;
                while (iterator.hasNext()) {
                    fieldName = (String) iterator.next();
                    MultipartFile file = dmServletRequest.getFile(fieldName);
                    if (file != null) {
                        DataSource ds = new MultipartFileDataSource(file);
                        service.getInputAttachments().put(fieldName, ds);
                    }
                }
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(service.getInputAttachments().size() + " attachments were extracted from the POST");
    }
    return hRequest;

}

From source file:org.openmrs.module.iqchartimport.web.controller.UploadController.java

@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public String handleSubmit(HttpServletRequest request, ModelMap model) {
    Utils.checkSuperUser();

    DefaultMultipartHttpServletRequest multipart = (DefaultMultipartHttpServletRequest) request;
    MultipartFile uploadFile = multipart.getFile("mdbfile");

    IQChartDatabase.clearInstance();/*from ww  w . j av a 2 s  . c o  m*/

    // Process uploaded database if there is one
    if (uploadFile != null) {
        try {
            // Copy uploaded MDB to temp file
            File tempMDBFile = File.createTempFile(uploadFile.getOriginalFilename(), ".temp");
            uploadFile.transferTo(tempMDBFile);

            // Store uploaded database as singleton
            IQChartDatabase.createInstance(uploadFile.getOriginalFilename(), tempMDBFile.getAbsolutePath());

        } catch (IOException e) {
            model.put("uploaderror", "Unable to upload database file");
        }
    }

    return showForm(request, model);
}

From source file:de.uni_koeln.spinfo.maalr.services.admin.shared.AdminService.java

public void importDatabase(HttpServletRequest request) throws IOException, InvalidEntryException,
        NoDatabaseAvailableException, JAXBException, XMLStreamException {
    DefaultMultipartHttpServletRequest dmhsRequest = (DefaultMultipartHttpServletRequest) request;
    MultipartFile multipartFile = (MultipartFile) dmhsRequest.getFile("file");
    InputStream in = multipartFile.getInputStream();
    Database.getInstance().importData(in);
}

From source file:org.openmrs.module.sdmxhdintegration.web.controller.MessageUploadFormController.java

/**
 * Handles form submission//from w w  w. ja v  a 2 s  . c o m
 * @param request the request
 * @param message the message
 * @param result the binding result
 * @param status the session status
 * @return the view
 * @throws IllegalStateException
 */
@RequestMapping(method = RequestMethod.POST)
public String handleSubmission(HttpServletRequest request, @ModelAttribute("message") SDMXHDMessage message,
        BindingResult result, SessionStatus status) throws IllegalStateException {

    DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request;
    MultipartFile file = req.getFile("sdmxhdMessage");
    File destFile = null;

    if (!(file.getSize() <= 0)) {
        AdministrationService as = Context.getAdministrationService();
        String dir = as.getGlobalProperty("sdmxhdintegration.messageUploadDir");
        String filename = file.getOriginalFilename();
        filename = "_" + (new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss")).format(new Date()) + "_" + filename;
        destFile = new File(dir + File.separator + filename);
        destFile.mkdirs();

        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            HttpSession session = request.getSession();
            session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                    "Could not save file. Make sure you have setup the upload directory using the configuration page and that the directory is readable by the tomcat user.");
            return "/module/sdmxhdintegration/messageUpload";
        }

        message.setZipFilename(filename);
    }

    new SDMXHDMessageValidator().validate(message, result);

    if (result.hasErrors()) {
        log.error("SDMXHDMessage object failed validation");
        if (destFile != null) {
            destFile.delete();
        }
        return "/module/sdmxhdintegration/messageUpload";
    }

    SDMXHDService service = Context.getService(SDMXHDService.class);
    ReportDefinitionService rds = Context.getService(ReportDefinitionService.class);
    service.saveMessage(message);

    // delete all existing mappings and reports
    List<KeyFamilyMapping> allKeyFamilyMappingsForMsg = service.getKeyFamilyMappingsFromMessage(message);
    for (Iterator<KeyFamilyMapping> iterator = allKeyFamilyMappingsForMsg.iterator(); iterator.hasNext();) {
        KeyFamilyMapping kfm = iterator.next();
        Integer reportDefinitionId = kfm.getReportDefinitionId();
        service.deleteKeyFamilyMapping(kfm);
        if (reportDefinitionId != null) {
            rds.purgeDefinition(rds.getDefinition(reportDefinitionId));
        }
    }

    // create initial keyFamilyMappings
    try {
        DSD dsd = Utils.getDataSetDefinition(message);
        List<KeyFamily> keyFamilies = dsd.getKeyFamilies();
        for (Iterator<KeyFamily> iterator = keyFamilies.iterator(); iterator.hasNext();) {
            KeyFamily keyFamily = iterator.next();

            KeyFamilyMapping kfm = new KeyFamilyMapping();
            kfm.setKeyFamilyId(keyFamily.getId());
            kfm.setMessage(message);
            service.saveKeyFamilyMapping(kfm);
        }
    } catch (Exception e) {
        log.error("Error parsing SDMX-HD Message: " + e, e);
        if (destFile != null) {
            destFile.delete();
        }

        service.deleteMessage(message);
        result.rejectValue("sdmxhdZipFileName", "upload.file.rejected",
                "This file is not a valid zip file or it does not contain a valid SDMX-HD DataSetDefinition");
        return "/module/sdmxhdintegration/messageUpload";
    }

    return "redirect:messages.list";
}

From source file:net.mindengine.oculus.frontend.web.controllers.report.ReportUploadFileController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
    log.info("uploading file");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {

        DefaultMultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest) request;

        int i = 0;
        boolean bNext = true;
        while (bNext) {
            i++;/*from   w  ww.java 2s  . c o  m*/
            MultipartFile multipartFile = multipartRequest.getFile("file" + i);
            if (multipartFile != null) {
                fileId++;
                Date date = new Date();
                String path = FileUtils.generatePath(date);
                String fullDirPath = config.getDataFolder() + File.separator + path;
                File dir = new File(fullDirPath);
                dir.mkdirs();
                //FileUtils.mkdirs(config.getDataFolder() + File.separator + path);

                String fileType = FileUtils.getFileType(multipartFile.getOriginalFilename()).toLowerCase();
                path += File.separator + date.getTime() + "_" + fileId + "." + fileType;

                File file = new File(config.getDataFolder() + File.separator + path);
                file.createNewFile();

                FileOutputStream fos = new FileOutputStream(file);
                fos.write(multipartFile.getBytes());
                fos.close();

                if (fileType.equals("png") || fileType.equals("jpg") || fileType.equals("gif")
                        || fileType.equals("bmp")) {
                    pw.println("[uploaded]?type=image-" + fileType + "&object=" + date.getTime() + "&item="
                            + fileId);
                }
                if (fileType.equals("txt") || fileType.equals("json") || fileType.equals("xml")) {
                    pw.println("[uploaded]?type=text-" + fileType + "&object=" + date.getTime() + "&item="
                            + fileId);
                }
            } else
                bNext = false;
        }
    } else
        pw.print("[error]not a multipart content");
    return null;
}

From source file:org.exem.flamingo.web.filesystem.s3.S3BrowserController.java

@RequestMapping(value = "upload", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseStatus(HttpStatus.OK)/*from   ww  w.j a  v a 2s .c o  m*/
public Response uploadObject(HttpServletRequest req) throws IOException {
    DefaultMultipartHttpServletRequest request = (DefaultMultipartHttpServletRequest) req;

    String bucketName = request.getParameter(S3Constansts.BUCKETNAME);
    String key = request.getParameter(S3Constansts.KEY);
    MultipartFile file = request.getFile(S3Constansts.FILE);

    s3BrowserService.upload(bucketName, key, file);

    Response response = new Response();
    response.setSuccess(true);
    return response;
}

From source file:com.jaspersoft.jasperserver.rest.utils.Utils.java

/**
 * Extract the attachments from the request and put the in the list of
 * input attachments of the service./*from   w w w.  j a  v a 2s  . com*/
 *
 * The method returns the currenst HttpServletRequest if the message is not
 * multipart, otherwise it returns a MultipartHttpServletRequest
 *
 *
 * @param service
 * @param hRequest
 */
public HttpServletRequest extractAttachments(LegacyRunReportService service, HttpServletRequest hRequest) {
    //Check whether we're dealing with a multipart request
    MultipartResolver resolver = new CommonsMultipartResolver();

    // handles the PUT multipart requests
    if (isMultipartContent(hRequest) && hRequest.getContentLength() != -1) {
        MultipartHttpServletRequest mreq = resolver.resolveMultipart(hRequest);
        if (mreq != null && mreq.getFileMap().size() != 0) {
            Iterator iterator = mreq.getFileNames();
            String fieldName = null;
            while (iterator.hasNext()) {
                fieldName = (String) iterator.next();
                MultipartFile file = mreq.getFile(fieldName);
                if (file != null) {
                    DataSource ds = new MultipartFileDataSource(file);
                    service.getInputAttachments().put(fieldName, ds);
                }
            }
            if (log.isDebugEnabled()) {
                log.debug(service.getInputAttachments().size() + " attachments were extracted from the PUT");
            }
            return mreq;
        }
        // handles the POST multipart requests
        else {
            if (hRequest instanceof DefaultMultipartHttpServletRequest) {
                DefaultMultipartHttpServletRequest dmServletRequest = (DefaultMultipartHttpServletRequest) hRequest;

                Iterator iterator = ((DefaultMultipartHttpServletRequest) hRequest).getFileNames();
                String fieldName = null;
                while (iterator.hasNext()) {
                    fieldName = (String) iterator.next();
                    MultipartFile file = dmServletRequest.getFile(fieldName);
                    if (file != null) {
                        DataSource ds = new MultipartFileDataSource(file);
                        service.getInputAttachments().put(fieldName, ds);
                    }
                }
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(service.getInputAttachments().size() + " attachments were extracted from the POST");
    }
    return hRequest;

}

From source file:org.exem.flamingo.web.filesystem.hdfs.HdfsBrowserController.java

/**
 * ?  ?? HDFS ? ./*from  www.  ja v a  2  s  .  c  o  m*/
 *
 * @return REST Response JAXB Object
 */
@RequestMapping(value = "upload", method = RequestMethod.POST, consumes = { "multipart/form-data" })
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<String> upload(HttpServletRequest req) throws IOException {
    Response response = new Response();

    if (!(req instanceof DefaultMultipartHttpServletRequest)) {
        response.setSuccess(false);
        response.getError().setCause("Request is not a file upload.");
        response.getError().setMessage("Failed to upload a file.");
        String json = new ObjectMapper().writeValueAsString(response);
        return new ResponseEntity(json, HttpStatus.BAD_REQUEST);
    }

    InputStream inputStream;
    DefaultMultipartHttpServletRequest request = (DefaultMultipartHttpServletRequest) req;

    String username = SessionUtils.getUsername();
    String dstPath = request.getParameter("dstPath");
    MultipartFile uploadedFile = request.getFile("fileName");
    String originalFilename = uploadedFile.getOriginalFilename();
    String pathToUpload = getPathFilter(dstPath);
    String fullyQualifiedPath = pathToUpload.equals("/") ? pathToUpload + originalFilename
            : pathToUpload + SystemUtils.FILE_SEPARATOR + originalFilename;

    inputStream = uploadedFile.getInputStream();

    //TODO HDFS  ? ? 
    /*List<String> paths = hdfsBrowserAuthService.getHdfsBrowserPatternAll(username);
    String hdfsPathPattern = hdfsBrowserAuthService.validateHdfsPathPattern(pathToUpload, paths);
            
    Map fileMap = new HashMap();
    fileMap.put("username", username);
    fileMap.put("hdfsPathPattern", hdfsPathPattern);
    fileMap.put("condition", "uploadFile");
    hdfsBrowserAuthService.getHdfsBrowserUserDirAuth(fileMap);*/

    // Engine? Remote?  ?.
    boolean isRemoteEngine = Boolean.parseBoolean(isRemote);

    // Remote ? ? ?, Remote? Store and Forward 
    if (!isRemoteEngine) {

        fileSystemService.validatePath(pathToUpload);

        String namenodeAgentUrl = MessageFormatter
                .arrayFormat("http://{}:{}/remote/agent/transfer/upload?fullyQualifiedPath={}&username={}",
                        new Object[] { namenodeAgentAddress, namenodeAgentPort,
                                URLEncoder.encode(fullyQualifiedPath, "UTF-8"), username })
                .getMessage();

        HttpPost httpPost = new HttpPost(namenodeAgentUrl);
        HttpEntity reqEntity = new InputStreamEntity(inputStream);
        httpPost.setEntity(reqEntity);
        HttpResponse execute = httpClient.execute(httpPost);

        if (execute.getStatusLine().getStatusCode() == 500) {
            response.setSuccess(false);
            response.getError().setMessage("?? ?? .");
        } else if (execute.getStatusLine().getStatusCode() == 600) {
            response.setSuccess(false);
            response.getError().setMessage("(/) ?   .");
        } else {
            response.setSuccess(true);
        }

        inputStream.close();
        httpPost.releaseConnection();
    } else {
        boolean saved;
        byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
        fileSystemService.validateBeforeUpload(pathToUpload, fullyQualifiedPath, bytes, username);
        saved = fileSystemService.save(pathToUpload, fullyQualifiedPath, bytes, username);
        response.setSuccess(saved);
    }

    response.getMap().put("directory", pathToUpload);
    String json = new ObjectMapper().writeValueAsString(response);
    HttpStatus statusCode = HttpStatus.OK;

    return new ResponseEntity(json, statusCode);
}

From source file:com.ephesoft.dcma.webservice.service.EphesoftWebService.java

/**
 * Sign up method./*  w w w . ja v  a  2  s. c om*/
 * @param request {@link HttpServletRequest}
 * @param response {@link HttpServletResponse}
 */
@RequestMapping(value = "/signUp", method = RequestMethod.POST)
@ResponseBody
public void signUp(final HttpServletRequest request, final HttpServletResponse response) {
    LOGGER.info("Start processing sign up process");
    String workingDir = WebServiceUtil.EMPTY_STRING;
    InputStream instream = null;
    if (request instanceof DefaultMultipartHttpServletRequest) {
        UserInformation userInformation = null;
        User user = null;
        String receiverName = null;
        try {
            final String webServiceFolderPath = batchSchemaService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            LOGGER.info("workingDir:" + workingDir);
            final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir);
            LOGGER.info("outputDir:" + outputDir);
            final DefaultMultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest) request;
            final String batchClassId = request.getParameter("batchClassId");
            final String batchClassPriority = request.getParameter("batchClassPriority");
            final String batchClassDescription = request.getParameter("batchClassDescription");
            String batchClassName = request.getParameter("batchClassName");
            batchClassName = getUniqueBatchClassName(batchClassName);
            final String batchInstanceLimit = request.getParameter("batchInstanceLimit");
            final String noOfDays = request.getParameter("noOfDays");
            final String pageCount = request.getParameter("pageCount");
            String uncFolder = "unc" + ICommonConstants.HYPHEN + batchClassName;
            LOGGER.info("Batch Class ID value is: " + batchClassId);
            LOGGER.info("Batch Class Priority value is: " + batchClassPriority);
            LOGGER.info("Batch Class Description value is: " + batchClassDescription);
            LOGGER.info("Batch Class Name value is: " + batchClassName);
            LOGGER.info("UNC Folder value is: " + uncFolder);
            final MultiValueMap<String, MultipartFile> fileMap = multipartRequest.getMultiFileMap();
            for (final String fileName : fileMap.keySet()) {
                if (fileName.toLowerCase(Locale.getDefault())
                        .indexOf(FileType.XML.getExtension().toLowerCase()) > -WebserviceConstants.ONE) {
                    final MultipartFile multipartFile = multipartRequest.getFile(fileName);
                    instream = multipartFile.getInputStream();
                    final Source source = XMLUtil.createSourceFromStream(instream);
                    userInformation = (UserInformation) batchSchemaDao.getJAXB2Template().getJaxb2Marshaller()
                            .unmarshal(source);
                    user = createUserObjectFromUserInformation(userInformation);
                    break;
                }
            }
            if (userInformation != null && user != null) {
                LOGGER.info("Recevier name created: " + receiverName);
                userConnectivityService.addUser(userInformation);
                LOGGER.info("Successfully added user for email id: " + userInformation.getEmail());
                userConnectivityService.addGroup(userInformation);
                LOGGER.info("Successfully added group for email id: " + userInformation.getEmail());
                BatchClass batchClass = batchClassService.copyBatchClass(
                        batchClassId, batchClassName, batchClassDescription, userInformation.getCompanyName()
                                + ICommonConstants.UNDERSCORE + userInformation.getEmail(),
                        batchClassPriority, uncFolder, true);
                LOGGER.info("Adding user information into database");
                user.setBatchClass(batchClass);
                userService.createUser(user);
                LOGGER.info("Successfully added user information into database");
                BatchClassCloudConfig batchClassCloudConfig = createBatchClassCloudConfig(batchInstanceLimit,
                        noOfDays, pageCount, batchClass);
                batchClassCloudConfigService.createBatchClassCloudConfig(batchClassCloudConfig);
                LOGGER.info("Successfully copied batch class for batch class: " + batchClassId);
                deploymentService.createAndDeployBatchClassJpdl(batchClass);
                LOGGER.info("Batch Class deployed successfully");
                wizardMailService.sendConfirmationMail(userInformation, false, null);
                LOGGER.info("User login information sent for email id: " + userInformation.getEmail());
            } else {
                LOGGER.error(
                        "user Information file is invalid. Unable create the User Information Object from XML.");
            }
        } catch (WizardMailException wizardMailException) {
            try {
                response.sendError(HttpServletResponse.SC_CREATED);
            } catch (IOException e) {
                LOGGER.error(ERROR_IN_SENDING_STATUS_USING_WEB_SERVICE);
            }
        } catch (Exception e) {
            LOGGER.error("Exception occurs while sign up process: " + e.getMessage(), e);
            if (userInformation != null && user != null) {
                LOGGER.info("Deleting created user/groups while signup for : " + userInformation.getEmail());
                userConnectivityService.deleteUser(userInformation.getEmail());
                userConnectivityService.deleteGroup(userInformation.getCompanyName()
                        + ICommonConstants.UNDERSCORE + userInformation.getEmail());
                userService.deleteUser(user);
                LOGGER.info(
                        "Successfully deleted user/groups while signup for : " + userInformation.getEmail());
                LOGGER.info("Sending error mail");
                try {
                    wizardMailService.sendConfirmationMail(userInformation, true,
                            ExceptionUtils.getStackTrace(e));
                    LOGGER.info("Error mail sent succesfully");
                } catch (WizardMailException e1) {
                    LOGGER.error("Error in sending error mail to client");
                }
            }
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            } catch (IOException e1) {
                LOGGER.error(ERROR_IN_SENDING_STATUS_USING_WEB_SERVICE);
            }

        }
    }
}

From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java

@RequestMapping(value = "/runReporting", method = RequestMethod.POST)
@ResponseBody/*from  w  w w. ja v  a  2  s  .  c  o m*/
public void runReporting(final HttpServletRequest req, final HttpServletResponse resp) {
    logger.info("Start processing the run reporting web service");
    String respStr = WebServiceUtil.EMPTY_STRING;
    try {
        if (req instanceof DefaultMultipartHttpServletRequest) {

            InputStream instream = null;
            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;
            final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();
            for (final String fileName : fileMap.keySet()) {
                final MultipartFile multiPartFile = multiPartRequest.getFile(fileName);
                instream = multiPartFile.getInputStream();
                final Source source = XMLUtil.createSourceFromStream(instream);
                final ReportingOptions option = (ReportingOptions) batchSchemaDao.getJAXB2Template()
                        .getJaxb2Marshaller().unmarshal(source);
                final String installerPath = option.getInstallerPath();
                if (installerPath == null || installerPath.isEmpty()
                        || !installerPath.toLowerCase().contains("build.xml")) {
                    respStr = "Improper input to server. Installer path not specified or it does not contain the build.xml path.";
                } else {
                    logger.info("synchronizing the database");
                    reportingService.syncDatabase(installerPath);
                    break;
                }
            }

        } else {
            respStr = "Improper input to server. Expected multipart request. Returning without processing the results.";
        }
    } catch (final XmlMappingException xmle) {
        respStr = "Error in mapping input XML in the desired format. Please send it in the specified format. Detailed exception is "
                + xmle;
    } catch (final Exception e) {
        respStr = "Internal Server error.Please check logs for further details." + e;
    }

    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {

        }
    }
}