Пример #1
0
 protected Link retrieveLink(final HttpServletRequest httpServletRequest) {
   String uri =
       httpServletRequest
           .getRequestURI()
           .substring(httpServletRequest.getRequestURI().lastIndexOf("/") + 1);
   _log.debug("Extracted URI: " + uri);
   return Link.create(uri);
 }
Пример #2
0
 /*
  * (non-Javadoc)
  *
  * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.
  * HttpServletRequest, javax.servlet.http.HttpServletResponse)
  */
 @Override
 protected void service(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   // request uri contains application context path,/contextPaht/hello
   resp.setContentType(MimeTypeUtils.TEXT_PLAIN.toString());
   if (req.getRequestURI().endsWith("hello")) {
     resp.getWriter().write("world.");
   } else if (req.getRequestURI().endsWith("make")) {
     resp.getWriter().write("love.");
   }
 }
Пример #3
0
  /**
   * 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;
  }
Пример #4
0
  private static Properties createCGIEnvironment(
      HttpServletRequest sreq, URI root_uri, File canonical_script_file) throws URISyntaxException {

    URI full_request_uri =
        new URI(
            sreq.getScheme(),
            null,
            sreq.getServerName(),
            sreq.getServerPort(),
            sreq.getRequestURI(),
            sreq.getQueryString(),
            null);

    Properties p =
        createCGIEnvironment(
            sreq.getMethod(),
            sreq.getProtocol(),
            full_request_uri,
            new InetSocketAddress(sreq.getLocalAddr(), sreq.getLocalPort()),
            new InetSocketAddress(sreq.getRemoteAddr(), sreq.getRemotePort()),
            sreq.getContextPath() + "/",
            root_uri,
            canonical_script_file);

    // Add request headers

    for (Enumeration e = sreq.getHeaderNames(); e.hasMoreElements(); ) {
      String h = (String) e.nextElement();
      p.setProperty(ESXX.httpToCGI(h), sreq.getHeader(h));
    }

    return p;
  }
  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>");
  }
Пример #6
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>");
  }
Пример #7
0
 public DownloadRequest(ServletContext context, HttpServletRequest request) {
   _context = context;
   _httpRequest = request;
   _path = request.getRequestURI();
   _encoding = request.getHeader(ACCEPT_ENCODING);
   String context_path = request.getContextPath();
   if (context_path != null) _path = _path.substring(context_path.length());
   if (_path == null) _path = request.getServletPath(); // This works for *.<ext> invocations
   if (_path == null) _path = "/"; // No path given
   _path = _path.trim();
   if (_context != null && !_path.endsWith("/")) {
     String realPath = _context.getRealPath(_path);
     // fix for 4474021 - getRealPath might returns NULL
     if (realPath != null) {
       File f = new File(realPath);
       if (f != null && f.exists() && f.isDirectory()) {
         _path += "/";
       }
     }
   }
   // Append default file for a directory
   if (_path.endsWith("/")) _path += "launch.jnlp";
   _version = getParameter(request, ARG_VERSION_ID);
   _currentVersionId = getParameter(request, ARG_CURRENT_VERSION_ID);
   _os = getParameterList(request, ARG_OS);
   _arch = getParameterList(request, ARG_ARCH);
   _locale = getParameterList(request, ARG_LOCALE);
   _knownPlatforms = getParameterList(request, ARG_KNOWN_PLATFORMS);
   String platformVersion = getParameter(request, ARG_PLATFORM_VERSION_ID);
   _isPlatformRequest = (platformVersion != null);
   if (_isPlatformRequest) _version = platformVersion;
   _query = request.getQueryString();
   _testJRE = getParameter(request, TEST_JRE);
 }
Пример #8
0
  private void rotateTokens(HttpServletRequest request) {
    HttpSession session = request.getSession(true);

    /** rotate master token * */
    String tokenFromSession = null;

    try {
      tokenFromSession = RandomGenerator.generateRandomId(getPrng(), getTokenLength());
    } catch (Exception e) {
      throw new RuntimeException(
          String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e);
    }

    session.setAttribute(getSessionKey(), tokenFromSession);

    /** rotate page token * */
    if (isTokenPerPageEnabled()) {
      @SuppressWarnings("unchecked")
      Map<String, String> pageTokens =
          (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

      try {
        pageTokens.put(
            request.getRequestURI(), RandomGenerator.generateRandomId(getPrng(), getTokenLength()));
      } catch (Exception e) {
        throw new RuntimeException(
            String.format("unable to generate the random token - %s", e.getLocalizedMessage()), e);
      }
    }
  }
Пример #9
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();
 }
Пример #10
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();
  }
Пример #11
0
  /**
   * 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.");
    }
  }
Пример #12
0
  public void updateTokens(HttpServletRequest request) {
    /** cannot create sessions if response already committed * */
    HttpSession session = request.getSession(false);

    if (session != null) {
      /** create master token if it does not exist * */
      updateToken(session);

      /** create page specific token * */
      if (isTokenPerPageEnabled()) {
        @SuppressWarnings("unchecked")
        Map<String, String> pageTokens =
            (Map<String, String>) session.getAttribute(CsrfGuard.PAGE_TOKENS_KEY);

        /** first time initialization * */
        if (pageTokens == null) {
          pageTokens = new HashMap<String, String>();
          session.setAttribute(CsrfGuard.PAGE_TOKENS_KEY, pageTokens);
        }

        /** create token if it does not exist * */
        if (isProtectedPageAndMethod(request)) {
          createPageToken(pageTokens, request.getRequestURI());
        }
      }
    }
  }
 private void insertLog(HttpServletRequest req, Connection connection) throws SQLException {
   try (PreparedStatement stmt =
       connection.prepareStatement("INSERT INTO LOGGING (date,ip,url) VALUES (?,?,?)")) {
     stmt.setTimestamp(1, new Timestamp((new java.util.Date()).getTime()));
     stmt.setString(2, req.getRemoteAddr());
     stmt.setString(3, req.getRequestURI());
     stmt.executeUpdate();
   }
 }
 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
   Owner owner = DatastoreManager.getCurrentOwner();
   if (owner == null) {
     UserService userService = UserServiceFactory.getUserService();
     resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
     return;
   }
   resp.sendRedirect("/driverselection.jsp");
 }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    System.out.println(
        "MyProtectedServlet.processRequest "
            + request.getRequestURI()
            + " "
            + request.getQueryString());

    String myUrl = request.getRequestURI();
    if (myUrl.indexOf("login") >= 0) {
      login(request, response);
      return;
    } else if (myUrl.indexOf("redirect") >= 0) {
      redirect(request, response);
      return;
    }

    if (request.getRemoteUser() == null) {
      String callUrl = request.getRequestURI();
      String query = request.getQueryString();
      if (query != null) {
        callUrl = callUrl + "?" + query;
      }
      String nextEncUrl = java.net.URLEncoder.encode(callUrl);
      String redirectUrl =
          request.getContextPath() + "/application/redirect?nextencurl=" + nextEncUrl;
      response.sendRedirect(redirectUrl);
    } else {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet MyProtectedServlet</title>");
      out.println("</head>");
      out.println("<body>");
      out.println("<h1>Servlet MyProtectedServlet at " + request.getContextPath() + "</h1>");
      out.println("</body>");
      out.println("</html>");

      out.close();
    }
  }
Пример #16
0
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    // read the last post id here .......................
    String url = req.getRequestURI();
    String urlprt[] = url.split("/");
    int urlcount = urlprt.length - 1;

    JSONParser parserPost = new JSONParser();
    JSONObject post = null;
    String id = urlprt[urlcount];

    // read the post  here .............................

    try {

      if (id != null) {
        Object objPost =
            parserPost.parse(new FileReader("..\\webapps\\Blog\\post\\" + id + ".json"));

        post = (JSONObject) objPost;
        String postauthor = post.get("author").toString();
        String posttitle = post.get("title").toString();
        String postcontent = post.get("content").toString();

        JSONArray arr = (JSONArray) post.get("comments");
        List<String> list = new ArrayList<String>();
        Iterator<String> iterator = arr.iterator();

        while (iterator.hasNext()) {
          list.add(iterator.next());
        }

        int listsz = list.size();
        String[] comments = new String[listsz];
        for (int i = 0; i < listsz; i++) {
          comments[i] = list.get(i);
        }

        req.setAttribute("title", posttitle);
        req.setAttribute("content", postcontent);
        req.setAttribute("author", postauthor);
        req.setAttribute("comments", comments);
        req.setAttribute("id", id);

        req.getRequestDispatcher("/view.jsp").forward(req, res);
      }

    } catch (Exception e) {
      res.setContentType("text/html");
      PrintWriter out = res.getWriter();
      out.println("get POST ......................");
      out.println(e);
      out.println("......................");
    }
  }
Пример #17
0
  public static void showSession(HttpServletRequest req, HttpServletResponse res, PrintStream out) {

    // res.setContentType("text/html");

    // Get the current session object, create one if necessary
    HttpSession session = req.getSession();

    // Increment the hit count for this page. The value is saved
    // in this client's session under the name "snoop.count".
    Integer count = (Integer) session.getAttribute("snoop.count");
    if (count == null) {
      count = 1;
    } else count = count + 1;
    session.setAttribute("snoop.count", count);

    out.println(HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag());
    out.println("<HEAD><TITLE>SessionSnoop</TITLE></HEAD>");
    out.println("<BODY><H1>Session Snoop</H1>");

    // Display the hit count for this page
    out.println(
        "You've visited this page " + count + ((!(count.intValue() != 1)) ? " time." : " times."));

    out.println("<P>");

    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration atts = session.getAttributeNames();
    while (atts.hasMoreElements()) {
      String name = (String) atts.nextElement();
      out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }

    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");

    out.println(
        "Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");

    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren't supported.");

    out.println("</BODY></HTML>");
  }
Пример #18
0
 /**
  * Show the pieces of the request, for debugging
  *
  * @param req the HttpServletRequest
  * @return parsed request
  */
 public static String getRequestParsed(HttpServletRequest req) {
   return req.getRequestURI()
       + " = "
       + req.getContextPath()
       + "(context), "
       + req.getServletPath()
       + "(servletPath), "
       + req.getPathInfo()
       + "(pathInfo), "
       + req.getQueryString()
       + "(query)";
 }
  @Test
  @Ignore
  public void showAllNonShippedOrders() throws Exception {
    orders.add(new Order("a", "b", "c"));
    orders.add(new Order("d", "e", "f"));

    when(request.getMethod()).thenReturn("GET");
    when(request.getRequestURI()).thenReturn("/orders");

    ordersController.service();

    verify(ordersView).show(orders);
  }
  @Test
  public void receiveAnOrder() throws Exception {
    when(request.getMethod()).thenReturn("POST");
    when(request.getRequestURI()).thenReturn("/orders");
    when(request.getParameter("order_code")).thenReturn("1234");
    when(request.getParameter("article_code")).thenReturn("ABCD");
    when(request.getParameter("address")).thenReturn("Some Place");

    ordersController.service();

    assertEquals(1, orders.size());
    assertEquals(new Order("1234", "ABCD", "Some Place"), orders.get(0));
  }
Пример #21
0
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();

    if (user != null) {
      // This is a bit horrible, should probably just redirect to a JSP?
      resp.setContentType("text/html");
      resp.getWriter()
          .println(
              "<html><head><link rel=\"icon\" type=\"image/png\" href=\"images/icon16.png\"><meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"><title>TabCloud</title></head><body><div style=\"margin: 40px auto; width: 600px;\"><img style=\"float: left; padding-right: 20px;\" src=\"images/tabcloud200.png\" alt=\"TabCloud\" /><div style=\"font-family:sans-serif; font-size: 1.8em; text-align: center; padding-top: 50px;\"><strong>You are now logged in.</strong><br />Click the TabCloud menu icon to access TabCloud.</div></div></body></html>");
    } else {
      resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
    }
  }
Пример #22
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);
    }
  }
  @Test
  @Ignore
  public void theControllerWillShipAnOrder() throws Exception {
    Order order = new Order("5555", "_", "_");
    orders.add(order);

    when(request.getMethod()).thenReturn("POST");
    when(request.getRequestURI()).thenReturn("/orders/shipped");
    when(request.getParameter("order_code")).thenReturn("5555");

    ordersController.service();

    assertEquals("controller should set shipped", true, order.isShipped());
    verify(ordersView).refresh();
  }
  @Test
  @Ignore
  public void shippedOrdersAreNotShown() throws Exception {
    Order shipped = new Order("X");
    Order notShipped = new Order("Y");
    orders.addAll(asList(shipped, notShipped));
    shipped.ship();

    when(request.getMethod()).thenReturn("GET");
    when(request.getRequestURI()).thenReturn("/orders");

    ordersController.service();

    verify(ordersView).show(asList(notShipped));
  }
Пример #25
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String[] uri = request.getRequestURI().split("/");
    if (uri.length < 4) {
      response.getWriter().print(XavaResources.getString(request, "module_name_missing"));
      return;
    }
    String url = "/naviox/index.jsp?application=" + uri[1] + "&module=" + uri[3];
    RequestDispatcher dispatcher = request.getRequestDispatcher(url);

    Style.setPotalInstance(
        NaviOXStyle
            .getInstance()); // We manage style in NaviOX as in the portal case, to override the
                             // style defined in xava.properties and by device
    dispatcher.forward(request, response);
  }
Пример #26
0
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    // read the last post id here .......................
    String url = req.getRequestURI();
    String urlprt[] = url.split("/");
    int urlcount = urlprt.length - 1;

    JSONParser parserPost = new JSONParser();
    JSONObject post = null;
    String id = urlprt[urlcount];

    // read the post  here .............................

    try {

      if (id != null) {
        Object objPost =
            parserPost.parse(new FileReader("..\\webapps\\Blog\\post\\" + id + ".json"));

        post = (JSONObject) objPost;
        JSONArray msg = (JSONArray) post.get("toapprove");
        msg.add(req.getParameter("content"));

        post.remove("toapprove");
        post.put("toapprove", msg);

        File file = new File("..\\webapps\\Blog\\post\\" + id + ".json");
        file.createNewFile();
        FileWriter filew = new FileWriter(file);
        filew.write(post.toJSONString());
        filew.flush();
        filew.close();

        doGet(req, res);
      }

    } catch (Exception e) {
      res.setContentType("text/html");
      PrintWriter out = res.getWriter();
      out.println("get POST ......................");
      out.println(e);
      out.println("......................");
    }
  }
Пример #27
0
  protected void doCommon(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    try {
      if (log.isDebugEnabled()) log.debug(HttpUtils.fmtRequest(httpRequest));

      // getRequestURL is the exact string used by the caller in the request.
      // Internally, it's the "request URI" that names the service

      // String requestURL = httpRequest.getRequestURL().toString() ;
      String uri = httpRequest.getRequestURI();

      if (uri.length() > urlLimit) {
        httpResponse.setStatus(HttpServletResponse.SC_REQUEST_URI_TOO_LONG);
        return;
      }

      String serviceURI = chooseServiceURI(uri, httpRequest);
      serviceURI = Service.canonical(serviceURI);

      String sender = httpRequest.getRemoteAddr();
      log.info("[" + sender + "] Service URI = <" + serviceURI + ">");

      // MIME-Type
      String contentType = httpRequest.getContentType();

      //            if ( Joseki.contentSPARQLUpdate.equals(contentType) ||
      //                Joseki.contentSPARQLUpdate_X.equals(contentType) )
      //            {}

      Request request = setupRequest(serviceURI, httpRequest);
      request.setParam(Joseki.VERB, httpRequest.getMethod());

      Response response = new ResponseHttp(request, httpRequest, httpResponse);
      Dispatcher.dispatch(serviceURI, request, response);
    } catch (Exception ex) {
      try {
        log.warn("Internal server error", ex);
        //                httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) ;
        //                httpResponse.flushBuffer() ;
        //                httpResponse.getWriter().close() ;
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      } catch (Exception e) {
      }
    }
  }
Пример #28
0
 public void doFilter(ServletRequest request0, ServletResponse response0, FilterChain filterChain)
     throws IOException, ServletException {
   HttpServletRequest request = (HttpServletRequest) request0;
   HttpServletResponse response = (HttpServletResponse) response0;
   if (request.getRequestURI().endsWith(requesturl)) {
     boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
     request.getSession().invalidate();
     if (isAjax) {
       Response<String> kv = new Response<String>();
       kv.setReturncode("00000000");
       kv.setReturnmsg("登出成功");
       outputJson(response, kv);
     } else {
       response.sendRedirect(request.getContextPath() + successurl);
     }
     return;
   }
   filterChain.doFilter(request, response);
 }
  /** Show appropriate order page. */
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    ServletContext sc = getServletContext();
    Connection conn = (Connection) sc.getAttribute("dbConnection");
    HttpSession session = request.getSession();
    synchronized (session) {
      LoginSession ls = (LoginSession) session.getAttribute("loginSession");
      if (ls == null) {
        return;
      }
      Basket basket = ls.getUser().getBasket();
      // If there is no basket, do nothing
      if (basket == null) {
        return;
      }
      if (request.getParameter("dialog").equals("yes")) {
        String msg = null;
        Order order = null;
        try {
          order = new Order();
          msg = order.form(basket, conn);
        } catch (SQLException exc) {
          request.setAttribute("sqlExc", exc);
          request.getRequestDispatcher("/error").forward(request, response);
          return;
        }
        // If there is a message (that means can't form an order)
        if (msg != null) {
          request.setAttribute("errMsg", msg);
        }
      }
      if (request.getParameter("dialog").equals("show")) {
        request.setAttribute("itemList", basket.getItemList());
      }
      request.setAttribute("url", request.getRequestURI());
      request.getRequestDispatcher("/WEB-INF/OrderVerified.jsp").forward(request, response);
    }
  }
 public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
   String[] driverStrings = null;
   if (req.getParameterValues("driver") != null) {
     driverStrings = req.getParameterValues("driver");
   }
   if (driverStrings != null && driverStrings.length > 5) {
     resp.setStatus(400);
   } else {
     NascarConfig config = NascarConfigSingleton.get();
     List<Driver> drivers =
         DatastoreManager.getDriversByNamesAndRace(driverStrings, config.getRaceKey());
     Owner owner = DatastoreManager.getCurrentOwner();
     Lineup lineup = new Lineup(config.getRaceKey());
     boolean driversAdded = lineup.setDrivers(drivers);
     if (driversAdded) {
       Team team = owner.getTeam();
       team.setLineup(lineup);
       DatastoreManager.persistObject(team);
     }
   }
   resp.sendRedirect(req.getRequestURI());
 }