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:com.portfolio.springsecurity.service.ProjectServiceImpl.java

public void addNewProject(Project project, String[] fieldNames, User_1 user, MultipartFile[] projectImages) {
    Collection<Field> fields = new HashSet<Field>();
    for (String fieldName : fieldNames) {
        fields.add(fieldDao.findFieldByName(fieldName));
    }//from ww w .j  a  v a2s  . c  o m
    project.setFieldCollection(fields);

    User_1 userFromDao = userDao.findById(user.getId());
    project.setUSERid(userFromDao);

    List<Image> imageList = new ArrayList<Image>();

    MultipartFile coverImage = projectImages[0];

    for (int i = 1; i < projectImages.length; i++) {

        if (!projectImages[i].isEmpty()) {

            try {
                String filepath = context.getRealPath("/static/");
                System.out.println(filepath);
                FileOutputStream fos;

                String[] multipartParts = projectImages[i].getOriginalFilename().split("\\.");
                String extension = multipartParts[multipartParts.length - 1];
                if (extension.equals("png") || extension.equals("jpg") || extension.equals("jpeg")) {

                    imageList.add(new Image());

                    String imageName = generateUniqueFileName() + "." + extension;
                    String filename = filepath + "\\" + imageName;
                    fos = new FileOutputStream(filename);
                    fos.write(projectImages[i].getBytes());
                    fos.close();

                    imageList.get(imageList.size() - 1).setPROJECTid(project);
                    imageList.get(imageList.size() - 1).setSrc(imageName);

                } else {
                    System.out.println("nije dobra extenzija");
                }

            } catch (FileNotFoundException ex) {
                Logger.getLogger(ProjectServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(ProjectServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }
    project.setImageCollection(imageList);

    if (!coverImage.isEmpty()) {
        try {

            String filepath = context.getRealPath("/static/");
            System.out.println(filepath);
            FileOutputStream fos;
            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            String[] multipartParts = coverImage.getOriginalFilename().split("\\.");
            String extension = multipartParts[multipartParts.length - 1];
            if (extension.equals("png") || extension.equals("jpg") || extension.equals("jpeg")) {

                String imageName = generateUniqueFileName() + "." + extension;
                String filename = filepath + "\\" + imageName;
                fos = new FileOutputStream(filename);
                fos.write(coverImage.getBytes());
                fos.close();

                project.setCoverImage(imageName);

            } else {
                System.out.println("nije dobra extenzija");
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(ProjectServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ProjectServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    projectDao.addNewProject(project);
}

From source file:org.dataone.proto.trove.mn.rest.v1.ObjectController.java

/**
 * update the object requested//ww w . j av  a 2 s . com
 *
 * @param request
 * @param response
 * @param pid
 * @throws InvalidToken
 * @throws ServiceFailure
 * @throws IOException
 * @throws NotAuthorized
 * @throws NotFound
 * @throws NotImplemented
 */
@RequestMapping(value = "/v1/object/{pid}", method = RequestMethod.PUT)
public void update(MultipartHttpServletRequest fileRequest, HttpServletResponse response,
        @PathVariable String pid)
        throws InvalidToken, ServiceFailure, IOException, NotAuthorized, NotFound, NotImplemented,
        InvalidRequest, InsufficientResources, InvalidSystemMetadata, IdentifierNotUnique, UnsupportedType {

    debugRequest(fileRequest);
    Identifier id = new Identifier();
    try {
        id.setValue(urlCodec.decode(pid, "UTF-8"));
    } catch (DecoderException ex) {
        throw new ServiceFailure("20000", ex.getMessage());
    } catch (UnsupportedEncodingException ex) {
        throw new ServiceFailure("20001", ex.getMessage());
    }
    if (!this.logRequest(fileRequest, Event.UPDATE, id)) {

        throw new ServiceFailure("20001", "unable to log request");
    }
    Session session = new Session();
    InputStream objectInputStream = null;
    MultipartFile sytemMetaDataMultipart = null;
    MultipartFile objectMultipart = null;

    SystemMetadata systemMetadata = null;
    Set<String> keys = fileRequest.getFileMap().keySet();
    for (String key : keys) {
        if (key.equalsIgnoreCase("sysmeta")) {
            sytemMetaDataMultipart = fileRequest.getFileMap().get(key);
        } else {
            objectMultipart = fileRequest.getFileMap().get(key);
        }
    }
    if (sytemMetaDataMultipart != null) {
        try {

            systemMetadata = (SystemMetadata) TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class,
                    sytemMetaDataMultipart.getInputStream());
        } catch (IOException ex) {
            throw new InvalidSystemMetadata("15001", ex.getMessage());
        } catch (JiBXException ex) {
            throw new InvalidSystemMetadata("15002", ex.getMessage());
        } catch (InstantiationException ex) {
            throw new InvalidSystemMetadata("15003", ex.getMessage());
        } catch (IllegalAccessException ex) {
            throw new InvalidSystemMetadata("15004", ex.getMessage());
        }
    } else {
        throw new InvalidSystemMetadata("15005",
                "System Metadata was not found as Part of Multipart Mime message");
    }
    if (objectMultipart != null && !(objectMultipart.isEmpty())) {
        try {
            objectInputStream = objectMultipart.getInputStream();
        } catch (IOException ex) {
            throw new InvalidRequest("15006", ex.getMessage());
        }
    } else {
        throw new InvalidRequest("15007", "Object to be created is not attached");
    }

    id.setValue(systemMetadata.getIdentifier().getValue());

    DateTime dt = new DateTime();
    systemMetadata.setDateSysMetadataModified(dt.toDate());

    mnStorage.update(id, null, id, null);
    InputStream in = mnRead.get(id);
    OutputStream out = response.getOutputStream();
    try {

        byte[] buffer = null;
        int filesize = in.available();
        if (filesize < 250000) {
            buffer = new byte[SMALL_BUFF_SIZE];
        } else if (filesize >= 250000 && filesize <= 500000) {
            buffer = new byte[MED_BUFF_SIZE];
        } else {
            buffer = new byte[LARGE_BUFF_SIZE];
        }
        while (true) {
            int amountRead = in.read(buffer);
            if (amountRead == -1) {
                break;
            }
            out.write(buffer, 0, amountRead);
            out.flush();
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.flush();
            out.close();
        }

    }
}

From source file:mx.edu.um.mateo.activos.web.ActivoController.java

@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, HttpServletResponse response, @Valid Activo activo,
        BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes,
        @RequestParam(value = "imagen", required = false) MultipartFile archivo) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }//from  w w  w . ja  v a2 s. c  om
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");

        Long empresaId = (Long) request.getSession().getAttribute("empresaId");

        List<String> motivos = new ArrayList<>();
        motivos.add("COMPRA");
        motivos.add("DONACION");
        modelo.addAttribute("motivos", motivos);

        Map<String, Object> params = new HashMap<>();
        params.put("empresa", empresaId);
        params.put("reporte", true);
        params = tipoActivoDao.lista(params);
        modelo.addAttribute("tiposDeActivo", params.get("tiposDeActivo"));

        List<CentroCosto> centrosDeCosto = centroCostoDao.listaPorEmpresa(ambiente.obtieneUsuario());
        modelo.addAttribute("centrosDeCosto", centrosDeCosto);

        return "activoFijo/activo/nuevo";
    }

    try {
        Usuario usuario = ambiente.obtieneUsuario();
        if (archivo != null && !archivo.isEmpty()) {
            Imagen imagen = new Imagen(archivo.getOriginalFilename(), archivo.getContentType(),
                    archivo.getSize(), archivo.getBytes());
            activo.getImagenes().add(imagen);
        }
        log.debug("TipoActivo: {}", activo.getTipoActivo().getId());
        activo = activoDao.crea(activo, usuario);
    } catch (ConstraintViolationException | IOException e) {
        log.error("No se pudo crear al activo", e);
        errors.rejectValue("codigo", "campo.duplicado.message", new String[] { "codigo" }, null);

        Long empresaId = (Long) request.getSession().getAttribute("empresaId");

        List<String> motivos = new ArrayList<>();
        motivos.add("COMPRA");
        motivos.add("DONACION");
        modelo.addAttribute("motivos", motivos);

        Map<String, Object> params = new HashMap<>();
        params.put("empresa", empresaId);
        params.put("reporte", true);
        params = tipoActivoDao.lista(params);
        modelo.addAttribute("tiposDeActivo", params.get("tiposDeActivo"));

        List<CentroCosto> centrosDeCosto = centroCostoDao.listaPorEmpresa(ambiente.obtieneUsuario());
        modelo.addAttribute("centrosDeCosto", centrosDeCosto);

        return "activoFijo/activo/nuevo";
    }

    redirectAttributes.addFlashAttribute("message", "activo.creado.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { activo.getFolio() });

    return "redirect:/activoFijo/activo/ver/" + activo.getId();
}

From source file:com.orchestra.portale.controller.EditDeepeningPageController.java

@RequestMapping(value = "/updatedpage", method = RequestMethod.POST)
public ModelAndView updatePoi(HttpServletRequest request, @RequestParam Map<String, String> params,
        @RequestParam(value = "file", required = false) MultipartFile[] files,
        @RequestParam(value = "cover", required = false) MultipartFile cover,
        @RequestParam(value = "fileprec", required = false) String[] fileprec,
        @RequestParam(value = "imgdel", required = false) String[] imgdel) throws InterruptedException {

    DeepeningPage poi = pm.findDeepeningPage(params.get("id"));
    CoverImgComponent coverimg = new CoverImgComponent();
    ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>();
    for (AbstractPoiComponent comp : poi.getComponents()) {

        //associazione delle componenti al model tramite lo slug
        String slug = comp.slug();
        int index = slug.lastIndexOf(".");
        String cname = slug.substring(index + 1).replace("Component", "").toLowerCase();
        if (cname.equals("coverimg")) {
            coverimg = (CoverImgComponent) comp;
        }//w w w.j a  v a 2  s. c o  m
    }
    ModelAndView model = new ModelAndView("okpageadmin");
    model.addObject("mess", "PAGINA MODIFICATA CORRETTAMENTE!");

    poi.setId(params.get("id"));

    ModelAndView model2 = new ModelAndView("errorViewPoi");

    poi.setName(params.get("name"));

    int i = 1;
    ArrayList<String> categories = new ArrayList<String>();
    while (params.containsKey("category" + i)) {

        categories.add(params.get("category" + i));

        model.addObject("nome", categories.get(i - 1));
        i = i + 1;
    }
    poi.setCategories(categories);

    //componente cover
    if (!cover.isEmpty()) {

        coverimg.setLink("cover.jpg");

    }
    listComponent.add(coverimg);
    //componente galleria immagini
    ImgGalleryComponent img_gallery = new ImgGalleryComponent();
    ArrayList<ImgGallery> links = new ArrayList<ImgGallery>();
    i = 0;

    if (files != null && files.length > 0) {
        while (i < files.length) {
            ImgGallery img = new ImgGallery();
            Thread.sleep(100);
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyhmmssSSa");
            String currentTimestamp = sdf.format(date);
            img.setLink("img_" + currentTimestamp + ".jpg");
            if (params.containsKey("newcredit" + (i + 1)))
                img.setCredit(params.get("newcredit" + (i + 1)));
            i = i + 1;
            links.add(img);
        }
    }
    int iximg = 0;
    if (fileprec != null && fileprec.length > 0) {
        while (iximg < fileprec.length) {
            ImgGallery img = new ImgGallery();
            img.setLink(fileprec[iximg]);
            if (params.containsKey("credit" + (iximg + 1)))
                img.setCredit(params.get("credit" + (iximg + 1)));
            iximg = iximg + 1;
            links.add(img);
        }
    }
    if ((fileprec != null && fileprec.length > 0) || (files != null && files.length > 0)) {
        img_gallery.setLinks(links);
        listComponent.add(img_gallery);
    }
    //DESCRIPTION COMPONENT
    i = 1;
    if (params.containsKey("par" + i)) {

        ArrayList<Section> list = new ArrayList<Section>();

        while (params.containsKey("par" + i)) {
            Section section = new Section();
            if (params.containsKey("titolo" + i)) {
                section.setTitle(params.get("titolo" + i));
            }
            section.setDescription(params.get("par" + i));
            list.add(section);
            i = i + 1;

        }
        DescriptionComponent description_component = new DescriptionComponent();
        description_component.setSectionsList(list);
        listComponent.add(description_component);
    }
    poi.setComponents(listComponent);

    pm.saveDeepeningPage(poi);

    DeepeningPage poi2 = pm.findDeepeningPageByName(poi.getName());

    for (int z = 0; z < files.length; z++) {
        MultipartFile file = files[z];

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "dpage" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + links.get(z).getLink());
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
            System.out.println("FILE CREATO IN POSIZIONE:" + serverFile.getAbsolutePath().toString());

        } catch (Exception e) {
            e.printStackTrace();
            return model;
        }
    }
    if (!cover.isEmpty()) {
        MultipartFile file = cover;

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "dpage" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists())
                dir.mkdirs();

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + "cover.jpg");
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

        } catch (Exception e) {
            return model;
        }
    }

    // DELETE IMMAGINI DA CANCELLARE

    if (imgdel != null && imgdel.length > 0) {
        for (int kdel = 0; kdel < imgdel.length; kdel++) {
            delimg(request, poi.getId(), imgdel[kdel]);
        }
    }

    return model;
}

From source file:org.dataone.proto.trove.mn.rest.v1.ObjectController.java

/**
 *
 *//* w ww .  j av  a 2  s  .  c  om*/
@RequestMapping(value = "/v1/object/{pid}", method = RequestMethod.POST)
public ModelAndView create(MultipartHttpServletRequest fileRequest, HttpServletResponse response)
        throws InvalidSystemMetadata, InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique,
        UnsupportedType, InsufficientResources, NotImplemented, InvalidRequest {

    Session session = new Session();
    Identifier identifier = new Identifier();
    MultipartFile sytemMetaDataMultipart = null;
    MultipartFile objectMultipart = null;
    SystemMetadata systemMetadata = null;
    Set<String> keys = fileRequest.getFileMap().keySet();
    for (String key : keys) {
        if (key.equalsIgnoreCase("sysmeta")) {
            sytemMetaDataMultipart = fileRequest.getFileMap().get(key);
        } else {
            objectMultipart = fileRequest.getFileMap().get(key);
        }
    }
    if (sytemMetaDataMultipart != null) {
        try {

            systemMetadata = (SystemMetadata) TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class,
                    sytemMetaDataMultipart.getInputStream());
        } catch (IOException ex) {
            throw new InvalidSystemMetadata("15001", ex.getMessage());
        } catch (JiBXException ex) {
            throw new InvalidSystemMetadata("15002", ex.getMessage());
        } catch (InstantiationException ex) {
            throw new InvalidSystemMetadata("15003", ex.getMessage());
        } catch (IllegalAccessException ex) {
            throw new InvalidSystemMetadata("15004", ex.getMessage());
        }
    } else {
        throw new InvalidSystemMetadata("15005",
                "System Metadata was not found as Part of Multipart Mime message");
    }
    identifier.setValue(systemMetadata.getIdentifier().getValue());
    InputStream objectInputStream = null;
    if (objectMultipart != null && !(objectMultipart.isEmpty())) {
        try {
            objectInputStream = objectMultipart.getInputStream();
        } catch (IOException ex) {
            throw new InvalidRequest("15006", ex.getMessage());
        }
    } else {
        throw new InvalidRequest("15007", "Object to be created is not attached");
    }
    DateTime dt = new DateTime();
    systemMetadata.setDateUploaded(dt.toDate());
    systemMetadata.setDateSysMetadataModified(dt.toDate());
    if (!this.logRequest(fileRequest, Event.CREATE, identifier)) {

        throw new ServiceFailure("20001", "unable to log request");
    }
    identifier = mnStorage.create(session, identifier, objectInputStream, systemMetadata);

    return new ModelAndView("xmlIdentifierViewResolver", "org.dataone.service.types.v1.Identifier", identifier);
}

From source file:org.opentravel.pubs.controllers.AdminController.java

@RequestMapping({ "/DoUpdateSpecification.html", "/DoUpdateSpecification.htm" })
public String doUpdateSpecificationPage(HttpSession session, Model model, RedirectAttributes redirectAttrs,
        @ModelAttribute("specificationForm") SpecificationForm specificationForm,
        @RequestParam(value = "archiveFile", required = false) MultipartFile archiveFile) {
    String targetPage = "updateSpecification";
    try {/*from   w  ww. ja va  2  s .  co m*/
        if (specificationForm.isProcessForm()) {
            PublicationDAO pDao = DAOFactoryManager.getFactory().newPublicationDAO();
            Publication publication = pDao.getPublication(specificationForm.getPublicationId());
            PublicationType publicationType = resolvePublicationType(specificationForm.getSpecType());
            PublicationState publicationState = (specificationForm.getPubState() == null) ? null
                    : PublicationState.valueOf(specificationForm.getPubState());

            publication.setName(StringUtils.trimString(specificationForm.getName()));
            publication.setType(publicationType);
            publication.setState(publicationState);

            try {
                ValidationResults vResults = ModelValidator.validate(publication);

                // Before we try to update the contents of the spefication, validate the
                // publication object to see if there are any errors.
                if (vResults.hasViolations()) {
                    throw new ValidationException(vResults);
                }

                if (!archiveFile.isEmpty()) {
                    pDao.updateSpecification(publication, archiveFile.getInputStream());
                }
                model.asMap().clear();
                redirectAttrs.addAttribute("publication", publication.getName());
                redirectAttrs.addAttribute("specType", publication.getType());
                targetPage = "redirect:/admin/ViewSpecification.html";

            } catch (ValidationException e) {
                addValidationErrors(e, model);

            } catch (Throwable t) {
                log.error("An error occurred while updating the spec: ", t);
                setErrorMessage(t.getMessage(), model);
            }
        }

    } catch (Throwable t) {
        log.error("Error during publication controller processing.", t);
        setErrorMessage(DEFAULT_ERROR_MESSAGE, model);
    }
    return applyCommonValues(model, targetPage);
}

From source file:com.newline.view.common.controller.RegistController.java

/**
 * //from  www  .  ja va2s. c  o  m
 * ????
 * 
 * @param request
 * @param company
 * @return
 * @see 
 * @author  2015-11-2?11:30:46
 * @since 1.0
 */
@RequestMapping("saveCompanyBaseInfo")
public String saveCompanyBaseInfo(HttpServletRequest request, NlCompanyEntity company,
        @RequestParam(value = "cm_license", required = false) MultipartFile file) {
    NlCompanyEntity sourceCompany = null;
    if (company.getId() != null) {
        sourceCompany = companyService.getComapnyById(company.getId());
    } else {
        sourceCompany = new NlCompanyEntity();
        Date now = new Date();
        sourceCompany.setUpdatetime(now);
        sourceCompany.setCreatedtime(now);
    }
    if (StringUtils.isNotBlank(company.getName())) {
        sourceCompany.setName(company.getName());
    }
    if (StringUtils.isNotBlank(company.getRealname())) {
        sourceCompany.setRealname(company.getRealname());
    }
    if (StringUtils.isNotBlank(company.getYyname())) {
        sourceCompany.setYyname(company.getYyname());
    }
    if (StringUtils.isNotBlank(company.getTelephone())) {
        sourceCompany.setTelephone(company.getTelephone());
    }
    if (StringUtils.isNotBlank(company.getProvince())) {
        sourceCompany.setProvince(company.getProvince());
    }
    if (StringUtils.isNotBlank(company.getPcity())) {
        sourceCompany.setPcity(company.getPcity());
    }
    if (StringUtils.isNotBlank(company.getArea())) {
        sourceCompany.setArea(company.getArea());
    }
    if (StringUtils.isNotBlank(company.getAddress())) {
        sourceCompany.setAddress(company.getAddress());
    }
    if (StringUtils.isNotBlank(company.getSize())) {
        sourceCompany.setSize(company.getSize());
    }
    if (company.getIndustryid() != null) {
        sourceCompany.setIndustryid(company.getIndustryid());
    }
    sourceCompany.setIsauth(2);
    if (!file.isEmpty()) {
        try {
            String newfileName = QiNiuUtils.uploadImg(file);
            if (StringUtils.isNotBlank(newfileName)) {
                if (StringUtils.isNotBlank(sourceCompany.getLicense())) {
                    QiNiuUtils.delete(sourceCompany.getLicense().trim());
                }
                sourceCompany.setLicense(newfileName);
            } else {
                log.error("??!");
            }
        } catch (Exception e) {
            log.error("??!" + e.getMessage());
            e.printStackTrace();
        }
    }
    companyService.updateCompany(sourceCompany);
    return "company/check";
}

From source file:service.OrderService.java

/**
 *  //from  w ww  .  j  a va  2  s. c om
 *
 * @param order
 * @param file
 * @throws IOException
 */
public void addFile(Order order, MultipartFile file) throws IOException {
    if (file != null && !file.isEmpty()) {
        OrderFile orderFile = new OrderFile();
        orderFile.setOrder(order);
        orderFile.setRusname(file.getOriginalFilename());
        orderFileDao.save(orderFile);
        fileStorage.saveFile(orderFile.getId(), file);
    }
}

From source file:service.OrderService.java

/**
 *    //from  ww  w .j a  v  a2  s  .com
 *
 * @param order 
 * @param file 
 * @throws IOException
 */
public void addReadyFile(Order order, MultipartFile file) throws IOException {
    if (file != null && !file.isEmpty()) {
        ReadyOrderFile orderFile = new ReadyOrderFile();
        orderFile.setOrder(order);
        orderFile.setRusname(file.getOriginalFilename());
        readyOrderFileDao.save(orderFile);
        fileStorage.saveFile(orderFile.getId(), file);
    }
}

From source file:service.OrderService.java

/**
 *  /*from  w  w w. j a  v  a  2  s  .com*/
 *
 * @param order
 * @param file
 * @param res
 * @return
 * @throws IOException
 */
public Long addOrder(Order order, MultipartFile[] files, ServiceResult res) throws IOException {
    order.setStatus(OrderStatus.NEW);
    order.setOrderDate(new Date());
    setDeadlineDateToNewOrder(order);
    Long orderId = validateSave(order, orderDao, res);
    if (!res.hasErrors() && orderId != null) {
        if (files != null) {
            for (MultipartFile file : files) {
                if (file != null && !file.isEmpty()) {
                    OrderFile orderFile = new OrderFile();
                    orderFile.setOrder(order);
                    orderFile.setRusname(file.getOriginalFilename());
                    saveFile(orderFile, file);
                    order.addFile(orderFile);
                }
            }
        }
        noticeRecorder.saveNoticesAddOrder(order);
    }
    return orderId;
}