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

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

Introduction

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

Prototype

default void transferTo(Path dest) throws IOException, IllegalStateException 

Source Link

Document

Transfer the received file to the given destination file.

Usage

From source file:org.jahia.modules.modulemanager.flow.ModuleManagementFlowHandler.java

public boolean uploadModule(MultipartFile moduleFile, MessageContext context, boolean forceUpdate,
        boolean autoStart) {
    if (moduleFile == null) {
        context.addMessage(new MessageBuilder().error().source("moduleFile")
                .code("serverSettings.manageModules.install.moduleFileRequired").build());
        return false;
    }//ww  w  . j  a  va2  s .  c o m
    String originalFilename = moduleFile.getOriginalFilename();
    if (!FilenameUtils.isExtension(StringUtils.lowerCase(originalFilename), "jar")) {
        context.addMessage(new MessageBuilder().error().source("moduleFile")
                .code("serverSettings.manageModules.install.wrongFormat").build());
        return false;
    }
    File file = null;
    try {
        file = File.createTempFile("module-", "." + StringUtils.substringAfterLast(originalFilename, "."));
        moduleFile.transferTo(file);
        installBundles(file, context, originalFilename, forceUpdate, autoStart);
        return true;
    } catch (Exception e) {
        context.addMessage(new MessageBuilder().source("moduleFile")
                .code("serverSettings.manageModules.install.failed").arg(e.getMessage()).error().build());
        logger.error(e.getMessage(), e);
    } finally {
        FileUtils.deleteQuietly(file);
    }
    return false;
}

From source file:org.opencron.server.controller.HomeController.java

@RequestMapping("/headpic/upload")
public void upload(@RequestParam(value = "file", required = false) MultipartFile file, Long userId, Map data,
        HttpServletRequest request, HttpSession httpSession, HttpServletResponse response) throws Exception {

    String extensionName = null;/* w w w  .  j  a  v a2 s  .  c  om*/
    if (file != null) {
        extensionName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        extensionName = extensionName.replaceAll("\\?\\d+$", "");
    }

    String successFormat = "{\"result\":\"%s\",\"state\":200}";
    String errorFormat = "{\"message\":\"%s\",\"state\":500}";

    Cropper cropper = JSON.parseObject((String) data.get("data"), Cropper.class);

    //?
    if (!".BMP,.JPG,.JPEG,.PNG,.GIF".contains(extensionName.toUpperCase())) {
        WebUtils.writeJson(response,
                String.format(errorFormat, "?,(bmp,jpg,jpeg,png,gif)?"));
        return;
    }

    User user = userService.getUserById(userId);

    if (user == null) {
        WebUtils.writeJson(response, String.format(errorFormat, "??"));
        return;
    }

    String path = httpSession.getServletContext().getRealPath("/") + "upload" + File.separator;

    String picName = user.getUserId() + extensionName.toLowerCase();

    File picFile = new File(path, picName);
    if (!picFile.exists()) {
        picFile.mkdirs();
    }

    try {
        file.transferTo(picFile);
        //?
        Image image = ImageIO.read(picFile);
        if (image == null) {
            WebUtils.writeJson(response, String.format(errorFormat, "?,"));
            picFile.delete();
            return;
        }

        //?
        if (picFile.length() / 1024 / 1024 > 5) {
            WebUtils.writeJson(response,
                    String.format(errorFormat, ",??5M"));
            picFile.delete();
            return;
        }

        //?
        ImageUtils.instance(picFile).rotate(cropper.getRotate())
                .clip(cropper.getX(), cropper.getY(), cropper.getWidth(), cropper.getHeight()).build();

        //?.....
        userService.uploadimg(picFile, userId);
        userService.updateUser(user);

        String contextPath = WebUtils.getWebUrlPath(request);
        String imgPath = contextPath + "/upload/" + picName + "?" + System.currentTimeMillis();
        user.setHeaderPath(imgPath);
        user.setHeaderpic(null);
        httpSession.setAttribute(OpencronTools.LOGIN_USER, user);

        WebUtils.writeJson(response, String.format(successFormat, imgPath));
        logger.info(" upload file successful @ " + picName);
    } catch (Exception e) {
        e.printStackTrace();
        logger.info("upload exception:" + e.getMessage());
    }
}

From source file:com.inkubator.hrm.service.impl.BioDataServiceImpl.java

@Override
@Transactional(readOnly = false, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void updatePhoto(String nik, MultipartFile multipart) throws Exception {
    EmpData empData = empDataDao.getEntityByNik(nik);
    BioData bioData = empData.getBioData();

    //delete old photo (if any)
    if (bioData.getPathFoto() != null) {
        File oldFile = new File(bioData.getPathFoto());
        FileUtils.deleteQuietly(oldFile);
    }//from   www. j av  a2 s.  com

    //save new photo to disk
    String pathPhoto = facesIO.getPathUpload() + bioData.getId() + "_" + multipart.getOriginalFilename();

    File file = new File(pathPhoto);
    multipart.transferTo(file);

    //save new path photo
    bioData.setPathFoto(pathPhoto);
    bioDataDao.update(bioData);

}

From source file:com.wavemaker.tools.ws.WebServiceToolsManager.java

/**
 * Imports the specified uploaded file from the request.
 * /*from w w  w  . ja  v  a  2  s . c om*/
 * @param file The uploaded file.
 * @param serviceId The service ID for this WSDL. If this is null, a generated one will be set in the WSDL.
 * @param overwrite true to overwrite the service with the same service ID; false to simply return the string
 *        "$already_exists".
 * @return The service ID, or the string "$already_exists$" if the service ID already exists and overwrite is false.
 * @throws IOException
 * @throws WSDLException
 * @throws JAXBException
 */
public String importUploadedFile(MultipartFile file, String serviceId, String overwrite, String username,
        String password) throws IOException, WSDLException, JAXBException {
    java.io.File tempDir = IOUtils.createTempDirectory();
    String fileName = file.getOriginalFilename();
    boolean isWSDL = true;
    if (fileName != null && fileName.length() > 0) {
        java.io.File f = new java.io.File(fileName);
        fileName = f.getName();
        // assuming all WADL files have file extension .wadl
        if (fileName.toLowerCase().endsWith(".wadl")) {
            isWSDL = false;
        }
    } else {
        // this should never been called since the uploaded file should
        // always has a file name associate with it.
        fileName = "temp.wsdl";
    }
    try {
        java.io.File wsdlFile = new java.io.File(tempDir, fileName);
        file.transferTo(wsdlFile);
        modifyServiceName(wsdlFile);
        if (isWSDL) {
            return importWSDL(wsdlFile.getCanonicalPath(), serviceId, Boolean.valueOf(overwrite), username,
                    password, null, null, null, null);
        } else {
            return importWADL(wsdlFile.getCanonicalPath(), serviceId, Boolean.valueOf(overwrite));
        }
    } catch (Exception ex) {
        throw new WSDLException(ex);
    } finally {
        IOUtils.deleteRecursive(tempDir);
    }
}

From source file:com.inkubator.hrm.service.impl.BioDataServiceImpl.java

@Override
@Transactional(readOnly = false, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void updateSignature(String nik, MultipartFile signatureFile) throws Exception {
    EmpData empData = empDataDao.getEntityByNik(nik);
    BioData bioData = empData.getBioData();

    //delete old signature (if any)
    if (bioData.getPathSignature() != null) {
        File oldFile = new File(bioData.getPathSignature());
        FileUtils.deleteQuietly(oldFile);
    }//from  w  w  w  .  j  a  v a  2  s  .com

    //save new signature to disk
    String pathSignature = facesIO.getPathUpload() + bioData.getId() + "_"
            + signatureFile.getOriginalFilename();
    File file = new File(pathSignature);
    signatureFile.transferTo(file);

    //save new path signature
    bioData.setPathSignature(pathSignature);
    bioDataDao.update(bioData);

}

From source file:com.inkubator.hrm.service.impl.BioDataServiceImpl.java

@Override
@Transactional(readOnly = false, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void updateFingerPrint(String nik, MultipartFile fingerPrintFile) throws Exception {
    EmpData empData = empDataDao.getEntityByNik(nik);
    BioData bioData = empData.getBioData();

    //delete old fingerPrint (if any)
    if (bioData.getPathFinger() != null) {
        File oldFile = new File(bioData.getPathFinger());
        FileUtils.deleteQuietly(oldFile);
    }//  w  ww . j av  a  2  s .com

    //save new fingerPrint to disk
    String pathFingerPrint = facesIO.getPathUpload() + bioData.getId() + "_"
            + fingerPrintFile.getOriginalFilename();
    File file = new File(pathFingerPrint);
    fingerPrintFile.transferTo(file);

    //save new path fingerPrint
    bioData.setPathFinger(pathFingerPrint);
    bioDataDao.update(bioData);

}

From source file:service.AdService.java

public void create(Boolean isAutherized, Long catId, String email, String phone, String price,
        MultipartFile previews[], String name, String desc, Long booleanIds[], String booleanVals[],
        Long stringIds[], String stringVals[], Long numIds[], String snumVals[], Long dateIds[],
        Date dateVals[], Long selIds[], Long selVals[], Long multyIds[], String multyVals[], Date dateFrom,
        Date dateTo, Long localIds[]) throws IOException {
    Boolean newUser = false;/*  w  w w  .ja v a 2 s  . c om*/
    if (catId != null) {
        Category cat = catDao.find(catId);
        if (cat != null) {
            if (isAutherized || (!isAutherized && email != null && !email.equals(""))) {

                PhoneEditor phe = new PhoneEditor();
                phone = phe.getPhone(phone);
                addError(phe.error);

                if ((phone == null || phone.equals("")) && (email == null || email.equals(""))) {
                    addError(
                            "  email    ? ");
                }

                User user = userService.getUserByMail(email);
                if (!isAutherized && user == null) {
                    user = userService.registerStandardUser(email);
                    newUser = true;
                    List<String> userErrors = userService.getErrors();
                    if (!userErrors.isEmpty()) {
                        for (String er : userErrors) {
                            addError("user_service: " + er + "; ");
                        }
                    }
                }
                Ad ad = new Ad();
                ad.setInsertDate(new Date());
                ad.setShowCount((long) 0);
                ad.setStatus(Ad.NEW);
                ad.setDateFrom(dateFrom);
                ad.setDateTo(dateTo);
                ad.setEmail(email);
                ad.setPhone(phone);

                ad.setAuthor(user);

                ad.setCat(cat);

                Set<Locality> locals = new HashSet();
                /*if (region != null) {
                 if (region.isAllRussia()) {
                 locals.addAll(locDao.getAll());
                 } else {
                 locals.addAll(region.getLocalities());
                 }
                 }*/
                if (localIds != null && localIds.length > 0) {
                    locals.addAll(locDao.getLocs(localIds));
                } else {
                    addError("  ?   ");
                }
                ad.setLocalities(locals);
                ad.setName(name);
                ad.setDescription(desc);
                ad.setPrice(getNumFromString(price, true));
                ad.setValues(new HashSet());
                if (validate(ad) && getErrors().isEmpty()) {
                    adDao.save(ad);

                    List<Long> reqParamIds = catDao.getRequiredParamsIds(catId);
                    List<Parametr> catParams = paramDao.getParamsFromCat(catId);
                    int i = 0;
                    ArrayList<String> paramValsErrs = new ArrayList();
                    // ? ??  ? ?  ? ??,  ?, ? ?  
                    //? ad

                    ArrayList<ParametrValue> list4Save = new ArrayList();

                    //      
                    if (booleanIds != null) {
                        if (booleanVals == null) {
                            booleanVals = new String[booleanIds.length];
                        }
                        while (i < booleanIds.length) {
                            Parametr p = paramDao.find(booleanIds[i]);
                            if (catParams.contains(p) && Parametr.BOOL == p.getParamType()) {
                                Long val = ParametrValue.NO;
                                String sval = "";
                                if (booleanVals[i] != null) {
                                    val = ParametrValue.YES;
                                    sval = "";
                                }
                                ParametrValue pv = new ParametrValue();
                                pv.setAd(ad);
                                pv.setParametr(p);
                                pv.setSelectVal(val);
                                pv.setStringVal(sval);
                                if (validate(pv)) {
                                    list4Save.add(pv);
                                }

                            }
                            i++;
                        }
                    }

                    if (stringVals != null && stringVals.length > 0) {
                        i = 0;
                        while (i < stringIds.length) {
                            Long paramId = stringIds[i];
                            Parametr p = paramDao.find(paramId);
                            if (catParams.contains(p) && Parametr.TEXT == p.getParamType()) {
                                String val = stringVals[i];
                                if (val != null && !val.equals("")) {
                                    if (reqParamIds.contains(paramId)) {
                                        reqParamIds.remove(paramId);
                                    }

                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setStringVal(val);
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }

                                }
                            }
                            i++;
                        }
                    }

                    if (snumVals != null && snumVals.length > 0) {
                        i = 0;
                        while (i < numIds.length) {
                            Long paramId = numIds[i];
                            Parametr p = paramDao.find(paramId);
                            if (catParams.contains(p) && Parametr.NUM == p.getParamType()) {
                                String sval = snumVals[i];
                                if (sval != null && !sval.equals("")) {
                                    Double val = getNumFromString(sval, true);
                                    if (reqParamIds.contains(paramId)) {
                                        reqParamIds.remove(paramId);
                                    }
                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setNumVal(val);
                                    pv.setStringVal(StringAdapter.getString(val));
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }

                                }
                            }
                            i++;
                        }
                        if (!getErrors().isEmpty()) {
                            for (String e : getErrors()) {
                                paramValsErrs.add(e);
                            }
                        }
                    }

                    if (dateVals != null && dateVals.length > 0) {
                        i = 0;
                        while (i < dateIds.length) {
                            Long paramId = dateIds[i];
                            Parametr p = paramDao.find(paramId);
                            if (catParams.contains(p) && Parametr.DATE == p.getParamType()) {
                                Date val = dateVals[i];
                                if (val != null) {
                                    if (reqParamIds.contains(paramId)) {
                                        reqParamIds.remove(paramId);
                                    }
                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setDateVal(val);
                                    pv.setStringVal(DateAdapter.formatByDate(val, DateAdapter.SMALL_FORMAT));
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }

                                }
                            }
                            i++;
                        }
                    }

                    if (selVals != null && selVals.length > 0) {
                        i = 0;

                        while (i < selIds.length) {
                            Long paramId = selIds[i];
                            Parametr p = paramDao.find(paramId);
                            if (catParams.contains(p) && Parametr.SELECTING == p.getParamType()) {
                                Long val = selVals[i];
                                if (val != null && !val.equals(0L)) {
                                    if (reqParamIds.contains(paramId)) {
                                        reqParamIds.remove(paramId);
                                    }
                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setSelectVal(val);
                                    pv.setStringVal(paramSelDao.find(val).getName());
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }

                                }
                            }
                            i++;
                        }
                    }

                    //?  ?
                    //TO DO       (??)
                    if (multyVals != null && multyVals.length > 0) {
                        for (String rawVal : multyVals) {
                            String idValArr[] = rawVal.split("_");
                            if (idValArr.length == 2) {
                                String strId = idValArr[0];
                                String strVal = idValArr[1];
                                Long paramId = Long.valueOf(strId);
                                Long val = Long.valueOf(strVal);
                                Parametr p = paramDao.find(paramId);
                                if (catParams.contains(p) && Parametr.MULTISELECTING == p.getParamType()) {
                                    if (reqParamIds.contains(paramId) && val != null) {
                                        reqParamIds.remove(paramId);
                                    }
                                    ParametrValue pv = new ParametrValue();
                                    pv.setAd(ad);
                                    pv.setParametr(p);
                                    pv.setSelectVal(val);
                                    pv.setStringVal(paramSelDao.find(val).getName());
                                    if (validate(pv)) {
                                        list4Save.add(pv);
                                    }
                                }
                            }
                        }
                    }

                    //?  ?    ?    ?
                    if (!reqParamIds.isEmpty() || !paramValsErrs.isEmpty()) {
                        for (Long id : reqParamIds) {
                            addError("    "
                                    + paramDao.find(id).getName() + "; ");
                        }
                        //?
                        adDao.delete(ad);
                    } else {

                        for (ParametrValue pv : list4Save) {
                            paramValueDao.save(pv);
                        }

                        File file = new File("/usr/local/seller/preview/" + ad.getId() + "/");
                        if (file.exists()) {
                            for (File f : file.listFiles()) {
                                f.delete();
                            }
                            file.delete();
                        }
                        file.mkdirs();
                        if (previews != null && previews.length > 0) {
                            i = 0;
                            while (i < 10 && i < previews.length) {
                                MultipartFile prev = previews[i];
                                if (prev != null && 0L < prev.getSize()) {
                                    if (prev.getSize() <= (long) 3 * 1024 * 1024) {
                                        File f = new File(
                                                "/usr/local/seller/preview/" + ad.getId() + "/supPreview");
                                        if (f.exists()) {
                                            f.delete();
                                        }
                                        prev.transferTo(f);
                                        //to do  ? - ??
                                        try {
                                            BufferedImage bi = ImageIO.read(f);
                                            BigDecimal x = BigDecimal.valueOf(0);
                                            BigDecimal y = BigDecimal.valueOf(0);
                                            BigDecimal h = BigDecimal.valueOf(bi.getHeight());
                                            BigDecimal w = BigDecimal.valueOf(bi.getWidth());
                                            if (h.compareTo(w) > 0) {
                                                y = (h.subtract(w)).divide(BigDecimal.valueOf(2),
                                                        RoundingMode.HALF_UP);
                                                h = w;
                                            } else if (h.compareTo(w) < 0) {
                                                x = (w.subtract(h)).divide(BigDecimal.valueOf(2),
                                                        RoundingMode.HALF_UP);
                                                w = h;
                                            }
                                            bi = bi.getSubimage(x.intValue(), y.intValue(), w.intValue(),
                                                    h.intValue());
                                            f.delete();
                                            f = new File("/usr/local/seller/preview/" + ad.getId() + "/" + i);
                                            ImageIO.write(bi, "png", f);
                                        } catch (Exception e) {
                                            addError(
                                                    "? ?   "
                                                            + prev.getName()
                                                            + /*"; s="+prev.getSize()+"; t="+prev.getContentType()+"; l="+previews.length+*/ "; "
                                                            + StringAdapter.getStackTraceException(e));
                                        }
                                    } else {
                                        addError(" " + prev.getName()
                                                + "   ,      ?  3 .");
                                    }
                                }
                                i++;
                            }
                        }

                        if (newUser) {
                            userService.notifyAboutRegistration(email);
                        }
                    }

                } /* else {
                  addError("user:" + user.getId() + " " + user.getName());
                  }*/

            } else {
                addError(
                        "?  ??     email");
            }
        } else {
            addError("? ?  " + catId + "   .");
        }
    } else {
        addError("?  ");
    }
}

From source file:com.vmware.appfactory.application.controller.AppApiController.java

/**
 * Step 2: Upload the installer and create the new file share application.
 *
 * Failure or success will respond with a json with a success flag. The Http status type does not
 * matter much, as this response is recieved in an iframe, and is not transposed over to the js callback.
 *
 * Docs: http://jquery.malsup.com/form/#file-upload
 *
 * @param uploadFile - multipart file being uploaded.
 * @param request - HttpServletRequest/*from   w w  w  .  j  ava2  s  . co m*/
 */
@ResponseBody
@RequestMapping(value = "/apps/upload", method = RequestMethod.POST)
public ResponseEntity<String> uploadAndCreate(@RequestParam("uploadFile") MultipartFile uploadFile,
        HttpServletRequest request) {
    ApplicationCreateRequest uploadApp = null;
    try {
        // Load and validate required fields.
        uploadApp = loadSessionUploadApp(uploadFile, request);
        final List<String> installerDirs = generateFolderNameListForUploadApp(uploadApp);

        // Get the destination ds and copy the installer.
        DsDatastore ds = _dsClient.findDatastore(uploadApp.getDsId(), true);

        // Developer mode! Copy the upload file to a local directory.
        if (_af.isDevModeDeploy() && StringUtils.isNotEmpty(_af.getDevModeUploadDir())) {

            // Path to file's directory
            String newPath = _af.getDevModeUploadDir();
            for (String dir : installerDirs) {
                newPath = FileHelper.constructFilePath2(File.separator, newPath, dir);
            }
            FileUtils.forceMkdir(new File(newPath));

            // Full path to file
            String newFile = FileHelper.constructFilePath2(File.separator, newPath,
                    uploadFile.getOriginalFilename());

            _log.debug("DEV MODE! Uploading " + uploadFile.getOriginalFilename() + " size "
                    + uploadFile.getSize() + " to " + newFile);

            // Copy it
            uploadFile.transferTo(new File(newFile));
        } else { // Production mode! Copy the upload file to the datastore.
            // Full path to directory where file will be copied to.
            String destFile = ds.createDirsIfNotExists(installerDirs.toArray(new String[installerDirs.size()]));
            destFile = destFile + uploadFile.getOriginalFilename();

            _log.debug("Uploading " + uploadFile.getOriginalFilename() + " size " + uploadFile.getSize()
                    + " to " + destFile);

            ds.copy(uploadFile, destFile, null);
        }

        // create the application now that uploaded installer has been copied.
        createUploadApp(installerDirs, uploadFile.getOriginalFilename(), request, uploadApp);
        _log.info("upload file & app: {} creation complete.", uploadApp.getAppName());
        return respondUploadMessage("Installer was uploaded and saved.", true, request);

    } catch (AfBadRequestException e) {
        _log.error("Saving file to ds error: " + e.getMessage(), e);
        return respondUploadMessage("Selected datastore couldnt not be accessed.", false, request);
    } catch (URISyntaxException urie) {
        _log.error("Application create error: " + urie.getMessage(), urie);
        return respondUploadMessage("Saving the application after installer upload failed.", false, request);
    } catch (IllegalStateException e) {
        _log.error("Save file to ds error: " + e.getMessage(), e);
        return respondUploadMessage("Installer couldnt be saved onto the datastore.", false, request);
    } catch (IOException e) {
        _log.error("Create folder /save file to ds error: " + e.getMessage(), e);
        return respondUploadMessage("Installer couldnt be saved onto the datastore.", false, request);
    } catch (DsException ds) {
        _log.error("Saving file to ds error: " + ds.getMessage(), ds);
        return respondUploadMessage("Selected datastore could not be accessed.", false, request);
    } catch (RuntimeException rts) {
        // This is the default runtime exception case that needs to be handled. The client handler can only
        // handle json response, and hence we catch all other runtime exceptions here.
        _log.error("Uploading installer failed with error: " + rts.getMessage(), rts);
        return respondUploadMessage("Uploading and creating an application failed.", false, request);
    } finally {
        if (uploadApp != null) {
            // Cleanup the progress listener session variable.
            ProgressReporter.removeProgressListener(request, uploadApp.getUploadId());
        }
    }
}

From source file:com.topsec.tsm.sim.sysconfig.web.SystemConfigController.java

@RequestMapping(value = "licenseImport", produces = "text/html;charset=utf-8")
@ResponseBody/* w  ww  . java2 s  . c o m*/
public Object licenseImport(SID sid, @RequestParam("theLicenseFile") MultipartFile theLicenseFile,
        HttpServletRequest request) throws Exception {

    Result result = new Result();
    if (theLicenseFile == null) {
        return JSON.toJSONString(result.buildError("?"));
    }

    //?
    if (theLicenseFile.getSize() > maxPostSize) {
        return JSON.toJSONString(result.buildError("??"));
    }

    //?
    File basefile = new File(TMP_LICENSE_PATH + theLicenseFile.getOriginalFilename());
    if (!basefile.exists()) {
        FileUtils.forceMkdir(basefile);
    }
    try {
        //
        theLicenseFile.transferTo(basefile);
        Result checkResult = LicenceServiceUtil.checkLicenseFile(basefile, "TAEX-S", "TAEX_S");
        AuditLogFacade.userOperation("??", sid.getUserName(), checkResult.getMessage(),
                IpAddress.IPV4_LOCALHOST, Severity.HIGHEST, AuditCategoryDefinition.SYS_UPGRADE,
                result.isSuccess());
        log.warn(checkResult.getMessage());
        result.build(checkResult.isSuccess(), checkResult.getMessage());
    } catch (Exception e) {
        result.build(false, "??");
    } finally {
        basefile.delete();
    }
    return JSON.toJSONString(result);
}

From source file:com.poscoict.license.service.ManagementService.java

public void modifyProduct(String userNo, String licenseKey, String productFileId, String newLicenseKey,
        String licenseQuantity, String selectFile, String checkBox, MultipartFile file, HttpSession session)
        throws UserException {
    logger.info("modifyProduct: userNo= " + userNo + " PRODUCT_FILE_ID= " + productFileId);
    TransactionStatus status = this.transactionManager.getTransaction(new DefaultTransactionDefinition());
    String licenseUpPath = Consts.LICENSE_FILE_HOME;

    try {//from w ww. ja  v a 2 s.  c o m
        String oldLiscensePath = managementDao.getLicensePath2(licenseKey, userNo);
        managementDao.updateInstallFilName((String) session.getAttribute("USER_NO"), userNo, licenseKey);
        managementDao.updateProductInfo(userNo, newLicenseKey, productFileId, licenseQuantity,
                (String) session.getAttribute("USER_NO"), licenseKey);
        if (selectFile.equals("change")) {
            String path = "";
            String licenseName = "";

            if (checkBox == null) {
                MultipartFile upFile = file;
                licenseName = upFile.getOriginalFilename(); // ???
                try {

                    File upfile = new File(licenseUpPath + userNo + File.separator + licenseName);
                    if (upfile.isFile())
                        throw new UserException(
                                "???? . ??  .");

                    if (!upfile.exists())
                        upfile.mkdirs();

                    upFile.transferTo(upfile);
                    path = upfile.getAbsolutePath();
                    logger.info("modifyProduct: upFileName= " + licenseName + " path= " + path);
                } catch (IOException e) {
                    logger.error("modifyProduct(File Upload Error): ", e);
                }
            }
            managementDao.updateLicenseInfo(userNo, licenseKey, licenseName, path,
                    (String) session.getAttribute("USER_NO"));

            // ?? ? 
            File oldLicenseFile = new File(oldLiscensePath);
            if (oldLicenseFile.exists())
                oldLicenseFile.delete();
        }
        this.transactionManager.commit(status);
    } catch (DuplicateKeyException e) {
        this.transactionManager.rollback(status);
        logger.error("plusProduct: ", e);
        throw new DuplicateKeyException(
                " ?. ?? ? .");
    } catch (RuntimeException e) {
        this.transactionManager.rollback(status);
        logger.error("plusProduct: ", e);
    }
}