Example usage for javax.servlet.http HttpServletRequest getServletContext

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

Introduction

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

Prototype

public ServletContext getServletContext();

Source Link

Document

Gets the servlet context to which this ServletRequest was last dispatched.

Usage

From source file:com.sundevils.web.controller.TopController.java

@RequestMapping(value = "/viewfile", method = RequestMethod.GET)
public @ResponseBody void downloadFiles(HttpServletRequest request, HttpServletResponse response,
        HttpSession session, String ssn) {
    String directorypath = "C:\\AppLogs\\";
    File folder = new File(directorypath);
    File[] listOfFiles = folder.listFiles();

    for (int i = 0; i < listOfFiles.length; i++) {
        String filepath = directorypath + "\\" + listOfFiles[i].getName();

        ServletContext context = request.getServletContext();
        File downloadFile = new File(filepath);
        FileInputStream inputStream = null;
        OutputStream outStream = null;

        try {//from   ww w  .j  av a  2  s .  c o m
            inputStream = new FileInputStream(downloadFile);

            response.setContentLength((int) downloadFile.length());
            response.setContentType(context.getMimeType(filepath));

            // response header
            String headerKey = "Content-Disposition";
            String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
            response.setHeader(headerKey, headerValue);

            // Write response
            outStream = response.getOutputStream();
            IOUtils.copy(inputStream, outStream);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != inputStream)
                    inputStream.close();
                if (null != inputStream)
                    outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}

From source file:vn.webapp.controller.cp.RegularTimetableController.java

@RequestMapping(value = "/CheckSlotNumFromExcelFile", method = RequestMethod.POST)
public String checkSlotNumFromExcelFile(HttpServletRequest request,
        @Valid @ModelAttribute("checkSlotNumFromExcel") FileValidation fileValidation, BindingResult result,
        Map model, HttpSession session) {
    /*/*from  ww w  .ja v a2  s.  co m*/
     * Get list of paper category and journalList
     */
    List<AcademicYear> academicYearList = academicYearService.list();
    model.put("academicYearList", academicYearList);

    /*
     * Put data back to view
     */
    if (result.hasErrors()) {
        return "cp.checkSlotNumFromExcel";
    } else {
        /*
         * Prepare data for inserting DB
         */

        /**
         * Uploading file
         */
        MultipartFile sourceUploadFile = fileValidation.getFileUpload();
        String fileName = sourceUploadFile.getOriginalFilename();
        String sourceUploadFileSrc = "";
        try {
            //Creating Date in java with today's date.
            Date currentDate = new Date();
            //change date into string yyyyMMdd format example "20110914"
            SimpleDateFormat dateformatyyyyMMdd = new SimpleDateFormat("HHmmssddMMyyyy");
            String sCurrentDate = dateformatyyyyMMdd.format(currentDate);

            byte[] bytes = sourceUploadFile.getBytes();
            String path = request.getServletContext().getRealPath("uploads");
            File dir = new File(path + "/regularTimetables");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create a file
            String currentUserName = session.getAttribute("currentUserName").toString();
            fileName = currentUserName + "_" + sCurrentDate + "_" + fileName;
            File serverFile = new File(dir.getAbsolutePath() + File.separator + fileName);
            if (serverFile.exists()) {
                sourceUploadFileSrc = dir.getAbsolutePath() + File.separator + fileName;
            }
            // Save data into file
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
            boolean isToAdd = true;
            ReadTimeTableExcelFormat2 obj = new ReadTimeTableExcelFormat2();
            obj.readFileExcel(dir.getAbsolutePath() + File.separator + fileName);
            ArrayList<ClassRoomWrapper> invalidSlotNumList = obj.invalidSlotNumList;
            model.put("invalidSlotNumList", invalidSlotNumList);
            System.out.println(invalidSlotNumList.size());
        } catch (Exception e) {
            e.printStackTrace();
            model.put("status", "You failed to upload " + fileName + " => " + e.getMessage());
        }

        return "cp.invalidSlotNumList";
    }
}

From source file:vn.webapp.controller.cp.RegularTimetableController.java

@RequestMapping(value = "/OverlapRoomList", method = RequestMethod.POST)
public String OverlapRoomList(HttpServletRequest request,
        @Valid @ModelAttribute("checkOverLapFromExcel") FileValidation fileValidation, BindingResult result,
        Map model, HttpSession session) {
    /*/*  w ww. j a  v a2s . c  o m*/
     * Get list of paper category and journalList
     */
    List<AcademicYear> academicYearList = academicYearService.list();
    model.put("academicYearList", academicYearList);

    /*
     * Put data back to view
     */
    if (result.hasErrors()) {
        return "cp.checkOverlapRoomFromExcel";
    } else {
        /*
         * Prepare data for inserting DB
         */

        /**
         * Uploading file
         */
        MultipartFile sourceUploadFile = fileValidation.getFileUpload();
        String fileName = sourceUploadFile.getOriginalFilename();
        String sourceUploadFileSrc = "";
        try {
            //Creating Date in java with today's date.
            Date currentDate = new Date();
            //change date into string yyyyMMdd format example "20110914"
            SimpleDateFormat dateformatyyyyMMdd = new SimpleDateFormat("HHmmssddMMyyyy");
            String sCurrentDate = dateformatyyyyMMdd.format(currentDate);

            byte[] bytes = sourceUploadFile.getBytes();
            String path = request.getServletContext().getRealPath("uploads");
            File dir = new File(path + "/regularTimetables");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create a file
            String currentUserName = session.getAttribute("currentUserName").toString();
            fileName = currentUserName + "_" + sCurrentDate + "_" + fileName;
            File serverFile = new File(dir.getAbsolutePath() + File.separator + fileName);
            if (serverFile.exists()) {
                sourceUploadFileSrc = dir.getAbsolutePath() + File.separator + fileName;
            }
            // Save data into file
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
            boolean isToAdd = true;
            ArrayList<OverlapRoom> overlapRooms = ReadTimeTableExcelFormat2
                    .CheckOverlap(dir.getAbsolutePath() + File.separator + fileName);
            System.out.println(overlapRooms);
            model.put("overlapRoomList", overlapRooms);
        } catch (Exception e) {
            e.printStackTrace();
            model.put("status", "You failed to upload " + fileName + " => " + e.getMessage());
        }

        return "cp.overlapRoomList";
    }
}

From source file:vn.webapp.controller.cp.RegularTimetableController.java

/**
 * Save a paper//w ww  .j a  va2s. com
 * @param paperValid
 * @param result
 * @param model
 * @param session
 * @return String
 */
@RequestMapping(value = "saveRegularTimetable", method = RequestMethod.POST)
public String saveRegularTimetable(HttpServletRequest request,
        @Valid @ModelAttribute("regularTimetableFormAdd") RegularTimetableValidation regularTimetableValidation,
        BindingResult result, Map model, HttpSession session) {
    List<AcademicYear> academicYearList = academicYearService.list();
    model.put("academicYearList", academicYearList);

    if (result.hasErrors()) {
        return "cp.addRegularTimetable";
    } else {
        /**
         * Uploading file
         */
        MultipartFile sourceUploadFile = regularTimetableValidation.getRegularTimetableFileUpload();
        String fileName = sourceUploadFile.getOriginalFilename();
        String sourceUploadFileSrc = "";
        try {
            //Creating Date in java with today's date.
            Date currentDate = new Date();
            //change date into string yyyyMMdd format example "20110914"
            SimpleDateFormat dateformatyyyyMMdd = new SimpleDateFormat("HHmmssddMMyyyy");
            String sCurrentDate = dateformatyyyyMMdd.format(currentDate);

            byte[] bytes = sourceUploadFile.getBytes();
            String path = request.getServletContext().getRealPath("uploads");
            File dir = new File(path + "/regularTimetables");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create a file
            String currentUserName = session.getAttribute("currentUserName").toString();
            fileName = currentUserName + "_" + sCurrentDate + "_" + fileName;
            File serverFile = new File(dir.getAbsolutePath() + File.separator + fileName);
            if (serverFile.exists()) {
                sourceUploadFileSrc = dir.getAbsolutePath() + File.separator + fileName;
            }
            // Save data into file
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();
            List<RegularCourseTimetableStatus> RCTTS_List = regularCourseTimetableStatusService.loadRCTTSList();
            boolean isToAdd = true;
            for (RegularCourseTimetableStatus RCTTS : RCTTS_List) {
                if ((RCTTS.getRCTTS_AcaYear_Code().equals(regularTimetableValidation.getAcademicYear()))
                        && (RCTTS.getRCTTS_Semester() == regularTimetableValidation.getSemester())) {
                    isToAdd = false;
                    break;
                }
            }
            if (isToAdd)
                regularCourseTimetableStatusService.save(regularTimetableValidation.getAcademicYear(),
                        regularTimetableValidation.getSemester(), 1);
            ArrayList<ClassRoom> classRooms = ReadTimeTableExcel
                    .readFileExcel(dir.getAbsolutePath() + File.separator + fileName);

            int err = 0;
            int rc = 0;
            int rctte = 0;
            ArrayList<String> error1 = new ArrayList<String>();
            ArrayList<String> error2 = new ArrayList<String>();
            ArrayList<String> error3 = new ArrayList<String>();
            ArrayList<String> error4 = new ArrayList<String>();
            int cnt = 0;
            String StatusMessages = "";

            try (DataOutputStream out = new DataOutputStream(
                    new FileOutputStream("regularTimeTableUploadStatus.bin", false))) {
                out.writeInt(classRooms.size());

                for (ClassRoom classroom : classRooms) {
                    cnt++;
                    out.writeInt(cnt);
                    System.out.println(cnt + ":" + classroom.getClassCode());
                    try {
                        String roomCode = classroom.getRoom();
                        String note = "";
                        String roomBuilding = "";
                        int clusterID = 5;
                        int cap = -1;
                        int floor = 0;
                        Rooms room = roomsService.loadByCode(roomCode);
                        if (room == null) {
                            String[] tokens = roomCode.split("-");
                            for (int i = 1; i < tokens.length - 1; i++)
                                tokens[0] += "-" + tokens[i];
                            switch (tokens[0]) {
                            case "D3":
                            case "D5":
                            case "D3-5":
                            case "D3,5":
                            case "D7":
                            case "D9":
                                clusterID = 1;
                                break;
                            case "D4":
                            case "D6":
                                clusterID = 2;
                                break;
                            case "TC":
                                clusterID = 3;
                                break;
                            case "T":
                                clusterID = 4;
                                break;
                            default:
                                clusterID = 5;
                                break;
                            }
                            roomBuilding = tokens[0];
                            try {
                                floor = Integer.parseInt(tokens[tokens.length - 1].substring(0, 1));
                            } catch (NumberFormatException e) {
                                floor = -1;
                            }
                            if (roomsService.save(roomCode, roomBuilding, cap, note, floor,
                                    roomClusterService.loadByCode(clusterID)) != 0) {
                                room = roomsService.loadByCode(roomCode);
                                StatusMessages += "<b>Cp nht thm phng: </b>" + room.getR_Code()
                                        + "<br/>";
                            } else {
                                err++;
                                error4.add(classroom.getClassCode() + ": cannot find or add "
                                        + classroom.getRoom());
                            }
                        }
                        /*      List<RegularCourseTimetableInterface> RCTTI_List = regularCourseTimetableInterfaceService.loadRCTTIList(regularTimetableValidation.getAcademicYear(),regularTimetableValidation.getSemester());
                        HashSet<String> classCodeSet=new HashSet<String>();
                        for(RegularCourseTimetableInterface rCTTI:RCTTI_List){
                         classCodeSet.add(rCTTI.getClasscode());
                        }
                         */
                        if (room != null) {
                            String tempRCTTECode = regularTimetableValidation.getAcademicYear() + "-"
                                    + regularTimetableValidation.getSemester() + "-" + classroom.getClassCode();
                            RegularCourse RC = regularCourseService.loadByCode(classroom.getCourseCode());
                            if (RC == null) {
                                rc++;
                                if (regularCourseService.save(classroom.getCourseCode(),
                                        classroom.getCourseName(), classroom.getSlotNum(),
                                        classroom.getFacultyCode()) == 0) {
                                    err++;
                                    error1.add(classroom.getCourseCode());
                                }
                                RC = regularCourseService.loadByCode(classroom.getCourseCode());
                            }

                            /*if(!classCodeSet.contains(classroom.getClassCode())){
                            if(regularCourseTimetableEntryService.save(regularTimetableValidation.getSemester(), classroom.getClassCode(), RC, tempRCTTECode, regularTimetableValidation.getAcademicYear(),classroom.getClassType(),classroom.getSemesterType(),"",classroom.getClassInfo(),classroom.getCourseInfo(),classroom.getClassStatus())==0){
                               err++;
                               error2.add(classroom.getClassCode());
                            }
                            } */
                            RegularCourseTimetableEntry rCTTE = regularCourseTimetableEntryService
                                    .loadRCTTEByCode(tempRCTTECode);

                            if (rCTTE == null) {
                                rctte++;
                                if (regularCourseTimetableEntryService.save(
                                        regularTimetableValidation.getSemester(), classroom.getClassCode(), RC,
                                        tempRCTTECode, regularTimetableValidation.getAcademicYear(),
                                        classroom.getClassType(), classroom.getSemesterType(), "",
                                        classroom.getClassInfo(), classroom.getCourseInfo(),
                                        classroom.getClassStatus()) == 0) {
                                    err++;
                                    error2.add(classroom.getClassCode());
                                } else {
                                    rCTTE = regularCourseTimetableEntryService.loadRCTTEByCode(tempRCTTECode);
                                }
                            }

                            int day = 0;
                            try {
                                day = Integer.parseInt(classroom.getDay());
                            } catch (NumberFormatException e) {
                                day = 0;
                            }
                            //System.out.println(classroom.getCourseCode() + " "+ classroom.getSlotNum());
                            RegularCourseTimetable rCTT = regularCourseTimetableService
                                    .loadByCode(rCTTE.getRCTTE_Code() + "-" + day);
                            if (rCTT == null) {
                                if (regularCourseTimetableService.save(day, classroom.getSlots(),
                                        classroom.getWeeks(), room.getR_Code(), rCTTE) == 0) {
                                    err++;
                                    error3.add(classroom.getCourseCode() + " " + classroom.getClassCode() + " "
                                            + classroom.getDay());
                                } else {
                                    //rCTT=regularCourseTimetableService.loadByCode(rCTTE.getRCTTE_Code()+"-"+day);
                                    //StatusMessages="Lp "+cnt+"/"+classRooms.size()+"<br/><b>Thm mi lp "+rCTTE.getRCTTE_Class_Code()+": </b><br/>"+"Tit "+classroom.getSlots()+" Th "+rCTT.getRCTT_Day()+" Tun "+classroom.getDay()+ " Phng "+classroom.getRoom()+"<br/>";
                                    //System.out.println("Thm mi lp "+rCTTE.getRCTTE_Class_Code());
                                    //model.put("status", StatusMessages);
                                }
                            } else {
                                if (!((rCTT.getRCTT_Day() == day)
                                        && (rCTT.getRCTT_Slots().equals(classroom.getSlots()))
                                        && (rCTT.getRCTT_Weeks().equals(classroom.getWeeks()))
                                        && (rCTT.getRCTT_Room_Code().equals(classroom.getRoom())))) {
                                    regularCourseTimetableService.edit(rCTT.getRCTT_ID(), day,
                                            classroom.getSlots(), classroom.getWeeks(), room.getR_Code(),
                                            rCTTE);
                                    //StatusMessages="Lp "+cnt+"/"+classRooms.size()+"<br/><b>Cp nht li lp "+rCTTE.getRCTTE_Class_Code()+": </b><br/>"+"Tit "+rCTT.getRCTT_Slots()+" Th "+rCTT.getRCTT_Day()+" Tun "+rCTT.getRCTT_Weeks()+ " Phng "+rCTT.getRCTT_Room_Code()+"<br/>";
                                    //rCTT=regularCourseTimetableService.loadByCode(rCTTE.getRCTTE_Code()+"-"+day);
                                    //StatusMessages+="===> Tit "+rCTT.getRCTT_Slots()+" Th "+rCTT.getRCTT_Day()+" Tun "+rCTT.getRCTT_Weeks()+ " Phng "+rCTT.getRCTT_Room_Code()+"<br/>";
                                    //System.out.println("Cp nht li lp "+rCTTE.getRCTTE_Class_Code());
                                    //model.put("status", StatusMessages);
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("M lp: " + classroom.getClassCode()
                                + " li khng nhp c d liu!");
                    }
                }
            } catch (FileNotFoundException e) {
                System.out.println(e.getMessage());
            } catch (IOException e) {
                System.out.println(e.getMessage());
            } finally {
                try (DataOutputStream out = new DataOutputStream(
                        new FileOutputStream("regularTimeTableUploadStatus.bin", false))) {
                } catch (Exception e) {

                }
            }
            model.put("status", StatusMessages);
            return "redirect:" + this.baseUrl + "/cp/RegularTimetables.html";
        } catch (Exception e) {
            e.printStackTrace();
            model.put("status", "You failed to upload " + fileName + " => " + e.getMessage());
        }

        return "cp.addRegularTimetable";
    }
}

From source file:eg.agrimarket.controller.ProductController.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from   www . jav a 2 s  .c  o  m*/
        PrintWriter out = response.getWriter();
        eg.agrimarket.model.pojo.Product product = new eg.agrimarket.model.pojo.Product();
        Product productJPA = new Product();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> it = items.iterator();

        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                byte[] image = item.get();
                if (image != null && image.length != 0) {
                    product.setImage(image);
                    productJPA.setImage(image);
                }
            } else {
                switch (item.getFieldName()) {
                case "name":
                    product.setName(item.getString());
                    productJPA.setName(item.getString());
                    System.out.println("name" + item.getString());
                    break;
                case "price":
                    product.setPrice(Float.valueOf(item.getString()));
                    productJPA.setPrice(Float.valueOf(item.getString()));
                    break;
                case "quantity":
                    product.setQuantity(Integer.valueOf(item.getString()));
                    productJPA.setQuantity(Integer.valueOf(item.getString()));
                    break;
                case "desc":
                    product.setDesc(item.getString());
                    productJPA.setDesc(item.getString());
                    System.out.println("desc: " + item.getString());
                    break;
                default:
                    Category category = new Category();
                    category.setId(Integer.valueOf(item.getString()));
                    product.setCategoryId(category);
                    productJPA.setCategoryId(category.getId());
                }
            }
        }

        ProductDao daoImp = new ProductDaoImp();
        boolean check = daoImp.addProduct(product);
        if (check) {
            List<Product> products = (List<Product>) request.getServletContext().getAttribute("products");
            if (products != null) {
                products.add(productJPA);
                request.getServletContext().setAttribute("products", products);

            }
            response.sendRedirect("http://" + request.getServerName() + ":" + request.getServerPort()
                    + "/AgriMarket/admin/getProducts?success=Successfully#header3-41");
        } else {
            response.sendRedirect("http://" + request.getServerName() + ":" + request.getServerPort()
                    + "/AgriMarket/admin/getProducts?status=Exist!#header3-41");
        }

    } catch (FileUploadException ex) {
        Logger.getLogger(ProductController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.dlshouwen.wzgl.servlet.UploadPic.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    String albumId = request.getParameter("albumId");
    //      String articleId = request.getParameter("articleId");
    String type = request.getParameter("albumFlag");
    //      String isFile = request.getParameter("isFile");
    //      String isVideo = request.getParameter("isVideo");
    PictureDao pictureDao = null;//  w w  w.j a va2s.  co  m
    try {
        pictureDao = (PictureDao) SpringUtils.getBean("pictureDao");
    } catch (Exception ex) {
        Logger.getLogger(UploadPic.class.getName()).log(Level.SEVERE, null, ex);
    }

    //    
    String tempPath = SysConfigLoader.getSystemConfig().getProperty("imageTemp", "C:\\files\\temp");
    //  
    File dirTempFile = new File(tempPath);
    if (!dirTempFile.exists()) {
        dirTempFile.mkdirs();
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(20 * 1024 * 1024); //5M     
    factory.setRepository(new File(tempPath)); //     
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    try {
        List items = upload.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            if (!item.isFormField()) {
                InputStream is = null;
                synchronized (this) {
                    try {
                        is = item.getInputStream();
                        JSONObject jobj = FileUploadClient.upFile(request, fileName, is);
                        String path = null;
                        if (null != jobj && jobj.getString("responseMessage").equals("OK")) {
                            if (StringUtils.isNotEmpty(jobj.getString("fpath"))) {
                                String sourceURL = AttributeUtils.getAttributeContent(
                                        request.getServletContext(), "source_webapp_file_postion");
                                path = sourceURL + jobj.getString("fpath");
                                //                                  filename = path.substring(path.lastIndexOf(File.separator) + 1);
                            }
                        }

                        if (albumId != null && albumId.trim().length() > 0) {
                            Picture pic = new Picture();
                            if (type != null) {
                                pic.setFlag(type);
                            }
                            pic.setPicture_name(fileName);
                            pic.setPath(path);
                            pic.setAlbum_id(albumId);
                            pic.setCreate_time(new Date());
                            SessionUser sessionUser = (SessionUser) request.getSession()
                                    .getAttribute(CONFIG.SESSION_USER);
                            String userName = sessionUser.getUser_name();
                            pic.setUser_name(userName);
                            pictureDao.insertPicture(pic);
                        }

                        String json = "{ \"state\": \"SUCCESS\",\"url\": \"" + path + "\",\"title\": \""
                                + fileName + "\",\"original\": \"" + fileName + "\"}";

                        response.setContentType("text/html;charset=utf-8");
                        response.setCharacterEncoding("UTF-8");
                        response.getWriter().print(json);
                    } catch (Exception ex) {
                        java.util.logging.Logger.getLogger(UploadPic.class.getName()).log(Level.SEVERE, null,
                                ex);
                    } finally {
                        if (is != null) {
                            is.close();
                        }
                    }
                }
            }
        }

    } catch (FileUploadException e) {
    }
}

From source file:SubirArchivoJSP.subirarchivojsp.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  w  w. j a v  a  2  s  . c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        /* TODO output your page here. You may use following sample code. */
        dir = getServletContext().getRealPath("/SubirArchivoJSP/img");
        HttpServletRequest respuesta = request;

        if (ServletFileUpload.isMultipartContent(request)) {

            FileItemFactory factory = new DiskFileItemFactory();

            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setSizeMax(5000 * 1024); // bytes

            List listUploadFiles = null;
            FileItem item = null;

            try {
                listUploadFiles = upload.parseRequest(request);

                Iterator it = listUploadFiles.iterator();
                while (it.hasNext()) {
                    item = (FileItem) it.next();
                    if (!item.isFormField()) {
                        if (item.getSize() > 0) {
                            nombre = item.getName();

                            File archivo = new File(dir, nombre);

                            item.write(archivo);
                            if (archivo.exists()) {
                                out.println("GUARDADO " + archivo.getAbsolutePath() + "</p>");
                            } else {
                                // nunca se llega a ejecutar
                                out.println(
                                        "FALLO AL GUARDAR. NO EXISTE " + archivo.getAbsolutePath() + "</p>");
                            }

                        }
                    } else {
                        // es un campo de formulario, podemos obtener clave y valor
                        String key = item.getFieldName();
                        String valor = item.getString();
                        respuesta.setAttribute(key, valor);
                    }
                }

            } catch (FileUploadException e) {
                out.println("Demasiado grande! <br>");
                e.printStackTrace();
            } catch (Exception e) {
                out.println("Ha ocurrido un error! <br>");
                e.printStackTrace();
            }
        }
        respuesta.setAttribute("foto", "/Servlet1/SubirArchivoJSP/img/" + nombre);
        out.print("hola");
        RequestDispatcher vista = request.getServletContext()
                .getRequestDispatcher("/SubirArchivoJSP/vista.jsp");
        vista.forward(respuesta, response);
    }
}

From source file:servlets.InsertTransferToken.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww w .  j a v a 2s .  co m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute("user");

    int destinationType = Integer.parseInt(request.getParameter("destinationType"));
    String amount = request.getParameter("ammount");
    String email = user.getEmail();
    String action = request.getParameter("action");

    if (amount.equals("")) {
        ArrayList<PageMessage> errors = new ArrayList();
        PageMessage e1 = new PageMessage();
        e1.setText(" obrigatrio a insero de um valor para a transferncia.");
        e1.setType("danger");
        errors.add(e1);
        session.setAttribute("messages", errors);
        response.sendRedirect("transaction.jsp");
    }

    Calendar cal = Calendar.getInstance();
    int mi = cal.get(Calendar.MILLISECOND);
    int code = (int) Math.abs((Math.random() * 1000) * mi);

    Calendar cal2 = Calendar.getInstance();
    int h = cal2.get(Calendar.HOUR_OF_DAY);
    int d = cal2.get(Calendar.DAY_OF_MONTH);
    int token = Math.abs((code * code * h) / (d));

    try {
        Email.sendToken(email, Integer.toString(token));
    } catch (EmailException ex) {
        internalError(session, response);
    }

    String accountToSend = null;

    if (destinationType == 1) {
        accountToSend = request.getParameter("same_account_number");
        request.setAttribute("same_account_number", accountToSend);
    } else {
        accountToSend = request.getParameter("other_account_number");
        String agencyToSend = request.getParameter("other_account_agency");
        String identifier = request.getParameter("identifier");

        if (accountToSend.equals("") || agencyToSend.equals("") || identifier.equals("")) {
            ArrayList<PageMessage> errors = new ArrayList();
            PageMessage e1 = new PageMessage();
            e1.setText("O formulrio est incompleto.");
            e1.setType("danger");
            errors.add(e1);
            session.setAttribute("messages", errors);
            response.sendRedirect("transaction.jsp");
        }

        request.setAttribute("other_account_number", accountToSend);
        request.setAttribute("other_account_agency", agencyToSend);
        request.setAttribute("identifier", identifier);
    }

    request.setAttribute("code", code);
    request.setAttribute("amount", amount);
    request.setAttribute("action", action);
    request.setAttribute("destinationType", destinationType);

    RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/insertToken.jsp");
    rd.forward(request, response);
}

From source file:org.mhi.servlets.adminManager.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException {

    ServiceQuery query = new ServiceQuery();
    ServiceUpdate update = new ServiceUpdate();
    ServiceDelete delete = new ServiceDelete();

    String sDelete = request.getParameter("delete");
    String sUpdate = request.getParameter("update");
    String sCreate = request.getParameter("create");
    String sUri = request.getRequestURI();

    boolean osp = false;
    boolean wsp = false;

    /* Create - Erstellen neuer Inhalte 
     ...................................
     *///www .ja va 2s .  c  o  m
    if (sCreate != null) {
        FileHandler fh = new FileHandler(request);

        /* Convert "on" "off" to boolean; */
        if (fh.getParameter("osp") != null) {
            if (fh.getParameter("osp").equals("on")) {
                osp = true;
            }
        }

        if (fh.getParameter("wsp") != null) {
            if (fh.getParameter("wsp").equals("on")) {
                wsp = true;
            }
        }
        switch (sCreate) {
        case "group":
            ArtMain main = new ArtMain();
            main.setName(fh.getParameter("group"));
            update.newGroup(main);

            request.getRequestDispatcher("/admin/creategroup.jsp").forward(request, response);
            break;
        case "ugroup":
            ArtMain artma = query.getGroupByID(Long.parseLong(fh.getParameter("mainGroup")));
            ArtCat artcat = new ArtCat();
            artcat.setMain(artma);
            artcat.setName(fh.getParameter("ugroup"));
            update.newCatGroup(artcat);

            request.getRequestDispatcher("/admin/creategroup.jsp").forward(request, response);
            break;
        case "article":
            ArtCat cat = query.getCatAListByID(Long.parseLong(fh.getParameter("selectCategory")));
            Article article = new Article();
            article.setCategory(cat);
            article.setTitel("Title 1");
            article.setText(fh.getParameter("article"));
            article.setOnlyStartPage(osp);
            article.setWithStartPage(wsp);
            article.setTimeStmp(new Date());
            update.newArticle(article);
            request.getRequestDispatcher("/admin/article").forward(request, response);
            break;
        case "gallery":
            ImgGallery gal = new ImgGallery();
            gal.setName(fh.getParameter("xs_gallery"));
            //gal.setDescription(fh.getParameter("xs_desc"));
            update.newGallery(gal);

            response.sendRedirect(request.getServletContext().getContextPath() + "/admin/gallery");
            break;
        case "category":
            if (fh.getParameter("gallery") != null && fh.getParameter("xs_category") != null
                    && fh.getFile("files") != null) {
                ImgGallery c_gal = query.getGalleryByID(Long.parseLong(fh.getParameter("gallery")));
                ImgCat c_cat = new ImgCat();
                c_cat.setName(fh.getParameter("xs_category"));
                //c_cat.setDescription(fh.getParameter("newDescription"));
                c_cat.setFileBlob(IOUtils.toByteArray(fh.getFile("files")));
                c_cat.setGallery(c_gal);
                update.newCategory(c_cat);
            }

            response.sendRedirect(request.getServletContext().getContextPath() + "/admin/category");
            break;
        default: /* Fehlermeldung */

        }
    }

    /**
     * For All Group Interactions
     */
    if (sUri.endsWith("/action")) {
        // Delete Group / Untergroup     
        if (sDelete != null) {
            if (request.getParameter("ugrp") != null) {
                delete.removeCatAList(query.getCatAListByID(Long.parseLong(sDelete)));
            } else {
                delete.removeGroup(query.getGroupByID(Long.valueOf(sDelete)));
            }
            request.getRequestDispatcher("/admin/creategroup.jsp").forward(request, response);
        }
        if (sUpdate != null) {
            FileHandler fh = new FileHandler(request);
            Article article = query.getArticleByID(Long.parseLong(sUpdate));
            article.setText(fh.getParameter("article"));
            update.updateArticle(article);
            response.sendRedirect("/z1/about");
        }
    }
}

From source file:com.tssa.cooperationBusiness.controller.CooperationController.java

@RequestMapping("/save")
@ResponseBody/*from w w w  . j  ava 2s . co  m*/
public ModelMap save(HttpServletRequest request, ModelMap map) {

    Users user = (Users) request.getSession().getAttribute("user");

    try {
        String cooperationCode = TSSAUtil.getCode("02", null);
        String cooperationName = request.getParameter("cooperationName");
        String tel1 = request.getParameter("tel1");
        String tel2 = request.getParameter("tel2");
        String cooperationType = request.getParameter("childTypeId");
        String address = request.getParameter("address");
        String businessLicense = request.getParameter("businessLicense");
        String account = request.getParameter("account");
        String pictureUrl = saveFile(request);
        String logoURL = saveLogoFile(request);

        String country = request.getParameter("country");
        String province = request.getParameter("province");
        String city = request.getParameter("city");

        String countryText = request.getParameter("countryText");
        String provinceText = request.getParameter("provinceText");
        String cityText = request.getParameter("cityText");
        String detailAddress = request.getParameter("detailAddressText");

        Date allianceDate = new Date();
        String operationUser = "";
        if (user != null) {
            operationUser = user.getUid();
        }

        // ???
        DetachedCriteriaTS<CooperationProductType> cooperTypeCriteria = new DetachedCriteriaTS<CooperationProductType>(
                CooperationProductType.class);
        if (cooperationType != null && !"".equals(cooperationType)) {
            cooperTypeCriteria.add(Restrictions.eq("typeCode", cooperationType));
        }
        CooperationProductType productType = cooperationProductTypeService.find(cooperTypeCriteria);

        CooperationBusiness cooperation = new CooperationBusiness();
        cooperation.setCooperCode(cooperationCode);
        cooperation.setCooperName(cooperationName);
        cooperation.setTel1(tel1);
        cooperation.setTel2(tel2);
        cooperation.setProductTypeId(productType);
        cooperation.setAddress(address);
        cooperation.setBusinessLicense(businessLicense);
        cooperation.setAccount(account);
        cooperation.setPictureUrl(pictureUrl);
        cooperation.setAllianceDate(allianceDate);
        cooperation.setVerificationState("01");
        cooperation.setOperationUser(operationUser);

        if (StringUtils.isBlank(logoURL)) {
            logoURL = request.getServletContext().getContextPath() + "/images/img2/default2.png";
        }

        cooperation.setLogoImageURL(logoURL);

        boolean resultFlag = cooperationService.cooperationSave(cooperation, country, province, city,
                countryText, provinceText, cityText, detailAddress);

        if (resultFlag) {
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("success", true);
            result.put("msg", "?");
            map.putAll(result);
        } else {
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("success", false);
            result.put("msg", "");
            map.putAll(result);
        }

        return map;

    } catch (Exception e) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", false);
        result.put("msg", "");
        map.putAll(result);
        LOG.error(e.getMessage(), e);
        return map;
    }
}