Example usage for javax.servlet.http HttpServletRequest getRealPath

List of usage examples for javax.servlet.http HttpServletRequest getRealPath

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRealPath.

Prototype

public String getRealPath(String path);

Source Link

Usage

From source file:com.br.uepb.controller.MedicaoController.java

@RequestMapping(value = "/home/medicao.html", method = RequestMethod.POST)
public ModelAndView medicaoPost(HttpServletRequest request, Model model,
        @ModelAttribute("uploadItem") UploadItem uploadItem) {

    String login = request.getSession().getAttribute("login").toString();

    SessaoBusiness sessao = GerenciarSessaoBusiness.getSessaoBusiness(login);
    MedicoesBusiness medicoesBusiness = new MedicoesBusiness();
    LoginDomain loginDomain = sessao.getLoginDomain();

    ModelAndView modelAndView = new ModelAndView();
    String mensagem = "";
    String status = "";

    @SuppressWarnings("deprecation")
    String uploadRootPath = request.getRealPath(File.separator);

    File uploadRootDir = new File(uploadRootPath);

    // Cria o diretrio se no existir
    if (!uploadRootDir.exists()) {
        uploadRootDir.mkdirs();//from   w w  w. j a va 2 s  .  co m
    }
    CommonsMultipartFile fileData = uploadItem.getFileData();

    // Nome do arquivo cliente
    String name = fileData.getOriginalFilename();

    if (name != null && name.length() > 0) {
        try {
            // Create the file on server
            File serverFile = new File(uploadRootDir.getAbsolutePath() + File.separator + name);

            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(fileData.getBytes());
            stream.close();
            // Salvou o arquivo xml

            String tipo_dispositivo = uploadItem.getTipo_dispositivo();
            String arquivo = serverFile.toString();

            if (tipo_dispositivo.equals("2")) { // oximetro
                modelAndView.addObject("tipoDispositivo", 2);
                if (medicoesBusiness.medicaoOximetro(arquivo, login)) {
                    //medicoesBusiness.medicaoOximetro(arquivo);
                    mensagem = "Medio Oximetro cadastrada com sucesso!";
                    status = "0";

                    MedicaoOximetroDomain oximetro = medicoesBusiness
                            .listaUltimaMedicaoOximetro(loginDomain.getPaciente().getId());
                    modelAndView.addObject("oximetro", oximetro);
                    modelAndView.addObject("balanca", null);
                    modelAndView.addObject("pressao", null);
                    modelAndView.addObject("icg", null);

                } else {
                    mensagem = "Erro ao cadastrar Oximetro arquivo XML!";
                    status = "1";
                }

            } else if (tipo_dispositivo.equals("1")) { // balanca
                modelAndView.addObject("tipoDispositivo", 1);
                if (medicoesBusiness.medicaoBalanca(arquivo, login)) {
                    mensagem = "Medio Balana cadastrada com sucesso!";
                    status = "0";

                    MedicaoBalancaDomain balanca = medicoesBusiness
                            .listaUltimaMedicaoBalanca(loginDomain.getPaciente().getId());
                    modelAndView.addObject("oximetro", null);
                    modelAndView.addObject("balanca", balanca);
                    modelAndView.addObject("pressao", null);
                    modelAndView.addObject("icg", null);
                } else {
                    mensagem = "Erro ao cadastrar Balana arquivo XML!";
                    status = "1";
                }

            } else if (tipo_dispositivo.equals("3")) { // pressao
                modelAndView.addObject("tipoDispositivo", 3);
                if (medicoesBusiness.medicaoPressao(arquivo, login)) {
                    mensagem = "Medio Presso cadastrada com sucesso!";
                    status = "0";

                    MedicaoPressaoDomain pressao = medicoesBusiness
                            .listaUltimaMedicaoPressao(loginDomain.getPaciente().getId());
                    modelAndView.addObject("oximetro", null);
                    modelAndView.addObject("balanca", null);
                    modelAndView.addObject("pressao", pressao);
                    modelAndView.addObject("icg", null);
                } else {
                    mensagem = "Erro ao cadastrar Presso arquivo XML!";
                    status = "1";
                }

            } else if (tipo_dispositivo.equals("0")) { // icg
                modelAndView.addObject("tipoDispositivo", 0);
                if (medicoesBusiness.medicaoIcg(arquivo, login)) {
                    mensagem = "Medio ICG cadastrada com sucesso!";
                    status = "0";

                    MedicaoIcgDomain icg = medicoesBusiness
                            .listaUltimaMedicaoIcg(loginDomain.getPaciente().getId());
                    modelAndView.addObject("oximetro", null);
                    modelAndView.addObject("balanca", null);
                    modelAndView.addObject("pressao", null);
                    modelAndView.addObject("icg", icg);

                } else {
                    mensagem = "Erro ao cadastrar ICG arquivo XML!";
                    status = "1";
                }
            } else {
                mensagem = "Erro ao cadastrar arquivo XML!";
                status = "1";
            }

        } catch (Exception e) {
            mensagem = "Erro ao cadastrar arquivo XML!";
            status = "1";
        }
    } else {
        mensagem = "O arquivo no foi informado ou est vazio";
        status = "1";
    }

    if (status == "1") {
        modelAndView.addObject("tipoDispositivo", null);
        modelAndView.addObject("oximetro", null);
        modelAndView.addObject("balanca", null);
        modelAndView.addObject("pressao", null);
        modelAndView.addObject("icg", null);
    }

    model.addAttribute("mensagem", mensagem);
    model.addAttribute("status", status);
    modelAndView.setViewName("home/medicao");
    return modelAndView;
}

From source file:controller.getReview.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from  w  ww.j  av  a2s.  co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
    HttpSession session = request.getSession();
    LoginBeans l = (LoginBeans) session.getAttribute("loginsession");
    /// Perview 
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet("https://documenta-dms.com/DMSWS/api/v1/file/" + l.getToken() + "/pdf_by_id/"
            + request.getParameter("id"));
    HttpResponse responses = httpclient.execute(httpget);

    HttpEntity entity = responses.getEntity();
    if (entity != null) {
        long len = entity.getContentLength();
        FileOutputStream fos;
        try (InputStream inputStream = entity.getContent()) {
            File f = new File(request.getRealPath("/fackpath") + "/" + l.getUserId() + "."
                    + request.getParameter("name").substring(0, request.getParameter("name").lastIndexOf("."))
                    + ".pdf");
            f.createNewFile();
            fos = new FileOutputStream(f);
            int inByte;
            while ((inByte = inputStream.read()) != -1) {
                fos.write(inByte);
            }
        }
        fos.close();
        // write the file to whether you want it.
    }

    String buffer = "<iframe style='width: 100%; height: 530px' src='web/viewer.html?file=../fackpath/"
            + l.getUserId() + "."
            + request.getParameter("name").substring(0, request.getParameter("name").lastIndexOf("."))
            + ".pdf#zoom=100'></iframe>";

    System.out.println("Buffer :" + buffer);
    response.getWriter().write(buffer);
}

From source file:org.jtwig.util.render.RenderHttpServletRequest.java

public RenderHttpServletRequest(HttpServletRequest initialRequest) {
    initialValues = snapshot(initialRequest, HttpServletRequest.class);
    Enumeration attributeNames = initialRequest.getAttributeNames();
    if (attributeNames != null) {
        while (attributeNames.hasMoreElements()) {
            String name = (String) attributeNames.nextElement();
            attributes.put(name, initialRequest.getAttribute(name));
        }/* w w  w  . j a v  a 2 s.c  om*/
    }
    realPath = initialRequest.getRealPath("");
    requestDispatcher = initialRequest.getRequestDispatcher(initialRequest.getServletPath());
}

From source file:ispyb.client.common.shipping.UploadShipmentAction.java

/**
 * DownloadFile//from   ww  w.ja  va  2s  .c  om
 * 
 * @param mapping
 * @param actForm
 * @param request
 * @param response
 * @return
 */
public ActionForward DownloadFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request,
        HttpServletResponse response) {

    ActionMessages errors = new ActionMessages();
    String fileType = request.getParameter(Constants.TEMPLATE_FILE_TYPE);

    if (fileType == null)
        fileType = this.mFileType;
    try {
        String targetUpload = new String("");
        String attachmentFilename = new String("");
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_TEMPLATE)) {
            targetUpload = Constants.TEMPLATE_RELATIVE_PATH;
            targetUpload = request.getRealPath(targetUpload);
            attachmentFilename = Constants.TEMPLATE_XLS_FILENAME;
        }
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_POPULATED_TEMPLATE)) {
            targetUpload = PopulateTemplate(request, true, false, false, null, null, false, 0, false, 0);
            attachmentFilename = PopulateTemplate(request, false, true, false, null, null, false, 0, false, 0);
        }
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_POPULATED_TEMPLATE_ADVANCED)) {
            targetUpload = PopulateTemplate(request, true, false, true, null, null, false, 0, false, 0);
            attachmentFilename = PopulateTemplate(request, false, true, true, null, null, false, 0, false, 0);
        }
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_EXPORT_SHIPPING)) {
            targetUpload = PopulateTemplate(request, true, false, false, null, null, false, 0, false, 0);
            attachmentFilename = PopulateTemplate(request, false, true, false, null, null, false, 0, false, 0);
        }
        if (fileType.equals(Constants.TEMPLATE_FILE_TYPE_POPULATED_TEMPLATE_FROM_SHIPMENT)) {
            Integer _shippingId = Integer.decode(request.getParameter(Constants.SHIPPING_ID));
            int shippingId = (_shippingId != null) ? _shippingId.intValue() : 0;
            targetUpload = PopulateTemplate(request, true, false, false, null, null, false, 0, true,
                    shippingId);
            attachmentFilename = PopulateTemplate(request, false, true, false, null, null, false, 0, true,
                    shippingId);
        }

        try {

            byte[] imageBytes = FileUtil.readBytes(targetUpload);
            response.setContentLength(imageBytes.length);
            ServletOutputStream out = response.getOutputStream();
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "max-age=0");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);

            out.write(imageBytes);
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString()));
        LOG.error(e.toString());
        saveErrors(request, errors);
        return mapping.findForward("error");
    }

    return null;
}

From source file:com.ba.forms.receipt.BAReceiptAction.java

public ActionForward baPrint(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Connection con = null;//from w  w w.j  av a2s  .  c  om
    com.fins.org.json.JSONObject json = new com.fins.org.json.JSONObject();
    try {
        logger.info("hotel_booking");
        // title is the title of the report.Here we are passing dynamically.So that this class is useful to remaining reports also.
        String jrept = "hotel_receipt.jrxml";
        String pdfFileName = "hotel_receipt";
        String receipt = request.getParameter("receipt");

        con = BADatabaseUtil.getConnection();
        String reportFileName = JasperCompileManager
                .compileReportToFile(request.getRealPath("/reports") + "/" + jrept);
        java.util.Map parameters = new java.util.HashMap();

        parameters.put("receipt", receipt);
        File reportFile = new File(reportFileName);
        if (!reportFile.exists()) {
            throw new JRRuntimeException(
                    "File WebappReport.jasper not found. The report design must be compiled first.");
        }
        JasperPrint jasperPrint = JasperFillManager.fillReport(reportFileName, parameters, con);
        JasperExportManager.exportReportToPdfFile(jasperPrint,
                request.getRealPath("/PDF") + "/" + pdfFileName + "_" + receipt + ".pdf");
        File f = new File(request.getRealPath("/PDF") + "/" + pdfFileName + "_" + receipt + ".pdf");
        FileInputStream fin = new FileInputStream(f);
        //            
        String path = "http://" + request.getServerName() + ":" + request.getServerPort() + "/"
                + request.getContextPath() + "/PDF" + "/" + pdfFileName + "_" + receipt + ".pdf";
        request.setAttribute("path", path);
        //                outStream.flush();
        fin.close();
        //                outStream.close();

        logger.info("print feed dc");

        json.put("exception", "");
        json.put("bookingDets", path);
        json.put("bookingExit", 1);
    } catch (Exception ex) {
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    } finally {
        BADatabaseUtil.closeConnection(con);
    }
    logger.info("CmsReasonMasterDaoImpl In CmsReasonMasterAction :: cmsGet() ends Here ");
    response.getWriter().write(json.toString());
    return null;
}

From source file:com.ba.forms.settlement.BASettlementAction.java

public ActionForward baPrint(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Connection con = null;//from   w w w .j a v  a 2s  .c o  m
    com.fins.org.json.JSONObject json = new com.fins.org.json.JSONObject();
    try {
        logger.info("hotel_booking");
        // title is the title of the report.Here we are passing dynamically.So that this class is useful to remaining reports also.
        String jrept = "hotel settlement.jrxml";
        String pdfFileName = "hotel settlement";
        String sqlBookid = request.getParameter("sqlBookid");
        String sqlRoomid = request.getParameter("sqlRoomid");

        con = BADatabaseUtil.getConnection();
        String reportFileName = JasperCompileManager
                .compileReportToFile(request.getRealPath("/reports") + "/" + jrept);
        java.util.Map parameters = new java.util.HashMap();

        parameters.put("sqlBookid", Integer.parseInt(sqlBookid));
        parameters.put("sqlRoomid", Integer.parseInt(sqlRoomid));
        File reportFile = new File(reportFileName);
        if (!reportFile.exists()) {
            throw new JRRuntimeException(
                    "File WebappReport.jasper not found. The report design must be compiled first.");
        }
        JasperPrint jasperPrint = JasperFillManager.fillReport(reportFileName, parameters, con);
        JasperExportManager.exportReportToPdfFile(jasperPrint,
                request.getRealPath("/PDF") + "/" + pdfFileName + "_" + sqlBookid + "_" + sqlRoomid + ".pdf");
        File f = new File(
                request.getRealPath("/PDF") + "/" + pdfFileName + "_" + sqlBookid + "_" + sqlRoomid + ".pdf");
        FileInputStream fin = new FileInputStream(f);
        //            
        String path = "http://" + request.getServerName() + ":" + request.getServerPort() + "/"
                + request.getContextPath() + "/PDF" + "/" + pdfFileName + "_" + sqlBookid + "_" + sqlRoomid
                + ".pdf";
        request.setAttribute("path", path);
        //                outStream.flush();
        fin.close();
        //                outStream.close();

        logger.info("print feed dc");

        json.put("exception", "");
        json.put("bookingDets", path);
        json.put("bookingExit", 1);
    } catch (Exception ex) {
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    } finally {
        BADatabaseUtil.closeConnection(con);
    }
    logger.info("CmsReasonMasterDaoImpl In CmsReasonMasterAction :: cmsGet() ends Here ");
    response.getWriter().write(json.toString());
    return null;
}

From source file:com.ba.forms.bookingForm.BABookingAction.java

public ActionForward baPrint(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Connection con = null;/*from  w w w  .jav a2s .co m*/
    com.fins.org.json.JSONObject json = new com.fins.org.json.JSONObject();
    try {
        logger.info("hotel_booking");
        // title is the title of the report.Here we are passing dynamically.So that this class is useful to remaining reports also.
        String jrept = "hotel_booking.jrxml";
        String pdfFileName = "hotel_booking";
        String bookingId = request.getParameter("bookingId");

        con = BADatabaseUtil.getConnection();
        String reportFileName = JasperCompileManager
                .compileReportToFile(request.getRealPath("/reports") + "/" + jrept);
        java.util.Map parameters = new java.util.HashMap();

        parameters.put("bookingId", bookingId);
        File reportFile = new File(reportFileName);
        if (!reportFile.exists()) {
            throw new JRRuntimeException(
                    "File WebappReport.jasper not found. The report design must be compiled first.");
        }
        JasperPrint jasperPrint = JasperFillManager.fillReport(reportFileName, parameters, con);
        JasperExportManager.exportReportToPdfFile(jasperPrint,
                request.getRealPath("/PDF") + "/" + pdfFileName + "_" + bookingId + ".pdf");
        File f = new File(request.getRealPath("/PDF") + "/" + pdfFileName + "_" + bookingId + ".pdf");
        FileInputStream fin = new FileInputStream(f);
        //            
        String path = "http://" + request.getServerName() + ":" + request.getServerPort() + "/"
                + request.getContextPath() + "/PDF" + "/" + pdfFileName + "_" + bookingId + ".pdf";
        request.setAttribute("path", path);
        //                outStream.flush();
        fin.close();
        //                outStream.close();

        logger.info("print feed dc");

        json.put("exception", "");
        json.put("bookingDets", path);
        json.put("bookingExit", 1);
    } catch (Exception ex) {
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    } finally {
        BADatabaseUtil.closeConnection(con);
    }
    logger.info("CmsReasonMasterDaoImpl In CmsReasonMasterAction :: cmsGet() ends Here ");
    response.getWriter().write(json.toString());
    return null;
}

From source file:com.ba.forms.foodBill.BAFoodBillAction.java

public ActionForward baPrint(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Connection con = null;/*  www .  j  a  v  a  2s .  c om*/
    com.fins.org.json.JSONObject json = new com.fins.org.json.JSONObject();
    try {
        logger.info("hotel_booking");
        // title is the title of the report.Here we are passing dynamically.So that this class is useful to remaining reports also.
        String jrept = "hotel_food.jrxml";
        String pdfFileName = "hotel_food";
        String foodBill = request.getParameter("foodBill");

        con = BADatabaseUtil.getConnection();
        String reportFileName = JasperCompileManager
                .compileReportToFile(request.getRealPath("/reports") + "/" + jrept);
        java.util.Map parameters = new java.util.HashMap();

        parameters.put("foodBill", foodBill);
        File reportFile = new File(reportFileName);
        if (!reportFile.exists()) {
            throw new JRRuntimeException(
                    "File WebappReport.jasper not found. The report design must be compiled first.");
        }
        JasperPrint jasperPrint = JasperFillManager.fillReport(reportFileName, parameters, con);
        JasperExportManager.exportReportToPdfFile(jasperPrint,
                request.getRealPath("/PDF") + "/" + pdfFileName + "_" + foodBill + ".pdf");
        File f = new File(request.getRealPath("/PDF") + "/" + pdfFileName + "_" + foodBill + ".pdf");
        FileInputStream fin = new FileInputStream(f);
        //            
        String path = "http://" + request.getServerName() + ":" + request.getServerPort() + "/"
                + request.getContextPath() + "/PDF" + "/" + pdfFileName + "_" + foodBill + ".pdf";
        request.setAttribute("path", path);
        //                outStream.flush();
        fin.close();
        //                outStream.close();

        logger.info("print feed dc");

        json.put("exception", "");
        json.put("bookingDets", path);
        json.put("bookingExit", 1);
    } catch (Exception ex) {
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    } finally {
        BADatabaseUtil.closeConnection(con);
    }
    logger.info("CmsReasonMasterDaoImpl In CmsReasonMasterAction :: cmsGet() ends Here ");
    response.getWriter().write(json.toString());
    return null;
}

From source file:com.dwf.tastyroad.controller.RestaurantController.java

@RequestMapping(value = "/addRestaurant", method = RequestMethod.POST)
//?? web client? ? restaurant? ? 
public ModelAndView addRestaurantAction(@ModelAttribute("restaurant") Restaurant restaurant,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    //Field/*w ww  .  j  a  va 2  s . co m*/
    String fileDir1 = request.getRealPath("/") + "resources/img";
    int max = 5 * 640 * 480;
    String fileInput = "";
    String fileName = "";
    String fileDir2 = "";

    System.out.println("_______________________________________________");
    System.out.println("==> /restaurant/addRestaurant __call !!!");
    System.out.println("_______________________________________________");

    //=============================================<MultipartRequest>========================================
    //
    //         +---------------------+         
    //         | author : .     |
    //         +---------------------+
    //         | Date : 2014-07-02     |
    //         +---------------------+
    //           
    //         1. ? ?    MultipartRequest .
    //         2. restaurantAdd.jsp?  file? Controller? MultipartRequest .
    //         3. restaurantAdd.jsp  ? 2.
    //                form enctype="multipart/form-data" ? .
    //                ?   input ? type="file"? ? .            
    //         4. MultipartRequest .
    //             MultipartRequest  ? ? File? Local File System?  .
    //             Enumeration file form name & file name?  . (while? ??)
    //             File?   new File()? , fileName? ?? . 
    //             key-value ? <String, File> map? , File??  .(while? ??)
    //             ??, ?? setter  ? set.(? ?? ? String  set.)
    //             While? ??, File?   ?? (text...)? ? value?  .
    //              ?? setter  ? set.
    //             DB? .(File ?  DB? .  File ? ftp ?  .)
    //
    //
    //===========================================================================================================

    MultipartRequest mpr = new MultipartRequest(request, fileDir1, max, "UTF-8", new DefaultFileRenamePolicy());
    Enumeration formNames = mpr.getFileNames();

    //ArrayList<File> fileList = new ArrayList<File>();
    //HashMap<String, File> fileMap = new HashMap<String, File>();

    while (formNames.hasMoreElements()) {

        System.out.println("============================");
        fileInput = (String) formNames.nextElement();
        System.out.println("fileInput : " + fileInput);
        //Console  ?. ==> fileInput : imgSmall1.

        fileName = mpr.getFilesystemName(fileInput);
        System.out.println("fileName : " + fileName);
        //Console  ?. ==> fileName : IMG_1200.png
        System.out.println("============================");

        if (fileName != null) {
            System.out.println("if ?");

            switch (fileInput) {

            case "imgSmall1":
                //fileDir2 = fileDir1 + "/main";
                System.out.println("fileDirectory : " + fileDir2);
                restaurant.setImgSmall1("main/" + fileName);
                System.out.println("restaurant.getImageSmall1 : " + restaurant.getImgSmall1());
                //Console  ?. ==> fileDirectory : C:\(?)\wtpwebapps\TastyRoad05\resources/img/
                //fileList.add(mpr.getFile(fileInput));
                fileMap.put("imgSmall1", mpr.getFile(fileInput));
                //System.out.println("getFile? ==> " + mpr.getFile(fileInput));
                //Console  ?. ==>C:\(?)\wtpwebapps\TastyRoad05\resources/img/(??).png
                break;

            case "imgBig1":
                //fileDir2 = fileDir1 + "/detail";
                System.out.println("fileDirectory : " + fileDir2);
                restaurant.setImgBig1("detail/" + fileName);
                System.out.println("restaurant.getImageBig1 : " + restaurant.getImgBig1());
                //Console  ?. ==> fileDirectory : C:\(?)\wtpwebapps\TastyRoad05\resources/img/
                //fileList.add(mpr.getFile(fileInput));
                fileMap.put("imgBig1", mpr.getFile(fileInput));
                //System.out.println("getFile? ==> " + mpr.getFile(fileInput));
                //Console  ?. ==>C:\(?)\wtpwebapps\TastyRoad05\resources/img/(??).png
                break;

            case "imgBig2":
                //fileDir2 = fileDir1 + "/detail";
                System.out.println("fileDirectory : " + fileDir2);
                restaurant.setImgBig2("detail/" + fileName);
                System.out.println("restaurant.getImageBig2 : " + restaurant.getImgBig2());
                //Console  ?. ==> fileDirectory : C:\(?)\wtpwebapps\TastyRoad05\resources/img/
                //fileList.add(mpr.getFile(fileInput));
                fileMap.put("imgBig2", mpr.getFile(fileInput));
                //System.out.println("getFile? ==> " + mpr.getFile(fileInput));
                //Console  ?. ==>C:\(?)\wtpwebapps\TastyRoad05\resources/img/(??).png
                break;

            case "imgBig3":
                //fileDir2 = fileDir1 + "/detail";
                System.out.println("fileDirectory : " + fileDir2);
                restaurant.setImgBig3("detail/" + fileName);
                System.out.println("restaurant.getImageBig3 : " + restaurant.getImgBig3());
                //Console  ?. ==> fileDirectory : C:\(?)\wtpwebapps\TastyRoad05\resources/img/
                //fileList.add(mpr.getFile(fileInput));
                fileMap.put("imgBig3", mpr.getFile(fileInput));
                //System.out.println("getFile? ==> " + mpr.getFile(fileInput));
                //Console  ?. ==>C:\(?)\wtpwebapps\TastyRoad05\resources/img/(??).png
                break;

            case "imgMenu":
                //fileDir2 = fileDir1 + "/menu";
                System.out.println("fileDirectory : " + fileDir2);
                restaurant.setImgMenu("menu/" + fileName);
                System.out.println("restaurant.getImageMenu : " + restaurant.getImgMenu());
                //Console  ?. ==> fileDirectory : C:\(?)\wtpwebapps\TastyRoad05\resources/img/
                //fileList.add(mpr.getFile(fileInput));
                fileMap.put("imgMenu", mpr.getFile(fileInput));
                //System.out.println("getFile? ==> " + mpr.getFile(fileInput));
                //Console  ?. ==>C:\(?)\wtpwebapps\TastyRoad05\resources/img/(??).png
                break;

            }//endOfSwith
        } //endOfIf

        //type = "file" ?   ? value?  set.
        restaurant.setName(mpr.getParameter("name"));
        restaurant.setAddr(mpr.getParameter("addr"));
        restaurant.setPhone(mpr.getParameter("phone"));
        restaurant.setLicenseNo(mpr.getParameter("licenseNo"));
        restaurant.setGeoLat(Double.parseDouble(mpr.getParameter("geoLat")));
        restaurant.setGeoLong(Double.parseDouble(mpr.getParameter("geoLong")));
        restaurant.setCopyComment(mpr.getParameter("copyComment"));
        restaurant.setResCategory(Integer.parseInt(mpr.getParameter("resCategory")));

    } //endOfWhile

    //=============================================<FTP  -INSERT>========================================
    //
    //         +---------------------+         
    //         | author : .     |
    //         +---------------------+
    //         | Date : 2014-07-02     |
    //         +---------------------+
    //           
    //         1. FTP ? ? ? ?? ?   .
    //         2. ?? ?  ? ,  ?   ?.
    //         3. FTP  .
    //             FTPTransfer inner ? , insert .
    //                    //inner class
    //                    public FTPTransfer{
    //                       insert(SERVER_IP, PORT, ID, PASSWORD, UPLOAD_DIR, Makedir, map)  
    //                    }
    //              
    //             FTPTransfer ? ? ?.
    //                  FTPTransfer transfer = new FTPTransfer();
    //
    //             insert  , 
    //              MultipartRequest File ?  <String, File> map?  .
    //                  transfer.insert(SERVER_IP, PORT, ID, PASSWORD, UPLOAD_DIR, null, fileMap);               
    //
    //             insert  ? for  map? value(File ?) , ftp.storeFile()? ,
    //              ftp .
    //
    //             ftp ? ??,  ? ?   ? ?? .
    //
    //
    //===========================================================================================================

    FTPTransfer transfer = new FTPTransfer();
    System.out.println("==============================ftp =======================================");
    boolean result = transfer.insert(SERVER_IP, PORT, ID, PASSWORD, UPLOAD_DIR, null, fileMap);
    //      transfer.FtpPut(SERVER_IP, PORT, ID, PASSWORD, UPLOAD_DIR, null, fileList);
    System.out.println("==============================ftp =======================================");

    //      for(int i=0; i<fileList.size();i++){
    //         System.out.println("Local File   for  ......");
    //         File file1 = new File(fileList.get(i).toString());
    //         file1.delete();
    //
    //            if(file1.exists()){
    //               System.out.println(" Failed......");
    //            }
    //               else{
    //                  System.out.println(" Ok!!!!!!");
    //               }
    //      }//endOfForStatement

    //ftp ? ?,  ? ?  ? ? ?? .
    if (result == true) {

        set = fileMap.keySet();
        //set.toString(); //Console  ?. ==> [imgSmall1, imgBig1, imgBig2, imgBig3, 
        keys = set.toString().subSequence(1, set.toString().length() - 1).toString().split(", ");

        for (int i = 0; i < keys.length; i++) {
            System.out.println("Local File   for  ......");
            File file1 = new File(fileMap.get(keys[i]).toString());
            file1.delete();

            if (file1.exists()) {
                System.out.println(" Failed......");
            } else {
                System.out.println(" Ok!!!!!!");
            }
        } //endOfForStatement
    }

    //      if(mpr.getFileNames().equals("imgSmall1")){
    //         filePath=dir+"/main/";
    //         imageFileLists.add(mpr.getFile("imgSmall1"));
    //         imageFileName.add(mpr.getOriginalFileName("imgSmall1"));
    //         System.out.println(mpr.getFile("imgSmall1"));
    //         System.out.println(mpr.getOriaginalFileName("imgSmall1"));
    //         
    //      }
    //         
    //         else if(mpr.getFileNames().equals("imgBig1")){
    //               filePath=dir+"/detail/";
    //               imageFileLists.add(mpr.getFile("imgBig1"));
    //               imageFileName.add(mpr.getOriginalFileName("imgBig1"));
    //               System.out.println(mpr.getFile("imgBig1"));
    //               System.out.println(mpr.getOriginalFileName("imgBig1"));
    //         }
    //         
    //         else if(mpr.getFileNames().equals("imgBig2")){
    //               filePath=dir+"/detail/";
    //               imageFileLists.add(mpr.getFile("imgBig2"));
    //               imageFileName.add(mpr.getOriginalFileName("imgBig2"));
    //               System.out.println(mpr.getFile("imgBig2"));
    //               System.out.println(mpr.getOriginalFileName("imgBig2"));
    //         }
    //         
    //         else if(mpr.getFileNames().equals("imgBig3")){
    //               filePath=dir+"/detail/";
    //               imageFileLists.add(mpr.getFile("imgBig3"));
    //               imageFileName.add(mpr.getOriginalFileName("imgBig3"));
    //               System.out.println(mpr.getFile("imgBig3"));
    //               System.out.println(mpr.getOriginalFileName("imgBig3"));
    //         }
    //         
    //         else if(mpr.getFileNames().equals("imgMenu")){
    //               filePath=dir+"/menu/";
    //               imageFileLists.add(mpr.getFile("imgMenu"));
    //               imageFileName.add(mpr.getOriginalFileName("imgMenu"));
    //               System.out.println(mpr.getFile("imgMenu"));
    //               System.out.println(mpr.getOriginalFileName("imgMenu"));
    //         }
    //         
    //         for(int i=0; i<imageFileName.size();i++){
    //            fileName = imageFileName.get(i);
    //            System.out.println(fileName);
    //            
    //            if(!fileName.equals("")){
    //               String fullFileName = filePath + fileName;
    //            }
    //         }
    //         
    /* by .*/
    //      try {  
    //         //? String File? Parsing MultipartParser ? ?
    //         //10 * 1024 * 1024 = 10MB.   ? ?
    //         MultipartParser mp = new MultipartParser(request, 10 * 1024 * 1024);  
    //         //UTF-8? . ?  ?
    //         mp.setEncoding("UTF-8");
    //         //A Part is an abstract upload part which represents an INPUT form element 
    //         //in a multipart/form-data form submission
    //         //Part ?/. Part form tag upload? part()? ?. file String?
    //         Part part = null;  
    //         //A ParamPart is an upload part which represents 
    //         //a normal INPUT (for example a non TYPE="file") form parameter.
    //         //ParamPart ? ?/. ParamPart Server ?   file?  parameter 
    //         //, name="", addr="?" ,..  ??? ? ParamPart
    //         ParamPart paramPart = null;
    //         //? parameter? ?. , name, addr, imgSmall1, imgBig1 
    //         String paramName = "";
    //         //?  parameter ? ? . , , ? 
    //         String paramValue = null; 
    //         //File ? ?/. ? ?? ? ?
    //         File file = null;
    //         //? ?? ?
    //         String fileName = "";
    //         //dynamic ?  ?  
    //         String baseFilePath = request.getRealPath("/")+"resources/img"; 
    //         //System.out.println(baseFilePath);
    //         
    //         //upload?  Part?   
    //         while ((part = (Part) mp.readNextPart()) != null) {
    //            
    //            paramName = part.getName();
    //            //? part? ? ???,  
    //            if (part.isFile()) {  
    //               //upload? ??  ? 
    //               String filePath = null;
    //               //Part? FilePart(?) ()
    //               FilePart filePart = (FilePart) part;  
    //               //FilePart  ? ? 
    //               fileName = (String) filePart.getFileName();  
    //               // +?? ?  StringBuffer type? fileRef ?
    //               StringBuffer fileRef = new StringBuffer(); 
    //               
    //               //parameter? ?? ? ?? ?  set
    //               switch(paramName){
    //                  case "imgSmall1" : 
    //                     filePath = baseFilePath + "/main"; 
    //                     break;
    //                  case "imgBig1" :
    //                  case "imgBig2" :
    //                  case "imgBig3" :
    //                     filePath = baseFilePath + "/detail"; 
    //                     break;
    //                  case "imgMenu" :
    //                     filePath = baseFilePath + "/menu"; 
    //                     break;
    //               }//end of switch
    //    
    //               // ? ?().   dynamic                  
    //               filePart.writeTo(new File(String.valueOf(fileRef.append(filePath).append(File.separator).append(fileName))));  
    //               //fileName ?? ?? ,  ?? ? ?    
    //               //DB? null? ? 
    //               if(fileName != null){
    //                  //restaurant ??  ? ? ? set(String).  ??  !
    //                  //? ?  resources/img ? ? ?.  ?   
    //                  //, imgSmall1? resources/img/main/?? 
    //                  // ?? main/??   ? DB? ? 
    //                  switch(paramName){
    //                     case "imgSmall1" :
    //                        restaurant.setImgSmall1("main/" +fileName);
    //                        break;
    //                     case "imgBig1" :
    //                        restaurant.setImgBig1("detail/" +fileName);
    //                        break;
    //                     case "imgBig2" :
    //                        restaurant.setImgBig2("detail/" +fileName);
    //                        break;
    //                     case "imgBig3" :
    //                        restaurant.setImgBig3("detail/" +fileName);
    //                        break;
    //                     case "imgMenu" :
    //                        restaurant.setImgMenu("menu/" +fileName);
    //                        break;
    //                  }//end of switch 
    //               }//end of if
    //            //text ? parameter?   - , file?  .
    //            }else { 
    //            //ParamPart    parameter    
    //            paramPart = (ParamPart)part;  
    //            //parameter? ? String 
    //            paramValue = new String(paramPart.getStringValue());  
    //               //paramValue ?  restaurant? set
    //               if(paramValue != null){
    //               //parameter ?? ? switch  restaurant ?? set
    //               // ? DB? 
    //                  switch(paramName){
    //                     case "name" :
    //                        restaurant.setName(paramValue);
    //                        break;
    //                     case "addr" :
    //                        restaurant.setAddr(paramValue);
    //                        break;
    //                     case "phone" :
    //                        restaurant.setPhone(paramValue);
    //                        break;
    //                     case "licenseNo" :
    //                        restaurant.setLicenseNo(paramValue);
    //                        break;
    //                     case "geoLat" :
    //                        restaurant.setGeoLat(Double.parseDouble(paramValue));
    //                        break;
    //                     case "geoLong" :
    //                        restaurant.setGeoLong(Double.parseDouble(paramValue));
    //                        break;               
    //                     case "copyComment" :
    //                        restaurant.setCopyComment(paramValue);
    //                        break;
    //                     case "resCategory" :
    //                        restaurant.setResCategory(Integer.parseInt(paramValue));
    //                        break;
    //                  }//end of switch
    //               }//end of if
    //            }//end of if-else  
    //         }//end of while
    //      } catch (Exception e){  
    //         e.printStackTrace();
    //         throw e;           
    //      }//end of catch 

    //     - DB? upload? ?? 
    restaurantService.addRestaurant(restaurant);

    //    ?  ?   ?? ??
    //return "forward:/restaurant/listRestaurant";

    //CurrentPage  1 set
    Search search = new Search();
    search.setCurrentPage(1);
    search.setPageSize(pageSize);

    //field? ? pageSize set
    search.setPageSize(pageSize);

    //DB? (? null)? ?  restaurant ?  
    List restaurantList = restaurantService.getRestaurantList(search);
    //Page instance ?(?? page navigation )
    Page resultPage = new Page(search.getCurrentPage(), restaurantService.getTotalCount(search), pageUnit,
            pageSize);

    //restaurant list console? 
    for (int i = 0; i < restaurantList.size(); i++) {
        restaurant = (Restaurant) restaurantList.get(i);
        System.out.println("restaurant.toString()" + restaurant.toString() + "__");
    }

    //response?  model view ? ModelAndView ? ?
    ModelAndView modelAndView = new ModelAndView();
    // view set. 
    //WEB-INF/restaurantViews/restaurantList.jsp (servlet-context.xml)
    modelAndView.setViewName("restaurantViews/restaurantList");
    //? 3??. ?,?  response? 
    modelAndView.addObject("restaurantList", restaurantList);
    modelAndView.addObject("resultPage", resultPage);
    modelAndView.addObject("search", search);

    return modelAndView;
}

From source file:Ynzc.YnzcAms.Controller.TractorInfoController.java

public void tractorSteerReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
    request.setCharacterEncoding("utf-8");
    HashMap map = new HashMap();
    String id = request.getParameter("id").trim();
    List<CarMoveReportSource> list = serviceManager.getTractorInfoService()
            .tractorSteerReport(Integer.valueOf(id));

    String FileUrl = request.getRealPath("/") + "drivingLicenceUpload/"
            + DateTimeUtil.formatDate(DateTimeUtil.getNow()) + "/";
    File file = new File(FileUrl);
    if (!file.isDirectory()) {
        file.mkdir();//from w  w w . j  a  va  2 s .c  om
    }
    String fineName = list.get(0).getLicense() + "_tractorSteerReport_"
            + DateTimeUtil.formatDate(DateTimeUtil.getNow());
    User user = (User) request.getSession().getAttribute("user");
    String wordType = request.getParameter("wordType");
    WordSet ws = serviceManager.getWordSetService().findWordSetByWordTypeandUnitid(wordType, user.getUnitid());
    if (ws == null) {
        ws = new WordSet();
        if (!StringUtil.isNotNullEmptyStr(ws.getLeftMargin())) {
            ws.setLeftMargin("5");
        }
        if (!StringUtil.isNotNullEmptyStr(ws.getRightMargin())) {
            ws.setRightMargin("5");
        }
        if (!StringUtil.isNotNullEmptyStr(ws.getTopMargin())) {
            ws.setTopMargin("5");
        }
        if (!StringUtil.isNotNullEmptyStr(ws.getBottomMargin())) {
            ws.setBottomMargin("5");
        }
    } else {
        ws = new WordSet();
        if (!StringUtil.isNotNullEmptyStr(ws.getLeftMargin())) {
            ws.setLeftMargin("5");
        }
        if (!StringUtil.isNotNullEmptyStr(ws.getRightMargin())) {
            ws.setRightMargin("5");
        }
        if (!StringUtil.isNotNullEmptyStr(ws.getTopMargin())) {
            ws.setTopMargin("5");
        }
        if (!StringUtil.isNotNullEmptyStr(ws.getBottomMargin())) {
            ws.setBottomMargin("5");
        }
    }
    String address = list.get(0).getAddress1();
    if (address.length() > 10) {
        list.get(0).setAddress1(address.substring(0, 10));
        list.get(0).setAddress2(address.substring(10, address.length()));
    }
    JasperReport report = IReportReCompile.getJasperReport(
            request.getRealPath("/") + "/Report/carMoveLicence.jrxml", ws.getTopMargin(), ws.getBottomMargin(),
            ws.getLeftMargin(), ws.getRightMargin());
    JRDataSource dataSource = new JRBeanCollectionDataSource(list);
    JasperPrint jasperPrint = JasperFillManager.fillReport(report, map, dataSource);
    String path = FileUrl + fineName + ".pdf";
    JasperExportManager.exportReportToPdfFile(jasperPrint, path);
    response.getWriter()
            .write("{success:true,url:'" + path
                    .replace(request.getRealPath("/"),
                            "http://" + InetAddress.getLocalHost().getHostAddress() + ":"
                                    + request.getServerPort() + request.getContextPath() + "/")
                    .replace("\\", "\\\\") + "'}");
    System.out
            .println(path
                    .replace(request.getRealPath("/"),
                            "http://" + InetAddress.getLocalHost().getHostAddress() + ":"
                                    + request.getServerPort() + request.getContextPath() + "/")
                    .replace("\\", "\\\\"));
}