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

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

Introduction

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

Prototype

@Override
InputStream getInputStream() throws IOException;

Source Link

Document

Return an InputStream to read the contents of the file from.

Usage

From source file:gr.abiss.calipso.tiers.controller.AbstractModelController.java

@RequestMapping(value = "{subjectId}/uploads/{propertyName}", method = { RequestMethod.POST,
        RequestMethod.PUT }, consumes = {}, produces = { "application/json", "application/xml" })
public @ResponseBody BinaryFile addUploadsToProperty(@PathVariable ID subjectId,
        @PathVariable String propertyName, MultipartHttpServletRequest request, HttpServletResponse response) {
    LOGGER.info("uploadPost called");

    Configuration config = ConfigurationFactory.getConfiguration();
    String fileUploadDirectory = config.getString(ConfigurationFactory.FILES_DIR);
    String baseUrl = config.getString("calipso.baseurl");

    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;
    BinaryFile bf = new BinaryFile();
    try {//  www.  j  ava  2  s  . c o m
        if (itr.hasNext()) {

            mpf = request.getFile(itr.next());
            LOGGER.info("Uploading {}", mpf.getOriginalFilename());

            bf.setName(mpf.getOriginalFilename());
            bf.setFileNameExtention(
                    mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf(".") + 1));

            bf.setContentType(mpf.getContentType());
            bf.setSize(mpf.getSize());

            // request targets specific path?
            StringBuffer uploadsPath = new StringBuffer('/')
                    .append(this.service.getDomainClass().getDeclaredField("PATH_FRAGMENT").get(String.class))
                    .append('/').append(subjectId).append("/uploads/").append(propertyName);
            bf.setParentPath(uploadsPath.toString());
            LOGGER.info("Saving image entity with path: " + bf.getParentPath());
            bf = binaryFileService.create(bf);

            LOGGER.info("file name: {}", bf.getNewFilename());
            bf = binaryFileService.findById(bf.getId());
            LOGGER.info("file name: {}", bf.getNewFilename());

            File storageDirectory = new File(fileUploadDirectory + bf.getParentPath());

            if (!storageDirectory.exists()) {
                storageDirectory.mkdirs();
            }

            LOGGER.info("storageDirectory: {}", storageDirectory.getAbsolutePath());
            LOGGER.info("file name: {}", bf.getNewFilename());

            File newFile = new File(storageDirectory, bf.getNewFilename());
            newFile.createNewFile();
            LOGGER.info("newFile path: {}", newFile.getAbsolutePath());
            Files.copy(mpf.getInputStream(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

            BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290);
            File thumbnailFile = new File(storageDirectory, bf.getThumbnailFilename());
            ImageIO.write(thumbnail, "png", thumbnailFile);
            bf.setThumbnailSize(thumbnailFile.length());

            bf = binaryFileService.update(bf);

            // attach file
            // TODO: add/update to collection
            Field fileField = GenericSpecifications.getField(this.service.getDomainClass(), propertyName);
            Class clazz = fileField.getType();
            if (BinaryFile.class.isAssignableFrom(clazz)) {
                T target = this.service.findById(subjectId);
                BeanUtils.setProperty(target, propertyName, bf);
                this.service.update(target);
            }

            bf.setUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/files/" + bf.getId());
            bf.setThumbnailUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/thumbs/" + bf.getId());
            bf.setDeleteUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/" + bf.getId());
            bf.setDeleteType("DELETE");
            bf.addInitialPreview("<img src=\"" + bf.getThumbnailUrl() + "\" class=\"file-preview-image\" />");

        }

    } catch (Exception e) {
        LOGGER.error("Could not upload file(s) ", e);
    }

    return bf;
}

From source file:com.tela.pms.PatientController.java

/**
 * createPatient will create a new patient and save in the cloud db
 *//* www  .j a  v a 2s.com*/
@RequestMapping(value = "/createPatient", method = RequestMethod.POST)
public String createPatient(HttpServletRequest request, HttpServletResponse response, Model model,
        @RequestParam("file") MultipartFile file) {
    String view = "patient";

    //Creating a new patient object
    String firstName = request.getParameter("fName");
    String lastName = request.getParameter("lName");
    String age = request.getParameter("age");
    String nic = request.getParameter("nic");
    String address = request.getParameter("address");
    String gender = request.getParameter("gender");
    String contactNo = request.getParameter("contactNo");
    String email = request.getParameter("email");
    String formatedString = request.getParameter("tags");
    String tags = formatedString.toString().replace("[", "") //remove the right bracket
            .replace("]", "");
    String patientName = firstName + " " + lastName;

    //Validating Empty fields
    if (nic.equals("") || nic == null) {
        nic = "Not Available";
    }
    if (address.equals("") || address == null) {
        address = "Not Available";
    }
    if (contactNo.equals("") || contactNo == null) {
        contactNo = "Not Available";
    }
    if (email.equals("") || email == null) {
        email = "Not@Available";
    }
    if (tags.equals("") || tags == null) {
        tags = "Not Available";
    }

    //Generating an unique id
    int id = 1001;
    List<Patient> pasList = patientService.retrieveAllPatients();

    if (pasList != null) {

        if (pasList.size() > 1) {

            Collections.sort(pasList, new Comparator<Patient>() {
                @Override
                public int compare(Patient p1, Patient p2) {
                    if (p1.getPatient_Id() > p1.getPatient_Id())
                        return 1;
                    if (p1.getPatient_Id() < p2.getPatient_Id())
                        return -1;
                    return 0;
                }
            });

            id = pasList.get(pasList.size() - 1).getPatient_Id() + 1;
        } else if (pasList.size() == 1) {

            id = pasList.get(0).getPatient_Id() + 1;

        } else {

            id = 1001;
        }

    } else {

        id = 78 * new Date().getDay() * new Date().getSeconds();

    }

    //Creating DateTime
    SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd  hh:mm  a", Locale.US);
    String createdAt = DATE_FORMAT.format(new Date());

    //Retrieving uploaded files
    MultipartFile patientPhoto = file;
    //byte[] bFile_patientPhoto = null;
    String imagePath = "N/A";

    String extensionFile = FilenameUtils.getExtension(patientPhoto.getOriginalFilename());
    System.out.println(extensionFile);
    boolean value = extensionFile.equals("jpeg") || extensionFile.equals("jpg") || extensionFile.equals("JPG")
            || extensionFile.equals("JPEG");
    if (patientPhoto != null && value) {
        File cloud_file = null;
        try {
            cloud_file = convertFile(patientPhoto);
        } catch (IOException e1) {
            logger.info("something went wrong in coverting the file @" + new Date());
            e1.printStackTrace();
        }

        /*
        try {
           //bFile_patientPhoto = new byte[(int) patientPhoto.getSize()];
           //InputStream inputStream_patientPhoto = patientPhoto.getInputStream();
           //inputStream_patientPhoto.read(bFile_patientPhoto);
           //inputStream_patientPhoto.close();            
                     
        } catch (IOException e) {         
           e.printStackTrace();
        }      */
        String extension = FilenameUtils.getExtension(patientPhoto.getOriginalFilename());
        Long fileSize = patientPhoto.getSize();

        if (extension.equals("JPG") || extension.equals("jpg") || extension.equals("jpeg")
                || extension.equals("JPEG")) {
            try {
                File catalinaBase = new File(System.getProperty("catalina.base")).getAbsoluteFile();
                logger.info("catalinaBase:" + catalinaBase.getAbsolutePath());

                InputStream inputStream = patientPhoto.getInputStream();
                String imageId = "patient-" + Integer.toString(id);
                String fileName = imageId + "." + "jpg";
                File newFile = new File(catalinaBase,
                        "webapps/pms/WEB-INF/views/images/Uploaded_images/Patients/" + fileName);

                if (!newFile.exists()) {
                    newFile.createNewFile();
                }
                OutputStream outputStream = new FileOutputStream(newFile);
                int read = 0;
                byte[] bytes = new byte[1024];

                while ((read = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
                imagePath = "resources/images/Uploaded_images/Patients/" + fileName;
                logger.info("Patient image successfully uploaded to local repo @" + new Date());
            } catch (FileNotFoundException e) {
                logger.info("something went wrong when patient photo uploading @" + new Date());
                e.printStackTrace();
            } catch (IOException e) {
                logger.info("something went wrong when patient photo uploading @" + new Date());
                e.printStackTrace();
            }

        } else {
            logger.info("Uploaded file is not a jpg or png " + new Date());
            if (gender.equals("Female")) {
                imagePath = "resources/images/patient-female.png";
            } else {
                imagePath = "resources/images/patient-male.png";
            }
        }

    } else {

        if (gender.equals("Female")) {
            imagePath = "resources/images/patient-female.png";
        } else {
            imagePath = "resources/images/patient-male.png";
        }

    }

    Patient patient = new Patient();

    patient.setPatient_Id(id);
    patient.setPatient_Name(patientName);
    patient.setPatient_Age(age);
    patient.setPatient_Address(address);
    patient.setPatient_ContactNo(contactNo);
    patient.setPatient_Gender(gender);
    patient.setPatient_Email(email);
    patient.setPatient_NIC(nic);
    patient.setPatient_CreatedAt(createdAt);
    patient.setPatient_Photo(imagePath);
    patient.setPatient_tags(tags);

    //System.out.println(patientName+"  "+age+"   "+patientPhoto.getOriginalFilename()+"   "+nic+"   "+address+"   "+gender+"   "+contactNo+"   "+email);

    List<Patient> palist = patientService.retrieveAllPatients();
    if (palist.size() == 0) {
        patientService.persistPatient(patient);
        logger.info("A New Patient " + id + " created @ " + new Date());
    } else {
        if (palist != null && palist.size() > 0) {
            boolean isNewPatient = true;
            boolean isNotExistingPatient = true;
            for (Patient pati : palist) {
                if (pati.getPatient_Id() == id) {
                    isNewPatient = false;
                    logger.info("Similar patient with same id exists.  " + id);
                    view = "error1";
                }
                if (pati.getPatient_Name().equals(patientName) && pati.getPatient_Photo().equals(imagePath)
                        && pati.getPatient_Age().equals(age)) {
                    logger.info("Similar patient exists.");
                    view = "error1";
                    isNotExistingPatient = false;
                    isNewPatient = false;
                }
            }
            if (isNewPatient || isNotExistingPatient) {
                patientService.persistPatient(patient);
                logger.info("A New Patient " + id + " created @ " + new Date());
            }
        }
    }

    Patient newPatient = patientService.findPatientById(id);
    model.addAttribute("patient", newPatient);

    List<Prescription> prescriptions = prescriptionService.retrieveAllPrescriptionsByPatientId(id);
    model.addAttribute("prescriptions", prescriptions);

    logger.info("New Patient " + id + " retrieved @ " + new Date());
    logger.info("Prescription list " + prescriptions + " retrieved @ " + new Date());
    model.addAttribute("status", "<strong>Great !</strong> A New Patient created successfully");
    model.addAttribute("style", "style=\"display:block;margin-top: 5px;\"");
    return view;
}

From source file:gr.abiss.calipso.controller.AbstractServiceBasedRestController.java

@RequestMapping(value = "{subjectId}/uploads/{propertyName}", method = { RequestMethod.POST,
        RequestMethod.PUT }, consumes = {}, produces = { "application/json", "application/xml" })
public @ResponseBody BinaryFile addUploadsToProperty(@PathVariable ID subjectId,
        @PathVariable String propertyName, MultipartHttpServletRequest request, HttpServletResponse response) {
    LOGGER.info("uploadPost called");

    Configuration config = ConfigurationFactory.getConfiguration();
    String fileUploadDirectory = config.getString(ConfigurationFactory.FILES_DIR);
    String baseUrl = config.getString("calipso.baseurl");

    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;
    BinaryFile bf = new BinaryFile();
    try {/*from   w w  w .ja  va 2 s. c om*/
        if (itr.hasNext()) {

            mpf = request.getFile(itr.next());
            LOGGER.info("Uploading {}", mpf.getOriginalFilename());

            bf.setName(mpf.getOriginalFilename());
            bf.setFileNameExtention(
                    mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf(".") + 1));

            bf.setContentType(mpf.getContentType());
            bf.setSize(mpf.getSize());

            // request targets specific path?
            StringBuffer uploadsPath = new StringBuffer('/')
                    .append(this.service.getDomainClass().getDeclaredField("PATH_FRAGMENT").get(String.class))
                    .append('/').append(subjectId).append("/uploads/").append(propertyName);
            bf.setParentPath(uploadsPath.toString());
            LOGGER.info("Saving image entity with path: " + bf.getParentPath());
            bf = binaryFileService.create(bf);

            LOGGER.info("file name: {}", bf.getNewFilename());
            bf = binaryFileService.findById(bf.getId());
            LOGGER.info("file name: {}", bf.getNewFilename());

            File storageDirectory = new File(fileUploadDirectory + bf.getParentPath());

            if (!storageDirectory.exists()) {
                storageDirectory.mkdirs();
            }

            LOGGER.info("storageDirectory: {}", storageDirectory.getAbsolutePath());
            LOGGER.info("file name: {}", bf.getNewFilename());

            File newFile = new File(storageDirectory, bf.getNewFilename());
            newFile.createNewFile();
            LOGGER.info("newFile path: {}", newFile.getAbsolutePath());
            Files.copy(mpf.getInputStream(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

            BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290);
            File thumbnailFile = new File(storageDirectory, bf.getThumbnailFilename());
            ImageIO.write(thumbnail, "png", thumbnailFile);
            bf.setThumbnailSize(thumbnailFile.length());

            bf = binaryFileService.update(bf);

            // attach file
            // TODO: add/update to collection
            Field fileField = GenericSpecifications.getField(this.service.getDomainClass(), propertyName);
            Class clazz = fileField.getType();
            if (BinaryFile.class.isAssignableFrom(clazz)) {
                T target = this.service.findById(subjectId);
                BeanUtils.setProperty(target, propertyName, bf);
                this.service.update(target);
            }

            bf.setUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/files/" + bf.getId());
            bf.setThumbnailUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/thumbs/" + bf.getId());
            bf.setDeleteUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/" + bf.getId());
            bf.setDeleteType("DELETE");
            bf.addInitialPreview("<img src=\"" + bf.getThumbnailUrl() + "\" class=\"file-preview-image\" />");

        }

    } catch (Exception e) {
        LOGGER.error("Could not upload file(s) ", e);
    }

    //        Map<String, Object> files= new HashMap<String, Object>();
    //files.put("files", list);
    return bf;
}

From source file:com.devnexus.ting.web.controller.admin.PresentationController.java

@RequestMapping(value = "/s/admin/{eventKey}/presentation/{presentationId}", method = RequestMethod.POST)
public String editPresentation(@PathVariable("presentationId") Long presentationId,
        @RequestParam MultipartFile uploadedFile, @Valid Presentation presentation, BindingResult result,
        HttpServletRequest request, RedirectAttributes redirectAttributes) {

    if (request.getParameter("cancel") != null) {
        return "redirect:/s/admin/{eventKey}/presentations";
    }//from w w  w  . j av a 2s  .  c o  m

    if (result.hasErrors()) {
        return "/admin/add-presentation";
    }

    final Presentation presentationFromDb = businessService.getPresentation(presentationId);

    if (request.getParameter("delete") != null) {
        businessService.deletePresentation(presentationFromDb);

        redirectAttributes.addFlashAttribute("successMessage", String
                .format("The presentation '%s' was deleted successfully.", presentationFromDb.getTitle()));
        return "redirect:/s/admin/{eventKey}/presentations";
    }

    presentationFromDb.setAudioLink(presentation.getAudioLink());
    presentationFromDb.setDescription(presentation.getDescription());
    presentationFromDb.setPresentationLink(presentation.getPresentationLink());
    presentationFromDb.setTitle(presentation.getTitle());

    presentationFromDb.setSkillLevel(presentation.getSkillLevel());

    if (presentation.getTrack().getId() != null) {
        final Track trackFromDb = businessService.getTrack(presentation.getTrack().getId());
        presentationFromDb.setTrack(trackFromDb);
    }

    presentationFromDb.setPresentationType(presentation.getPresentationType());

    final Set<PresentationTag> presentationTagsToSave = businessService
            .processPresentationTags(presentation.getTagsAsText());
    presentationFromDb.getPresentationTags().clear();
    presentationFromDb.getPresentationTags().addAll(presentationTagsToSave);

    if (uploadedFile != null && uploadedFile.getSize() > 0) {

        final FileData presentationData;
        if (presentationFromDb.getPresentationFile() == null) {
            presentationData = new FileData();
        } else {
            presentationData = presentationFromDb.getPresentationFile();
        }

        try {

            presentationData.setFileData(IOUtils.toByteArray(uploadedFile.getInputStream()));
            presentationData.setFileSize(uploadedFile.getSize());
            presentationData.setFileModified(new Date());
            presentationData.setName(uploadedFile.getOriginalFilename());
            presentationData.setType(uploadedFile.getContentType());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        presentationFromDb.setPresentationFile(presentationData);

        String message = "File '" + presentationData.getName() + "' uploaded successfully";
        redirectAttributes.addFlashAttribute("successMessage", message);
    }

    final List<Speaker> goodSpeakers = new ArrayList<>();

    if (presentation.getSpeakers() != null) {
        for (Speaker speaker : presentation.getSpeakers()) {
            if (speaker != null && speaker.getId() != null) {
                Speaker speakerFromDb = businessService.getSpeaker(speaker.getId());
                goodSpeakers.add(speakerFromDb);
            }
        }
    }

    if (goodSpeakers.size() > 0) {
        presentationFromDb.getSpeakers().clear();
        presentationFromDb.getSpeakers().addAll(goodSpeakers);
    }

    businessService.savePresentation(presentationFromDb);

    redirectAttributes.addFlashAttribute("successMessage",
            String.format("The presentation '%s' was edited successfully.", presentationFromDb.getTitle()));

    return "redirect:/s/admin/{eventKey}/presentations";
}

From source file:cn.edu.henu.rjxy.lms.controller.TeaController.java

@RequestMapping(value = "scworkfj", method = RequestMethod.POST)
public @ResponseBody String course_submit(HttpServletRequest request, @RequestParam("file") MultipartFile file)
        throws IOException, Exception {
    String workid = request.getParameter("workid");
    String coursename = request.getParameter("courseName");
    String term = request.getParameter("term");
    String tec_name = TeacherDao.getTeacherBySn(getCurrentUsername()).getTeacherName();
    String sn = getCurrentUsername();
    String collage = TeacherDao.getTeacherBySn(getCurrentUsername()).getTeacherCollege();
    //                                      ?   ??          ??
    String ff = getFileFolder(request) + "homework/" + term + "/" + collage + "/" + sn + "/" + tec_name + "/"
            + coursename + "/" + workid + "/" + 1 + "/";
    file(ff);//??
    if (haveFile(ff) != 0) {
        return "0";
    }//from   ww w  .  ja va  2s .  c  om
    File f = new File(ff);
    //
    if (!file.isEmpty()) {
        try {
            InputStream in;
            try (FileOutputStream os = new FileOutputStream(f + "/" + file.getOriginalFilename())) {
                in = file.getInputStream();
                int b = 0;
                while ((b = in.read()) != -1) {
                    os.write(b);
                }
                os.flush();
            }
            in.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block  
            e.printStackTrace();
        }
    }

    return "1";

}

From source file:com.prcsteel.platform.account.service.impl.AccountServiceImpl.java

/**
 * ?/*ww  w .ja v  a2  s . c o  m*/
 *
 * @param file 
 * @return
 */
@Override
public String uploadFile(MultipartFile file) {
    checkFile(file);

    Calendar cal = Calendar.getInstance();
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    String basePath = Constant.FILESAVETEMPPATH + format.format(cal.getTime()) + File.separator; // 
    String tempPath = new Date().getTime() + "." + FileUtil.getFileSuffix(file.getOriginalFilename());
    String savePath = basePath + tempPath;
    String url = "";
    try {
        url = fileService.saveFile(file.getInputStream(), savePath);
        if (StringUtils.isEmpty(url)) {
            throw new BusinessException(Constant.EXCEPTIONCODE_BUSINESS, "?");
        }
    } catch (Exception ex) {
        throw new BusinessException(Constant.EXCEPTIONCODE_BUSINESS, "?" + ex.getMessage());
    }
    return url;
}

From source file:service.EventService.java

public void readXls(MultipartFile fileXls, Long[] tagIds, Long pkId, Long campaignId, Boolean update)
        throws Exception {
    Campaign campaign = campaignDao.find(campaignId);
    //List<String> uniqs = campaignDao.getUniqs(campaignId, pkId);
    if (!Objects.equals(campaign.getStatus(), Campaign.CLOSE)) {
        PersonalCabinet pk = personalCabinetDao.find(pkId);
        HashMap<String, String> commentMap = new HashMap();
        List<Client> clientsListForSave = new ArrayList();
        List<Client> clientsListForUpdate = new ArrayList();
        List<Event> eventsListForSave = new ArrayList();
        HashMap<String, Client> addedInPkClientsMap = getClientsMapInPk(pkId);
        HashMap<String, Client> addedInCampaignClientsMap = getClientsMapInCampaign(campaignId, pkId);
        //HashMap<String, Client> addingClientsMapForSave = new HashMap();
        List<Client> noContactList = new ArrayList();
        List<Integer> noUniqueIdList = new ArrayList();
        InputStream fis = fileXls.getInputStream();
        HSSFWorkbook inputWorkbook = new HSSFWorkbook(fis);
        int sheetCount = inputWorkbook.getNumberOfSheets();
        boolean nomoreclients = false;
        for (int i = 0; i < sheetCount; i++) {
            HSSFSheet hss = inputWorkbook.getSheetAt(i);
            int rowCount = 0;
            Iterator<Row> it = hss.iterator();
            while (it.hasNext()) {
                rowCount++;// w w  w.ja  va  2  s  . c om
                Row rw = it.next();
                if (!(StringAdapter.getString(rw.getCell(0))).trim()
                        .equals("? ")) {
                    String uid = StringAdapter.HSSFSellValue(rw.getCell(0));
                    String name = StringAdapter.HSSFSellValue(rw.getCell(1));
                    String secretaryPhone = HSSFPhoneValue(rw.getCell(2));
                    String comment = StringAdapter.HSSFSellValue(rw.getCell(3));
                    String contface = StringAdapter.HSSFSellValue(rw.getCell(4));
                    String lprPhone = HSSFPhoneValue(rw.getCell(5));
                    String namelpr = StringAdapter.HSSFSellValue(rw.getCell(6));
                    String adress = StringAdapter.HSSFSellValue(rw.getCell(7));
                    if (uid.equals("")
                            && (!name.equals("") || !secretaryPhone.equals("") || !lprPhone.equals(""))) {
                        noUniqueIdList.add(rowCount);
                    } else if (!uid.equals("") && !name.equals("")
                            && (!secretaryPhone.equals("") || !lprPhone.equals(""))) {
                        //  
                        if (!addedInPkClientsMap.keySet().contains(uid)) {
                            Client cl = new Client();
                            cl.setUniqueId(uid);
                            cl.setNameCompany(name);
                            cl.setNameSecretary(contface);
                            cl.setNameLpr(namelpr);
                            cl.setPhoneSecretary(secretaryPhone);
                            cl.setPhoneLpr(lprPhone);
                            cl.setAddress(adress);
                            commentMap.put(uid, comment);
                            cl.setCabinet(pk);
                            if (validate(cl)) {
                                if ((secretaryPhone != null && !secretaryPhone.equals(""))
                                        || (lprPhone != null && !lprPhone.equals(""))) {
                                    if (adminService.mayAddClient(pkId)) {
                                        clientsListForSave.add(cl);
                                    } else {
                                        nomoreclients = true;
                                    }
                                } else {
                                    noContactList.add(cl);
                                }
                            }
                        } else {
                            Client cl = addedInPkClientsMap.get(uid);
                            if (update) {
                                cl.setUniqueId(uid);
                                cl.setNameCompany(name);
                                cl.setNameSecretary(contface);
                                cl.setNameLpr(namelpr);
                                cl.setPhoneSecretary(secretaryPhone);
                                cl.setPhoneLpr(lprPhone);
                                cl.setAddress(adress);
                                commentMap.put(uid, comment);
                                cl.setCabinet(pk);
                                if (validate(cl)) {
                                    if ((secretaryPhone != null && !secretaryPhone.equals(""))
                                            || (lprPhone != null && !lprPhone.equals(""))) {
                                        clientsListForUpdate.add(cl);
                                    } else {
                                        noContactList.add(cl);
                                    }
                                }
                            }
                            // ?,    
                            if (!addedInCampaignClientsMap.keySet().contains(uid)) {
                                Event event = new Event();
                                event.setCabinet(pk);
                                event.setClient(cl);
                                event.setUniqueId(uid);
                                event.setCampaign(campaign);
                                event.setComment(StringAdapter.getString(commentMap.get(cl.getUniqueId())));
                                event.setStatus(Event.UNASSIGNED);
                                if (validate(event)) {
                                    eventsListForSave.add(event);
                                }
                            }
                        }
                    }
                }
            }
            if (nomoreclients) {
                addError(
                        "   ?    ?? ? ? ");
            }
        }
        if (noContactList.isEmpty() && noUniqueIdList.isEmpty()) {
            for (Client cl : clientsListForSave) {
                clientDao.save(cl);
                if (tagIds != null && tagIds.length > 0) {
                    tagService.addTagsToClient(cl.getId(), tagIds, pkId);
                }
                Event event = new Event();
                event.setCabinet(pk);
                event.setClient(cl);
                event.setUniqueId(cl.getUniqueId());
                event.setCampaign(campaign);
                event.setComment(StringAdapter.getString(commentMap.get(cl.getUniqueId())));
                event.setStatus(Event.UNASSIGNED);
                if (validate(event)) {
                    eventsListForSave.add(event);
                }
            }
            for (Client cl : clientsListForUpdate) {
                clientDao.update(cl);
                if (tagIds != null && tagIds.length > 0) {
                    tagService.addTagsToClient(cl.getId(), tagIds, pkId);
                }
            }
            for (Event ev : eventsListForSave) {
                eventDao.save(ev);
                addEventComment(" ", EventComment.CREATE, ev, pkId);
                addEventComment(": " + ev.getComment(), EventComment.COMMENTED, ev, pkId);
            }
        } else {
            if (!noContactList.isEmpty()) {
                String err = "?    ? : ";
                for (Client cl : noContactList) {
                    err += cl.getUniqueId() + "; ";
                }
                addError(err
                        + " ?     ?   .");
            }
            if (!noUniqueIdList.isEmpty()) {
                String err = "?     ? ?: ";
                for (Integer rc : noUniqueIdList) {
                    err += rc + "; ";
                }
                addError(err);
            }
        }

    } else {
        addError("??     .");
    }
}

From source file:com.prcsteel.platform.account.service.impl.AccountServiceImpl.java

@Override
@Transactional/*  w  w w . j  a va2  s .  c  o  m*/
public int saveContractTemplate(AccountContractTemplate act, MultipartFile thumbnailFile) {
    if (thumbnailFile != null && !thumbnailFile.isEmpty()) {
        Account account = accountDao.selectByPrimaryKey(act.getAccountId());
        String savePath = ATTACHMENTSAVEPATH + account.getCode() + File.separator + "contracttemplate"
                + File.separator + act.getType() + File.separator + act.getId() + "."
                + FileUtil.getFileSuffix(thumbnailFile.getOriginalFilename());
        // FileUtil.saveFile(thumbnailFile, basePath);
        String key = "";
        try {
            key = fileService.saveFile(thumbnailFile.getInputStream(), savePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        act.setThumbnailUrl(key);
    }
    if (act.getEnabled() == 1) {
        actDao.disableOtherByAccountIdAndType(act.getAccountId(), act.getType());
    }
    if (act.getId() == null) {
        actDao.insertSelective(act);
    } else {
        act.setStatus(ContractTemplateStatus.PENDING.getValue()); //?
        actDao.updateByPrimaryKeySelective(act);
    }

    return 0;
}

From source file:cn.edu.henu.rjxy.lms.controller.Tea_Controller.java

@RequestMapping("kcnr_submit")
public @ResponseBody String kcnr_submit(HttpServletRequest request, @RequestParam("desc") String desc,
        @RequestParam("file") MultipartFile file) throws IOException {
    String sn = getCurrentUsername();
    Teacher tec = TeacherDao.getTeacherBySn(sn);
    String tec_sn = tec.getTeacherSn();
    String tec_name = tec.getTeacherName();
    String collage = tec.getTeacherCollege();
    String term = request.getParameter("term");
    String courseName = request.getParameter("courseName");
    String node1 = request.getParameter("node1");
    String node2 = request.getParameter("node2");
    String node3 = request.getParameter("node3");
    String type = request.getParameter("type");
    System.out.println(type);//from  w ww . ja va2 s . c o  m
    System.out.println(node1 + " " + node2 + "  " + node3 + "  " + term + "  " + courseName);
    String ff = getFileFolder(request) + term + "/" + collage + "/" + tec_sn + "/" + tec_name + "/" + courseName
            + "/" + "" + "/";
    if (node2.equals("undefined") && node3.equals("undefined")) {//1
        ff = ff + node1;
    } else if (node3.equals("undefined") && (!node2.equals("undefined"))) {//2
        ff = ff + "/" + node1 + "/" + node2 + "/";
    } else if ((!node1.equals("undefined")) && (!node2.equals("undefined")) && (!node3.equals("undefined"))) {//3
        ff = ff + "/" + node1 + "/" + node2 + "/" + node3 + "/";
    }
    File f = new File(ff);
    //??
    if (!f.exists() && !f.isDirectory()) {
        System.out.println("?");
        f.mkdirs();
    }

    //?
    if (type.endsWith("")) {
        ff = ff + "/" + "" + "/";
        File fwork = new File(ff);
        if (!fwork.exists() && !fwork.isDirectory()) {
            System.out.println("?");
            fwork.mkdirs();
        }
    }
    //
    if (!file.isEmpty()) {
        try {
            InputStream in;
            try (FileOutputStream os = new FileOutputStream(f + "/" + file.getOriginalFilename())) {
                in = file.getInputStream();
                int b = 0;
                while ((b = in.read()) != -1) {
                    os.write(b);
                }
                os.flush();
            }
            in.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block  
            e.printStackTrace();
        }
    }
    //        System.out.println(" "+file.getOriginalFilename());
    //        DocConverter dc=new DocConverter(f+"/"+file.getOriginalFilename());
    //        boolean res=dc.conver();
    //        String swftmp=(f+"/"+file.getOriginalFilename()).replace(getFileFolder(request), "");
    //        swftmp=swftmp.substring(0,swftmp.lastIndexOf("."))+".swf";
    //        if (res){
    //            System.out.println("?flash??:http://localhost:8080/Web/getswf?uri="+swftmp);
    //        }
    return "1";
}

From source file:com.siblinks.ws.service.impl.UploadEssayServiceImpl.java

/**
 * {@inheritDoc}/* w w  w.  j  a v a2 s .c om*/
 */
@Override
@RequestMapping(value = "/uploadEssayStudent", method = RequestMethod.POST)
public ResponseEntity<Response> uploadEssayStudent(@RequestParam("desc") final String desc,
        @RequestParam("userId") final String userId, @RequestParam("fileName") final String fileName,
        @RequestParam("title") final String title, @RequestParam("schoolId") final String schoolId,
        @RequestParam("majorId") final String majorId, @RequestParam("file") final MultipartFile file) {
    SimpleResponse simpleResponse = null;
    String statusMessage = "";
    boolean status = true;
    try {

        if (!AuthenticationFilter.isAuthed(context)) {
            simpleResponse = new SimpleResponse(SibConstants.FAILURE, "Authentication required.");
            return new ResponseEntity<Response>(simpleResponse, HttpStatus.FORBIDDEN);
        }

        statusMessage = validateEssay(file);
        if (StringUtil.isNull(desc)) {
            statusMessage = "Essay description can't blank!";
        } else {
            if (desc.length() > 1000) {
                statusMessage = "Essay description can't over 1000 characters!";
            }
        }

        if (StringUtil.isNull(title)) {
            statusMessage = "Essay title can't blank!";
        } else {
            if (title.length() > 250) {
                statusMessage = "Essay title can't over 250 characters!";
            }
        }
        if (StringUtil.isNull(statusMessage)) {

            boolean msgs = true;
            List<Map<String, String>> allWordFilter = cachedDao.getAllWordFilter();
            String strContent = CommonUtil.filterWord(desc, allWordFilter);
            String strTitle = CommonUtil.filterWord(title, allWordFilter);
            String strFileName = CommonUtil.filterWord(fileName, allWordFilter);

            Object[] queryParams = { userId, file.getInputStream(), strContent, file.getContentType(),
                    strFileName, strTitle, file.getSize(), schoolId, majorId };
            msgs = dao.insertUpdateObject(SibConstants.SqlMapper.SQL_STUDENT_UPLOAD_ESSAY, queryParams);
            if (msgs) {
                statusMessage = "Done";
            } else {
                status = false;
                statusMessage = "You failed to upload ";
            }

        } else {
            status = false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        status = false;
        statusMessage = "You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage();
        logger.error(e.getMessage(), e.getCause());
    }

    simpleResponse = new SimpleResponse("" + status, "essay", "upload", statusMessage);
    return new ResponseEntity<Response>(simpleResponse, HttpStatus.OK);
}