private void write() {
    if (Constants.FORMAT_JSON.equals(action.getFormat())) {
      response.setCharacterEncoding("UTF-8");
      response.setContentType("text/plain");
      try {
        PrintWriter out = response.getWriter();
        out.write(getActionJSON());
        out.flush();
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }

    } else if (Constants.FORMAT_XML.equals(action.getFormat())) {
      response.setCharacterEncoding("UTF-8");
      response.setContentType("text/xml");
      try {
        PrintWriter out = response.getWriter();
        out.write(getActionXML());
        out.flush();
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
      throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    try {
      Authentication authentication = authenticationService.getAuthentication(httpRequest);
      SecurityContextHolder.getContext().setAuthentication(authentication);
      filterChain.doFilter(httpRequest, httpResponse);

    } catch (SignatureException exception) {
      httpResponse.setCharacterEncoding("UTF-8");
      httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
      httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

      ObjectMapper mapper = new ObjectMapper();

      FailureResponse error =
          new FailureResponse(
              httpRequest.getMethod(),
              httpRequest.getRequestURI(),
              "unauthorized JWT (invalid signature or expired token). Please use auth api to take another valid token.");
      httpResponse.getWriter().println(mapper.writeValueAsString(error));

      SecurityContextHolder.clearContext();

    } catch (MalformedJwtException exception) {
      httpResponse.setCharacterEncoding("UTF-8");
      httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
      httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

      ObjectMapper mapper = new ObjectMapper();

      FailureResponse error =
          new FailureResponse(
              httpRequest.getMethod(),
              httpRequest.getRequestURI(),
              "malformed token. Please use auth api to take another valid token.");
      httpResponse.getWriter().println(mapper.writeValueAsString(error));

      SecurityContextHolder.clearContext();

    } catch (Exception exception) {
      httpResponse.setCharacterEncoding("UTF-8");
      httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
      httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      ObjectMapper mapper = new ObjectMapper();

      FailureResponse error =
          new FailureResponse(
              httpRequest.getMethod(),
              httpRequest.getRequestURI(),
              "Internal server error, please contact the backend team.");
      httpResponse.getWriter().println(mapper.writeValueAsString(error));
      LOGGER.error(exception.getMessage(), exception);
      SecurityContextHolder.clearContext();
    }
  }
Esempio n. 3
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("text/html;charset=utf-8");
    String no = request.getParameter("no");
    String name = request.getParameter("name");
    String sex = request.getParameter("sex");
    String dept = request.getParameter("dept");

    String sql = new String("insert into Student(Sno,Sname,Ssex,Sdept) values(?,?,?,?)");
    Connection conn = null;
    PreparedStatement ps = null;
    System.out.println(no + name + sex + dept);
    try {
      conn = DBConnecton.getConnection();
      ps = conn.prepareStatement(sql);
      ps.setString(1, no);
      ps.setString(2, name);
      ps.setString(3, sex);
      ps.setString(4, dept);
      ps.executeUpdate();
      System.out.println("Add success£¡");
      conn.close();
      response.sendRedirect("/StudentMsg/main.jsp");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 4
0
  @Override
  public void create(Mapping mapping, Call call) throws IOException, ServletException {
    HttpContext context = call.getContext();
    HttpServletResponse response = context.getResponse();

    if (mimeType != null) {
      response.setContentType(mimeType);
    }

    if (encoding == null) {
      response.setCharacterEncoding(encoding);
    } else {
      response.setCharacterEncoding(DEFAULT_ENCODING);
    }

    if (name != null) {
      response.setHeader("Content-Transfer-Encoding", mimeType);
      response.setHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");
    }

    ServletOutputStream outputStream = response.getOutputStream();
    try {
      IOUtils.copy(stream, outputStream);
      stream.close();
    } finally {
      IOUtils.closeQuietly(stream);
    }
  }
Esempio n. 5
0
  public void core() {
    // 获取HttpServletRequest,HttpServletResponse对象,以实现数据流交互
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    try {
      request.setCharacterEncoding("utf-8");
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    response.setCharacterEncoding("utf-8");
    httpServletBean.setHttpServletRequest(request);

    coreService.setHttpServletBean(httpServletBean);
    String result = coreService.dispose();
    try {
      response.setCharacterEncoding("utf-8");
      response.getWriter().print(result);
      response.getWriter().flush();
      response.getWriter().close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String action = req.getParameter("action");
    String uuid = req.getParameter("uuid");
    String profileName = req.getParameter("profile");
    String taskName = req.getParameter("taskname");
    String taskFormValue = req.getParameter("tfvalue");

    IDiagramProfile profile = ServletUtil.getProfile(req, profileName, getServletContext());
    String[] packageAssetInfo = ServletUtil.findPackageAndAssetInfo(uuid, profile);
    String packageName = packageAssetInfo[0];
    // String assetName = packageAssetInfo[1];

    if (action != null && action.equals(ACTION_LOAD)) {
      resp.setContentType("text/html");
      resp.setCharacterEncoding("UTF-8");
      PrintWriter pw = resp.getWriter();
      pw.write(getTaskFormFromGuvnor(taskName, packageName, profile));
    } else if (action != null && action.equals(ACTION_SAVE)) {
      resp.setContentType("text/plain");
      resp.setCharacterEncoding("UTF-8");
      PrintWriter pw = resp.getWriter();
      try {
        pw.write(storeTaskFormToGuvnor(taskName, packageName, profile, taskFormValue));
      } catch (Exception e) {
        pw.write("error: " + e.getMessage());
      }
    }
  }
Esempio n. 7
0
  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    System.out.println("IN Login Filter");
    this.request = (HttpServletRequest) req;
    this.response = (HttpServletResponse) res;

    log.debug(
        "Processing doFilter"
            + userManagementService
            + "password is "
            + (null != request.getParameter("password") ? request.getParameter("password") : ""));

    // pull the username and password
    if (StringUtils.isNullOrEmpty(request.getParameter("username"))
        || StringUtils.isNullOrEmpty(request.getParameter("password"))) {
      response.sendRedirect("/");
      log.debug("Finished processing doFilter");
      return;
    }

    // else check validate user exists in the system
    try {
      System.out.println("\nPassword== " + request.getParameter("password"));
      System.out.println(
          "Encrypted password==" + MD5Utils.md5String(request.getParameter("password")));
      Users user =
          userManagementService.findByUserNameAndPassword(
              request.getParameter("username"),
              MD5Utils.md5String(request.getParameter("password")));
      System.out.println("user.getEmployeeId().toString()===" + user.getEmployeeId().toString());
      Employee emp = employeeManagementService.findByEmployeeId(user.getEmployeeId());
      System.out.println("\n Employee ==" + emp);
      request.getSession(true).setAttribute("loginUserInfo", user.getUsername());
      request
          .getSession(true)
          .setAttribute("loginUserEmail", emp.getContactDetails().getOfficeEmail());
      String name = user.getUsername();
      LoggedUser.setUsername(name);
      response.setContentType("text/plain");
      response.setCharacterEncoding("UTF-8");
      if (user.getIsAdmin()) {
        response.getWriter().write("/admin");
        return;
      }
      response.getWriter().write("/userHome");
      return;
    } catch (Exception e) {
      log.error(e.getMessage());
      response.setContentType("text/plain");
      response.setCharacterEncoding("UTF-8");
      response.getWriter().write("/errorLogin?Status=error");
      // response.sendRedirect("/errorLogin?Status=error");
      return;
    }
  }
  /**
   * Handles the HTTP <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 {
    //        processRequest(request, response);
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
      BufferedReader reader = request.getReader();
      while ((line = reader.readLine()) != null) {
        jb.append(line);
      }
      String datt = String.valueOf(jb.toString());

      JSONObject jsonObj = new JSONObject(datt);

      //            BCicloAcademico oBCicloAcademico = new BCicloAcademico();
      String value;
      value = (String) jsonObj.get("tipoCicloAcademico");
      oBCicloAcademico.setTipoCiclo(value);

      value = (String) jsonObj.get("fechaInicio");
      Date fechaIni = convertStringToDate(value);
      java.sql.Date sqlDateIni = new java.sql.Date(fechaIni.getTime());
      oBCicloAcademico.setFechaInicio(sqlDateIni);

      value = (String) jsonObj.get("fechaFin");
      Date fechaFin = convertStringToDate(value);
      java.sql.Date sqlDateFin = new java.sql.Date(fechaFin.getTime());
      oBCicloAcademico.setFechaFin(sqlDateFin);

      value = (String) jsonObj.get("costo");
      oBCicloAcademico.setCosto(Double.parseDouble(value));

      int idCiclo = new DAOCicloAcademico().registrarCicloAcademico(oBCicloAcademico);

      if (idCiclo != 0) {
        //                String json1 = new Gson().toJson("Ciclo Academico Registrado!");
        String json1 = new Gson().toJson(oBCicloAcademico.getIdCiclo());
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(json1);
      } else {
        String json1 = new Gson().toJson("Error al registrar Ciclo academico");
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(json1);
      }

      BTipoCobro oBTipoCobro = new BTipoCobro();
      oBTipoCobro.setIdCiclo(idCiclo);
    } catch (Exception e) {
    }
  }
Esempio n. 9
0
 public void get() throws ClassNotFoundException, SQLException, IOException {
   Class.forName("com.mysql.jdbc.Driver");
   String url = "jdbc:mysql://localhost:3306/cpsystem";
   String usernameMysql = "root";
   String passwordMysql = "root";
   Connection conn = DriverManager.getConnection(url, usernameMysql, passwordMysql);
   Statement stmt = conn.createStatement();
   HttpServletRequest request = ServletActionContext.getRequest();
   JSONObject dt = JSONObject.parseObject(request.getParameter("dt"));
   String account = (String) dt.get("account");
   String sql = "select * from user where phone='" + account + "'";
   ResultSet userinfo = stmt.executeQuery(sql);
   JSONObject json = new JSONObject();
   JSONObject info = new JSONObject();
   if (userinfo.next()) {
     if (userinfo.getInt("type") == 1) { // driver
       info.put("id", userinfo.getInt("id"));
       info.put("phone", userinfo.getString("phone"));
       info.put("email", userinfo.getString("email"));
       info.put("name", userinfo.getString("name"));
       info.put("type", userinfo.getInt("type"));
       sql = "select * from driver_info where id=" + userinfo.getInt("id");
       stmt = conn.createStatement();
       ResultSet driverinfo = stmt.executeQuery(sql);
       if (driverinfo.next()) {
         info.put("success_count", driverinfo.getInt("success_count"));
         info.put("success_thismonth", driverinfo.getInt("success_thismonth"));
         info.put("send_count", driverinfo.getInt("send_count"));
         info.put("send_thismonth", driverinfo.getInt("send_thismonth"));
       }
       json.put("info", info);
       HttpServletResponse response = ServletActionContext.getResponse();
       response.setCharacterEncoding("utf-8");
       response.getWriter().write(json.toString());
     } else if (userinfo.getInt("type") == 2) { // passenger
       info.put("id", userinfo.getInt("id"));
       info.put("phone", userinfo.getString("phone"));
       info.put("email", userinfo.getString("email"));
       info.put("type", userinfo.getString("type"));
       sql = "select * from passenger_info where id=" + userinfo.getInt("id");
       stmt = conn.createStatement();
       ResultSet passengerinfo = stmt.executeQuery(sql);
       if (passengerinfo.next()) {
         info.put("take_count", passengerinfo.getInt("take_count"));
         info.put("take_thismonth", passengerinfo.getInt("take_thismonth"));
       }
       json.put("info", info);
       HttpServletResponse response = ServletActionContext.getResponse();
       response.setCharacterEncoding("utf-8");
       response.getWriter().write(json.toString());
     }
   }
 }
Esempio n. 10
0
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    request.setCharacterEncoding("UTF-8");

    try {
      // client�뿉�꽌 id,pw 諛쏄린
      String id = request.getParameter("id");
      String pw = request.getParameter("pw");

      MemberDAO mDAO = new MemberDAO();

      String mpw = mDAO.userCheck(id);
      String mlv = mDAO.getlv(id);

      // db�뿉 ���옣�맂 鍮꾨�踰덊샇�옉 媛숈�吏� �솗�씤

      if (mlv.equals("1") && pw.equals(mpw)) {
        HttpSession sessionL = request.getSession();
        sessionL.setAttribute("mid", id);
        sessionL.setAttribute("sessionId", sessionL.getId());
        sessionL.setAttribute("pw", pw);
        sessionL.setMaxInactiveInterval(10 * 60);
        response.setStatus(200);
        response.sendRedirect("main.jsp");
      } else if (mlv.equals("2") && pw.equals(mpw)) {

        response.setCharacterEncoding("euc-kr");
        PrintWriter writer = response.getWriter();
        writer.println("<script type='text/javascript'>");
        writer.println("alert('관리자 계정이 아닙니다.');");
        writer.println("history.go(-1);");
        writer.println("</script>");
        writer.flush();
        return;
      } else {
        response.setCharacterEncoding("euc-kr");
        PrintWriter writer = response.getWriter();
        writer.println("<script type='text/javascript'>");
        writer.println("alert('입력 정보를 다시 한번 확인해주세요.');");
        writer.println("history.go(-1);");
        writer.println("</script>");
        writer.flush();
        return;
      }

    } catch (Exception e) {
      response.setStatus(404);
      response.sendRedirect("main.jsp");
    }
  }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String action = req.getParameter("action");
    String uuid = Utils.getUUID(req);
    String profileName = req.getParameter("profile");
    String taskName = req.getParameter("taskname");
    String taskFormValue = req.getParameter("tfvalue");
    String formType = req.getParameter("formtype");

    if (profile == null) {
      profile = _profileService.findProfile(req, profileName);
    }
    Repository repository = profile.getRepository();

    Asset<String> processAsset = null;
    try {
      processAsset = repository.loadAsset(uuid);

      if (action != null && action.equals(ACTION_LOAD)) {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter pw = resp.getWriter();
        String taskResponse =
            getTaskFormFromRepository(
                formType, taskName, processAsset.getAssetLocation(), repository);
        pw.write(taskResponse);
      } else if (action != null && action.equals(ACTION_SAVE)) {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter pw = resp.getWriter();
        try {
          pw.write(
              storeTaskFormInRepository(
                      formType,
                      taskName,
                      processAsset.getAssetLocation(),
                      taskFormValue,
                      repository)
                  .toString());
        } catch (Exception e) {
          e.printStackTrace();
          pw.write(new JSONObject().toString());
        }
      }
    } catch (Exception e) {
      PrintWriter pw = resp.getWriter();
      pw.write("error: " + e.getMessage());
    }
  }
Esempio n. 12
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   * @throws java.lang.ClassNotFoundException
   * @throws java.sql.SQLException
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, ClassNotFoundException, SQLException,
          CloneNotSupportedException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    try (PrintWriter out = response.getWriter()) {
      /* TODO output your page here. You may use following sample code. */
      out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">");
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet CheckLogin</title>");
      out.println("</head>");
      out.println("<body>");
      boolean kt = false;
      String username = request.getParameter("username");
      String password = request.getParameter("password");
      String action = request.getParameter("btAction");
      HttpSession session = request.getSession();
      ArrayList arr = new ArrayList();
      DataServices mydb = new DataServices();
      if (action.equals("Login")) {
        kt = mydb.checkUser(username, password);
        if (kt) {
          String sSql = "select staffName from tbl_staff where staffID='" + username + "'";
          ResultSet rs = mydb.executeQuery(sSql);
          while (rs.next()) {
            session.setAttribute("name", rs.getString("staffName"));
            session.setAttribute("username", username);
          }

          arr = mydb.quyen(username);
          session.setAttribute("quyen", arr);
          RequestDispatcher dispatcher = request.getRequestDispatcher("/JSP/index.jsp");
          dispatcher.forward(request, response);
        } else {
          RequestDispatcher dispatcher = request.getRequestDispatcher("/JSP/login.jsp");
          dispatcher.forward(request, response);
        }
      }
      mydb.closeDB();
      out.println("</body>");
      out.println("</html>");
    }
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
  }
  static void sendJSONResponse(HttpServletResponse response, Map<String, String> responseMap) {
    if (!Boolean.parseBoolean(responseMap.get("success"))) {
      int serverCode = 500;
      if (responseMap.containsKey("serverCode")) {
        serverCode = Integer.parseInt(responseMap.get("serverCode"));
      }
      response.setStatus(serverCode);
    }

    String responseContent = new Gson().toJson(responseMap);
    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");
    response.setHeader("Content-Length", Integer.toString(responseContent.length()));

    Writer writer = null;
    try {
      writer = response.getWriter();
      writer.write(responseContent);
    } catch (IOException ex) {
      Logger.getLogger(RequestResponseHelper.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      if (writer != null) {
        try {
          writer.close();
        } catch (IOException ex) {
          Logger.getLogger(RequestResponseHelper.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }
  }
Esempio n. 14
0
 /**
  * 根据班级查找学生
  *
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return
  */
 public ActionForward findStuByBj(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response) {
   String bjbh = request.getParameter("bjbh");
   List list = this.getIJcffglService().findStuByBj(bjbh);
   response.setCharacterEncoding("utf-8");
   response.setDateHeader("Expires", 0);
   response.setHeader("Cache-Control", "no-cache");
   String str = "";
   try {
     PrintWriter out = response.getWriter();
     for (int i = 0; i < list.size(); i++) {
       Xs0101 xs0101 = (Xs0101) list.get(i);
       str += xs0101.getXsbh() + "," + xs0101.getXm() + "#";
     }
     out.println(str);
     out.flush();
     out.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return null;
 }
Esempio n. 15
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    ServletOutputStream out = response.getOutputStream();
    response.setContentType("text/html; charset=utf-8");
    response.setCharacterEncoding("utf-8");

    String sToken = request.getParameter("token");
    String sPushKey = request.getParameter("pushkey");

    if (sToken != null && sPushKey != null) { // 푸쉬키 맞는지 판별
      if (tc.isToken(sToken)) { // 토큰이 없을 경우
        if (!tl.searchToken(sToken)) {
          tl.deleteOverlapPushkey(sPushKey);
          tl.aTokenList.add(new TokenObj(sToken, sPushKey, true)); // 토큰추가
          out.print(true);
          System.out.println("[동작] TOKEN 발급 완료");
        } else {
          out.print(false);
          System.out.println("[동작] TOKEN 발급 거부");
        }
      } else { // 틀릴 경우
        out.print(false);
        System.out.println("[동작] TOKEN 발급 거부");
      }
    } else {
      out.print(false);
      System.out.println("[동작] TOKEN 발급 거부");
    }
    out.close();
  }
Esempio n. 16
0
 /**
  * Ajax请求(根据院系得到班级信息)
  *
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return
  */
 public ActionForward findBjInfoByYx(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response) {
   String yxbh = request.getParameter("yxbh");
   response.setCharacterEncoding("utf-8");
   response.setDateHeader("Expires", 0);
   response.setHeader("Cache-Control", "no-cache");
   try {
     PrintWriter out = response.getWriter();
     List list = this.getIJcffglService().findBjInfoByYx(yxbh);
     String str = "";
     for (int i = 0; i < list.size(); i++) {
       Xs0206 xs0206 = (Xs0206) list.get(i);
       str += xs0206.getBjbh() + "#" + xs0206.getBjmc() + "$";
     }
     out.print(str);
     out.flush();
     out.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return null;
 }
Esempio n. 17
0
 /**
  * 根据院系查找专业
  *
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return
  */
 public ActionForward findZyByYx(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response) {
   String yxbh = request.getParameter("yxbh");
   String pycc = request.getParameter("pycc");
   List list = this.getIJcffglService().findZyByYx(yxbh, pycc);
   response.setCharacterEncoding("utf-8");
   response.setDateHeader("Expires", 0);
   response.setHeader("Cache-Control", "no-cache");
   String str = "";
   try {
     PrintWriter out = response.getWriter();
     for (int i = 0; i < list.size(); i++) {
       Jx01 jx01 = (Jx01) list.get(i);
       str += jx01.getZybh() + "," + jx01.getZymc() + "#";
     }
     out.println(str);
     out.flush();
     out.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return null;
 }
  @RequestMapping(value = "/wfstepDelete", method = RequestMethod.GET)
  @RequestScoped
  public ModelAndView wfStepDelete(HttpServletRequest request, HttpServletResponse response) {
    response.setCharacterEncoding("UTF-8");
    String wfstepid = null;

    try {
      wfstepid = request.getParameter("wfstepidDelete");
      String msg = wfstepService.wfstepDelete(wfstepid);

      if (msg.equals("S")) {
        sess = request.getSession(false);
        Date date = new Date();
        String modifiedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        auditLogService.setAuditLogSave(
            sess.getAttribute("userId").toString(),
            "D",
            "Process Step",
            "ROW",
            String.valueOf(wfstepid),
            "1",
            modifiedDate,
            sess.getAttribute("userName").toString());
        request.setAttribute("wfstepDeleteSuccess", "Work Flow Step has been deleted");
      } else {
        request.setAttribute("wfstepDeleteError", "Work Flow Step has not been deleted");
      }
    } catch (Exception e) {
      request.setAttribute("wfstepDeleteError", "Work Flow Step has not been deleted");
      e.printStackTrace();
    }
    return new ModelAndView("wfstepHome", "wfstepAdd", new WFStep());
  }
Esempio n. 19
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    System.out.println("Tree---------------请求到来!");
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");

    // 获取单击的节点id
    String node = request.getParameter("node");
    System.out.println("获取的节点ID: " + node);
    String json = "";

    if ("0".equals(node)) { // 全部分组
      json +=
          "[{id:'1', checked: false, text: '我的好友'}, {id:'2', checked: false, text: '我的同学'},{id:'3', checked: false, text: '陌生人', leaf: true}]";
    } else if ("1".equals(node)) {
      json +=
          "[{id:'11', checked: false, text: '张三', leaf: true}, {id:'12', checked: false, text: '李四', leaf: true}, {id:'13', checked: false, text: '王五', leaf: true}]";
    } else if ("2".equals(node)) {
      json +=
          "[{id:'21', checked: false, text: '刘备', leaf: true}, {id:'22', checked: false, text: '曹操', leaf: true}, {id:'23', checked: false, text: '孙尚香', leaf: true}]";
    }

    System.out.println("返回数据: " + json);
    response.getWriter().write(json);
    System.out.println("Tree---------------请求结束!");
  }
  /**
   * Handles the HTTP <code>GET</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 doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String ccIDStr = (String) request.getParameter("ccID");
    int ccID = Integer.parseInt(ccIDStr);
    MissionDAO msonDAO = new MissionDAO();
    IntelligenceDAO intlDAO = new IntelligenceDAO();

    ArrayList<Excerpt> returnList = new ArrayList<Excerpt>();

    ArrayList<Integer> eentIDList = msonDAO.GetEEntityIDsOfCC(ccID);
    ArrayList<Excerpt> excrList;

    for (Integer id : eentIDList) {
      for (Excerpt excr : intlDAO.GetExcerptOfEEntity(id)) {
        if (!returnList.contains(excr)) {
          returnList.add(excr);
        }
      }
    }

    JSONArray excrJArr = new JSONArray(returnList.toArray());
    String excrJSON = excrJArr.toString();

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(excrJSON);
  }
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    System.out.println(request.getRequestURI());

    Collection<File> traceFiles =
        Arrays.asList(
            traceDirectory.listFiles(
                (FilenameFilter) new WildcardFileFilter("*.json", IOCase.INSENSITIVE)));

    if (request.getRequestURI().endsWith("unusedTraces")) {
      traceFiles = extractUnusedTraceFiles(traceFiles);
    }

    Collection<SelectOptionDTO> traceFileDTOs =
        CollectionUtils.collect(
            traceFiles,
            new Transformer<File, SelectOptionDTO>() {
              @Override
              public SelectOptionDTO transform(File f) {
                SelectOptionDTO dto = new SelectOptionDTO();
                dto.value = MessageFormat.format(TRACE_URL_FORMAT, f.getName());
                dto.text = f.getName().replace(".json", "");
                return dto;
              }
            });

    String json = new GsonBuilder().setPrettyPrinting().create().toJson(traceFileDTOs);

    response.setCharacterEncoding("UTF-8");
    response.getWriter().append(json);
  }
Esempio n. 22
0
 private HttpServletResponse prepareSendResponse() {
   HttpServletResponse response = getResponse();
   response.setContentType("text/json;charset=utf-8");
   response.setCharacterEncoding("UTF-8");
   response.setDateHeader("Expires", 0);
   return response;
 }
Esempio n. 23
0
 /**
  * 删除用户
  *
  * @param request
  * @param response
  */
 @RequestMapping("/user_del")
 public void delUser(HttpServletRequest request, HttpServletResponse response) {
   Map<String, Object> resMap = new HashMap<String, Object>();
   String ids = request.getParameter("ids");
   logger.debug("ids:" + ids);
   List<Integer> paramList = new ArrayList<Integer>();
   if (StringUtils.isNoneBlank(ids)) {
     String[] s_array = ids.split(",", -1);
     if (s_array != null && s_array.length > 0) {
       for (String item : s_array) {
         paramList.add(new Integer(item));
       }
       Integer[] i_array = new Integer[paramList.size()];
       for (int i = 0; i < paramList.size(); i++) {
         i_array[i] = paramList.get(i);
       }
       userService.delUserById(i_array);
       resMap.put("msg", "ok");
     } else {
       resMap.put("msg", "error");
     }
   }
   try {
     response.setCharacterEncoding("utf-8");
     response.setHeader("Content-type", "text/html;charset=UTF-8");
     PrintWriter out = response.getWriter();
     Gson gson = new Gson();
     logger.debug("json输出:" + gson.toJson(resMap));
     out.println(gson.toJson(resMap));
     out.flush();
     out.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Esempio n. 24
0
  public static ModelAndView Render(
      Object obj, String jsonpCallback, HttpServletResponse response) {
    PrintWriter out = null;
    try {
      StringBuffer jsonp = new StringBuffer();
      if (StringUtils.isBlank(jsonpCallback)) {
        jsonp.append(JsonUtil.Object2JsonStr(obj));
        response.setContentType("application/json");
      } else {
        jsonp.append(jsonpCallback + "(" + JsonUtil.Object2JsonStr(obj) + ")");
        response.setContentType("application/javascript");
      }
      response.setCharacterEncoding("utf-8");
      Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
      Matcher m = p.matcher(jsonp.toString());
      StringBuffer res = new StringBuffer();
      while (m.find()) {
        m.appendReplacement(res, "\\" + toUnicode(m.group()));
      }
      m.appendTail(res);

      out = response.getWriter();
      out.write(res.toString());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (null != out) out.close();
    }

    return null;
  }
Esempio n. 25
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @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.setCharacterEncoding("UTF-8");
    response.setHeader("Expires", "-1");
    PrintWriter out = response.getWriter();
    try {
      Long langId = Long.parseLong(request.getParameter("langId"));
      Long dataId = Long.parseLong(request.getParameter("dataId"));
      long type = dataId; // type of value (like 4096)
      if ((type & 0xC000) != 0xC000) {
        dataId = (type & 0xFFF); // remove type to get an index 4096&0xFFF -> 0
      } else {
        dataId = (type & 0xFFFF);
      }

      DataDao dataDao = DbImplDecider.use(DaoType.MYSQL).getDao(DataDao.class);
      Data translate = dataDao.getById(dataId, langId);
      out.print("<html>");
      out.print("<message>");
      if (translate.getId() != null) {
        out.print(translate.getUnicodeLabel());
      } else {
        out.print("Translation does not exist");
      }
      out.println("</message>");
      out.print("</html>");
    } catch (Exception ex) {
      out.print("<message>");
      out.print(
          "Error occur during execution the query. \n"
              + "Perhaps translation for this data type does not exist .");
      out.println("</message>");
    }
  }
Esempio n. 26
0
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/xml");
    response.setCharacterEncoding("UTF-8");

    System.out.println("*** Data tags");
    String sid = (String) request.getParameter("sid");
    if (sid == null) throw new IOException("Invalid session");

    String firstLetter = (String) request.getParameter("firstLetter");

    // Headers required by Internet Explorer
    response.setHeader("Pragma", "public");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0,pre-check=0");
    response.setHeader("Expires", "0");

    PrintWriter writer = response.getWriter();
    writer.write("<list>");
    for (int i = 0; i < 1000; i++) {
      writer.print("<tag>");
      writer.print("<index>" + i + "</index>");
      if (firstLetter != null) {
        writer.print("<word>" + firstLetter.charAt(0) + "tag" + i + "</word>");
        writer.print("<count>" + i + "</count>");
      } else {
        writer.print("<word>tag" + i + "</word>");
        writer.print("<count></count>");
      }
      writer.print("</tag>");
    }
    writer.write("</list>");
  }
Esempio n. 27
0
  @RequestMapping("toProcess.do")
  public String toProcess(
      HttpServletRequest request, HttpServletResponse response, ModelMap model) {
    response.setCharacterEncoding("UTF-8");

    return null;
  }
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset = utf-8");

    int operation = Integer.parseInt(request.getParameter(MyOpcode.Operation.OPERATION));
    int EmployeeId = Integer.parseInt(request.getParameter(MyOpcode.Employee.EmployeeId));

    PrintWriter out = response.getWriter();
    MySpring context = MySpring.getInstance();
    IBllFrame iBllFrame = (IBllFrame) context.getContext().getBean("cBllFrameImpl");

    CEntityEmployee cEntityEmployee = new CEntityEmployee.Builder().EmployeeId(EmployeeId).build();
    CEntityMissionArray cEntityMissionArray = iBllFrame.GetWaitTakeMissionArray(cEntityEmployee);

    boolean bisGet = false;
    if (cEntityMissionArray != null) {
      bisGet = true;
    }

    JSONObject outjson =
        new CEntityMission.BuildJsonObject()
            .Operation(operation)
            .Check(bisGet)
            .MyJSONArray(cEntityMissionArray.toJsonArray())
            .build();

    System.out.println(outjson);
    out.println(outjson);
    out.flush();
    out.close();
  }
Esempio n. 29
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // 接收时设置的编码
    request.setCharacterEncoding("utf-8");
    // 转发时设置的编码
    response.setCharacterEncoding("utf-8");
    // 以 超文本格式 方式转发
    response.setContentType("text/html");
    // 获取了一个输出流
    PrintWriter out = response.getWriter();

    // 修改库存数量Ajax
    String id = request.getParameter("id");
    String number = request.getParameter("number");
    NeProductsDao neProductsDao = new NeProductsDaoImpl();
    int count = neProductsDao.updateNumber(Integer.parseInt(id), Integer.parseInt(number));
    if (count > 0) {
      out.println("商品" + id + "库存数量修改成功");
    } else {
      out.println("商品" + id + "库存数量修改失败");
    }

    out.flush();
    out.close();
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    DistributedTable table = getTable(req, resp);
    if (table == null) {
      return;
    }

    int diff;
    try {
      table.useTransaction(sessionID);
      diff = table.rollback();
      table.removeTransaction(sessionID);
    } catch (IllegalStateException e) {
      resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      return;
    } finally {
      manager.deleteTableByID(sessionID);
    }

    resp.setStatus(HttpServletResponse.SC_OK);

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF8");
    resp.getWriter().println("diff=" + diff);
  }