Example usage for org.springframework.web.multipart MultipartFile isEmpty

List of usage examples for org.springframework.web.multipart MultipartFile isEmpty

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Return whether the uploaded file is empty, that is, either no file has been chosen in the multipart form or the chosen file has no content.

Usage

From source file:org.shareok.data.webserv.JournalDataController.java

@RequestMapping(value = "/dspace/safpackage/{publisher}/upload", method = RequestMethod.POST)
public ModelAndView safPackageDataUpload(RedirectAttributes redirectAttrs,
        @RequestParam("file") MultipartFile file, @PathVariable("publisher") String publisher) {

    if (!file.isEmpty()) {
        try {/*from w  ww. j  ava  2s .  c om*/
            String[] filePaths = DspaceJournalServiceManager.getDspaceSafPackageDataService(publisher)
                    .getSafPackagePaths(file);
            if (null != filePaths && filePaths.length > 0) {

                ModelAndView model = new ModelAndView();
                RedirectView view = new RedirectView();
                view.setContextRelative(true);

                List<String> downloadLinks = new ArrayList<>();
                for (String path : filePaths) {
                    String link = DspaceJournalDataUtil.getDspaceSafPackageDataDownloadLinks(path);
                    downloadLinks.add(link);
                }
                ObjectMapper mapper = new ObjectMapper();
                String downloadLink = mapper.writeValueAsString(downloadLinks);
                //                    String uploadFileLink = downloadLink.split("/journal/"+publisher+"/")[1];
                //                    uploadFileLink = uploadFileLink.substring(0, uploadFileLink.length()-1);

                model.setViewName("journalDataUploadDisplay");
                model.addObject("safPackages", downloadLink);
                model.addObject("publisher", publisher);
                //                    model.addObject("uploadFile", uploadFileLink);
                view.setUrl("/dspace/safpackage/ouhistory/display");
                model.setView(view);

                return model;
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    } else {
        return null;
    }
    return null;
}

From source file:com.baifendian.swordfish.webserver.service.ResourceService.java

/**
 * ?:<br>//from   ww  w . java  2s  . co m
 * 1) ?, ???, ????<br>
 * 2) ? hdfs , ???(??)<p>
 *
 * @param operator
 * @param projectName
 * @param name
 * @param desc
 * @param file
 * @return
 */
@Transactional(value = "TransactionManager")
public Resource createResource(User operator, String projectName, String name, String desc,
        MultipartFile file) {

    verifyResName(name);
    verifyDesc(desc);

    // 
    if (file.isEmpty()) {
        logger.error("File is empty: {}", file.getOriginalFilename());
        throw new ParameterException("file");
    }

    Project project = projectMapper.queryByName(projectName);
    if (project == null) {
        logger.error("Project does not exist: {}", projectName);
        throw new NotFoundException("Not found project \"{0}\"", projectName);
    }

    // ??
    if (!projectService.hasWritePerm(operator.getId(), project)) {
        logger.error("User {} has no right permission for the project {}", operator.getName(),
                project.getName());
        throw new PermissionException("User \"{0}\" is not has project \"{1}\" write permission",
                operator.getName(), project.getName());
    }

    // ??
    Resource resource = resourceMapper.queryResource(project.getId(), name);

    if (resource != null) {
        logger.error("Resource {} does not empty", name);
        throw new ServerErrorException("Resource has exist, can't create again.");
    }

    // ??
    resource = new Resource();
    Date now = new Date();

    resource.setName(name);

    resource.setOriginFilename(file.getOriginalFilename());
    resource.setDesc(desc);
    resource.setOwnerId(operator.getId());
    resource.setOwner(operator.getName());
    resource.setProjectId(project.getId());
    resource.setProjectName(projectName);
    resource.setCreateTime(now);
    resource.setModifyTime(now);

    try {
        resourceMapper.insert(resource);
    } catch (DuplicateKeyException e) {
        logger.error("Resource has exist, can't create again.", e);
        throw new ServerErrorException("Resource has exist, can't create again.");
    }

    // 
    if (!upload(project, name, file)) {
        logger.error("upload resource: {} file: {} failed.", name, file.getOriginalFilename());
        throw new ServerErrorException("upload resource: {} file: {} failed.", name, fileSystemStorageService);
    }

    return resource;
}

From source file:com.nts.alphamaleWeb.controller.ServiceController.java

@RequestMapping(value = "/installApp", method = RequestMethod.POST)
@ResponseBody// w w  w.  jav  a2  s .c om
public String installApp(@RequestParam String devJson, @RequestPart("file_apk") MultipartFile mpf) {

    ResultBody<String> result = new ResultBody<String>();
    List<String> devices = getDeivceListFromString(devJson);
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String path = mpf.getOriginalFilename();
    try {
        if (mpf.isEmpty()) {
            result.setCode(Code.F400);
        } else {
            File file = new File(path);
            mpf.transferTo(new File(file.getAbsolutePath()));
            String results = alphamaleController.installApp(devices, true, file.getAbsolutePath());
            String resultJson = gson.toJson(results);
            result.setCode(Code.OK, resultJson);
        }
    } catch (IOException e) {
        e.printStackTrace();
        result.setCode(Code.F400);
    }

    return result.toJson();
}

From source file:mx.edu.um.mateo.inventario.web.ProductoController.java

@RequestMapping(value = "/actualiza", method = RequestMethod.POST)
public String actualiza(HttpServletRequest request, @Valid Producto producto, BindingResult bindingResult,
        Errors errors, Model modelo, RedirectAttributes redirectAttributes,
        @RequestParam(value = "imagen", required = false) MultipartFile archivo) {
    if (bindingResult.hasErrors()) {
        log.error("Hubo algun error en la forma, regresando");
        return "inventario/producto/edita";
    }//from  w  w w .  j a  v  a 2  s. c  o  m

    try {
        if (archivo != null && !archivo.isEmpty()) {
            log.debug("SUBIENDO ARCHIVO: {}", archivo.getOriginalFilename());
            Imagen imagen = new Imagen(archivo.getOriginalFilename(), archivo.getContentType(),
                    archivo.getSize(), archivo.getBytes());
            producto.getImagenes().add(imagen);
        }
        Usuario usuario = ambiente.obtieneUsuario();
        producto = productoDao.actualiza(producto, usuario);
    } catch (IOException e) {
        log.error("No se pudo actualizar el producto", e);
        errors.rejectValue("imagenes", "problema.con.imagen.message",
                new String[] { archivo.getOriginalFilename() }, null);

        Map<String, Object> params = new HashMap<>();
        params.put("almacen", request.getSession().getAttribute("almacenId"));
        params.put("reporte", true);
        params = tipoProductoDao.lista(params);
        modelo.addAttribute("tiposDeProducto", params.get("tiposDeProducto"));

        return "inventario/producto/edita";
    } catch (ConstraintViolationException e) {
        log.error("No se pudo actualizar el producto", e);
        errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null);

        Map<String, Object> params = new HashMap<>();
        params.put("almacen", request.getSession().getAttribute("almacenId"));
        params.put("reporte", true);
        params = tipoProductoDao.lista(params);
        modelo.addAttribute("tiposDeProducto", params.get("tiposDeProducto"));

        return "inventario/producto/edita";
    }

    redirectAttributes.addFlashAttribute("message", "producto.actualizado.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { producto.getNombre() });

    return "redirect:/inventario/producto/ver/" + producto.getId();
}

From source file:controllers.ProcessController.java

@RequestMapping("management/staffs/add")
public ModelAndView staffs(@RequestParam("name") String name, @RequestParam("gender") String genderString,
        @RequestParam("birthday") String birthdayString, @RequestParam("avatar") MultipartFile avatar,
        @RequestParam("email") String email, @RequestParam("phone") String phone,
        @RequestParam("salary") String salaryString, @RequestParam("notes") String notes,
        @RequestParam("depart") String departId) throws IOException {
    String avatarFileName = "default-avatar.png";
    if (!avatar.isEmpty()) {
        String avatarPath = context.getRealPath("/resources/images/" + avatar.getOriginalFilename());
        avatar.transferTo(new File(avatarPath));
        avatarFileName = new File(avatarPath).getName();
    }//from   ww  w. j  av  a  2  s . co  m
    StaffsDAO staffsDAO = new StaffsDAO();
    staffsDAO.addStaff(name, genderString, birthdayString, avatarFileName, email, phone, salaryString, notes,
            departId);
    return new ModelAndView("redirect:../staffs.htm");
}

From source file:org.iti.agrimarket.administration.view.AddCategoryController.java

/**
 * Amr upload image and form data/*from w  w  w. j a v a 2  s . com*/
 *
 */
@RequestMapping(method = RequestMethod.POST, value = "/admin/addcategory")
public String addCategory(@RequestParam("nameAr") String nameAr, @RequestParam("nameEn") String nameEn,
        @RequestParam("parentCategoryId") int parentCategoryId, @RequestParam("file") MultipartFile file) {

    System.out.println("save user func ---------");
    System.out.println("full Name :" + nameAr);

    Category category = new Category();
    category.setNameAr(nameAr);
    category.setNameEn(nameEn);
    Category parentCategory = categoryService.getCategory(parentCategoryId);

    category.setCategory(parentCategory);

    category.setSoundUrl("/to be continue");
    int res = categoryService.addCategory(category);

    if (!file.isEmpty()) {
        String fileName = category.getId() + String.valueOf(new Date().getTime());

        try {

            System.out.println("fileName   :" + fileName);
            byte[] bytes = file.getBytes();
            MagicMatch match = Magic.getMagicMatch(bytes);
            final String ext = "." + match.getExtension();

            File parentDir = new File(Constants.IMAGE_PATH + Constants.CATEGORY_PATH);
            if (!parentDir.isDirectory()) {
                parentDir.mkdirs();
            }

            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File(Constants.IMAGE_PATH + Constants.CATEGORY_PATH + fileName)));
            stream.write(bytes);

            stream.close();
            category.setImageUrl(Constants.IMAGE_PRE_URL + Constants.CATEGORY_PATH + fileName + ext);
            categoryService.updateCategory(category);
        } catch (Exception e) {
            //                  logger.error(e.getMessage());
            categoryService.deleteCategory(category.getId()); // delete the category if something goes wrong
            return "redirect:/admin/categories_page.htm";
        }

    } else {

        category.setImageUrl(Constants.IMAGE_PRE_URL + Constants.CATEGORY_PATH + "default_category.jpg");
        categoryService.updateCategory(category);

    }

    return "redirect:/admin/categories_page.htm";
}

From source file:org.iti.agrimarket.administration.view.AddProductController.java

/**
 * Amr upload image and form data/*from  w  ww  .ja  v a2 s .c o m*/
 *
 */
@RequestMapping(method = RequestMethod.POST, value = "/admin/addproduct")
public String addproduct(@RequestParam("nameAr") String nameAr, @RequestParam("nameEn") String nameEn,
        @RequestParam("parentCategoryId") int parentCategoryId, @RequestParam("file") MultipartFile file) {

    System.out.println("save user func ---------");
    System.out.println("full Name :" + nameAr);

    Product product = new Product();
    product.setNameAr(nameAr);

    product.setNameEn(nameEn);
    Category parentCategory = categoryService.getCategory(parentCategoryId);

    product.setCategory(parentCategory);

    product.setSoundUrl("/to be continue");

    int res = productService.addProduct(product);

    if (!file.isEmpty()) {
        String fileName = product.getId() + String.valueOf(new Date().getTime());

        try {

            System.out.println("fileName   :" + fileName);
            byte[] bytes = file.getBytes();
            MagicMatch match = Magic.getMagicMatch(bytes);
            final String ext = "." + match.getExtension();

            File parentDir = new File(Constants.IMAGE_PATH + Constants.PRODUCT_PATH);
            if (!parentDir.isDirectory()) {
                parentDir.mkdirs();
            }

            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File(Constants.IMAGE_PATH + Constants.PRODUCT_PATH + fileName)));
            stream.write(bytes);

            stream.close();
            product.setImageUrl(Constants.IMAGE_PRE_URL + Constants.PRODUCT_PATH + fileName + ext);
            productService.updateProduct(product);
        } catch (Exception e) {
            //                  logger.error(e.getMessage());
            productService.deleteProduct(product.getId()); // delete the category if something goes wrong
            return "redirect:/admin/products_page.htm";
        }

    } else {

        product.setImageUrl(Constants.IMAGE_PRE_URL + Constants.PRODUCT_PATH + "default_category.jpg");
        productService.updateProduct(product);

    }

    return "redirect:/admin/products_page.htm";
}

From source file:net.shopxx.plugin.abcPayment.AbcPaymentController.java

@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(String paymentName, String merchantId, MultipartFile keyFile, String keyPassword,
        PaymentPlugin.FeeType feeType, BigDecimal fee, String logo, String description,
        @RequestParam(defaultValue = "false") Boolean isEnabled, Integer order,
        RedirectAttributes redirectAttributes) {
    PluginConfig pluginConfig = abcPaymentPlugin.getPluginConfig();
    Map<String, String> attributes = new HashMap<String, String>();
    attributes.put(PaymentPlugin.PAYMENT_NAME_ATTRIBUTE_NAME, paymentName);
    attributes.put("merchantId", merchantId);
    if (keyFile != null && !keyFile.isEmpty()) {
        InputStream inputStream = null;
        try {/*from   w ww.  j a  va 2s .c om*/
            inputStream = keyFile.getInputStream();
            PrivateKey privateKey = (PrivateKey) RSAUtils.getKey("PKCS12", inputStream, keyPassword);
            attributes.put("key", RSAUtils.getKeyString(privateKey));
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (RuntimeException e) {
            addFlashMessage(redirectAttributes, Message.warn("admin.plugin.abcPayment.keyInvalid"));
            return "redirect:setting.jhtml";
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    } else {
        attributes.put("key", pluginConfig.getAttribute("key"));
    }
    attributes.put(PaymentPlugin.FEE_TYPE_ATTRIBUTE_NAME, feeType.toString());
    attributes.put(PaymentPlugin.FEE_ATTRIBUTE_NAME, fee.toString());
    attributes.put(PaymentPlugin.LOGO_ATTRIBUTE_NAME, logo);
    attributes.put(PaymentPlugin.DESCRIPTION_ATTRIBUTE_NAME, description);
    pluginConfig.setAttributes(attributes);
    pluginConfig.setIsEnabled(isEnabled);
    pluginConfig.setOrder(order);
    pluginConfigService.update(pluginConfig);
    addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
    return "redirect:/admin/payment_plugin/list.jhtml";
}

From source file:org.fenixedu.qubdocs.ui.documenttemplates.AcademicServiceRequestTemplateController.java

@Atomic
public void updateAcademicServiceRequestTemplate(org.fenixedu.commons.i18n.LocalizedString name,
        org.fenixedu.commons.i18n.LocalizedString description, java.lang.Boolean active,
        MultipartFile documentTemplateFile, Model model) throws IOException {

    getAcademicServiceRequestTemplate(model).setName(name);
    getAcademicServiceRequestTemplate(model).setDescription(description);
    getAcademicServiceRequestTemplate(model).setActive(active);

    if (!documentTemplateFile.isEmpty()) {
        DocumentTemplateFile oldFile = getAcademicServiceRequestTemplate(model).getDocumentTemplateFile();
        oldFile.delete();/*w  w w .  j ava  2 s. c  o  m*/

        DocumentTemplateFile.create(getAcademicServiceRequestTemplate(model),
                documentTemplateFile.getOriginalFilename(), documentTemplateFile.getBytes());
    }
}