Esempio n. 1
0
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String pathInfo = req.getPathInfo();

    HttpSession session = req.getSession();
    if (session == null) {
      resp.setStatus(401);
      return;
    }
    String username = (String) session.getAttribute("username");
    if (username == null) {
      resp.setStatus(401);
      return;
    }

    Map userMap = loadUserSettingsMap(username);
    if (userMap == null) {
      resp.setStatus(401);
      return;
    }
    if (pathInfo.equals("/")) {
      resp.setContentType("application/json; charset=UTF-8");
      resp.getWriter().write(JSONUtil.write(userMap));
      return;
    }

    String key = pathInfo.substring(1);
    String value = (String) userMap.get(key);

    Map jsonObject = new HashMap();
    jsonObject.put(key, value);
    resp.setContentType("application/json; charset=UTF-8");
    resp.getWriter().write(JSONUtil.write(jsonObject));
  }
Esempio n. 2
0
 private void outputJson(HttpServletResponse response, Response<String> kv)
     throws IOException, JsonGenerationException, JsonMappingException {
   response.setContentType("application/json;charset=UTF-8");
   response.setHeader("Pragma", "No-cache");
   response.setHeader("Cache-Control", "no-cache");
   response.setDateHeader("Expires", 0);
   response.setContentType("application/json");
   PrintWriter out = response.getWriter();
   ObjectMapper om = JsonHelper.getObjectMapperInstance();
   out.print(om.writeValueAsString(kv));
   out.flush();
   out.close();
 }
Esempio n. 3
0
  @Override
  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html");

    String path = request.getRequestURI();
    // use routes if present
    if (this.routes != null) {
      String route = this.routes.getProperty(path);
      if (route != null) {
        path = route;
        // then we also need to replace the HttpServletRequest.getRequestURI method
        // request = getRequestWrapper(request, path);
      }
    }

    if (path.endsWith("/")) path += "index";
    String source = null;
    // check for changes first
    if (this.debug && contextCache.checkForChanges()) {
      if (this.pageInfoCache != null) this.pageInfoCache.clear();
    }
    ScriptContext context = contextCache.getContext();
    try {
      serve(request, response, context, path, null);
    } catch (Exception e) {
      int status = getStatus(e);
      response.setStatus(status);
      response.setContentType("text/plain");
      System.out.println(e.toString());
      if (errorPath != null && status >= 500) {
        try {
          serve(request, response, context, errorPath, e);
        } catch (Exception f) {
          e.printStackTrace(response.getWriter());
          response.getWriter().write("ERROR IN ERROR HANDLER PAGE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
          f.printStackTrace(response.getWriter());
        }
      } else if (debug && status == 500) {
        e.printStackTrace(response.getWriter());
      } else if (e instanceof JavaScriptException) {
        JavaScriptException je = (JavaScriptException) e;
        response.getWriter().write(je.getValue().toString());
      } else {
        response.getWriter().write(e.getMessage());
      }
    } finally {
      contextCache.returnContext(context);
    }
  }
Esempio n. 4
0
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html; charset=UTF-8");
   Tools.sendDisableCacheHeaders(response);
   final PrintWriter out = response.getWriter();
   out.println("<html>");
   out.println(" <body>");
   Cookie cookie = getCookie("carlos-cookie-test", request);
   if (cookie == null) {
     print(out, "No cookie set.");
   } else {
     print(out, "<b>Cookie ID</b>: " + cookie.getName() + "<br>");
     print(out, "<b>Value</b>: " + cookie.getValue() + "<br>");
     refreshCookie(cookie, response);
   }
   out.println("  <br>");
   out.println("  <form method=\"post\">");
   out.println("   <input type=\"submit\" value=\"create\" name=\"button\"><br><br>");
   out.println("   <input type=\"submit\" value=\"delete\" name=\"button\"><br><br>");
   out.println("   <input type=\"submit\" value=\"no-pass\" name=\"button\"><br>");
   out.println("  </form>");
   out.println(" </body>");
   out.println("</html>");
   out.close();
 }
Esempio n. 5
0
  public void doGet(HttpServletRequest rq, HttpServletResponse rs) {
    PrintWriter pw = null;
    try {
      pw = rs.getWriter();
      rs.setContentType("application/json");
      LoyaltyApplication loyaltyApplication = new LoyaltyApplication();
      loyaltyApplication.removeOperator(Integer.parseInt(rq.getParameter("code")));
      pw.println("{");
      pw.println("\"success\":true,");
      pw.println("\"message\":\"removed\"");
      pw.println("}");

    } catch (ApplicationException ae) {

      System.out.println(ae);

      pw.println("{");
      pw.println("\"success\":false,");
      pw.println("\"errorMessage\":" + "\"" + ae + "\"");
      pw.println("}");

    } catch (IOException ioe) {
      System.out.println(ioe);
    }
  }
  /**
   * Called by the server (via the <code>service</code> method) to allow a servlet to handle a TRACE
   * request.
   *
   * <p>A TRACE returns the headers sent with the TRACE request to the client, so that they can be
   * used in debugging. There's no need to override this method.
   *
   * @param req the {@link HttpServletRequest} object that contains the request the client made of
   *     the servlet
   * @param resp the {@link HttpServletResponse} object that contains the response the servlet
   *     returns to the client
   * @exception IOException if an input or output error occurs while the servlet is handling the
   *     TRACE request
   * @exception ServletException if the request for the TRACE cannot be handled
   */
  protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    int responseLength;

    String CRLF = "\r\n";
    StringBuilder buffer =
        new StringBuilder("TRACE ")
            .append(req.getRequestURI())
            .append(" ")
            .append(req.getProtocol());

    Enumeration<String> reqHeaderEnum = req.getHeaderNames();

    while (reqHeaderEnum.hasMoreElements()) {
      String headerName = reqHeaderEnum.nextElement();
      buffer.append(CRLF).append(headerName).append(": ").append(req.getHeader(headerName));
    }

    buffer.append(CRLF);

    responseLength = buffer.length();

    resp.setContentType("message/http");
    resp.setContentLength(responseLength);
    ServletOutputStream out = resp.getOutputStream();
    out.print(buffer.toString());
    out.close();
    return;
  }
Esempio n. 7
0
  void sendHTML(
      HttpServletRequest request,
      HttpServletResponse response,
      String script,
      Exception scriptError,
      Object scriptResult,
      StringBuffer scriptOutput,
      boolean capture)
      throws IOException {
    // Format the output using a simple templating utility
    SimpleTemplate st = new SimpleTemplate(BshServlet.class.getResource("page.template"));
    st.replace("version", getBshVersion());

    // String requestURI = HttpUtils.getRequestURL( request ).toString()
    // I was told this should work
    String requestURI = request.getRequestURI();

    st.replace("servletURL", requestURI);
    if (script != null) st.replace("script", script);
    else st.replace("script", exampleScript);
    if (capture) st.replace("captureOutErr", "CHECKED");
    else st.replace("captureOutErr", "");
    if (script != null)
      st.replace(
          "scriptResult", formatScriptResultHTML(script, scriptResult, scriptError, scriptOutput));

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    st.write(out);
    out.flush();
  }
Esempio n. 8
0
  public void doGet(HttpServletRequest rq, HttpServletResponse rs) {
    PrintWriter pw = null;
    try {
      pw = rs.getWriter();
      rs.setContentType("application/json");
      OperatorBLInterface operatorInterface = new Operator();
      LoyaltyApplication loyaltyApplication = new LoyaltyApplication();
      boolean found = loyaltyApplication.operatorExists(Integer.parseInt(rq.getParameter("code")));

      pw.println("{");
      pw.println("\"success\":true,");
      pw.println("\"found\":" + found);

      pw.println("}");
    } catch (ApplicationException ae) {
      System.out.println(ae);

      pw.println("{");
      pw.println("\"success\":false,");
      pw.println("\"errorMessage\":" + "\"" + ae + "\"");
      pw.println("}");
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  /**
   * Attempts to send an internal server error HTTP error, if possible. Otherwise simply pushes the
   * exception message to the output stream.
   *
   * @param message Message to be printed to the logger and to the output stream.
   * @param t Exception that caused the error.
   */
  protected void filterError(String message, Throwable t) {
    log.error("XSLT filter error: " + message, t);
    if (false == origResponse.isCommitted()) {
      // Reset the buffer and previous status code.
      origResponse.reset();
      origResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      origResponse.setContentType("text/html; charset=UTF-8");
    }

    // Response committed. Just push the error to the output stream.
    try {
      final OutputStream os = origResponse.getOutputStream();
      final PrintWriter osw = new PrintWriter(new OutputStreamWriter(os, "iso8859-1"));
      osw.write("<html><body><!-- " + XSLTFilterConstants.ERROR_TOKEN + " -->");
      osw.write("<h1 style=\"color: red; margin-top: 1em;\">");
      osw.write("Internal server exception");
      osw.write("</h1>");
      osw.write("<b>URI</b>: " + origRequest.getRequestURI() + "\n<br/><br/>");
      serializeException(osw, t);
      if (t instanceof ServletException && ((ServletException) t).getRootCause() != null) {
        osw.write("<br/><br/><h2>ServletException root cause:</h2>");
        serializeException(osw, ((ServletException) t).getRootCause());
      }
      osw.write("</body></html>");
      osw.flush();
    } catch (IOException e) {
      // Not much to do in such case (connection broken most likely).
      log.debug("Filter error could not be returned to client.");
    }
  }
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    try {
      userObj = new User();
      tmsManager = new TMSManager();

      RequestDispatcher rd1 = request.getRequestDispatcher("./header");
      rd1.include(request, response);

      out.println("<html><head><title>UpdateUser</title></head>");
      out.println("<body onload=onSubmit() bgcolor =\"#ffcc00\">");
      out.println("<form  method =\"POST\"  action =\"./updateUser\" ><br><br><br>");
      out.println("<table border = 1 width = \"40%\" align = \"center\" bgcolor = \"#bbccff\">");
      out.println("<caption><b>UpdateUser</b></caption>");
      out.println("<tr><td style = font face: verdana>Enter User ID</td>");
      out.println("<td><input type = \"text\" name = \"user_id\" ></td></tr>");
      out.println(
          "<tr><td colspan = 2 align = \"center\"><input type = \"submit\"  name = \"Submit\" value = \"Submit\">");
      out.println("<input type = \"Reset\"  name = \"Reset\" value = \"Clear\"></td></tr>");
      out.println("</table>");
      out.println("</body></html>");

      // String user_id = request.getParameter("user_id");
      //    userObj = tmsManager.getUser(user_id);
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }

    RequestDispatcher rd2 = request.getRequestDispatcher("./footer");
    rd2.include(request, response);
  }
Esempio n. 11
0
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html");
    resp.getWriter().println("<a href='/'>Back to home</a><br/>");
    resp.getWriter().println("This is the admin page for making system updates.");
    resp.getWriter()
        .println("Please expect the system to take about 15 seconds to perform these actions.");

    NascarConfig config = NascarConfigSingleton.get();
    Race race = config.getRace();
    resp.getWriter()
        .println(
            String.format(
                "<h3>Current race: %d - %d (%s)</h3>",
                race.getYear(), race.getWeek(), race.getRaceName()));
    resp.getWriter().println("<form method='POST'>");
    resp.getWriter()
        .println(
            "<p>Click the following magic button after the race results are in to prepare the system for the new week.</p>");
    resp.getWriter().println("<input type='hidden' name='action' value='nextrace'/>");
    resp.getWriter()
        .println("<button type='submit'>Calculate Results and go to next Race</button></form>");

    resp.getWriter().println("<form method='POST'>");
    String lineupString = config.getCanEditLineup() ? "Lineups are unlocked" : "Lineups are locked";
    resp.getWriter().println(lineupString);
    resp.getWriter().println("<input type='hidden' name='action' value='toggleeditable'/>");
    String lineupText = config.getCanEditLineup() ? "Lock lineups" : "Unlock lineups";
    resp.getWriter().println("<button type='submit'>" + lineupText + "</button></form>");

    resp.getWriter().println("<BR/>Last operation: " + LAST_OPERATION_MESSAGE);
  }
Esempio n. 12
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Reading All Request Parameters";
    out.println(
        ServletUtilities.headWithTitle(title)
            + "<BODY BGCOLOR=\"#FDF5E6\">\n"
            + "<H1 ALIGN=CENTER>"
            + title
            + "</H1>\n"
            + "<TABLE BORDER=1 ALIGN=CENTER>\n"
            + "<TR BGCOLOR=\"#FFAD00\">\n"
            + "<TH>Parameter Name<TH>Parameter Value(s)");
    Enumeration paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
      String paramName = (String) paramNames.nextElement();
      out.println("<TR><TD>" + paramName + "\n<TD>");
      String[] paramValues = request.getParameterValues(paramName);
      if (paramValues.length == 1) {
        String paramValue = paramValues[0];
        if (paramValue.length() == 0) out.print("<I>No Value</I>");
        else out.print(paramValue);
      } else {
        out.println("<UL>");
        for (int i = 0; i < paramValues.length; i++) {
          out.println("<LI>" + paramValues[i]);
        }
        out.println("</UL>");
      }
    }
    out.println("</TABLE>\n</BODY></HTML>");
  }
  /**
   * Method execute
   *
   * @param ActionMapping mapping
   * @param ActionForm form
   * @param HttpServletRequest request
   * @param HttpServletResponse response
   * @return ActionForward
   * @throws Exception
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    HttpSession session = request.getSession();
    // clientXML = (XMLClient) session.getAttribute("client");
    clientXML = XMLClient.getInstance();
    sessionLogin = (String) session.getAttribute("login");

    ajoutsuppressionForm ajoutForm = (ajoutsuppressionForm) form;

    String idperm = ajoutForm.getId1();
    String idrole = ajoutForm.getId2();

    response.setContentType("text/html");

    boolean ajout = clientXML.ajouterPermissionRole(sessionLogin, idperm, idrole);

    if (ajout) {
      String result = "INFO: Permission ajoutée au role";

      session.setAttribute("Resultat", result);
      return mapping.findForward("ok");
    } else {
      String erreur = "ERREUR: Permission non ajoutée au role";

      session.setAttribute("Resultat", erreur);
      return mapping.findForward("failed");
    }
  }
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String button = req.getParameter("id");
    System.out.println("Funtion Comes inside fetch servlet of AnswerConnect");
    resp.setContentType("text/json");
    PrintWriter out = resp.getWriter();
    PersistenceManager pmf = PMF.get().getPersistenceManager();
    /*Query q = pmf.newQuery(Fullclient.class);
    q.setFilter("ID==clickedId");
    q.declareParameters("String clickedId");*/
    System.out.println("data value is setted");
    try {
      AnswerConnect results = (AnswerConnect) pmf.getObjectById(AnswerConnect.class, button);
      System.out.println(results);
      System.out.println("query successfull");
      ObjectWriter objectwriter = new ObjectMapper().writer().withDefaultPrettyPrinter();
      String json = objectwriter.writeValueAsString(results);
      System.out.println(json);
      out.print(json);
    } catch (JDOObjectNotFoundException e) {

    } finally {
      pmf.close();
      out.flush();
      System.out.println("AnswerConnect function closes here");
    }
  }
Esempio n. 15
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Session Tracking Example";
    HttpSession session = request.getSession(true);
    String heading;

    Integer accessCount = (Integer) session.getAttribute("accessCount");

    if (accessCount == null) {
      accessCount = new Integer(0);
      heading = "Welcome, Newcomer";
    } else {
      heading = "Welcome Back";
      accessCount = new Integer(accessCount.intValue() + 1);
    }

    session.setAttribute("accessCount", accessCount);
    out.println(
        "<BODY BGCOLOR=\"#FDF5E6\">\n"
            + "<H1 ALIGN=\"CENTER\">"
            + heading
            + "</H1>\n"
            + "<H2>Information on Your Session:</H2>\n"
            + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n"
            + "<TR BGCOLOR=\"#FFAD00\">\n"
            + "  <TH>Info Type<TH>Value\n"
            + "<TR>\n"
            + "  <TD>ID\n"
            + "  <TD>"
            + session.getId()
            + "\n"
            + "<TR>\n"
            + "  <TD>Creation Time\n"
            + "  <TD>"
            + new Date(session.getCreationTime())
            + "\n"
            + "<TR>\n"
            + "  <TD>Time of Last Access\n"
            + "  <TD>"
            + new Date(session.getLastAccessedTime())
            + "\n"
            + "<TR>\n"
            + "  <TD>Number of Previous Accesses\n"
            + "  <TD>"
            + accessCount
            + "\n"
            + "</TR>"
            + "</TABLE>\n");

    // the following two statements show how to retrieve parameters in
    // the request.  The URL format is something like:
    // http://localhost:8080/project2/servlet/ShowSession?myname=Chen%20Li
    String myname = request.getParameter("myname");
    if (myname != null) out.println("Hey " + myname + "<br><br>");

    out.println("</BODY></HTML>");
  }
Esempio n. 16
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

    String support = "support"; // valid username

    HttpSession session = null;
    session = req.getSession(false); // Get user's session object (no new one)
    if (session == null) {

      invalidUser(out); // Intruder - reject
      return;
    }

    String userName = (String) session.getAttribute("user"); // get username

    if (!userName.equals(support)) {

      invalidUser(out); // Intruder - reject
      return;
    }

    String action = "";
    if (req.getParameter("todo") != null) action = req.getParameter("todo");

    if (action.equals("update")) {

      doUpdate(out);
      return;
    }

    out.println("<p>Nothing to do.</p>todo=" + action);
  }
Esempio n. 17
0
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    Enumeration values = req.getParameterNames();
    String name = "";
    String value = "";
    String id = "";
    while (values.hasMoreElements()) {
      name = ((String) values.nextElement()).trim();
      value = req.getParameter(name).trim();
      if (name.equals("id")) id = value;
    }
    if (url.equals("")) {
      url = getServletContext().getInitParameter("url");
      cas_url = getServletContext().getInitParameter("cas_url");
    }
    HttpSession session = null;
    session = req.getSession(false);
    if (session != null) {
      session.invalidate();
    }
    res.sendRedirect(cas_url);
    return;
  }
Esempio n. 18
0
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   String title = "Showing Request Headers";
   StringBuilder sb = new StringBuilder();
   sb.append("<html>\n<head>\n");
   sb.append("<title>" + title + "</title>\n");
   sb.append("</head>\n");
   sb.append("<body bgcolor='#FDF5E6'>\n");
   sb.append("<h1 align='center'>" + title + "</h1>\n");
   sb.append("<b> Request Method: </b>" + request.getMethod() + "<br>\n");
   sb.append("<b> Request URI: </b>" + request.getRequestURI() + "<br>\n");
   sb.append("<b> Request Protocol: </b>" + request.getProtocol() + "<br>\n");
   sb.append("<table border=1 align='center'>\n");
   sb.append("<tr bgcolor='#FFAD00'>\n");
   sb.append("<th> Header Name </th><th> Header Value </th></tr>\n");
   Enumeration headerNames = request.getHeaderNames();
   while (headerNames.hasMoreElements()) {
     String headerName = (String) headerNames.nextElement();
     sb.append("<tr><td>" + headerName + "</td>");
     sb.append("<td>" + request.getHeader(headerName) + "</td></tr>\n");
   }
   sb.append("</table>\n");
   sb.append("</body></html>");
   out.println(sb.toString());
   out.close();
 }
Esempio n. 19
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    if (request.getParameter("setcookie") != null) {
      Cookie cookie = new Cookie("Learningjava", "Cookies!");
      cookie.setMaxAge(3600);
      response.addCookie(cookie);
      out.println("<html><body><h1>Cookie Set...</h1>");
    } else {
      out.println("<html><body>");
      Cookie[] cookies = request.getCookies();
      if (cookies.length == 0) {
        out.println("<h1>No cookies found...</h1>");
      } else {
        for (int i = 0; i < cookies.length; i++)
          out.print(
              "<h1>Name: "
                  + cookies[i].getName()
                  + "<br>"
                  + "Value: "
                  + cookies[i].getValue()
                  + "</h1>");
      }
      out.println(
          "<p><a href=\""
              + request.getRequestURI()
              + "?setcookie=true\">"
              + "Reset the Learning Java cookie.</a>");
    }
    out.println("</body></html>");
  }
Esempio n. 20
0
  private void callMethodForMultiPart(HttpServletRequest req, HttpServletResponse resp)
      throws Exception {
    String pinfo = req.getPathInfo();
    int pos = pinfo.indexOf('.');
    String cname = pinfo.substring(1, pos).replace('/', '.');
    String mname = pinfo.substring(pos + 1);

    MultiPartMap map = new MultiPartMap();
    FileItemIterator ite = new FileUpload().getItemIterator(req);
    while (ite.hasNext()) {
      FileItemStream item = ite.next();
      if (item.isFormField()) {
        map.put(item.getFieldName(), IOUtil.streamToString(item.openStream(), "UTF-8"));
      } else {
        FileItem val =
            new FileItem(
                item.getFileName(), item.getContentType(), IOUtil.streamToBytes(item.openStream()));
        map.put(item.getFieldName(), val);
      }
    }

    Class clazz = Class.forName(cname);
    Class[] types = new Class[] {MultiPartMap.class};
    Method method = clazz.getMethod(mname, types);
    if (method == null) {
      throw new RuntimeException("Not found method " + mname + "(Map)");
    }

    Object result = method.invoke(null, map);

    resp.setContentType(MIME_HTML + ";charset=utf-8");
    resp.getWriter().write(result.toString());
  }
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {
    res.setContentType("text/html");
    try {
      PrintWriter pw = res.getWriter();
      pw.println("<html><head><TITLE>Web-Enabled Automated Manufacturing System</TITLE></head>");
      pw.println(
          "<body><br><br><br><form name=modifyuser method=post action='http://peers:8080/servlet/showUser')");
      v = U.allUsers();
      pw.println("<table align='center' border=0> <tr><td>");
      pw.println(
          "Select User Name To Modify</td><td><SELECT id=select1 name=uid style='HEIGHT: 22px; LEFT: 74px; TOP: 222px; WIDTH: 155px'>");
      pw.println("<OPTION selected value=''></OPTION>");
      for (i = 0; i < v.size(); i++)
        pw.println(
            "<OPTION value="
                + (String) v.elementAt(i)
                + ">"
                + (String) v.elementAt(i)
                + "</OPTION>");
      pw.println(
          "</SELECT></td></tr><tr><td></td><td><input type='submit' name='submit' value='Submit'></td></tr></table></form></body></html>");
      pw.flush();
      pw.close();

    } catch (Exception e) {
    }
  }
  public void doGet(HttpServletRequest solicitacao, HttpServletResponse resposta)
      throws IOException, ServletException {

    resposta.setContentType("text/html");
    PrintWriter out = resposta.getWriter();

    out.println("<html>");
    out.println("<body>");
    out.println("<center>");
    out.println("<h1>Insira os dados para a criação do cookie</h1>");
    out.println("</center>");
    out.println("<table border='0' width='400'>");
    out.println("<tr>");
    out.println("<td>");
    out.println("<form method='post' action='ExemploCookies'>");
    out.println("<font face='verdana' size='2'>");
    out.println("Nome do cookie:&nbsp;&nbsp;&nbsp;< / font >        ");
    out.println("<input type='text' name='nome' size =        '20'>");
    out.println("<br>");
    out.println("<font face='verdana' size='2'>");
    out.println("Valor do cookie:&nbsp;&nbsp;&nbsp;&nbsp;< / font >        ");
    out.println("<input type='text' name='valor' size ='20'><br >        ");
    out.println("</td>");
    out.println("</tr>");
    out.println("<tr>");
    out.println("<td align='center'>");
    out.println("<input type='submit' value='Criar' name =        'S1'>");
    out.println("&nbsp;");
    out.println("<input type='reset' value='Limpar' name =        'S2'>");
    out.println("</td>");
    out.println("</tr>");
    out.println("</table>");
    out.println("</body>");
    out.println("</html>");
  }
Esempio n. 23
0
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String thisUsersId = req.getParameter("userId");
    if ("true".equals(req.getParameter("pingAlive"))) {
      updateLastAliveTime(thisUsersId);
    } else {
      ObjectMapper mapper = new ObjectMapper();

      ArrayNode usersArray = mapper.createArrayNode();

      for (Map.Entry<String, User> userEntry : users.entrySet()) {
        if (!thisUsersId.equals(userEntry.getKey())) {
          User user = userEntry.getValue();
          Date now = new Date();
          if ((now.getTime() - user.getLastAliveTime().getTime()) / 1000 <= 10) {
            ObjectNode userJson = mapper.createObjectNode();
            userJson.put("user_id", userEntry.getKey());
            userJson.put("user_name", user.getName());
            usersArray.add(userJson);
          }
        }
      }

      ObjectNode usersJson = mapper.createObjectNode();
      usersJson.put("opponents", usersArray);

      resp.setContentType("application/json; charset=UTF-8");
      mapper.writeValue(resp.getWriter(), usersJson);
    }
  }
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

    UserService userService = UserServiceFactory.getUserService();
    if (userService.isUserLoggedIn()) {
      User user = userService.getCurrentUser();
      out.println("<p>You are signed in as " + user.getNickname() + ". ");
      if (userService.isUserAdmin()) {
        out.println("You are an administrator. ");
      }
      out.println("<a href=\"" + userService.createLogoutURL("/") + "\">Sign out</a>.</p>");
    } else {
      out.println(
          "<p>You are not signed in to Google Accounts. "
              + "<a href=\""
              + userService.createLoginURL(req.getRequestURI())
              + "\">Sign in</a>.</p>");
    }

    out.println(
        "<ul>"
            + "<li><a href=\"/\">/</a></li>"
            + "<li><a href=\"/required\">/required</a></li>"
            + "<li><a href=\"/admin\">/admin</a></li>"
            + "</ul>");

    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSS");
    fmt.setTimeZone(new SimpleTimeZone(0, ""));
    out.println("<p>The time is: " + fmt.format(new Date()) + "</p>");
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    try {

      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      /*String n=request.getParameter("username");
      out.print("Welcome "+n);*/

      String name = request.getParameter("name");
      String dob = request.getParameter("dob");
      String address = request.getParameter("address");
      String email = request.getParameter("email");
      HttpSession session = request.getSession(true);
      String userid = (String) session.getAttribute("theName");
      int AccNo = 0;
      String AccMsg = "";

      DbCommunication db_comm = new DbCommunication();
      AccNo = db_comm.accountCreation(name, dob, address, email, userid);
      // db_comm.accountCreation(name,email);
      AccMsg = "Account created successfully. Account number is:" + AccNo;
      // out.println(AccMsg);

      String redirectURL = "accountCreationPage.jsp";
      response.sendRedirect(redirectURL);
      session.setAttribute("AccCreationalMsgStatus", "set");
      session.setAttribute("AccCreationalMsg", AccMsg);

    } catch (Exception e) {
      System.out.println(e);
    }
  }
Esempio n. 26
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("text/xml;charset=gbk");

    String cmd = JUtil.convertNull(request.getParameter("cmd"));

    String xml = null;
    try {
      if (cmd.equals("calExterContractApplyType")) {
        // 根据公司ID,获得对外合同申请的合同类别
        xml = this.calExterContractApplyType(request, response);
      } else if (cmd.equals("calDefaultExterContractApprover")) {
        // 获得对外合同申请的默认审批人
        xml = this.calDefaultExterContractApprover(request, response);
      } else if (cmd.equals("calDefaultGnOrgApprover")) {
        // 获得国内合作渠道申请的默认审批人
        xml = this.calDefaultGnOrgApprover(request, response);
      } else if (cmd.equals("calNeedInputMoney")) {
        xml = this.calNeedInputMoney(request, response);
      } else if (cmd.equals("checkRepeatGnOrg")) {
        // 检查国内合作渠道的名称是否有重复
        xml = this.checkRepeatGnOrg(request, response);
      } else {
        xml = "";
      }
    } catch (Throwable e) {
      e.printStackTrace();
    }
    java.io.PrintWriter out = response.getWriter();
    out.write(xml);
  }
Esempio n. 27
0
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String strCallResult = "";
    resp.setContentType("text/plain");

    String strId = req.getParameter("id");
    String strCount = req.getParameter("count");
    int id = -1;
    int count = -1;
    try {
      id = Integer.valueOf(strId);
      count = Integer.valueOf(strCount);
    } catch (NumberFormatException e) {
      e.printStackTrace();
    }

    try {

      TopsCalculator.getTopUrlsForDay();
      TopsCalculator.getTopUrlsForMonth();
      TopsCalculator.getTopUrlsForYear();
      TopsCalculator.getTopHostsForDay();
      TopsCalculator.getTopHostsForMonth();
      TopsCalculator.getTopHostsForYear();

      if (id == 0) {
        DbHelper.setStartTime(System.currentTimeMillis());
      } else if (id == count - 1) {
        DbHelper.setRunTime(System.currentTimeMillis() - DbHelper.getStartTime());
      }

    } catch (Exception ex) {
      strCallResult = "FAIL: Fetching top lists";
      System.out.println(strCallResult);
    }
  }
Esempio n. 28
0
 private void setContentType(HttpServletResponse pResp, String pContentType) {
   boolean encodingDone = false;
   try {
     pResp.setCharacterEncoding("utf-8");
     pResp.setContentType(pContentType);
     encodingDone = true;
   } catch (NoSuchMethodError error) {
     /* Servlet 2.3 */
   } catch (UnsupportedOperationException error) {
     /* Equinox HTTP Service */
   }
   if (!encodingDone) {
     // For a Servlet 2.3 container or an Equinox HTTP Service, set the charset by hand
     pResp.setContentType(pContentType + "; charset=utf-8");
   }
 }
Esempio n. 29
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // POST method only used for tracked login operation
    HttpSession session = request.getSession();
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();

    // Get the username and password from request
    String username = request.getParameter("id");
    String password = request.getParameter("pwd");

    Long id = 0L;
    try {
      id = Long.parseLong(username);
    } catch (Exception ex) {
    }

    if (username != null && password != null) {
      // Login into tracked system
      CTracked ctracked = db.loginTrackedFromMobile(id, password).getResult();

      if (ctracked != null) {
        // Login successful
        out.print("OK," + ctracked.getUsername());
        session.setAttribute("device_id", ctracked.getUsername());
        log.info(ctracked + " : logined!");
      }
    }
  }
Esempio n. 30
0
 public void service(HttpServletRequest request, HttpServletResponse response)
     throws ServletException {
   try {
     ConnectionPool conPool = getConnectionPool();
     if (!realAuthentication(request, conPool)) {
       String queryString = request.getQueryString();
       if (request.getQueryString() == null) {
         queryString = "";
       }
       // if user is not authenticated send to signin
       response.sendRedirect(
           response.encodeRedirectURL(URLAUTHSIGNIN + "?" + URLBUY + "?" + queryString));
     } else {
       response.setHeader("Cache-Control", "no-cache");
       response.setHeader("Expires", "0");
       response.setHeader("Pragma", "no-cache");
       response.setContentType("text/html");
       String errorMessage = processRequest(request, response, conPool);
       if (errorMessage != null) {
         request.setAttribute(StringInterface.ERRORPAGEATTR, errorMessage);
         RequestDispatcher rd = getServletContext().getRequestDispatcher(PATHUSERERROR);
         rd.include(request, response);
       }
     }
   } catch (Exception e) {
     throw new ServletException(e);
   }
 }