/**
   * Deletes a meeting from the database
   *
   * <p>- Requires a cookie for the session user - Requires a meetingId request parameter for the
   * HTTP GET
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void deletemeetingAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    if (req.getMethod() == HttpMethod.Get) {

      // Get the meeting
      int meetingId = Integer.parseInt(req.getParameter("meetingId"));
      MeetingManager meetingMan = new MeetingManager();
      Meeting meeting = meetingMan.get(meetingId);
      meetingMan.deleteMeeting(meetingId);

      // Update the User Session to remove meeting
      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");
      List<Meeting> adminMeetings = userSession.getUser().getMeetings();

      for (int i = 0; i < adminMeetings.size(); i++) {
        Meeting m = adminMeetings.get(i);
        if (m.getId() == meeting.getId()) {
          adminMeetings.remove(i);
          break;
        }
      }

      redirectToLocal(req, res, "/home/dashboard");
      return;

    } else if (req.getMethod() == HttpMethod.Post) {
      httpNotFound(req, res);
    }
  }
Beispiel #2
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.setContentType("text/html;charset=UTF-8");
   PrintWriter out = response.getWriter();
   if (request.getParameter("get") != null) {
     switch (request.getParameter("get")) {
       case "Title":
         out.print(HTMLEncode(getTitle(request)));
         break;
       case "Ariane":
         out.print(getAriane(request));
         break;
       case "PreviousLink":
         out.print(getPreviousLink(request));
         break;
       case "PreviousName":
         out.print(getPreviousName(request));
         break;
       default:
         out.print("&lt;" + HTMLEncode(request.getParameter("get")) + "&gt");
     }
   } else {
     if (request.getMethod().equals("GET")) printPage(out, request, response);
     else if (request.getMethod().equals("POST")) printPagePost(out, request, response);
   }
 }
  /**
   * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (!initParams.getEnabled()) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    long startTime = 0;
    if (logger.isTraceEnabled()) {
      startTime = System.currentTimeMillis();
    }

    FileFilterMode.setClient(Client.webdav);

    try {
      // Create the appropriate WebDAV method for the request and execute it
      final WebDAVMethod method = createMethod(request, response);

      if (method == null) {
        if (logger.isErrorEnabled())
          logger.error("WebDAV method not implemented - " + request.getMethod());

        // Return an error status

        response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
        return;
      } else if (method.getRootNodeRef() == null) {
        if (logger.isDebugEnabled()) {
          logger.debug(
              "No root node for request ["
                  + request.getMethod()
                  + " "
                  + request.getRequestURI()
                  + "]");
        }

        // Return an error status
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
      }

      // Execute the WebDAV request, which must take care of its own transaction
      method.execute();
    } catch (Throwable e) {
      ExceptionHandler exHandler = new ExceptionHandler(e, request, response);
      exHandler.handle();
    } finally {
      if (logger.isTraceEnabled()) {
        logger.trace(
            request.getMethod()
                + " took "
                + (System.currentTimeMillis() - startTime)
                + "ms to execute ["
                + request.getRequestURI()
                + "]");
      }

      FileFilterMode.clearClient();
    }
  }
  /**
   * Publish the request/response statistics
   *
   * @param request
   * @param requestTime
   * @param response : boolean
   * @return
   * @throws APIFaultException
   * @throws APIManagementException
   */
  public boolean publishStatistics(HttpServletRequest request, long requestTime, boolean response)
      throws APIManagementException {

    UsageStatConfiguration statConf = new UsageStatConfiguration();
    APIMgtUsageDataPublisher publisher = statConf.getPublisher();
    if (publisher != null) {
      publisher.init();
      APIStatsPublisher statsPublisher = new APIStatsPublisher(publisher, statConf.getHostName());
      if (response) {
        statsPublisher.publishResponseStatistics(
            apiKeyValidationDTO,
            request.getRequestURI(),
            request.getContextPath(),
            request.getPathInfo(),
            request.getMethod(),
            requestTime);
      } else {
        statsPublisher.publishRequestStatistics(
            apiKeyValidationDTO,
            request.getRequestURI(),
            request.getContextPath(),
            request.getPathInfo(),
            request.getMethod(),
            requestTime);
      }
      return true;
    }
    return false;
  }
  @RequestMapping(
      value = "/updateBrokerConfig.do",
      method = {RequestMethod.GET, RequestMethod.POST})
  public String updateBrokerConfig(
      ModelMap map,
      HttpServletRequest request,
      @RequestParam(required = false) String brokerAddr,
      @RequestParam(required = false) String clusterName,
      @RequestParam(required = false) String key,
      @RequestParam(required = false) String value) {
    Collection<Option> options = brokerService.getOptionsForUpdateBrokerConfig();
    putPublicAttribute(map, "updateBrokerConfig", options, request);
    try {
      if (request.getMethod().equals(GET)) {

      } else if (request.getMethod().equals(POST)) {
        checkOptions(options);
        brokerService.updateBrokerConfig(brokerAddr, clusterName, key, value);
        putAlertTrue(map);
      } else {
        throwUnknowRequestMethodException(request);
      }
    } catch (Throwable t) {
      putAlertMsg(t, map);
    }
    return TEMPLATE;
  }
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest req, HttpServletResponse resp ){
		
		if("GET".equals(req.getMethod())){
			JSONObject json = AndroidHelper.DoGetForbiddenException();
			req.setAttribute("json", json.toString());
			return mapping.findForward("succes");
		
		}else if("POST".equals(req.getMethod())){
			
			String email = request.getParameter("mail");
			String mdp = req.getParameter("mdp");
			org.json.JSONObject json = new JSONObject();
			PersonneDAO persDAO = new PersonneDAO();
			
			// check the login and the pwd
			if( mail != null && mdp != null){
				Personne p = persDAO.getmailPersonne(mail);
				// managing the misfound exceptions
				if(p == null) {
					json = AndroidHelper.UserNotFoundException();
				// Uncorrect password
				}else if(!mdp.equals(p.getmdpPersonne())){
					json = AndroidHelper.PassIncorrectException()
				} else {
					p.setmailPersonne("");
					p.setmdpPersonne("");
					json = new JSONObject(p);
				}
			
			} else{
  @Override
  public Authentication attemptAuthentication(
      HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    if (!request.getMethod().equals("POST")) {
      throw new AuthenticationServiceException(
          "Authentication method not supported: " + request.getMethod());
    }

    String username = obtainUsername(request);
    String password = obtainPassword(request);

    // Validates username and password
    username = username.trim();

    User user = UserUtil.getUser(username);
    Md5PasswordEncoder encoder = new Md5PasswordEncoder();
    password = encoder.encodePassword(password, AuthenticationFilter.SALT);
    if (user == null || !user.getPassword().equals(password)) {
      throw new AuthenticationServiceException("password or username is notEquals");
    }

    UsernamePasswordAuthenticationToken authRequest =
        new UsernamePasswordAuthenticationToken(username, password);

    setDetails(request, authRequest);

    // return authRequest;
    return this.getAuthenticationManager().authenticate(authRequest);
  }
  /**
   * {@inheritDoc}
   *
   * @see org.sakaiproject.kernel.api.rest.RestProvider#dispatch(java.lang.String[],
   *     javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  public void dispatch(
      String[] elements, HttpServletRequest request, HttpServletResponse response) {
    try {
      FriendsParams params =
          new FriendsParams(
              elements, request, sessionManagerService, userEnvironmentResolverService);
      Map<String, Object> map = Maps.newHashMap();
      switch (params.major) {
        case connect:
          if (!"POST".equals(request.getMethod())) {
            throw new RestServiceFaultException(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
          }
          switch (params.minor) {
            case request:
              map = doRequestConnect(params, request, response);
              break;
            case accept:
              map = doAcceptConnect(params, request, response);
              break;
            case cancel:
              map = doCancelConnect(params, request, response);
              break;
            case reject:
              map = doRejectConnect(params, request, response);
              break;
            case ignore:
              map = doIgnoreConnect(params, request, response);
              break;
            case remove:
              map = doRemoveConnect(params, request, response);
              break;
            default:
              doRequestError();
              break;
          }
          break;
        case status:
          if (!"GET".equals(request.getMethod())) {
            throw new RestServiceFaultException(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
          }
          map = doStatus(params, request, response);
          break;
        default:
          doRequestError();
          break;
      }

      if (map != null) {
        String responseBody = beanConverter.convertToString(map);
        response.setContentType(RestProvider.CONTENT_TYPE);
        response.getOutputStream().print(responseBody);
      }
    } catch (SecurityException ex) {
      throw ex;
    } catch (RestServiceFaultException ex) {
      throw ex;
    } catch (Exception ex) {
      throw new RestServiceFaultException(ex.getMessage(), ex);
    }
  }
Beispiel #9
0
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    HttpSession session = request.getSession();
    Project project = (Project) session.getAttribute("project");
    if (project == null) {
      response.sendRedirect("main.jspx?m=login");
    } else {
      String m = request.getParameter("m");
      if ("login".equals(m) || m == null) {
        login(request, response);
      } else if ("addGoal".equals(m)) {
        if ("POST".equals(request.getMethod())) {
          addGoal(request, response);
        } else {
          response.sendError(405);
        }
      } else if ("editGoal".equals(m)) {
        if ("POST".equals(request.getMethod())) {
          editGoal(request, response);
        } else {
          response.sendError(405);
        }
      } else if ("deleteGoal".equals(m)) {
        deleteGoal(request, response);
      } else {
        response.sendError(404, "参数错误!");
      }
    }
  }
Beispiel #10
0
  /**
   * appends memento timegate link to all resources, that are accessed via GET on resource
   * webservice
   *
   * @param servletRequest
   * @param servletResponse
   * @param filterChain
   * @throws IOException
   * @throws ServletException
   */
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    if (servletRequest instanceof HttpServletRequest) {
      HttpServletRequest request = (HttpServletRequest) servletRequest;

      // memento is only for reading
      if (request.getMethod().equals("GET") || request.getMethod().equals("HEAD")) {
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        URL resource = getResourceURL(request);

        // build timegate link
        if (resource != null) {
          response.addHeader(
              "Link",
              "<"
                  + MementoUtils.timegateURI(resource.toString(), configurationService.getBaseUri())
                  + ">; rel=\"timegate\","
                  + "<"
                  + MementoUtils.timemapURI(resource.toString(), configurationService.getBaseUri())
                  + ">; rel=\"timemap\"");
        }

        filterChain.doFilter(servletRequest, response);
        return;
      }
    }
    filterChain.doFilter(servletRequest, servletResponse);
  }
Beispiel #11
0
 protected <T> T getParamJson(Class<T> clazz) throws Exception {
   RequestJson<T> requestJson = null;
   boolean isError = false;
   try {
     if (request.getMethod().equalsIgnoreCase("POST"))
       requestJson =
           JsonUtils.toObject(
               IOUtils.toString(request.getInputStream()), RequestJson.class, clazz);
     else if (request.getMethod().equalsIgnoreCase("GET")) {
       requestJson =
           JsonUtils.toObject(
               new String(request.getParameter("param").getBytes("ISO-8859-1"), "UTF-8"),
               RequestJson.class,
               clazz);
     }
     if (null != requestJson) {
       return requestJson.getData();
     } else {
       return null;
     }
   } catch (Exception e) {
     isError = true;
     throw e;
   } finally {
     if (isError) outFailResult("json格式错误。");
   }
 }
Beispiel #12
0
  /**
   * Handles a servlet request.
   *
   * @param request the {@link HttpServletRequest}
   * @param response the {@link HttpServletResponse}
   * @throws IOException on error
   */
  public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.log(Level.FINE, "Handing HttpServletRequest " + request.getMethod());
    }

    // set response type
    response.setContentType(JSONRPC_RESPONSE_CONTENT_TYPE);

    // setup streams
    InputStream input = null;
    OutputStream output = response.getOutputStream();

    // POST
    if (request.getMethod().equals("POST")) {
      input = request.getInputStream();

      // GET
    } else if (request.getMethod().equals("GET")) {
      input =
          createInputStream(
              request.getParameter("method"),
              request.getParameter("id"),
              request.getParameter("params"));

      // invalid request
    } else {
      throw new IOException("Invalid request method, only POST and GET is supported");
    }

    // service the request
    handle(input, output);
  }
  @Override
  public void addAtributesFor(HttpServletRequest req, URI resource, JSONObject representation) {
    IPath path = new Path(req.getPathInfo() == null ? "" : req.getPathInfo());

    if (!(("/" + SITE_CONFIGURATION_SERVLET_ALIAS).equals(req.getServletPath()))) return;

    try {
      WebUser webUser = getWebUser(req);
      if (path.segmentCount() == 0) {
        if ("GET".equals(req.getMethod())) { // $NON-NLS-1$
          // GET /site/ (get all site configs)
          JSONArray siteConfigurations =
              representation.optJSONArray(SiteConfigurationConstants.KEY_SITE_CONFIGURATIONS);
          if (siteConfigurations != null) {
            for (int i = 0; i < siteConfigurations.length(); i++) {
              addStatus(req, siteConfigurations.getJSONObject(i), webUser, resource);
            }
          }
        } else if ("POST".equals(req.getMethod())) { // $NON-NLS-1$
          // POST /site/ (create a site config)
          addStatus(req, representation, webUser, resource);
        }
      } else if (path.segmentCount() == 1) {
        // GET /site/siteConfigId (get a single site config)
        addStatus(req, representation, webUser, resource);
      }
    } catch (JSONException e) {
      // Shouldn't happen, but since we are just decorating someone else's response we shouldn't
      // cause a failure
      LogHelper.log(e);
    }
  }
Beispiel #14
0
  /**
   * {@inheritDoc}
   *
   * @see org.sakaiproject.kernel.api.rest.RestProvider#dispatch(java.lang.String[],
   *     javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  public void dispatch(
      String[] elements, HttpServletRequest request, HttpServletResponse response) {
    try {
      if (elements.length >= 1) {
        // the URL is the path to the resource.

        Map<String, Object> map = null;
        if (PRIVATE.equals(elements[1]) && "POST".equals(request.getMethod())) {
          map = doPatchPrivate(elements, request, response);
        } else if (SHARED.equals(elements[1]) && "POST".equals(request.getMethod())) {
          map = doPatchShared(elements, request, response);
        } else {
          throw new RestServiceFaultException(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
        if (map != null) {
          String responseBody = beanConverter.convertToString(map);
          response.setContentType(RestProvider.CONTENT_TYPE);
          response.getOutputStream().print(responseBody);
        }
      }
    } catch (AccessDeniedException ex) {
      throw new RestServiceFaultException(HttpServletResponse.SC_FORBIDDEN, ex.getMessage(), ex);
    } catch (SecurityException ex) {
      throw ex;
    } catch (RestServiceFaultException ex) {
      throw ex;
    } catch (Exception ex) {
      throw new RestServiceFaultException(ex.getMessage(), ex);
    }
  }
  @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();
    }
  }
 public void doService(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   if (req.getMethod().equalsIgnoreCase("get")) {
     doGet(req, resp);
   } else if (req.getMethod().equalsIgnoreCase("post")) {
     doPost(req, resp);
   }
 }
Beispiel #17
0
 @Override
 protected void service(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   if (req.getMethod().equals("UNION")) doUnion(req, resp);
   else if (req.getMethod().equals("INTERSECTION")) doIntersection(req, resp);
   else if (req.getMethod().equals("SUBTRACT")) doSubtract(req, resp);
   else super.service(req, resp);
 }
 private HttpServletRequest requestForCrossContextGet() {
   HttpServletRequest currReq = requestAndResponseAccessFilter.getHttpServletRequest();
   if (currReq == null
       || StringUtils.isBlank(currReq.getMethod())
       || !(currReq.getMethod().equalsIgnoreCase("GET"))) {
     return currReq = new MockHttpServletRequest(servletContext, "GET", "/ssp");
   }
   return currReq;
 }
  /**
   * The web.xml file sets this {@link StartupFilter} to be the first filter for all requests.
   *
   * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
   *     javax.servlet.FilterChain)
   */
  public final void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    if (skipFilter((HttpServletRequest) request)) {
      chain.doFilter(request, response);
    } else {

      HttpServletRequest httpRequest = (HttpServletRequest) request;
      HttpServletResponse httpResponse = (HttpServletResponse) response;

      String servletPath = httpRequest.getServletPath();
      // for all /images and /initfilter/scripts files, write the path
      // (the "/initfilter" part is needed so that the openmrs_static_context-servlet.xml file
      // doesn't
      //  get instantiated early, before the locale messages are all set up)
      if (servletPath.startsWith("/images") || servletPath.startsWith("/initfilter/scripts")) {
        servletPath =
            servletPath.replaceFirst(
                "/initfilter", "/WEB-INF/view"); // strip out the /initfilter part
        // writes the actual image file path to the response
        File file = new File(filterConfig.getServletContext().getRealPath(servletPath));
        if (httpRequest.getPathInfo() != null) file = new File(file, httpRequest.getPathInfo());

        try {
          InputStream imageFileInputStream = new FileInputStream(file);
          OpenmrsUtil.copyFile(imageFileInputStream, httpResponse.getOutputStream());
          imageFileInputStream.close();
        } catch (FileNotFoundException e) {
          log.error("Unable to find file: " + file.getAbsolutePath());
        }
      } else if (servletPath.startsWith("/scripts")) {
        log.error(
            "Calling /scripts during the initializationfilter pages will cause the openmrs_static_context-servlet.xml to initialize too early and cause errors after startup.  Use '/initfilter"
                + servletPath
                + "' instead.");
      }
      // for anything but /initialsetup
      else if (!httpRequest.getServletPath().equals("/" + WebConstants.SETUP_PAGE_URL)) {
        // send the user to the setup page
        httpResponse.sendRedirect(
            "/" + WebConstants.WEBAPP_NAME + "/" + WebConstants.SETUP_PAGE_URL);
      } else {

        if (httpRequest.getMethod().equals("GET")) {
          doGet(httpRequest, httpResponse);
        } else if (httpRequest.getMethod().equals("POST")) {
          // only clear errors before POSTS so that redirects can show errors too.
          errors.clear();
          doPost(httpRequest, httpResponse);
        }
      }
      // Don't continue down the filter chain otherwise Spring complains
      // that it hasn't been set up yet.
      // The jsp and servlet filter are also on this chain, so writing to
      // the response directly here is the only option
    }
  }
Beispiel #20
0
 @Override
 public void handle(
     String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
     throws IOException, ServletException {
   baseRequest = Optional.ofNullable((request instanceof Request) ? (Request) request : null);
   this.response = response;
   isTarget = target.equals(CONTEXT_PATH);
   isPostRequest = request.getMethod().equalsIgnoreCase("post");
   isGetRequest = request.getMethod().equalsIgnoreCase("get");
 }
 public RestRequest(HttpServletRequest request) {
   elements = new HashMap<String, String>(10);
   if ("POST".equalsIgnoreCase(request.getMethod())) {
     action = CREATE;
   } else if ("GET".equalsIgnoreCase(request.getMethod())) {
     action = FIND;
   } else if ("PUT".equalsIgnoreCase(request.getMethod())) {
     action = UPDATE;
   } else if ("DELETE".equalsIgnoreCase(request.getMethod())) {
     action = DELETE;
   }
   String pathInfo = request.getRequestURI();
   String context = request.getContextPath();
   int startIndex = pathInfo.indexOf(context) + context.length();
   pathInfo = pathInfo.substring(startIndex);
   // substring du context
   if (pathInfo.startsWith("/")) {
     pathInfo = pathInfo.substring(1);
   }
   SilverTrace.debug(
       "mailingList", "RestRequest()", "root.MSG_GEN_ENTER_METHOD", "Parsing:" + pathInfo);
   StringTokenizer tokenizer = new StringTokenizer(pathInfo, "/", false);
   String element = tokenizer.nextToken();
   String id = tokenizer.nextToken();
   if ("RmailingList".equalsIgnoreCase(element)) {
     componentId = id;
     SilverTrace.debug(
         "mailingList", "RestRequest()", "root.MSG_GEN_ENTER_METHOD", "componentId=" + id);
   } else if (id != null) {
     elements.put(element, id);
     SilverTrace.debug(
         "mailingList", "RestRequest()", "root.MSG_GEN_ENTER_METHOD", element + '=' + id);
   }
   boolean isKey = true;
   String key = null;
   String value = null;
   while (tokenizer.hasMoreTokens()) {
     value = tokenizer.nextToken();
     if (isKey) {
       key = value;
       isKey = false;
     } else {
       elements.put(key, value);
       SilverTrace.debug(
           "mailingList", "RestRequest()", "root.MSG_GEN_ENTER_METHOD", key + '=' + value);
       isKey = true;
     }
   }
   if (DELETE_ACTION.equalsIgnoreCase(value)) {
     this.action = DELETE;
   } else if (UPDATE_ACTION.equalsIgnoreCase(value)) {
     this.action = UPDATE;
   }
 }
  protected void service(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    Writer output = new OutputStreamWriter(resp.getOutputStream(), "utf-8");
    Reader input = new InputStreamReader(req.getInputStream(), "utf-8");
    resp.setContentType("application/json; charset=utf-8");

    try {
      String path = req.getPathInfo();
      String search = req.getParameter("search");
      if (path.startsWith("/customers")) {
        String id =
            path.length() >= 11
                ? URLDecoder.decode(path.substring("/customers/".length()), "utf-8")
                : "";
        if (!id.isEmpty() && "GET".equals(req.getMethod())) {
          StoredCustomer customer = getXmlStore().findCustomerById(id);
          if (customer != null) {
            JsonHelper.instance().toJson(customer, output);
          } else {
            resp.setStatus(404);
          }
        } else if ("POST".equals(req.getMethod())) {
          Customer customer = JsonHelper.instance().fromJson(input);
          StoredCustomer stored = getXmlStore().addCustomer(customer);
          JsonHelper.instance().toJson(stored, output);
        } else if (!id.isEmpty() && "PUT".equals(req.getMethod())) {
          Customer customer = JsonHelper.instance().fromJson(input);
          if (!getXmlStore().updateCustomerById(id, customer)) {
            resp.setStatus(404);
          } else {
            JsonHelper.instance().toJson(customer, output);
          }
        } else if (!id.isEmpty() && "DELETE".equals(req.getMethod())) {
          if (!getXmlStore().deleteCustomerById(id)) resp.setStatus(404);
        } else if (search != null) {
          Collection<StoredCustomer> customers = getXmlStore().findCustomersByText(search);
          JsonHelper.instance().toJson(customers, output);
        } else {
          Collection<StoredCustomer> customers = getXmlStore().findAllCustomers();
          JsonHelper.instance().toJson(customers, output);
        }
      } else if ("/types".equals(path)) {
        JsonHelper.instance().toJsonTypes(output);
      } else {
        resp.setStatus(404);
      }

    } catch (Throwable e) {
      resp.setStatus(500);
      error(output, "Exception: " + e);
    }

    output.flush();
  }
Beispiel #23
0
  public View handle(
      final ConsumedPath path, final HttpServletRequest request, final HttpServletResponse response)
      throws Exception {
    String pageName = path.next();
    if (pageName == null || "".equals(pageName)) {
      return new RedirectToPageView(_wikiUrls, PAGE_FRONT_PAGE);
    }
    if (pageName.contains("/")) {
      throw new InvalidInputException(PATH_WALK_ERROR_MESSAGE);
    }

    final PageReference pageReference = new PageReferenceImpl(pageName);
    request.setAttribute("page", pageReference);

    final Page page = _pageSource.get(pageReference);
    if ("attachments".equals(path.peek())) {
      path.next();
      final boolean isPost = request.getMethod().equals("POST");
      if (path.hasNext()) {
        if (isPost && request.getParameter(DefaultPageImpl.SUBMIT_DELETE) != null) {
          return page.deleteAttachment(pageReference, path, request, response);
        }
        return page.attachment(pageReference, path, request, response);
      } else {
        if (isPost) {
          return page.attach(pageReference, path, request, response);
        } else {
          return page.attachments(pageReference, path, request, response);
        }
      }
    } else if (path.hasNext() && !"".equals(path.peek()) && !"opensearch.xml".equals(path.peek())) {
      throw new NotFoundException();
    } else if (request.getParameter("history") != null) {
      return page.history(pageReference, path, request, response);
    } else if ("POST".equals(request.getMethod())) {
      if (request.getParameter(SUBMIT_SAVE) != null
          || request.getParameter(SUBMIT_COPY) != null
          || request.getParameter(SUBMIT_RENAME) != null
          || request.getParameter(SUBMIT_UNLOCK) != null) {
        return page.set(pageReference, path, request, response);
      } else {
        return page.editor(pageReference, path, request, response);
      }
    } else {
      if (request.getParameter(SUBMIT_RENAME) != null) {
        return new JspView("Rename");
      } else if (request.getParameter(SUBMIT_COPY) != null) {
        return new JspView("Copy");
      }
      return page.get(pageReference, path, request, response);
    }
  }
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {

    System.out.println(
        "CachingInterceptor.preHandle() - " + request.getRequestURI() + "-" + request.getMethod());
    if (isResourceCached(request.getRequestURI() + "-" + request.getMethod())) {
      response.setStatus(HttpStatus.NOT_MODIFIED.value());
      return false;
    }

    return true;
  }
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    boolean result = super.preHandle(request, response, handler);

    if (handler instanceof HandlerMethod) {
      HandlerMethod method = (HandlerMethod) handler;

      // If current method is annotated with @PublicSpace, don't go further : we should have access
      // even if we are not logged in !
      PublicSpace publicSpaceAnnotation = method.getMethodAnnotation(PublicSpace.class);
      if (publicSpaceAnnotation != null) {
        return result;
      }

      // Starting from here, we should ensure user is logged in !
      AuthenticatedUser user = SessionHolder.getAuthenticatedUser(request);
      // If not logged in, send redirect to auth url
      if (user == null) {
        LOG.warn(
            "Access to {} ({}) needs an authenticated user !",
            request.getMethod(),
            request.getRequestURI());
        HttpResponses.sendJSONRedirect(authUrl, request, response);
        return false;
      }

      // Now checking if current method is annotated with @RequireGlobalAuthorizations : if so,
      // current authenticated user
      // should match @RequireGlobalAuthorizations authorizations restrictions
      RequireGlobalAuthorizations requireGlobalAuthorizationsAnnotation =
          method.getMethodAnnotation(RequireGlobalAuthorizations.class);
      if (requireGlobalAuthorizationsAnnotation != null) {
        GlobalAuthorization[] globalAuthorization = requireGlobalAuthorizationsAnnotation.value();
        ConditionnalOperator operator = requireGlobalAuthorizationsAnnotation.operator();

        if (!Permissions.hasAuthorizations(user, operator, globalAuthorization)) {
          LOG.warn(
              "User {} and globalAuthorizations {} cannot access {} {} (insufficient privileges !)",
              user.getIdentity().getEmail(),
              user.getGlobalAuthorizations(),
              request.getMethod(),
              request.getRequestURI());
          HttpResponses.sendJSONRedirect(authUrl, request, response);
          return false;
        }
      }
    }

    return result;
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String path = req.getRequestURI().substring(req.getContextPath().length());

    InputStream reqInputStream = req.getInputStream();
    String bodyContent = IOUtils.toString(reqInputStream, StandardCharsets.UTF_8.name());
    if (bodyContent != null && !bodyContent.isEmpty()) {
      LOGGER.info("request body content:{}", bodyContent);
    }

    String outputMime = null;
    OutputStream out = resp.getOutputStream();

    InputStream is = null;

    if (!req.getMethod().equalsIgnoreCase(HttpMethod.GET)) {
      LOGGER.info("checking for path:/{}{}.json", req.getMethod(), path);
      is = this.getClass().getResourceAsStream("/" + req.getMethod() + path + ".json");
    }

    if (is == null) {
      LOGGER.info("checking for path:{}.json", path);
      is = this.getClass().getResourceAsStream(path + ".json");
    }

    if (is != null) {
      outputMime = MediaType.APPLICATION_JSON;
    } else {
      LOGGER.info("checking for path:{}.txt", path);
      is = this.getClass().getResourceAsStream(path + ".txt");
      if (is != null) {
        outputMime = MediaType.APPLICATION_OCTET_STREAM;
      }
    }

    if (outputMime != null) {
      resp.setContentType(outputMime);
    }

    if (is == null) {
      resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {
      IOUtils.copy(is, out);
      is.close();
    }

    out.close();
  }
Beispiel #27
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.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      if (request.getMethod().equals("GET")) {
        HttpSession session = request.getSession();
        String username = session.getAttribute("USERNAME").toString();
        UserEntityDAO userDAO = new UserEntityDAO();
        UserEntity thisUser = userDAO.getUserDetails(username);

        UnavailableProjectDAO unavailableProjDAO = new UnavailableProjectDAO();
        List<UnavailableProjectEntity> currentProj =
            unavailableProjDAO.getAllProjectsTypeOrg(ProjectCharterDAO.ON_GOING, thisUser.getId());

        unavailableProjDAO = new UnavailableProjectDAO();
        List<UnavailableProjectEntity> currentProjList =
            unavailableProjDAO.getAllProjectsTypeOrgCommunity(
                ProjectCharterDAO.ON_GOING, thisUser.getId());

        request.setAttribute("currentProj", currentProj);
        request.setAttribute("currentProjList", currentProjList);
        session.removeAttribute("isChangeCharter");
        RequestDispatcher dispatcher = request.getRequestDispatcher("/sysOrg/CurrentProjects.jsp");
        dispatcher.forward(request, response);
      } else if (request.getMethod().equals("POST")) {
        if (request.getParameter("ViewFullProjectCharter") != null) {
          String project_id = request.getParameter("ViewFullProjectCharter");
          HttpSession session = request.getSession();
          session.setAttribute("project_id", project_id);
          response.sendRedirect("ViewFullProjectCharter");
        } else if (request.getParameter("WorkStructure") != null) {
          String project_id = request.getParameter("WorkStructure");
          String[] id_type = project_id.split("-");
          HttpSession session = request.getSession();
          session.setAttribute("project_id", id_type[0]);
          if (id_type[1].equals("Seminar")) {
            session.setAttribute("typeOfStructure", "seminar");
            response.sendRedirect("WorkStructure_Seminar");
          } else {
            session.setAttribute("typeOfStructure", "health");
            response.sendRedirect("WorkStructure_Health");
          }
        }
      }
    } finally {
      out.close();
    }
  }
Beispiel #28
0
 @Override
 protected void service(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException {
   final int delay =
       req.getParameter("delay") == null ? 0 : Integer.parseInt(req.getParameter("delay"));
   try {
     Thread.sleep(delay);
   } catch (InterruptedException e) {
     // ignore
   }
   final String q = req.getParameter("q") == null ? "" : req.getParameter("q");
   if (q.equals("png")) {
     final ServletOutputStream out = res.getOutputStream();
     res.setContentType("image/png");
     copy(getClass().getClassLoader().getResourceAsStream("data/google.png"), out);
   } else {
     final PrintWriter out = res.getWriter();
     switch (q) {
       case "html":
         res.setContentType("text/html");
         out.print("<html><body><ul>");
         for (int i = 0; i < 50; i++) {
           out.println("<li>" + i + "</li>");
         }
         out.print("</ul></body></html>");
         break;
       case "json":
         res.setContentType("application/json");
         final ObjectMapper mapper = new ObjectMapper();
         final Map<String, Object> map = new HashMap<>();
         map.put("method", req.getMethod());
         map.put("url", req.getRequestURL().toString());
         map.put("headers", headers(req));
         map.put("query", query(req));
         mapper.writeValue(out, map);
         break;
       case "error":
         res.sendError(500, "Dummy error message");
         break;
       default:
         out.println(req.getMethod() + " " + req.getRequestURL());
         headers(req, out);
         query(req, out);
         copy(req.getReader(), out);
     }
   }
   res.flushBuffer();
 }
Beispiel #29
0
  /**
   * Handles a single request from the given {@link InputStream}, that is to say that a single
   * {@link JsonNode} is read from the stream and treated as a JSON-RPC request. All responses are
   * written to the given {@link OutputStream}.
   *
   * @param ips the {@link InputStream}
   * @param ops the {@link OutputStream}
   * @throws JsonParseException
   * @throws JsonMappingException
   * @throws IOException
   */
  public void handle(HttpServletRequest request, HttpServletResponse response)
      throws JsonParseException, JsonMappingException, IOException {

    // set response type
    response.setContentType(JSONRPC_RESPONSE_CONTENT_TYPE);

    // setup streams
    InputStream input = null;
    OutputStream output = response.getOutputStream();

    // POST
    if (request.getMethod().equals("POST")) {
      input = request.getInputStream();

      // GET
    } else if (request.getMethod().equals("GET")) {

      // get parameters
      String method = request.getParameter("method");
      String id = request.getParameter("id");
      String params =
          URLDecoder.decode(new String(Base64.decode(request.getParameter("params"))), "UTF-8");

      // create full RPC request
      StringBuilder buff = new StringBuilder();
      buff.append("{ ")
          .append("\"id\": \"")
          .append(id)
          .append("\", ")
          .append("\"method\": \"")
          .append(method)
          .append("\", ")
          .append("\"params\": ")
          .append(params)
          .append(" ")
          .append("}");

      // setup stream to byte array
      input = new ByteArrayInputStream(buff.toString().getBytes());

      // invalid request
    } else {
      throw new IOException("Invalid request method, only POST and GET is supported");
    }

    // service the request
    handleNode(mapper.readValue(input, JsonNode.class), output);
  }
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    String relativeUrl = request.getRequestURI(); /* 以根开头的URL */
    String path = request.getContextPath(); /* 获取客户端请求的上下文根 */

    /** 如果是登录请求,则进行登录认证。 如果是其它请求,则进行IP绑定匹配。 */
    if (relativeUrl.replaceAll(path, "").equals("/login")) { // 登录请求,登录认证
      if (request.getMethod().equals("POST")) { // 登录参数必须通过post方式传过来,security要求的
        int status = myAuthentication.getAuthenticationStatus(request); // 调用认证逻辑
        if (status == 0) { // 通过认证,则保存登录IP到session,并通过此过滤器
          request.getSession().setAttribute("bindIp", RequestIP.getRequestIp(request));
          chain.doFilter(request, response);
        } else { // 未通过认证,则拒绝登录,并返回登录页面提示相关信息
          response.sendRedirect(path + "/toIndex.action?error=" + status);
        }
      } else { // 如果不是POST方式,则返回登录页面,并提示信息
        response.sendRedirect(path + "/toIndex.action?error=9"); // 登录必须用POST方式
      }
    } else { // 其它请求(filters="none"的请求不会被处理,logout请求在此filter之前会被处理)
      // PC端进行IP认证
      String loginIp = (String) request.getSession().getAttribute("bindIp"); // 登录时记录的IP
      String currentIp = RequestIP.getRequestIp(request); // 当前请求的IP
      if (loginIp != null && !loginIp.equals(currentIp)) { // 如果此次请求的IP与登录IP不符,则禁止访问,并返回提示
        response.sendRedirect(path + "/toIndex.action?error=10");
      } else { // 如果IP匹配,则通过此过滤器
        chain.doFilter(request, response);
      }
    }
  }