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:vn.webapp.controller.cp.ExamController.java

/**
 * Save a room//from w w w.j  a v  a  2s . c o  m
        
 */
@RequestMapping(value = "saveExam", method = RequestMethod.POST)
public String saveExam(HttpServletRequest request,
        @Valid @ModelAttribute("examAdd") ExamValidation examValidation, BindingResult result, Map model,
        HttpSession session) {
    /*
     * Get list of paper category and journalList
     */

    /*
     * Put data back to view
     */

    if (result.hasErrors()) {
        return "cp.addExam";
    } else {
        /*
         * Prepare data for inserting DB
         */

        /**
         * Uploading file
         */
        MultipartFile sourceUploadFile = examValidation.getExamFileUpload();
        String fileName = sourceUploadFile.getOriginalFilename();
        String sourceUploadFileSrc = "";
        String StatusMessages = "";
        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 + "/exam");
            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<ExamStatus> EXS_List = examStatusService.loadEXSList();
            boolean isToAdd = true;
            for (ExamStatus EXS : EXS_List) {
                if ((EXS.getEXS_AcaYear_Code().equals(examValidation.getAcademicYear()))
                        && (EXS.getEXS_Semester() == examValidation.getSemester())) {
                    isToAdd = false;
                    break;
                }
            }

            if (isToAdd)
                examStatusService.save(examValidation.getAcademicYear(), examValidation.getSemester(), 1);

            List<ExamInfo> examinfos = ReadExamInfos
                    .readFileExcel(dir.getAbsolutePath() + File.separator + fileName);
            int cnt = 0;
            try (DataOutputStream out = new DataOutputStream(
                    new FileOutputStream("examUploadStatus.bin", false))) {
                out.writeInt(examinfos.size());

                for (ExamInfo ei : examinfos) {
                    cnt++;
                    out.writeInt(cnt);
                    if (ei != null) {
                        String RCE_Code = examValidation.getAcademicYear() + "-" + examValidation.getSemester()
                                + "-" + ei.getClassCode() + "-" + ei.getGroup() + "-" + ei.getTurn() + "-"
                                + ei.getRoom();
                        Exam ex = examService.loadByCode(RCE_Code);
                        if (ex == null) {
                            examService.save(RCE_Code, examValidation.getAcademicYear(),
                                    examValidation.getSemester(), ei.getClassCode(), ei.getCourseCode(),
                                    ei.getCourseName(), Integer.parseInt(ei.getWeek()),
                                    Integer.parseInt(ei.getDay()), ei.getDate(), ei.getTurn(), ei.getSlots(),
                                    ei.getGroup(), ei.getRoom());
                        } else {
                            if (!((ex.getRCE_Date().equals(ei.getDate()))
                                    && (ex.getRCE_Day() == Integer.parseInt(ei.getDay()))
                                    && (ex.getRCE_Week() == Integer.parseInt(ei.getWeek()))
                                    && (ex.getRCE_Room_Code().equals(ei.getRoom())))) {
                                examService.edit(RCE_Code, examValidation.getAcademicYear(),
                                        examValidation.getSemester(), ei.getClassCode(), ei.getCourseCode(),
                                        ei.getCourseName(), Integer.parseInt(ei.getWeek()),
                                        Integer.parseInt(ei.getDay()), ei.getDate(), ei.getTurn(),
                                        ei.getSlots(), ei.getGroup(), ei.getRoom());
                                StatusMessages += "Cp nht thnh cng lp " + ex.getClass() + " nhm "
                                        + ex.getRCE_Group() + " thi\n";
                            }
                        }
                    }

                }
                StatusMessages += "Thm mi thnh cng " + cnt + " lp thi\n";
                model.put("status", StatusMessages);
                /**
                 * Preparing data for adding into DB
                 */

                //if(i_InsertAPaper > 0){
                //model.put("status", "Successfully saved a paper: ");
                //model.put("status",StatusMessages);
                System.out.println(StatusMessages);
                return "redirect:" + this.baseUrl + "/cp/Exams.html";
                //}
            } catch (Exception e) {
                model.put("status", "You failed to upload " + fileName + " => " + e.getMessage());
            }
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            try (DataOutputStream out = new DataOutputStream(
                    new FileOutputStream("examUploadStatus.bin", false))) {
            } catch (Exception e) {
            }
        }
        return "cp.addExam";
    }
}

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

/**
 * Save a room//from  ww w .java  2s. c  om
         
 */
@RequestMapping(value = "saveRoom", method = RequestMethod.POST)
public String saveRoom(HttpServletRequest request,
        @Valid @ModelAttribute("roomAdd") RoomValidation roomValidation, BindingResult result, Map model,
        HttpSession session) {
    /*
     * Get list of paper category and journalList
     */

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

        /**
         * Uploading file
         */
        MultipartFile sourceUploadFile = roomValidation.getRoomsUpload();
        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 + "/rooms");
            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();

            HustRoomData roomData = new HustRoomData();
            List<RoomInfo> roominfos = roomData
                    .readFileExcel(dir.getAbsolutePath() + File.separator + fileName);
            for (RoomInfo ri : roominfos) {
                RoomCluster roomCluster = roomClusterService.loadByCode(ri.getClusterID());
                Rooms r = roomsService.loadByCode(ri.getRoomCode());
                if (r == null)
                    roomsService.save(ri.getRoomCode(), ri.getBuilding(), ri.getCapacity(), ri.getNote(),
                            ri.getFloor(), roomCluster);
                else
                    roomsService.edit(r.getR_ID(), ri.getRoomCode(), ri.getBuilding(), ri.getCapacity(),
                            ri.getNote(), ri.getFloor(), roomCluster);
            }

            /**
             * Preparing data for adding into DB
             */

            //if(i_InsertAPaper > 0){
            //model.put("status", "Successfully saved a paper: ");
            return "redirect:" + this.baseUrl + "/cp/Rooms.html";
            //}
        } catch (Exception e) {
            model.put("status", "You failed to upload " + fileName + " => " + e.getMessage());
        }
        return "cp.rooms";
    }
}

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

@RequestMapping(value = "/OverlapExamListFromExcel", method = RequestMethod.POST)
public String overlapExamListFromExcel(HttpServletRequest request,
        @Valid @ModelAttribute("checkOverLapExam") FileValidation fileValidation, BindingResult result,
        Map model, HttpSession session) {
    /*/*from  w  w  w .  j  a v  a 2 s . c o  m*/
     * Get list of paper category and journalList
     */

    /*
     * Put data back to view
     */

    if (result.hasErrors()) {
        return "cp.checkOverLapExamFromExcel";
    } else {
        /*
         * Prepare data for inserting DB
         */

        /**
         * Uploading file
         */
        MultipartFile sourceUploadFile = fileValidation.getFileUpload();
        String fileName = sourceUploadFile.getOriginalFilename();
        String sourceUploadFileSrc = "";
        String StatusMessages = "";
        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 + "/exam");
            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();

            HashMap<String, ArrayList<String>> m = ReadExamInfos
                    .Exam2TimeMapping(dir.getAbsolutePath() + File.separator + fileName);
            AcademicYear curAcadYear = academicYearService.getCurAcadYear();
            List<RegularCourseTimetableInterface> RCTTI_List = regularCourseTimetableInterfaceService
                    .loadRCTTIList(curAcadYear.getACAYEAR_Code());

            HashSet<String> exWeekSet = new HashSet<String>();
            for (String key : m.keySet()) {
                exWeekSet.add(key.split("_")[1]);
            }

            for (RegularCourseTimetableInterface rCTTI : RCTTI_List) {
                List<String> weeks = StringConvert.ExpandToListString(rCTTI.getWeek());
                int day = rCTTI.getDay();
                String room = rCTTI.getRoom();
                String[] slots = StringConvert.Expand(rCTTI.getSlot()).split(",");
                int startTurn = 0, endTurn = 0;
                try {
                    startTurn = (Integer.parseInt(slots[0]) - 1) / 3 + 1;
                    endTurn = (Integer.parseInt(slots[slots.length - 1]) - 1) / 3 + 1;
                } catch (NumberFormatException e) {
                    startTurn = endTurn = 0;
                }
                for (String exWeek : exWeekSet) {
                    if (weeks.contains(exWeek)) {
                        for (int i = startTurn; i <= endTurn; i++) {
                            String key = room + "_" + exWeek + "_" + day + "_Kp " + i;
                            if (m.containsKey(key)) {
                                ArrayList<String> val = m.get(key);
                                val.add("Lp h?c: " + rCTTI.getClasscode() + " " + rCTTI.getCoursecode()
                                        + " " + rCTTI.getCoursename());
                            }
                        }
                    }
                }
            }

            ArrayList<OverlapExam> overlapExamList = new ArrayList<OverlapExam>();
            ArrayList<String> val = new ArrayList<String>();

            for (String key : m.keySet()) {
                val = m.get(key);
                if (val.size() >= 2) {
                    int ok = 0;
                    String code = "";
                    for (String ex : m.get(key)) {
                        String[] tks = ex.split(" ");
                        if (code.equals(""))
                            code = tks[2];
                        else {
                            if (!code.equals(tks[2])) {
                                ok = 1;
                                break;
                            }
                        }
                    }
                    if (ok == 1) {
                        OverlapExam ovlE = new OverlapExam();
                        ovlE.setClassExamLst(val);
                        ovlE.setOverlapTime(key);
                        overlapExamList.add(ovlE);
                    }
                }
            }
            System.out.println("Done " + overlapExamList.size());
            model.put("status", StatusMessages);
            model.put("overlapExamList", overlapExamList);
            System.out.println(StatusMessages);
        } catch (Exception e) {
            model.put("status", "You failed to upload " + fileName + " => " + e.getMessage());
        }
        return "cp.overlapExamList";
    }
}

From source file:org.gliderwiki.admin.PatchController.java

/**
 *   ? ? ?? . // w ww  . j a va  2s.c o m
 * @param request
 * @param response
 * @return
 * @throws Throwable
 */
@RequestMapping(value = "/admin/getPatch", method = RequestMethod.POST)
@ResponseBody
public JsonResponse getPatch(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    JsonResponse res = new JsonResponse();

    String functionIdx = request.getParameter("idx");
    String callUrl = request.getParameter("url");

    logger.debug("#### functionIdx : " + functionIdx);
    logger.debug("#### callUrl : " + callUrl);

    // Call URL  RestClient   . - ? we_patch  
    WePatch restVo = new WePatch();
    restVo.setWe_function_idx(Integer.parseInt(functionIdx));

    HttpEntity<WePatch> entity = new HttpEntity<WePatch>(restVo);
    String restUrl = REST_SERVER_URL + callUrl;
    ResponseEntity<WePatch> entityResponse = restTemplate.postForEntity(restUrl, entity, WePatch.class);

    //  ?  ? WePatch  . 
    // ? ,  ?,  ,  ??    . 
    WePatch patchVo = entityResponse.getBody();

    String filePath = patchVo.getWe_file_path();
    String fileName = patchVo.getWe_file_name();
    String localPath = patchVo.getWe_patch_path();
    String patchType = patchVo.getWe_patch_type(); //  ? ? ? Biz Logic ? . 

    String fullPath = filePath + "/" + fileName;

    //  ?   
    String listUrl = REST_SERVER_URL + fullPath;

    HttpClient httpClient = new DefaultHttpClient();

    //  ?  (jar?  WEB-INF / lib  ?.  ?, jsp? ?  
    ServletContext context = request.getServletContext();
    String destination = context.getRealPath(localPath) + "/" + fileName;

    logger.debug("##destination : " + destination);

    logger.debug("##listUrl : " + listUrl);

    // GliderWiki ?  ?  HttpClient   Stream ?. 
    HttpGet httpGet = new HttpGet(listUrl);

    HttpResponse httpResponse = httpClient.execute(httpGet);

    // httpEntity  Spring ??   full import . 
    org.apache.http.HttpEntity httpEntity = httpResponse.getEntity();

    // ? ? ?. 
    if (httpEntity != null) {

        try {
            FileOutputStream fos = new FileOutputStream(destination);
            httpEntity.writeTo(fos);
            fos.close();

            res.setResult(fileName);
            res.setStatus(ResponseStatus.SUCCESS);
        } catch (Exception e) {
            res.setResult(fileName);
            res.setStatus(ResponseStatus.FAIL);
            e.printStackTrace();
        }
    }
    logger.debug("#### res : " + res.toString());
    return res;
}

From source file:net.swas.explorer.servlet.ms.DeployResourceRules.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//*  w  w  w.j av  a 2s .  c o  m*/
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String ruleFileString = "";
    String resource = "";
    String fullResource = "";
    String userID = request.getParameter("userID");
    String resourceName = request.getParameter("resource");
    String status = "", msg = "";

    PrintWriter out = response.getWriter();
    JSONObject respJson = new JSONObject();
    JSONObject messageJson = new JSONObject();

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");

    if (FormFieldValidator.isLogin(request.getSession())) {
        List<Entity> ruleList = handler.getRuleByResource(resourceName, userID);
        DOProfile profile = new DOProfile(getServletContext());
        try {
            resource = profile.getUrlByResource(resourceName);
        } catch (SQLException e) {

            e.printStackTrace();
        }
        String[] resources = resource.split("/");
        for (int i = 3; i < resources.length; i++) {

            fullResource += "/" + resources[i];

        }

        log.info("Rule List size : " + ruleList.size());
        ruleFileString = "<location " + fullResource + ">\n";
        for (Entity entity : ruleList) {
            log.info("----------------->>>>> RULE");
            Rule rule = (Rule) entity;
            ruleFileString += ModSecTranslator.getRuleString(rule);
        }
        ruleFileString += "</location>";

        log.info("Rule String :\n" + ruleFileString);
        //produce message
        messageJson.put("action", "deployRules");
        messageJson.put("ruleString", ruleFileString);
        this.prod.send(messageJson.toJSONString());

        //consume message 
        String revMsg = this.cons.getReceivedMessage(request.getServletContext());
        log.info("Received Message :" + revMsg);
        if (revMsg != null) {

            JSONParser parser = new JSONParser();
            JSONObject revJson = null;
            try {

                revJson = (JSONObject) parser.parse(revMsg);
                respJson = revJson;

            } catch (ParseException e) {

                status = "1";
                msg = "Unable to reach modsercurity service. Please try later";
                e.printStackTrace();

            }

        } else {

            status = "1";
            msg = "Unable to reach modsercurity service. Please try later";
            log.info(">>>>>>>>>   Message is not received......");

        }

        if (!status.equals("")) {

            respJson.put("status", status);
            respJson.put("message", msg);

        }

    } else {
        status = "2";
        msg = "User Session Expired";
        respJson.put("status", status);
        respJson.put("message", msg);
    }

    try {
        log.info("Sending Json : " + respJson.toString());
        out.print(respJson.toString());
    } finally {
        out.close();
    }
}

From source file:com.dlshouwen.jspc.zwpc.controller.SelfEvaluateController.java

/**
 * ??/*ww w  .j  a va2 s.co  m*/
 *
 * @param expId
 * @param request 
 * @return AJAX?
 * @throws Exception 
 */
@RequestMapping(value = "/{expId}/getAllItems", method = RequestMethod.POST)
@ResponseBody
@Transactional
public AjaxResponse getAllItems(@PathVariable String expId, HttpServletRequest request) throws Exception {
    //          AJAX?
    AjaxResponse aresp = new AjaxResponse();

    //          ??
    List<EvalItem> evalItems = new ArrayList<EvalItem>();
    evalItems = dao.getAllByExpId(expId);

    //          
    List ET[] = new ArrayList[8];

    for (int i = 0; i < ET.length; i++) {
        ET[i] = new ArrayList<EvalItem>();
    }

    for (EvalItem item : evalItems) {
        if (item.getType().equals("JSYR")) {//
            ET[0].add(item);
        } else if (item.getType().equals("KCJX")) {//
            ET[1].add(item);
        } else if (item.getType().equals("JYJXYJ")) {//
            ET[2].add(item);
        } else if (item.getType().equals("YXL")) {//?
            ET[3].add(item);
        } else if (item.getType().equals("JYJXJL")) {//??
            ET[4].add(item);
        } else if (item.getType().equals("JXJYJL")) {//?
            ET[5].add(item);
        } else if (item.getType().equals("ZYJSZC")) {//?
            ET[6].add(item);
        } else if (item.getType().equals("QT")) {//
            ET[7].add(item);
        }
    }

    Map map = new HashMap();
    map.put("JSYR", getItemForHtml(ET[0], request.getServletContext()));
    map.put("KCJX", getItemForHtml(ET[1], request.getServletContext()));
    map.put("JYJXYJ", getItemForHtml(ET[2], request.getServletContext()));
    map.put("YXL", getItemForHtml(ET[3], request.getServletContext()));
    map.put("JYJXJL", getItemForHtml(ET[4], request.getServletContext()));
    map.put("JXJYJL", getItemForHtml(ET[5], request.getServletContext()));
    map.put("ZYJSZC", getItemForHtml(ET[6], request.getServletContext()));
    map.put("QT", getItemForHtml(ET[7], request.getServletContext()));
    aresp.setExtParam(map);
    aresp.setSuccess(true);
    aresp.setSuccessMessage("?");
    return aresp;
}

From source file:com.ccsna.safetynet.AdminNewsServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w w  w.j  av  a2 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();
        String smallUrl = "", largeUrl = "", message = "", title = "", content = "", startDate = "",
                endDate = "", newsType = "", st = "", endTime = "", startTime = "", fileType = null;
        Date sDate = null, eDate = null;
        Time eTime = null, sTime = null;
        String fullPath = null;
        int action = 0, newsId = 0;
        boolean dataValid = true;
        News news = null;
        Member loggedInMember = UserAuthenticator.loggedInUser(request.getSession());
        if (loggedInMember != null) {
            String home = "";
            String alertPage = "";
            if (loggedInMember.getRole().equals(Menu.MEMBER)) {
                home = "/pages/member.jsp";
                alertPage = "/pages/memberAlert.jsp";

            } else {
                home = "/pages/agencyAdmin.jsp";
                alertPage = "/pages/editAlert.jsp";

            }
            log.info("home page is : " + home);
            log.info("alert page is : " + alertPage);

            String createdBy = String.valueOf(loggedInMember.getMemberId());
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            log.info("isMultipart :" + isMultipart);
            if (isMultipart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                String appPath = request.getServletContext().getRealPath("");

                //String glassfishInstanceRootPropertyName = "com.sun.aas.instanceRoot";
                //String instanceRoot = System.getProperty(glassfishInstanceRootPropertyName) + "/applications/user-pix/";
                try {
                    List items = upload.parseRequest(request);
                    Iterator iterator = items.iterator();
                    while (iterator.hasNext()) {
                        FileItem item = (FileItem) iterator.next();
                        if (!item.isFormField()) {
                            //log.info("item is form field");
                            String fileName = item.getName();
                            //log.info("the name of the item is :" + fileName);
                            String contentType = item.getContentType();
                            //log.info("the content type is :" + contentType);
                            if (item.getContentType().equalsIgnoreCase(JPEG)
                                    || item.getContentType().equalsIgnoreCase(JPG)
                                    || item.getContentType().equalsIgnoreCase(PDF)) {
                                String root = appPath;
                                log.info("pdf content recognised");
                                log.info("root path is :" + appPath);
                                //String smallLoc = "/uploads/small";
                                String largeLoc = "/uploads/large";
                                log.info("largeLoc:" + largeLoc);
                                //File pathSmall = new File(root + smallLoc);
                                File pathLarge = new File(root + largeLoc);
                                //log.info("small image path :" + pathSmall);
                                log.info("large image path :" + pathLarge);
                                if (!pathLarge.exists()) {
                                    // boolean status = pathSmall.mkdirs();
                                    pathLarge.mkdirs();
                                }
                                if (item.getContentType().equalsIgnoreCase(PDF)) {
                                    log.info("loading pdf file");
                                    fileType = Menu.PDF;
                                    fileName = createdBy + "_" + System.currentTimeMillis() + "."
                                            + PDF_EXTENSION;

                                    //File uploadedFileSmall = new File(pathSmall + "/" + fileName);
                                    File uploadedFileLarge = new File(pathLarge + "/" + fileName);
                                    Menu.uploadPdfFile(item.getInputStream(), uploadedFileLarge);

                                } else {
                                    fileType = Menu.IMAGE;
                                    fileName = createdBy + "_" + System.currentTimeMillis() + "."
                                            + JPEG_EXTENSION;

                                    log.info("filename is : " + fileName);
                                    // File uploadedFileSmall = new File(pathSmall + "/" + fileName);
                                    File uploadedFileLarge = new File(pathLarge + "/" + fileName);
                                    //Menu.resizeImage(item.getInputStream(), 160, uploadedFileSmall);
                                    Menu.resizeImage(item.getInputStream(), 160, uploadedFileLarge);
                                }
                                //smallUrl = smallLoc + "/" + fileName + "";
                                largeUrl = largeLoc + "/" + fileName + "";
                                log.info("largeUrl image url is :" + largeUrl);
                                fullPath = request.getContextPath() + "/" + largeUrl;

                            }
                        } else {
                            if (item.getFieldName().equalsIgnoreCase("newsTitle")) {
                                title = item.getString();
                                log.info("title is :" + title);
                            }
                            if (item.getFieldName().equalsIgnoreCase("type")) {
                                newsType = item.getString();
                                log.info("newsType is :" + newsType);
                            }
                            if (item.getFieldName().equalsIgnoreCase("content")) {
                                content = item.getString();
                                log.info("content is :" + content);
                            }
                            if (item.getFieldName().equalsIgnoreCase("start_Date")) {
                                startDate = item.getString();
                                if (startDate != null && !startDate.isEmpty()) {
                                    sDate = Menu
                                            .convertDateToSqlDate(Menu.stringToDate(startDate, "yyyy-MM-dd"));
                                }
                                log.info("startDate is :" + startDate);
                            }
                            if (item.getFieldName().equalsIgnoreCase("end_Date")) {
                                endDate = item.getString();
                                if (endDate != null && !endDate.isEmpty()) {
                                    eDate = Menu.convertDateToSqlDate(Menu.stringToDate(endDate, "yyyy-MM-dd"));
                                }
                                log.info("endDate is :" + endDate);
                            }
                            if (item.getFieldName().equalsIgnoreCase("action")) {
                                action = Integer.parseInt(item.getString());
                                log.info("the action is :" + action);
                            }
                            if (item.getFieldName().equalsIgnoreCase("newsId")) {
                                newsId = Integer.parseInt(item.getString());
                                log.info("the newsid is :" + newsId);
                            }
                            if (item.getFieldName().equalsIgnoreCase("status")) {
                                st = item.getString();
                                log.info("the status is :" + st);
                            }
                            if (item.getFieldName().equalsIgnoreCase("end_Time")) {
                                endTime = item.getString();
                                if (endTime != null && !endTime.isEmpty()) {
                                    eTime = Menu.convertStringToSqlTime(endTime);
                                }
                                log.info("eTime is :" + eTime);

                            }

                            if (item.getFieldName().equalsIgnoreCase("start_Time")) {
                                startTime = item.getString();
                                if (startTime != null && !startTime.isEmpty()) {
                                    sTime = Menu.convertStringToSqlTime(startTime);
                                }
                                log.info("sTime is :" + sTime);

                            }
                        }
                    }
                } catch (FileUploadException e) {
                    e.printStackTrace();
                }
            }
            switch (Validation.Actions.values()[action]) {
            case CREATE:
                log.info("creating new serlvet ................");
                news = new NewsModel().addNews(title, newsType, content, sDate, eDate, new Date(), createdBy,
                        Menu.ACTIVE, largeUrl, fileType, fullPath);
                if (news != null) {
                    log.info("news successfully created...");
                    message += "News item has been successfully added";
                    Validation.setAttributes(request, Validation.SUCCESS, message);
                    response.sendRedirect(request.getContextPath() + home);
                } else {
                    log.info("news creating failed...");
                    message += "Unable to add news item";
                    Validation.setAttributes(request, Validation.ERROR, message);
                    response.sendRedirect(request.getContextPath() + home);
                }
                break;
            case UPDATE:
                log.info("updating news ...");
                if (title != null && !title.isEmpty()) {
                    news = new NewsModel().findByParameter("title", title);
                }

                if (news != null && (news.getNewsId() == newsId)) {
                    log.info("news is :" + news.getNewsId());
                    dataValid = true;
                } else {
                    dataValid = false;
                }
                if (news == null) {
                    dataValid = true;
                }

                log.info("dataValid is :" + dataValid);

                if (dataValid) {
                    boolean newsUpdated = new NewsModel().updateNews(newsId, title, newsType, content, sDate,
                            eDate, createdBy, st, largeUrl, smallUrl, sTime, eTime);
                    if (newsUpdated) {
                        message += "News/Alert has been successfully updated";
                        Validation.setAttributes(request, Validation.SUCCESS, message);
                        response.sendRedirect(request.getContextPath() + home);

                    } else {
                        message += "Unable to update news item";
                        Validation.setAttributes(request, Validation.ERROR, message);
                        response.sendRedirect(request.getContextPath() + alertPage + "?id=" + newsId);
                    }
                } else {
                    message += "News with same title already exist, Enter a different title";
                    Validation.setAttributes(request, Validation.ERROR, message);
                    response.sendRedirect(request.getContextPath() + alertPage + "?id=" + newsId);
                }
                break;
            }
        } else {
            message += "Session expired, Kindly login with username and password";
            Validation.setAttributes(request, Validation.ERROR, message);
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
    } catch (Exception e) {

    }

}

From source file:br.com.ifpb.bdnc.projeto.geo.servlets.CadastraImagem.java

private Image mountImage(HttpServletRequest request) {
    Image image = new Image();
    image.setCoord(new Coordenate());
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {//from w w  w  .ja va2s. co m
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    InputStream in = item.openStream();
                    byte[] b = new byte[in.available()];
                    in.read(b);
                    if (item.getFieldName().equals("description")) {
                        image.setDescription(new String(b));
                    } else if (item.getFieldName().equals("authors")) {
                        image.setAuthors(new String(b));
                    } else if (item.getFieldName().equals("end")) {
                        image.setDate(
                                LocalDate.parse(new String(b), DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                    } else if (item.getFieldName().equals("latitude")) {
                        image.getCoord().setLat(new String(b));
                    } else if (item.getFieldName().equals("longitude")) {
                        image.getCoord().setLng(new String(b));
                    } else if (item.getFieldName().equals("heading")) {
                        image.getCoord().setHeading(new String(b));
                    } else if (item.getFieldName().equals("pitch")) {
                        image.getCoord().setPitch(new String(b));
                    } else if (item.getFieldName().equals("zoom")) {
                        image.getCoord().setZoom(new String(b));
                    }
                } else {
                    if (!item.getName().equals("")) {
                        MultipartData md = new MultipartData();
                        String folder = "historicImages";
                        md.setFolder(folder);
                        String path = request.getServletContext().getRealPath("/");
                        System.out.println(path);
                        String nameToSave = "pubImage" + Calendar.getInstance().getTimeInMillis()
                                + item.getName();
                        image.setImagePath(folder + "/" + nameToSave);
                        md.saveImage(path, item, nameToSave);
                        String imageMinPath = folder + "/" + "min" + nameToSave;
                        RedimencionadorImagem.resize(path, folder + "/" + nameToSave,
                                path + "/" + imageMinPath.toString(), IMAGE_MIN_WIDTH, IMAGE_MIM_HEIGHT);
                        image.setMinImagePath(imageMinPath);
                    }
                }
            }
        } catch (FileUploadException | IOException ex) {
            System.out.println("Erro ao manipular dados");
        }
    }
    return image;
}

From source file:org.auraframework.impl.adapter.ServletUtilAdapterImpl.java

/**
 * Handle an exception in the servlet.//from   w w w. j  ava 2 s. com
 *
 * This routine should be called whenever an exception has surfaced to the top level of the servlet. It should not be
 * overridden unless Aura is entirely subsumed. Most special cases can be handled by the Aura user by implementing
 * {@link ExceptionAdapter ExceptionAdapter}.
 *
 * @param t the throwable to write out.
 * @param quickfix is this exception a valid quick-fix
 * @param context the aura context.
 * @param request the request.
 * @param response the response.
 * @param written true if we have started writing to the output stream.
 * @throws IOException if the output stream does.
 * @throws ServletException if send404 does (should not generally happen).
 */
@Override
public void handleServletException(Throwable t, boolean quickfix, AuraContext context,
        HttpServletRequest request, HttpServletResponse response, boolean written) throws IOException {
    try {
        Throwable mappedEx = t;
        boolean map = !quickfix;
        Format format = context.getFormat();

        //
        // This seems to fail, though the documentation implies that you can do
        // it.
        //
        // if (written && !response.isCommitted()) {
        // response.resetBuffer();
        // written = false;
        // }
        if (!written) {
            // Should we only delete for JSON?
            setNoCache(response);
        }
        if (mappedEx instanceof IOException) {
            //
            // Just re-throw IOExceptions.
            //
            throw (IOException) mappedEx;
        } else if (mappedEx instanceof NoAccessException) {
            Throwable cause = mappedEx.getCause();
            String denyMessage = mappedEx.getMessage();

            map = false;
            if (cause != null) {
                //
                // Note that the exception handler can remap the cause here.
                //
                cause = exceptionAdapter.handleException(cause);
                denyMessage += ": cause = " + cause.getMessage();
            }
            //
            // Is this correct?!?!?!
            //
            if (format != Format.JSON) {
                this.send404(request.getServletContext(), request, response);
                if (!isProductionMode(context.getMode())) {
                    // Preserve new lines and tabs in the stacktrace since this is directly being written on to the
                    // page
                    denyMessage = "<pre>" + AuraTextUtil.escapeForHTML(denyMessage) + "</pre>";
                    response.getWriter().println(denyMessage);
                }
                return;
            }
        } else if (mappedEx instanceof QuickFixException) {
            if (isProductionMode(context.getMode())) {
                //
                // In production environments, we want wrap the quick-fix. But be a little careful here.
                // We should never mark the top level as a quick-fix, because that means that we gack
                // on every mis-spelled app. In this case we simply send a 404 and bolt.
                //
                if (mappedEx instanceof DefinitionNotFoundException) {
                    DefinitionNotFoundException dnfe = (DefinitionNotFoundException) mappedEx;

                    if (dnfe.getDescriptor() != null
                            && dnfe.getDescriptor().equals(context.getApplicationDescriptor())) {
                        // We're in production and tried to hit an aura app that doesn't exist.
                        // just show the standard 404 page.
                        this.send404(request.getServletContext(), request, response);
                        return;
                    }
                }
                map = true;
                mappedEx = new AuraUnhandledException("404 Not Found (Application Error)", mappedEx);
            }
        }
        if (map) {
            mappedEx = exceptionAdapter.handleException(mappedEx);
        }

        PrintWriter out = response.getWriter();

        //
        // If we have written out data, We are kinda toast in this case.
        // We really want to roll it all back, but we can't, so we opt
        // for the best we can do. For HTML we can do nothing at all.
        //
        if (format == Format.JSON) {
            if (!written) {
                out.write(CSRF_PROTECT);
            }
            //
            // If an exception happened while we were emitting JSON, we want the
            // client to ignore the now-corrupt data structure. 404s and 500s
            // cause the client to prepend /*, so we can effectively erase the
            // bad data by appending a */ here and then serializing the exception
            // info.
            //
            out.write("*/");
            //
            // Unfortunately we can't do the following now. It might be possible
            // in some cases, but we don't want to go there unless we have to.
            //
        }
        if (format == Format.JS || format == Format.CSS) {
            // Make sure js and css doesn't get cached in browser, appcache, etc
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        }
        if (format == Format.JSON || format == Format.HTML || format == Format.JS || format == Format.CSS) {
            //
            // We only write out exceptions for HTML or JSON.
            // Seems bogus, but here it is.
            //
            // Start out by cleaning out some settings to ensure we don't
            // check too many things, leading to a circular failure. Note
            // that this is still a bit dangerous, as we seem to have a lot
            // of magic in the serializer.
            //
            // Clear the InstanceStack before trying to serialize the exception since the Throwable has likely
            // rendered the stack inaccurate, and may falsely trigger NoAccessExceptions.
            InstanceStack stack = this.contextService.getCurrentContext().getInstanceStack();
            List<String> list = stack.getStackInfo();
            for (int count = list.size(); count > 0; count--) {
                stack.popInstance(stack.peek());
            }

            serializationService.write(mappedEx, null, out);
            if (format == Format.JSON) {
                out.write("/*ERROR*/");
            }
        }
    } catch (IOException ioe) {
        throw ioe;
    } catch (Throwable death) {
        //
        // Catch any other exception and log it. This is actually kinda bad, because something has
        // gone horribly wrong. We should write out some sort of generic page other than a 404,
        // but at this point, it is unclear what we can do, as stuff is breaking right and left.
        //
        try {
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            exceptionAdapter.handleException(death);
            if (!isProductionMode(context.getMode())) {
                response.getWriter().println(death.getMessage());
            }
        } catch (IOException ioe) {
            throw ioe;
        } catch (Throwable doubleDeath) {
            // we are totally hosed.
            if (!isProductionMode(context.getMode())) {
                response.getWriter().println(doubleDeath.getMessage());
            }
        }
    } finally {
        this.contextService.endContext();
    }
}

From source file:org.o3project.odenos.remoteobject.rest.servlet.SubscriptionsServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession();

    // this "obj" separated for casting warning avoidance. 
    Object obj = session.getAttribute(Attributes.SUBSCRIPTION_TABLE);
    @SuppressWarnings("unchecked")
    Map<String, Set<String>> origTable = (Map<String, Set<String>>) obj;
    if (origTable == null) {
        this.logger.debug("A Subscription Table is not found. /{}", session.getId());
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;//w w  w  . j a v a  2s.  com
    }

    String reqBody = IOUtils.toString(req.getReader());
    Map<String, Set<String>> reqTable = this.deserialize(reqBody);
    if (reqTable == null) {
        this.logger.debug("Failed to deserialize the request body. /{}", reqBody);
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    Map<String, Collection<String>> addedMap = new HashMap<String, Collection<String>>();
    Map<String, Collection<String>> removedMap = new HashMap<String, Collection<String>>();

    for (Entry<String, Set<String>> reqEntry : reqTable.entrySet()) {
        String objectId = reqEntry.getKey();
        Set<String> reqEvents = reqEntry.getValue();

        Set<String> origEvents = origTable.get(objectId);
        if (origEvents == null) {
            // All events are unregistered yet.
            addedMap.put(objectId, reqEvents);
            origTable.put(objectId, reqEvents);
            continue;
        }

        // generating diff.
        @SuppressWarnings("unchecked")
        Collection<String> added = (Collection<String>) CollectionUtils.subtract(reqEvents, origEvents);
        addedMap.put(objectId, added);

        @SuppressWarnings("unchecked")
        Collection<String> removed = (Collection<String>) CollectionUtils.subtract(origEvents, reqEvents);
        removedMap.put(objectId, removed);
    }

    session.setAttribute(Attributes.SUBSCRIPTION_TABLE, reqTable);

    RESTTranslator translator = (RESTTranslator) req.getServletContext()
            .getAttribute(Attributes.REST_TRANSLATOR);
    translator.modifyDistributionSetting(this.subscriptionId, addedMap, removedMap);

    resp.setStatus(HttpServletResponse.SC_OK);
    resp.getWriter().write(toJsonStringFrom(reqTable));
}