Esempio n. 1
0
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    HttpSession session = req.getSession();

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

    /* if ( chemin.startsWith( "/resources" )
            || req.getServletPath().contains( "/javax.faces.resource" ) ) {

        chain.doFilter( request, response );
        return;
    }*/

    if (session.isNew()) {
      doLogin(request, response, req);
      return;
    }

    UserAdmin user = (UserAdmin) session.getAttribute("user");

    if (user == null) {
      doLogin(request, response, req);
      return;
    }

    if (user.getRoles().get(0).getRolename().equals("administrateur")) {
      if (req.getServletPath().contains("login.xhtml")) {
        resp.sendRedirect("/PFE_GP/Admin/admin.xhtml");
        return;
      }

    } else if (user.getRoles().get(0).getRolename().equals("planification")) {
      if (req.getServletPath().contains("login.xhtml")) {
        resp.sendRedirect("/PFE_GP/Planification/planification.xhtml");
        return;
      }
    } else if (user.getRoles().get(0).getRolename().equals("prod")) {
      if (req.getServletPath().contains("login.xhtml")) {
        resp.sendRedirect("/PFE_GP/Production/production.xhtml");
        return;
      }
    } else if (user.getRoles().get(0).getRolename().equals("maintenance")) {
      if (req.getServletPath().contains("login.xhtml")) {
        resp.sendRedirect("/PFE_GP/Maintenance/maintenance.xhtml");
        return;
      }
    }

    if (user.getRoles().get(0).getRolename().equals("maintenance")
        && !req.getRequestURI().contains("maintenance")) {
      resp.sendRedirect("/PFE_GP/accessDenied.xhtml");
    } else if (user.getRoles().get(0).getRolename().equals("prod")
        && !req.getRequestURI().contains("production")) {
      resp.sendRedirect("/PFE_GP/accessDenied.xhtml");
    }

    chain.doFilter(request, response);
  }
 protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
   String flowId = flowUrlHandler.getFlowId(request);
   if (getApplicationContext().containsBean(flowId)) {
     Object handler = getApplicationContext().getBean(flowId);
     if (handler instanceof FlowHandler) {
       if (logger.isDebugEnabled()) {
         logger.debug(
             "Mapping request with URI '"
                 + request.getRequestURI()
                 + "' to flow with id '"
                 + flowId
                 + "'; custom FlowHandler "
                 + handler
                 + " will manage flow execution");
       }
       return handler;
     }
   }
   if (flowRegistry.containsFlowDefinition(flowId)) {
     if (logger.isDebugEnabled()) {
       logger.debug(
           "Mapping request with URI '"
               + request.getRequestURI()
               + "' to flow with id '"
               + flowId
               + "'");
     }
     return new DefaultFlowHandler(flowId);
   }
   if (logger.isDebugEnabled()) {
     logger.debug("No flow mapping found for request with URI '" + request.getRequestURI() + "'");
   }
   return null;
 }
  @Override
  public void handle(
      final HttpServletRequest request,
      final HttpServletResponseWithGetStatus wrapper,
      final StubbedDataManager stubbedDataManager)
      throws Exception {

    if (!request.getRequestURI().equals(AdminHandler.ADMIN_ROOT)) {
      wrapper.setStatus(HttpStatus.METHOD_NOT_ALLOWED_405);
      wrapper.getWriter().println("Method POST is not allowed on URI " + request.getRequestURI());
      return;
    }

    final String post = HandlerUtils.extractPostRequestBody(request, AdminHandler.NAME);
    if (!StringUtils.isSet(post)) {
      final String errorMessage =
          String.format(
              "%s request on URI %s was empty", request.getMethod(), request.getRequestURI());
      HandlerUtils.configureErrorResponse(wrapper, HttpStatus.NO_CONTENT_204, errorMessage);
      return;
    }

    stubbedDataManager.refreshStubbedData(new YamlParser(), post);

    if (stubbedDataManager.getStubHttpLifecycles().size() == 1) {
      wrapper.addHeader(HttpHeaders.LOCATION, stubbedDataManager.getOnlyStubRequestUrl());
    }

    wrapper.setStatus(HttpStatus.CREATED_201);
    wrapper.getWriter().println("Configuration created successfully");
  }
  /**
   * 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;
  }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    String fileName = req.getRequestURI().split("/")[req.getRequestURI().split("/").length - 1];
    boolean bExcept = false;
    for (String prefix : exceptList) {
      if (fileName.startsWith(prefix)) {
        bExcept = true;
        break;
      }
    }

    if (!bExcept) {
      HttpSession session = ((HttpServletRequest) request).getSession();
      if (!(session != null && session.getAttribute("user") != null)) {
        session.setAttribute("lastFileName", fileName);
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.sendRedirect("login.jsp");
        return;
      }
    }
    //    String browserDet = ((HttpServletRequest) request).getHeader("User-Agent").toLowerCase();
    //    if (browserDet.indexOf("msie") != -1) {
    //      PrintWriter out = response.getWriter();
    //      out.println("<html><head></head><body>");
    //      out.println("<h1>Sorry, page cannot be displayed!</h1>");
    //      out.println("</body></html>");
    //      out.flush();
    //      return;
    //    }
    chain.doFilter(request, response);
  }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
      throws IOException, ServletException {
    if (response instanceof HttpServletResponse && request instanceof HttpServletRequest) {
      HttpServletRequest httpRequest = (HttpServletRequest) request;
      HttpServletResponse httpResponse = (HttpServletResponse) response;

      // skip auth for static content, middle of auth flow, notify servlet
      if (httpRequest.getRequestURI().startsWith("/static")
          || httpRequest.getRequestURI().equals("/oauth2callback")
          || httpRequest.getRequestURI().contains("/_ah")) {
        LOG.info("Skipping auth check for certain urls");
        filterChain.doFilter(request, response);
        return;
      }

      LOG.fine("Checking to see if anyone is logged in");
      if (AuthUtil.getUserId(httpRequest) == null
          || AuthUtil.getCredential(AuthUtil.getUserId(httpRequest)) == null
          || AuthUtil.getCredential(AuthUtil.getUserId(httpRequest)).getAccessToken() == null) {
        // redirect to auth flow
        httpResponse.sendRedirect(WebUtil.buildUrl(httpRequest, "/oauth2callback"));
        return;
      }

      // Things checked out OK :)
      filterChain.doFilter(request, response);
    } else {
      LOG.warning("Unexpected non HTTP servlet response. Proceeding anyway.");
      filterChain.doFilter(request, response);
    }
  }
  /**
   * Converts filter information from the URL (the request's filename) into a request attributes for
   * use in the Storefront's controllers.
   *
   * @param aRequest the request
   * @param aResponse not used
   */
  public void resolve(final HttpServletRequest aRequest, final HttpServletResponse aResponse) {

    if (LOG.isDebugEnabled()) {
      LOG.debug("Received request :" + aRequest.getRequestURI());
    }

    // Sets the SEO URL for future comparison. This is required because
    // the request URI gets changed when the request is forwarded and we need
    // to save the original request URI for it to be compared at a later stage.
    aRequest.setAttribute(
        WebConstants.SEO_URL_STRING, urlUtility.decodeUrl2Text(aRequest.getRequestURI()));

    // The information we want is in the request's filename.
    final String pageStr = getUriFilename(aRequest.getRequestURI());
    final String[] tokens = pageStr.split(fieldSeparator);

    // Process the information into request attributes
    try {
      setupRequestAttributes(tokens, aRequest, aResponse);
    } catch (IOException exc) {
      LOG.warn("Exception occurred while parsing the SEO URL", exc);
    }

    LOG.debug("Urlrewrite --- before infomation call");
    processPossibleLocaleChange(aRequest, aResponse);
  }
  /**
   * @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();
    }
  }
Esempio n. 9
0
  @RequestMapping
  public @ResponseBody String dispatch(HttpServletRequest request) throws Exception {
    String path = request.getRequestURI();
    if (path.indexOf(request.getContextPath()) > -1) {
      path = path.substring(request.getContextPath().length());
    }
    List<Service> services = serviceRepository.findAll();
    for (Service service : services) {
      if (service.getUrl().matches(path)) {
        System.out.println("MATCH: " + service.getUrl());
        SoapService soap = new SoapService();
        soap.setBody(request.getInputStream());
        System.out.println(soap.dispatch());
      }
    }
    System.out.println("PATH " + request.getServletPath());
    System.out.println("QUERY " + request.getQueryString());
    System.out.println("URL " + request.getRequestURL());

    System.out.println("CONTEXT " + request.getContextPath());
    System.out.println("URI " + request.getRequestURI());

    System.out.println(serviceRepository.count());

    return "RESPONSE: " + request;
  }
Esempio n. 10
0
  /**
   * Dispatches client requests to the {@link #service(URI, URI, HttpServletRequest,
   * HttpServletResponse)} method.
   *
   * <p>If the servlet path matches the regular expression declared by the property {@link
   * ServletProperties#FILTER_STATIC_CONTENT_REGEX} then the request is forwarded to the next filter
   * in the filter chain so that the underlying servlet engine can process the request otherwise
   * Jersey will process the request.
   *
   * @param request the {@link HttpServletRequest} object that contains the request the client made
   *     to the servlet.
   * @param response the {@link HttpServletResponse} object that contains the response the servlet
   *     returns to the client.
   * @param chain the chain of filters from which the next filter can be invoked.
   * @throws java.io.IOException in case of an I/O error.
   * @throws javax.servlet.ServletException in case of an error while executing the filter chain.
   */
  public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    if (request.getAttribute("javax.servlet.include.request_uri") != null) {
      final String includeRequestURI =
          (String) request.getAttribute("javax.servlet.include.request_uri");

      if (!includeRequestURI.equals(request.getRequestURI())) {
        doFilter(
            request,
            response,
            chain,
            includeRequestURI,
            (String) request.getAttribute("javax.servlet.include.servlet_path"),
            (String) request.getAttribute("javax.servlet.include.query_string"));
        return;
      }
    }

    /**
     * JERSEY-880 - WAS interprets HttpServletRequest#getServletPath() and
     * HttpServletRequest#getPathInfo() differently when accessing a static resource.
     */
    final String servletPath =
        request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());

    doFilter(
        request, response, chain, request.getRequestURI(), servletPath, request.getQueryString());
  }
Esempio n. 11
0
 /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String reqUrl =
       request
           .getRequestURI()
           .substring(request.getContextPath().length(), request.getRequestURI().length());
   switch (reqUrl) {
     case "/deleteAuthor":
       try {
         deleteAuthor(request, response);
       } catch (SQLException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
       }
       break;
     case "/pageAuthor":
       try {
         readAllAuthors(request, response);
       } catch (SQLException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
       }
       break;
     default:
       break;
   }
 }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
      throws IOException, ServletException {

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

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

      ObjectMapper mapper = new ObjectMapper();

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

      SecurityContextHolder.clearContext();

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

      ObjectMapper mapper = new ObjectMapper();

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

      SecurityContextHolder.clearContext();

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

      ObjectMapper mapper = new ObjectMapper();

      FailureResponse error =
          new FailureResponse(
              httpRequest.getMethod(),
              httpRequest.getRequestURI(),
              "Internal server error, please contact the backend team.");
      httpResponse.getWriter().println(mapper.writeValueAsString(error));
      LOGGER.error(exception.getMessage(), exception);
      SecurityContextHolder.clearContext();
    }
  }
Esempio n. 13
0
 /*    */ protected String processPath(HttpServletRequest request, HttpServletResponse response)
     throws IOException
       /*    */ {
   /* 50 */ String path = null;
   /*    */
   /* 53 */ path = (String) request.getAttribute("javax.servlet.include.path_info");
   /* 54 */ if (path == null) {
     /* 55 */ path = request.getPathInfo();
     /*    */ }
   /* 57 */ if ((path != null) && (path.length() > 0)) {
     /* 58 */ return path;
     /*    */ }
   /*    */
   /* 62 */ path = (String) request.getAttribute("javax.servlet.include.servlet_path");
   /* 63 */ if (path == null) {
     /* 64 */ path = request.getServletPath();
     /*    */ }
   /* 66 */ String prefix = getModuleConfig(request).getPrefix();
   /* 67 */ if (!path.startsWith(prefix)) {
     /* 68 */ log.error(getInternal().getMessage("processPath", request.getRequestURI()));
     /* 69 */ response.sendError(
         400, getInternal().getMessage("processPath", request.getRequestURI()));
     /* 70 */ return null;
     /*    */ }
   /* 72 */ path = path.substring(prefix.length());
   /* 73 */ int slash = path.lastIndexOf("/");
   /* 74 */ int period = path.lastIndexOf(".");
   /* 75 */ if ((period >= 0) && (period > slash)) {
     /* 76 */ path = path.substring(1, period);
     /*    */ }
   /* 78 */ return path;
   /*    */ }
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    System.out.println(request.getRequestURI());

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

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

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

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

    response.setCharacterEncoding("UTF-8");
    response.getWriter().append(json);
  }
Esempio n. 15
0
  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
    HttpServletRequest r = (HttpServletRequest) req;

    // Some info
    LOG.log(Level.INFO, "URL={0}", r.getRequestURL());
    LOG.log(Level.INFO, "URI={0}", r.getRequestURI());
    LOG.log(Level.INFO, "SERVLET PATH={0}", r.getServletPath());
    LOG.log(Level.INFO, "PATH INFO={0}", r.getPathInfo());
    LOG.log(Level.INFO, "QUERY={0}", r.getQueryString());
    LOG.log(Level.INFO, "--------------------------");

    String uri = r.getRequestURI();
    String path = r.getServletPath();
    try {
      // Pass through resources
      if (resources.matcher(uri).matches()) {
        chain.doFilter(req, res);
      } else if (path.equals("/") || path.equals("/home")) {
        req.getRequestDispatcher(TEMPLATE + "?partial=home").forward(req, res);
      } else {
        chain.doFilter(req, res);
      }
    } catch (IOException | ServletException ex) {
      LOG.log(Level.WARNING, ex.getMessage());
      try {
        req.setAttribute("error", ex.getMessage());
        req.getRequestDispatcher(TEMPLATE + "?partial=error").forward(req, res);
      } catch (ServletException | IOException ex1) {
        LOG.log(Level.SEVERE, ex1.getMessage());
      }
    }
  }
Esempio n. 16
0
  private boolean validarPermissao(HttpServletRequest request) {

    UsuarioVO usuarioVO = (UsuarioVO) request.getSession().getAttribute(ConstantesIF.LOGIN);
    boolean permissao = true;

    if (PerfilUsuarioIF.BRAND.equals(usuarioVO.getPerfil())) {
      if (urlBrand.get(request.getRequestURI()) == null) {
        permissao = false;
      }
    } else if (PerfilUsuarioIF.CLIENTE.equals(usuarioVO.getPerfil())) {
      if (urlCliente.get(request.getRequestURI()) == null) {
        permissao = false;
      }
    }
    if (PerfilUsuarioIF.FORNECEDOR.equals(usuarioVO.getPerfil())) {
      if (urlFornecedor.get(request.getRequestURI()) == null) {
        permissao = false;
      }
    } else {
      permissao = false;
    }

    if (!permissao) {
      request.getSession().invalidate();
      request.setAttribute("msg", "O usuário não possui permissão para funcionalidade.");
    }

    return permissao;
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    if (trusteeHomeUrls.contains(req.getRequestURI())) {
      timeOutPage = "TrusteeHome.xhtml";
    } else {
      timeOutPage = "Login.xhtml";
    }

    if (!req.getRequestURI().equals("/Evoting/Login.xhtml")
        && !req.getRequestURI().equals("/Evoting/")
        && !req.getRequestURI().equals("/Evoting/TrusteeHome.xhtml")
        && !req.getRequestURI().equals("/Evoting/DecodeVotes.xhtml")
        && !req.getRequestURI().equals("/Evoting/MixNode.xhtml")) {

      if (isSessionInvalid(req)) {
        System.out.println("Session is invalid");
        String timeOutUrl = req.getContextPath() + "/" + timeOutPage;
        res.sendRedirect(timeOutUrl);
        return;
      }
    }

    chain.doFilter(request, response);
  }
Esempio n. 18
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);
 }
Esempio n. 19
0
 @Override
 public void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   if (req.getRequestURI().startsWith("/issues/")) {
     handleIssueRequest(getPersistenceManager(), req, resp, req.getRequestURI());
   } else {
     show404(resp);
   }
 }
Esempio n. 20
0
  /**
   * Gets the request URI relative to the current context path.
   *
   * <p>As an example:
   *
   * <pre>
   * requestURI = "/webapp/index.jsp"
   * contextPath = "/webapp"
   * </pre>
   *
   * The method will return {@code "/index.jsp"}.
   *
   * @param pRequest the current HTTP request
   * @return the request URI relative to the current context path.
   */
  public static String getContextRelativeURI(final HttpServletRequest pRequest) {
    String context = pRequest.getContextPath();

    if (!StringUtil.isEmpty(context)) { // "" for root context
      return pRequest.getRequestURI().substring(context.length());
    }

    return pRequest.getRequestURI();
  }
 public long getLastModified(HttpServletRequest request) {
   if (Calendar.getInstance().getTimeInMillis() > 0)
     return Calendar.getInstance()
         .getTimeInMillis(); // comment this line if you want allow browser to check when resource
                             // was last modified
   String userID = (String) request.getSession().getAttribute(SportletProperties.PORTLET_USER);
   if (userID == null || userID.equals("")) {
     if (DEBUG)
       log(
           "LastModifiedRequest blocked (userID="
               + userID
               + ") !!! Request: "
               + request.getRequestURI()
               + "\nIP: "
               + request.getRemoteAddr()
               + "\n");
     return Calendar.getInstance().getTimeInMillis();
   } else if (!inited) {
     return Calendar.getInstance().getTimeInMillis();
   } else {
     String userDirPath = secureDirPath + "/" + userID;
     if (!(new File(userDirPath).isDirectory())) {
       if (DEBUG)
         log(
             "LastModifiedRequest blocked (userDirPath="
                 + userDirPath
                 + " is not directory) !!! Request: "
                 + request.getRequestURI()
                 + "\nIP: "
                 + request.getRemoteAddr()
                 + "\n");
       return Calendar.getInstance().getTimeInMillis();
     } else {
       String resourcePath =
           util.substitute(
               "s!" + request.getContextPath() + request.getServletPath() + "!!",
               request.getRequestURI());
       File resource = new File(userDirPath + resourcePath);
       if (!resource.exists()) {
         log(
             "LastModifiedRequest blocked (Not found, resource="
                 + userDirPath
                 + resourcePath
                 + ") !!! Request: "
                 + request.getRequestURI()
                 + "\nIP: "
                 + request.getRemoteAddr()
                 + "\n");
         return new Date().getTime();
       } else {
         return resource.lastModified();
       }
     }
   }
 }
Esempio n. 22
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.");
   }
 }
Esempio n. 23
0
 @RequestMapping(method = RequestMethod.POST, value = "/login/**")
 protected ModelAndView handleFormPostAction(
     HttpServletRequest request, HttpServletResponse response) throws Exception {
   String requestURI = request.getRequestURI();
   if (StringUtils.isNotEmpty(requestURI)) {
     if (requestURI.matches(".*[0-9A-Fa-f]{64}$")) {
       log.trace("form post {}", requestURI);
       return new ModelAndView("forward:/api/" + request.getRequestURI());
     }
   }
   return new ModelAndView("forward:/api/" + request.getRequestURI());
 }
  @Override
  public Object invoke(MethodInvocation invocation) throws Throwable {
    HttpServletRequest request = requestFactory.getObject();

    LOG.info(String.format("start: %s %s", request.getRequestURI(), invocation.getMethod()));

    try {
      return invocation.proceed();
    } finally {
      LOG.info(String.format("end: %s %s", request.getRequestURI(), invocation.getMethod()));
    }
  }
  @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;
  }
  /**
   * Handles the inlining process.
   *
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    logger.debug("Serve {} page request.", request.getRequestURI());

    // return json
    response.setContentType("application/json");
    // Do not cache
    response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
    response.setHeader("Pragma", "no-cache");

    // serve request
    DroidMateUser user = (DroidMateUser) getServletContext().getAttribute("user");
    JSONObject result = new JSONObject();

    // handle START_INLINER request
    String startInliner = request.getParameter(START_INLINER);
    if (startInliner != null) {
      logger.debug(
          "{}: Handle {} parameter {} with value {}",
          request.getRequestURI(),
          request.getMethod(),
          START_INLINER,
          startInliner);

      JSONResponseWrapper startInliningResult = new JSONResponseWrapper();

      // Inliner is already started, return
      if (user.isInlinerStarted()) {
        startInliningResult = new JSONResponseWrapper(false, "Inliner is already started.");
      } else {
        // try start inliner
        try {
          boolean inlinerResult = user.startInliner();
          if (inlinerResult) {
            startInliningResult =
                new JSONResponseWrapper(inlinerResult, "Inliner successfully finished.");
          } else {
            startInliningResult =
                new JSONResponseWrapper(inlinerResult, "Inliner had an intern error.");
          }
        } catch (Exception e) {
          startInliningResult = new JSONResponseWrapper(false, e.getMessage());
        }
      }

      result.put(START_INLINER, startInliningResult.toJSONObject());
    }

    logger.debug("{}: Request result: {}", request.getRequestURI(), result);
    response.getWriter().print(result);
  }
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   HttpSession session = req.getSession();
   String userLogin = (String) session.getAttribute(SessionKeys.USER_LOGIN);
   String userRootDir = "/delete/" + userLogin;
   String currentPath =
       URLDecoder.decode(req.getRequestURI(), "UTF-8").substring(userRootDir.length());
   Path absolutePath = Paths.get(PATH_TO_SANDBOX + userLogin + currentPath);
   String itemNameForDelete = req.getParameter("name");
   Path itemForDeletePath = absolutePath.resolve(itemNameForDelete);
   recursiveDelete(itemForDeletePath.toFile());
   resp.sendRedirect(req.getRequestURI().replaceFirst("delete", "storage"));
 }
 protected boolean handleLogout(HttpServletRequest request) {
   if ("/logout".equals(request.getRequestURI()) || "/v1/logout".equals(request.getRequestURI())) {
     log.info(
         "Web API logging out "
             + request.getSession()
             + " for user "
             + request.getSession().getAttribute(AUTHENTICATED_USER_SESSION_ATTRIBUTE));
     provider.logout(request.getSession());
     request.getSession().removeAttribute(AUTHENTICATED_USER_SESSION_ATTRIBUTE);
     request.getSession().invalidate();
     return true;
   }
   return false;
 }
  /**
   * Default constructor that duplicates a request.
   *
   * @param request the request to duplicate
   */
  @SuppressWarnings("unchecked")
  public ParameterRequestWrapper(HttpServletRequest request) throws Exception {
    super(request);
    params = new HashMap<String, String[]>(request.getParameterMap());
    localParams = new ArrayList<String>();

    if (request.getRequestURI() != null && request.getRequestURI().endsWith("/search")) {
      if (params.size() > 0 && params.get("pid") == null) {
        params.put("pid", new String[] {"true"});
        localParams.add("pid");
      }
    } else if (request.getRequestURI() != null && request.getRequestURI().endsWith("/objects")) {
      if (params.size() > 0 && params.get("pid") == null) {
        params.put("pid", new String[] {"true"});
        localParams.add("pid");
      }
    }

    // this was handling format parameter rewriting to force RDF/XML output, which is then
    // parsed in RISearchFilter, which subsequently transforms to the actual format requested
    // RISearchFilter is currently disabled, so this removed as it also prevents "count" reponses
    // being processed correctly.
    // See: FCREPO-600

    /*else if (request.getRequestURI() != null
            && request.getRequestURI().endsWith("/risearch")) {
        if (logger.isDebugEnabled()) {
            logger.debug("Entered format check");
        }

        format = params.get("format");

        if (logger.isDebugEnabled()) {
            if (format != null) {
                for (String f : format) {
                    logger.debug("Format: " + f);
                }
            }
        }

        if (format != null && !Arrays.asList(format).contains("RDF/XML")) {
            if (logger.isDebugEnabled()) {
                logger.debug("Setting format to: RDF/XML");
            }

            params.put("format", new String[] {"RDF/XML"});
        }
    } */
  }