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.esd.cs.worker.WorkerController.java

/**
 * ?/* ww  w . ja v  a  2s  .c o m*/
 */
@RequestMapping(value = "/importworker", method = RequestMethod.POST)
public ModelAndView importworker(HttpServletRequest request, HttpServletResponse response,
        HttpSession session) {
    Integer userId = Integer.parseInt(session.getAttribute(Constants.USER_ID).toString());
    // ??????workerTemp?
    wtService.deleteByUserId(userId);
    logger.debug("importWorker:{}");
    // ?
    String upload = "upload";
    String workerFolder = "worker";
    String url = request.getServletContext().getRealPath("/");
    String upLoadPath = url + upload + File.separator + workerFolder + File.separator;
    File uploadPath = new File(url + "upload");
    File tempPath = new File(uploadPath + File.separator + workerFolder);
    //  
    if (!uploadPath.exists()) {
        logger.debug(upload + " Does not exist,Create " + upload + " Folder");
        uploadPath.mkdir();
    }
    if (!tempPath.exists()) {
        logger.debug(workerFolder + " Does not exist,Create " + workerFolder + " Folder");
        tempPath.mkdir();
    }

    // 
    Map<String, String> paramMap = importfile(upLoadPath, request, response);
    String fileError = paramMap.get("fileError");// ?
    if (fileError != null) {
        // ?
        request.setAttribute("errorInfo", fileError);
        return new ModelAndView("basicInfo/worker_importInfo");
    }
    // ??
    String filePath = paramMap.get("filePath");// 
    Integer companyId = Integer.valueOf(paramMap.get("companyId"));// companyID
    String year = paramMap.get("year");// 
    AuditParameter auditParameter = auditParameterService.getByYear(year);
    // ??

    // List<Worker> workerErrorList = new ArrayList<Worker>();// ?
    // List<Worker> workerCorrectList = new ArrayList<Worker>();// ?
    List<Worker> list = null;

    if (fileError == null) {
        try {
            File f = new File(filePath);
            // ?excel
            list = WorkerUtil.parse(f, 0);
            // ??
            workerCount = list.size();
            if (list == null || list.size() <= 0) {
                // excel??
                logger.error("importWorkerError:{}", WORDERROR);
                request.setAttribute("errorInfo", WORDERROR);
                // ??
                return new ModelAndView("basicInfo/worker_importInfo");
            }
            for (int i = 0; i < list.size(); i++) {
                // 
                WorkerTemp t = new WorkerTemp();
                t.setUserId(userId);
                // false--????
                t.setIsOk(false);
                Worker w = null;
                // ??
                currentCount = i + 1;
                try {
                    Worker worker = list.get(i);
                    // 
                    String workerHandicapCode = worker.getWorkerHandicapCode();
                    // ??
                    String workerName = worker.getWorkerName().replace(" ", "");// 
                    w = new Worker();
                    w.setWorkerName(worker.getWorkerName());
                    w.setWorkerHandicapCode(workerHandicapCode);
                    // 
                    t.setWorkerName(workerName);
                    t.setWorkerHandicapCode(workerHandicapCode);
                    // 1.???
                    if (StringUtils.isEmpty(workerName) || StringUtils.equals(workerName, "null")) {
                        // ?
                        w.setRemark(NAMENULL);
                        // workerErrorList.add(w);
                        t.setRemark(NAMENULL);
                        wtService.save(t);
                        logger.error("impoerWorkerError:{},info:{}", w, NAMENULL);
                        continue;
                    }
                    // 2.??
                    if (workerName.length() > 20) {
                        // ?
                        w.setRemark("???");
                        // workerErrorList.add(w);
                        t.setRemark("???");
                        wtService.save(t);
                        logger.error("impoerWorkerError:{},info:{}", w, "???");
                        continue;
                    }
                    // 3.???
                    if (StringUtils.isBlank(workerHandicapCode)
                            || StringUtils.equals(workerHandicapCode, "null")) {
                        // ?
                        w.setRemark(LENGTHERROR);
                        // workerErrorList.add(w);
                        t.setRemark(LENGTHERROR);
                        wtService.save(t);
                        logger.error("impoerWorkerError:{},info:{}", w, LENGTHERROR);
                        continue;
                    }
                    // ??
                    workerHandicapCode.replace(" ", "");// 
                    // 4.??
                    if (workerHandicapCode.length() < MIN_HANDICAPCODE
                            || workerHandicapCode.length() > MAX_HANDICAPCODE) {
                        // ?
                        w.setRemark(LENGTHERROR);
                        // workerErrorList.add(w);
                        t.setRemark(LENGTHERROR);
                        wtService.save(t);
                        logger.error("impoerWorkerError:{},info:{}", w, LENGTHERROR);
                        continue;
                    }
                    // 5.????
                    if (CommonUtil.chineseValid(workerHandicapCode)) {
                        // ?
                        w.setRemark(ILLEGALSTR);
                        // workerErrorList.add(w);
                        t.setRemark(ILLEGALSTR);
                        wtService.save(t);
                        logger.error("impoerWorkerError:{},info:{}", w, LENGTHERROR);
                        continue;
                    }
                    // 6.20??
                    String handicapStr = workerHandicapCode.substring(0, 19);
                    if (!handicapStr.matches("\\d+")) {
                        w.setRemark("???20??");
                        // workerErrorList.add(w);
                        t.setRemark("???20??");
                        wtService.save(t);
                        logger.error("impoerWorkerError:{},info:{}", w, TYPEERROR);
                        continue;
                    }
                    // 7.
                    String handicapTypeStr = workerHandicapCode.substring(18, 19);
                    boolean ishandicapType = handicapTypeStr.matches("\\d+");// true,??
                    // 8.?
                    if (ishandicapType) {
                        int handicapType = Integer.valueOf(handicapTypeStr);
                        if (handicapType > 7 || handicapType == 0) {
                            w.setRemark(TYPEERROR);
                            // workerErrorList.add(w);
                            t.setRemark(TYPEERROR);
                            wtService.save(t);
                            logger.error("impoerWorkerError:{},info:{}", w, TYPEERROR);
                            continue;
                        }
                    }

                    // 9.??
                    String handicapLevelStr = workerHandicapCode.substring(19, 20);
                    boolean ishandicapLevel = handicapLevelStr.matches("\\d+");// true,??
                    if (ishandicapLevel) {
                        int handicapLevel = Integer.valueOf(handicapLevelStr);
                        if (handicapLevel > 4 || handicapLevel == 0) {
                            w.setRemark(LEVELERROR);
                            // workerErrorList.add(w);
                            t.setRemark(LEVELERROR);
                            wtService.save(t);
                            logger.error("impoerWorkerError:{},info:{}", w, LEVELERROR);
                            continue;
                        }
                    }

                    // 10.?
                    List<String> ageResult = new WorkerUtil().ageVerifi(workerHandicapCode, auditParameter);
                    if (ageResult != null) {
                        String ageErrorInfo = "" + ageResult.get(0).toString()
                                + "," + ageResult.get(1).toString() + ""
                                + ageResult.get(2).toString();
                        w.setRemark(ageErrorInfo);
                        // workerErrorList.add(w);
                        t.setRemark(ageErrorInfo);
                        wtService.save(t);
                        logger.error("impoerWorkerError:{},info:{}", w, ageErrorInfo);
                        continue;
                    }

                    // 11.????
                    List<Map<String, String>> validateList = validateOrganizationCode(
                            workerHandicapCode.substring(0, 18), year);
                    Map<String, String> validateResult = validateList.get(0);
                    logger.debug("LineNumber:{},validataType:{}", i, validateResult.get("type"));
                    // 12.? ?
                    if (StringUtils.equals(validateResult.get("type"), "1")) {
                        // ?
                        String errinfo = "?" + validateList.get(1).get("companyName")
                                + " ?????"
                                + validateList.get(1).get("companyCode");
                        w.setRemark(errinfo);
                        // workerErrorList.add(w);
                        t.setRemark(errinfo);
                        wtService.save(t);
                        logger.error("impoerWorkerError:{},info:{}", w, errinfo);
                        continue;
                    }
                    // .???? ? ??
                    if (StringUtils.equals(validateResult.get("type"), "2")
                            || StringUtils.equals(validateResult.get("type"), "3")) {
                        Worker workerUp = new Worker();
                        workerUp.setWorkerName(worker.getWorkerName());
                        workerUp.setWorkerHandicapCode(workerHandicapCode);

                        Worker workerCorrect = WorkerUtil.assembly(workerUp);
                        // workerCorrectList.add(workerCorrect);
                        // ??? 
                        t.setWorkerName(workerCorrect.getWorkerName());
                        t.setWorkerHandicapCode(workerCorrect.getWorkerHandicapCode());
                        t.setIsOk(true);
                        t.setWorkerBirth(workerCorrect.getWorkerBirth());
                        t.setWorkerBirthYear(workerCorrect.getWorkerBirthYear());
                        t.setWorkerGender(workerCorrect.getWorkerGender());
                        t.setWorkerHandicapLevel(workerCorrect.getWorkerHandicapLevel().getId());
                        t.setWorkerHandicapType(workerCorrect.getWorkerHandicapType().getId());
                        t.setWorkerIdCard(workerCorrect.getWorkerIdCard());
                        // , ??, ?id??
                        if (StringUtils.equals(validateResult.get("type"), "2")) {
                            t.setPreId(Integer.parseInt(validateResult.get("workerId").toString()));
                        }
                        wtService.save(t);
                        continue;
                    }
                } catch (Exception e) {
                    w.setRemark("");
                    // workerErrorList.add(w);
                    t.setRemark("");
                    wtService.save(t);
                    logger.error("impoerWorkerUpError:{}", "false");
                }
            }
            // ?

            // ??
            List<WorkerTemp> workerErrorList = wtService.getByCheck(false, userId);// ?
            if (workerErrorList.size() != 0) {
                String errorFilePath = upLoadPath + companyId + ".xls";
                // ??
                if (PoiCreateExcel.createExcel(errorFilePath, workerErrorList)) {
                    logger.debug("upLoadErrorListCreateSuccess!");
                    String destPath = request.getLocalAddr() + ":" + request.getLocalPort()
                            + request.getContextPath();
                    // ?
                    request.setAttribute("errorFilePath", "http://" + destPath + "/" + upload + "/"
                            + workerFolder + "/" + companyId + ".xls");//
                } else {
                    logger.error("upLoadErrorListCreateError");
                    request.setAttribute("errorInfo", CREATEERRORFILE);
                }
            }
            // 
            f.delete();

            // int totalLength = wtService.getCountByCheck(null, userId,
            // null);
            // int succesLength = wtService.getCountByCheck(true, userId,
            // null);
            // int errorLength = totalLength - succesLength;
            int totalLength = 0;
            int succesLength = 0;
            int errorLength = 0;
            // ??
            if (workerErrorList != null) {
                errorLength = workerErrorList.size();
            }
            // // ??
            if (list != null) {
                totalLength = list.size();
                succesLength = totalLength - errorLength;
            }
            request.setAttribute("totalLength", totalLength);// ?
            request.setAttribute("errorLength", errorLength);// ?
            request.setAttribute("succesLength", succesLength);// ??
            // request.setAttribute("workerCorrectList", workerCorrectList);
            // //?, ???
            // // ??
            request.setAttribute("errorInfo", "null");// ??
            request.setAttribute("companyId", companyId);// ??iD
            request.setAttribute("year", year);// 

            logger.debug("totalLength:{}", totalLength);// ?
            logger.debug("errorLength:{}", errorLength);// ?
            logger.debug("succesLength:{}", succesLength);// ??

            // ?
            list.clear();
            list = null;
            workerErrorList.clear();// ?
            workerErrorList = null;

        } catch (IllegalStateException e) {
            e.printStackTrace();
            logger.error("importWorkerError:{}", e.getMessage());
        } catch (IOException e) {
            logger.error("importWorkerError:{}", e.getMessage());
        }
    }

    // ??
    return new ModelAndView("basicInfo/worker_importInfo");
}

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

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//*from w  w  w.  j  a v a2 s .  c om*/
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String[] ruleIDs = request.getParameter("ruleID").split(",");
    String ruleFileString = "";
    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())) {
        //get the rule file string 
        for (String ruleID : ruleIDs) {

            log.info(" RuleID :  " + ruleID);
            if (ruleID.split("\\.")[0].equals("Rule")) {

                log.info("----------------->>>>> RULE");
                Rule rule = (Rule) rulehandler.get(ruleID.split("\\.")[1]);
                ruleFileString += ModSecTranslator.getRuleString(rule);

            } else {

                log.info("----------------->>>>> CHAIN RULE");
                ChainRule chainRule = (ChainRule) chRuleHandler.get(ruleID.split("\\.")[1]);
                ruleFileString += ModSecTranslator.getRuleString(chainRule);

            }

        }

        //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:net.swas.explorer.servlet.ms.DeployRuleGroup.java

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

    String groupName = request.getParameter("groupName");
    String ruleFileString = "";
    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())) {
        //get the rule file string 
        List<Entity> ruleList = rulehandler.getRuleByGroup(groupName);

        for (Entity entity : ruleList) {
            log.info("Entity : " + entity.toString());

            Rule simpleRule = null;
            ChainRule chainRule = null;
            if (entity instanceof Rule) {
                simpleRule = (Rule) entity;
                ruleFileString += ModSecTranslator.getRuleString(simpleRule);
            } else if (entity instanceof ChainRule) {
                chainRule = (ChainRule) entity;
                ruleFileString += ModSecTranslator.getRuleString(chainRule);
            }
        }

        //produce message
        messageJson.put("action", "deployRules");
        messageJson.put("groupName", groupName);
        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:cdc.util.Upload.java

public boolean anexos(HttpServletRequest request) throws Exception {
    request.setCharacterEncoding("ISO-8859-1");
    if (ServletFileUpload.isMultipartContent(request)) {
        int cont = 0;
        ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
        List fileItemsList = null;
        try {/*w  ww.jav a  2 s  .c o m*/
            fileItemsList = servletFileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        String optionalFileName = "";
        FileItem fileItem = null;
        Iterator it = fileItemsList.iterator();
        do {
            //cont++;
            FileItem fileItemTemp = (FileItem) it.next();
            if (fileItemTemp.isFormField()) {
                if (fileItemTemp.getFieldName().equals("file")) {
                    optionalFileName = fileItemTemp.getString();
                }
                parametros.put(fileItemTemp.getFieldName(), fileItemTemp.getString());
            } else {
                fileItem = fileItemTemp;
            }
            if (cont != (fileItemsList.size())) {
                if (fileItem != null) {
                    String fileName = fileItem.getName();
                    if (fileItem.getSize() > 0) {
                        if (optionalFileName.trim().equals("")) {
                            fileName = FilenameUtils.getName(fileName);
                        } else {
                            fileName = optionalFileName;
                        }
                        String dirName = request.getServletContext().getRealPath(pasta);
                        File saveTo = new File(dirName + "/" + fileName);
                        //verificando se a pasta existe. Caso contrrio, criar ela
                        File pasta = new File(dirName);
                        if (!pasta.exists())
                            pasta.mkdirs();//criando a pasta

                        parametros.put("foto", fileName);

                        try {
                            fileItem.write(saveTo);//Escrevendo o arquivo temporrio no diretrio correto
                        } catch (Exception e) {
                        }
                    }
                }
            }
            cont++;
        } while (it.hasNext());
        return true;
    } else {
        return false;
    }
}

From source file:com.arcadian.loginservlet.CourseContentServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }//from ww  w .  ja v  a 2 s . co m
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        String materialid = "";
        String materialname = "";
        String subjectid = "";
        String classname = "";
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();
            if (fileItem.isFormField()) {

                String name = fileItem.getFieldName();
                System.out.println(name);

                String value = fileItem.getString();
                System.out.println(value);

                if (name.equalsIgnoreCase("materialid")) {
                    materialid = value;
                }
                if (name.equalsIgnoreCase("materialname")) {
                    materialname = value;
                }
                if (name.equalsIgnoreCase("subjectid")) {
                    subjectid = value;
                }
                if (name.equalsIgnoreCase("semname")) {
                    classname = value;
                }

            }

            if (fileItem.getName() != null) {

                File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                        + fileItem.getName());
                System.out.println("Absolute Path at server=" + file.getAbsolutePath());
                fileItem.write(file);

                contentService = new CourseContentService();
                contentService.updatecoursematerial(materialid, materialname, classname, subjectid, username,
                        fileItem.getName());
            }
        }

    } catch (FileUploadException e) {
        System.out.println("Exception in file upload" + e);
    } catch (Exception ex) {
        Logger.getLogger(CourseContentServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    processRequest(request, response);

}

From source file:com.arcadian.loginservlet.LecturesServlet.java

/**
 * Handles the HTTP//from   w  w  w  .j a v  a 2 s.  co m
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        String lectureid = "";
        String lecturename = "";
        String subjectid = "";
        String classname = "";
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();
            if (fileItem.isFormField()) {

                String name = fileItem.getFieldName();
                System.out.println(name);

                String value = fileItem.getString();
                System.out.println(value);

                if (name.equalsIgnoreCase("lectureid")) {
                    lectureid = value;
                }
                if (name.equalsIgnoreCase("lecturename")) {
                    lecturename = value;
                }
                if (name.equalsIgnoreCase("subjectid")) {
                    subjectid = value;
                }
                if (name.equalsIgnoreCase("semname")) {
                    classname = value;
                }

            }

            if (fileItem.getName() != null) {

                File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                        + fileItem.getName());
                System.out.println("Absolute Path at server=" + file.getAbsolutePath());
                fileItem.write(file);

                lecturesService = new LecturesService();
                lecturesService.updateLectures(lectureid, lecturename, classname, subjectid, username,
                        fileItem.getName());
            }
        }

    } catch (FileUploadException e) {
        System.out.println("Exception in file upload" + e);
    } catch (Exception ex) {
        Logger.getLogger(CourseContentServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    processRequest(request, response);
}

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

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

    request.setCharacterEncoding("UTF-8");

    // Service Class for DB - Actions
    ServiceQuery query = new ServiceQuery();
    ServiceUpdate update = new ServiceUpdate();

    String imgName = request.getParameter("name");
    String imgDesc = request.getParameter("desc");
    String imgCat = request.getParameter("category");
    String fileSize = null;// www.jav a  2 s . co  m
    String fileName = null;
    String contentType = null;
    String[] parts = null;

    InputStream inputStream = null; // input stream of the upload file

    // obtains the upload file part in this multipart request
    Part filePart = request.getPart("files");

    if (filePart != null) {
        // Fill up Information extract from File
        fileSize = "" + filePart.getSize();
        parts = filePart.getSubmittedFileName().split("\\.");
        contentType = filePart.getContentType();

        // obtains input stream of the upload file
        inputStream = filePart.getInputStream();

        // new Image
        Images img = new Images();
        // Set Parameters
        img.setFileName(imgName + "." + parts[1]);
        img.setName(imgName);
        img.setDescription(imgDesc);
        img.setFileBlob(IOUtils.toByteArray(inputStream));
        img.setFileSize(fileSize);
        img.setcTyp(contentType);
        // Relationship to Category
        ImgCat cat = query.getCategoryByID(Long.valueOf(imgCat));
        img.setCategory(cat);
        // Persist to Database
        update.insertImage(img);
    }
    response.sendRedirect(request.getServletContext().getContextPath() + "/admin/upload");

}

From source file:com.joseflavio.uxiamarelo.servlet.UxiAmareloServlet.java

@Override
protected void doPost(HttpServletRequest requisicao, HttpServletResponse resposta)
        throws ServletException, IOException {

    String tipo = requisicao.getContentType();
    if (tipo == null || tipo.isEmpty())
        tipo = "text/plain";

    String codificacao = requisicao.getCharacterEncoding();
    if (codificacao == null || codificacao.isEmpty())
        codificacao = "UTF-8";

    resposta.setCharacterEncoding(codificacao);
    PrintWriter saida = resposta.getWriter();

    try {//from ww  w .  ja  v a  2s.co m

        JSON json;

        if (tipo.contains("json")) {
            json = new JSON(IOUtils.toString(requisicao.getInputStream(), codificacao));
        } else {
            json = new JSON();
        }

        Enumeration<String> parametros = requisicao.getParameterNames();

        while (parametros.hasMoreElements()) {
            String chave = parametros.nextElement();
            String valor = URLDecoder.decode(requisicao.getParameter(chave), codificacao);
            json.put(chave, valor);
        }

        if (tipo.contains("multipart")) {

            Collection<Part> arquivos = requisicao.getParts();

            if (!arquivos.isEmpty()) {

                File diretorio = new File(uxiAmarelo.getDiretorio());

                if (!diretorio.isAbsolute()) {
                    diretorio = new File(requisicao.getServletContext().getRealPath("") + File.separator
                            + uxiAmarelo.getDiretorio());
                }

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

                String diretorioStr = diretorio.getAbsolutePath();

                String url = uxiAmarelo.getDiretorioURL();

                if (uxiAmarelo.isDiretorioURLRelativo()) {
                    String url_esquema = requisicao.getScheme();
                    String url_servidor = requisicao.getServerName();
                    int url_porta = requisicao.getServerPort();
                    String url_contexto = requisicao.getContextPath();
                    url = url_esquema + "://" + url_servidor + ":" + url_porta + url_contexto + "/" + url;
                }

                if (url.charAt(url.length() - 1) == '/') {
                    url = url.substring(0, url.length() - 1);
                }

                Map<String, List<JSON>> mapa_arquivos = new HashMap<>();

                for (Part arquivo : arquivos) {

                    String chave = arquivo.getName();
                    String nome_original = getNome(arquivo, codificacao);
                    String nome = nome_original;

                    if (nome == null || nome.isEmpty()) {
                        try (InputStream is = arquivo.getInputStream()) {
                            String valor = IOUtils.toString(is, codificacao);
                            valor = URLDecoder.decode(valor, codificacao);
                            json.put(chave, valor);
                            continue;
                        }
                    }

                    if (uxiAmarelo.getArquivoNome().equals("uuid")) {
                        nome = UUID.randomUUID().toString();
                    }

                    while (new File(diretorioStr + File.separator + nome).exists()) {
                        nome = UUID.randomUUID().toString();
                    }

                    arquivo.write(diretorioStr + File.separator + nome);

                    List<JSON> lista = mapa_arquivos.get(chave);

                    if (lista == null) {
                        lista = new LinkedList<>();
                        mapa_arquivos.put(chave, lista);
                    }

                    lista.add((JSON) new JSON().put("nome", nome_original).put("endereco", url + "/" + nome));

                }

                for (Entry<String, List<JSON>> entrada : mapa_arquivos.entrySet()) {
                    List<JSON> lista = entrada.getValue();
                    if (lista.size() > 1) {
                        json.put(entrada.getKey(), lista);
                    } else {
                        json.put(entrada.getKey(), lista.get(0));
                    }
                }

            }

        }

        String copaiba = (String) json.remove("copaiba");
        if (StringUtil.tamanho(copaiba) == 0) {
            throw new IllegalArgumentException("copaiba = nome@classe@metodo");
        }

        String[] copaibaParam = copaiba.split("@");
        if (copaibaParam.length != 3) {
            throw new IllegalArgumentException("copaiba = nome@classe@metodo");
        }

        String comando = (String) json.remove("uxicmd");
        if (StringUtil.tamanho(comando) == 0)
            comando = null;

        if (uxiAmarelo.isCookieEnviar()) {
            Cookie[] cookies = requisicao.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    String nome = cookie.getName();
                    if (uxiAmarelo.cookieBloqueado(nome))
                        continue;
                    if (!json.has(nome)) {
                        try {
                            json.put(nome, URLDecoder.decode(cookie.getValue(), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            json.put(nome, cookie.getValue());
                        }
                    }
                }
            }
        }

        if (uxiAmarelo.isEncapsulamentoAutomatico()) {
            final String sepstr = uxiAmarelo.getEncapsulamentoSeparador();
            final char sep0 = sepstr.charAt(0);
            for (String chave : new HashSet<>(json.keySet())) {
                if (chave.indexOf(sep0) == -1)
                    continue;
                String[] caminho = chave.split(sepstr);
                if (caminho.length > 1) {
                    Util.encapsular(caminho, json.remove(chave), json);
                }
            }
        }

        String resultado;

        if (comando == null) {
            try (CopaibaConexao cc = uxiAmarelo.conectarCopaiba(copaibaParam[0])) {
                resultado = cc.solicitar(copaibaParam[1], json.toString(), copaibaParam[2]);
                if (resultado == null)
                    resultado = "";
            }
        } else if (comando.equals("voltar")) {
            resultado = json.toString();
            comando = null;
        } else {
            resultado = "";
        }

        if (comando == null) {

            resposta.setStatus(HttpServletResponse.SC_OK);
            resposta.setContentType("application/json");

            saida.write(resultado);

        } else if (comando.startsWith("redirecionar")) {

            resposta.sendRedirect(Util.obterStringDeJSON("redirecionar", comando, resultado));

        } else if (comando.startsWith("base64")) {

            String url = comando.substring("base64.".length());

            resposta.sendRedirect(url + Base64.getUrlEncoder().encodeToString(resultado.getBytes("UTF-8")));

        } else if (comando.startsWith("html_url")) {

            HttpURLConnection con = (HttpURLConnection) new URL(
                    Util.obterStringDeJSON("html_url", comando, resultado)).openConnection();
            con.setRequestProperty("User-Agent", "Uxi-amarelo");

            if (con.getResponseCode() != HttpServletResponse.SC_OK)
                throw new IOException("HTTP = " + con.getResponseCode());

            resposta.setStatus(HttpServletResponse.SC_OK);
            resposta.setContentType("text/html");

            try (InputStream is = con.getInputStream()) {
                saida.write(IOUtils.toString(is));
            }

            con.disconnect();

        } else if (comando.startsWith("html")) {

            resposta.setStatus(HttpServletResponse.SC_OK);
            resposta.setContentType("text/html");

            saida.write(Util.obterStringDeJSON("html", comando, resultado));

        } else {

            throw new IllegalArgumentException(comando);

        }

    } catch (Exception e) {

        resposta.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resposta.setContentType("application/json");

        saida.write(Util.gerarRespostaErro(e).toString());

    }

    saida.flush();

}

From source file:Admin.products.ProductS.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w w  w  .  ja va2s.  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 brand = request.getParameter("sel01n");
        String category_1 = request.getParameter("sel02n");
        String category_2 = request.getParameter("sel03n");
        String category_3 = request.getParameter("sel04n");
        String product_name = request.getParameter("txf01n");
        String description = request.getParameter("txa01n");
        String specifications = request.getParameter("spe00n");

        try {

            String Name = null;
            String Price = null;
            String QTY = null;

            FileItemFactory item = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(item);

            List<FileItem> list = upload.parseRequest(request);

            for (FileItem fileItem : list) {

                if (fileItem.isFormField()) { //form field

                    //                        fileItem.getFieldName().equals("sel01n")) {
                    Name = fileItem.getString();

                    if (fileItem.getFieldName().equals("spe01n")) {
                        System.out.println("NAME-----:" + Name);
                    } else if (fileItem.getFieldName().equals("spe02n")) {
                        System.out.println("VALUE-----:" + Name);
                    }

                } else {

                    System.out.println("---------------" + fileItem.getName());

                    //                        String n = new File(fileItem.getName()).getName();
                    System.out.println(request.getServletContext().getRealPath("/04_admin/product/img/") + "\\"
                            + System.currentTimeMillis() + ".jpg");
                    fileItem.write(new File(request.getServletContext().getRealPath("/04_admin/product/img/")
                            + "\\" + System.currentTimeMillis() + ".jpg"));
                }
            }

        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
}

From source file:com.dlshouwen.jspc.zjpc.controller.ExpreviewController.java

/**
 * ??/*from w w  w. j a  v  a 2s  .c  om*/
 *
 * @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 = evalItemDao.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;
}