コード例 #1
0
 private void redirectDuoAuth(
     Principal principal,
     HttpServletRequest httpServletRequest,
     HttpServletResponse httpServletResponse,
     String contextPath)
     throws java.io.IOException {
   // Redirect to servlet if we can.  If the request is committed,
   // we can't, possibly because there's already a redirection in
   // progress; this is what Seraph's SecurityFilter does.
   if (!httpServletResponse.isCommitted()) {
     String sigRequest = DuoWeb.signRequest(ikey, skey, akey, principal.getName());
     final String originalURL =
         contextPath
             + httpServletRequest.getServletPath()
             + (httpServletRequest.getPathInfo() == null ? "" : httpServletRequest.getPathInfo())
             + (httpServletRequest.getQueryString() == null
                 ? ""
                 : "?" + httpServletRequest.getQueryString());
     String qs;
     String redirectUrl;
     qs = DUO_REQUEST_KEY + "=" + URLEncoder.encode(sigRequest, "UTF-8");
     qs = qs + "&" + DUO_HOST_KEY + "=" + URLEncoder.encode(host, "UTF-8");
     qs = qs + "&" + DUO_ORIGINAL_URL_KEY + "=" + URLEncoder.encode(originalURL, "UTF-8");
     redirectUrl = contextPath + loginUrl + "?" + qs;
     httpServletResponse.sendRedirect(redirectUrl);
   } else {
     log.warn("Could not redirect to Duo auth page.");
   }
 }
コード例 #2
0
  /**
   * 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;
  }
コード例 #3
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());
  }
コード例 #4
0
ファイル: JsonHandler.java プロジェクト: eheb/SimpleWeb4j
  /**
   * Handle a request.
   *
   * @param target The target of the request - either a URI or a name.
   * @param baseRequest The original unwrapped request object.
   * @param request The request either as the {@link Request} object or a wrapper of that request.
   * @param response The response as the {@link org.eclipse.jetty.server.Response} object or a
   *     wrapper of that request.
   * @throws IOException in case of IO error.
   */
  @SuppressWarnings("unchecked")
  @Override
  public void handle(
      String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    if (baseRequest.isHandled()) {
      return;
    }
    Route route = findRoute(request.getMethod(), request.getPathInfo());
    if (route == null) {
      return;
    }

    Object param = getRouteParam(request, route);
    try {
      beginTransaction();
      Response<?> handlerResponse =
          route.handle(param, new RouteParameters(route.getRouteParams(request.getPathInfo())));
      commitTransaction();
      writeHttpResponse(request, response, handlerResponse);
    } catch (HttpErrorException httpError) {
      commitTransaction();
      writeHttpError(response, httpError);
    } catch (Exception exception) {
      rollBackTransaction();
      writeInternalError(response, exception);
    }
    baseRequest.setHandled(true);
  }
コード例 #5
0
ファイル: ProxyServlet.java プロジェクト: kanzelm3/eureka
  @Override
  protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
      throws ServletException, IOException {

    LOGGER.debug("ProxyServlet - POST");

    StringBuilder stringBuilder = new StringBuilder(1000);
    Scanner scanner = new Scanner(servletRequest.getInputStream());
    while (scanner.hasNextLine()) {
      stringBuilder.append(scanner.nextLine());
    }
    LOGGER.debug("json: {}", stringBuilder.toString());
    StringBuilder uri = new StringBuilder(500);
    uri.append(getTargetUri());
    // Handle the path given to the servlet
    if (servletRequest.getPathInfo() != null) { // ex: /my/path.html
      uri.append(servletRequest.getPathInfo());
    }
    LOGGER.debug("uri: {}", uri.toString());
    try {
      servicesClient.proxyPost(uri.toString(), stringBuilder.toString());
    } catch (ClientException e) {
      e.printStackTrace();
    }
  }
コード例 #6
0
ファイル: RWikiServlet.java プロジェクト: yllyx/sakai
  // XXX this should not be here!! The RequestHelper should perform this
  // functionality.
  private boolean isPageToolDefault(HttpServletRequest request) {
    // SAK-13408 - Tomcat and WAS have different URL structures; Attempting to add a
    // link or image would lead to site unavailable errors in websphere if the tomcat
    // URL structure is used.
    if ("websphere".equals(ServerConfigurationService.getString("servlet.container"))) {
      String tid = org.sakaiproject.tool.cover.ToolManager.getCurrentPlacement().getId();
      if (request.getPathInfo() != null
          && request.getPathInfo().startsWith("/tool/" + tid + "/helper/")) {
        return false;
      }
    } else {
      if (request.getPathInfo() != null && request.getPathInfo().startsWith("/helper/")) {
        return false;
      }
    }

    String action = request.getParameter(RequestHelper.ACTION);
    if (action != null && action.length() > 0) {
      return false;
    }

    String pageName = request.getParameter(ViewBean.PAGE_NAME_PARAM);
    if (pageName == null || pageName.trim().length() == 0) {
      return true;
    } else {
      return false;
    }
  }
コード例 #7
0
  @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);
    }
  }
コード例 #8
0
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();

    // String baseUrl = "http://linux06.fomfrv.dk:8081/aisview/rest";
    String baseUrl = "http://localhost:8092/aisview/rest";
    String url = baseUrl;
    if (request.getPathInfo() != null) {
      url += request.getPathInfo();
    }
    if (request.getQueryString() != null) {
      url += "?" + request.getQueryString();
    }

    LOG.debug("JSOPN proxy request for service: " + url);

    String output;
    try {
      output = requestUrl(url);
      response.setStatus(HttpServletResponse.SC_OK);
    } catch (IOException e) {
      output = "{\"error\":true}";
      response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
    }
    out.print(output);
  }
コード例 #9
0
 public void doPut(
     HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
   String requestPath =
       httpServletRequest.getPathInfo() != null && httpServletRequest.getContextPath() != null
           ? httpServletRequest.getPathInfo()
           : httpServletRequest.getRequestURI();
   if (requestPath.equals("/dumpToLog")) {
     mockServer.dumpToLog(
         httpRequestSerializer.deserialize(
             IOStreamUtils.readInputStreamToString(httpServletRequest)));
     httpServletResponse.setStatus(HttpStatusCode.ACCEPTED_202.code());
   } else if (requestPath.equals("/reset")) {
     mockServer.reset();
     httpServletResponse.setStatus(HttpStatusCode.ACCEPTED_202.code());
   } else if (requestPath.equals("/clear")) {
     mockServer.clear(
         httpRequestSerializer.deserialize(
             IOStreamUtils.readInputStreamToString(httpServletRequest)));
     httpServletResponse.setStatus(HttpStatusCode.ACCEPTED_202.code());
   } else {
     Expectation expectation =
         expectationSerializer.deserialize(
             IOStreamUtils.readInputStreamToString(httpServletRequest));
     mockServer
         .when(expectation.getHttpRequest(), expectation.getTimes())
         .thenRespond(expectation.getHttpResponse());
     httpServletResponse.setStatus(HttpStatusCode.CREATED_201.code());
   }
 }
コード例 #10
0
ファイル: BrijjServlet.java プロジェクト: sourcewave/Brijj
 @Override
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws IOException, ServletException {
   try {
     String pathInfo = request.getPathInfo();
     if (pathInfo.startsWith("/download/"))
       doDownload(request, response, Integer.parseInt(pathInfo.substring("/download/".length())));
     else if (pathInfo.startsWith("/bridj")) {
       passthrough(request, response, getPost(request));
     } else if (pathInfo.startsWith("/call/")) {
       handle(request, response);
     } else {
       logger.log(
           Level.SEVERE,
           "Page not found. pathInfo='"
               + request.getPathInfo()
               + "' requestUrl='"
               + request.getRequestURI()
               + "'");
       response.sendError(HttpServletResponse.SC_NOT_FOUND);
     }
   } catch (Exception ex) {
     logger.log(Level.SEVERE, ex.toString());
     try {
       response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
       response.getWriter().write(ex.getLocalizedMessage());
       // response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, ex.getLocalizedMessage());
     } catch (Exception ignore) {
     }
   }
 }
コード例 #11
0
  /** Retrieve {@link com.opensymphony.module.sitemesh.Decorator} based on 'pattern' tag. */
  public Decorator getDecorator(HttpServletRequest request, Page page) {
    String thisPath = request.getServletPath();

    // getServletPath() returns null unless the mapping corresponds to a servlet
    if (thisPath == null) {
      String requestURI = request.getRequestURI();
      if (request.getPathInfo() != null) {
        // strip the pathInfo from the requestURI
        thisPath = requestURI.substring(0, requestURI.indexOf(request.getPathInfo()));
      } else {
        thisPath = requestURI;
      }
    } else if ("".equals(thisPath)) {
      // in servlet 2.4, if a request is mapped to '/*', getServletPath returns null (SIM-130)
      thisPath = request.getPathInfo();
    }

    String name = null;
    try {
      name = configLoader.getMappedName(thisPath);
    } catch (ServletException e) {
      e.printStackTrace();
    }

    Decorator result = getNamedDecorator(request, name);
    return result == null ? super.getDecorator(request, page) : result;
  }
コード例 #12
0
 /**
  * Query RadarServer controller for Spring Framework
  *
  * @param request HttpServletRequest
  * @param response HttpServletResponse
  * @return ModelAndView
  * @throws Exception
  */
 protected ModelAndView handleRequestInternal(
     HttpServletRequest request, HttpServletResponse response) throws Exception {
   try {
     // Gather diagnostics for logging request.
     log.info("handleRequestInternal(): " + UsageLog.setupRequestContext(request));
     // catch rogue invalid request here
     if (request.getQueryString() == null) {
       log.info("Invalid dataset url reference " + request.getPathInfo());
       throw new RadarServerException("Invalid dataset url reference " + request.getPathInfo());
     }
     // Query results in model
     Map<String, Object> model = new HashMap<String, Object>();
     radarQuery(request, response, model);
     if (model == null || model.size() == 0) {
       ModelAndView mav = new ModelAndView(CREATE_VIEW);
       mav.addObject(MODEL_KEY, MSG_CODE);
       return mav;
     } else {
       return new ModelAndView("queryXml", model);
     }
   } catch (RadarServerException e) {
     throw e; // pass it onto Spring exceptionResolver
   } catch (Throwable e) {
     log.error("handleRequestInternal(): Problem handling request.", e);
     log.info(
         "handleRequestInternal(): "
             + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_BAD_REQUEST, -1));
     throw new RadarServerException("handleRequestInternal(): Problem handling request.");
   }
 }
コード例 #13
0
ファイル: FileHandler.java プロジェクト: stbrandy/SocialSDK
  @Override
  public void service(final HttpServletRequest request, final HttpServletResponse response)
      throws ServletException, IOException {

    ProxyEndpointService proxyEndpointService = null;
    String pathinfo = request.getPathInfo().substring(request.getPathInfo().indexOf("/files"));
    String[] pathTokens = pathinfo.split("/");
    if (pathTokens.length > 4) {
      String serviceType = pathTokens[3];
      Application application = Application.get();
      List<Object> proxyServiceProviders =
          application.findServices(ProxyEndpointServiceProvider.PROXY_SERVICE_TYPE);
      if (proxyServiceProviders != null && !proxyServiceProviders.isEmpty()) {
        for (Object o : proxyServiceProviders) {
          ProxyEndpointServiceProvider pvdr = (ProxyEndpointServiceProvider) o;
          proxyEndpointService = pvdr.createProxyEndpointService(serviceType);
          if (proxyEndpointService != null) {
            break;
          }
        }
      }
    }
    if (proxyEndpointService != null) {
      proxyEndpointService.service(request, response);
    } else {
      logger.log(
          Level.SEVERE, "ProxyEndpoint Service could not be retrieved for PathInfo {0}", pathinfo);
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST, "ProxyEndpoint Service could not be retrieved");
    }
  }
コード例 #14
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    logger.debug("servlet path info = {}", request.getPathInfo());

    if ("/verify".equals(request.getPathInfo())) {
      logger.info("Verify OpenId auth response.");

      try {
        Identifier id = this.consumer.verifyResponse(request);
        if (id == null) {
          logger.info("Access denied");
          this.onAccessDenied(request, response);
          return;
        }

        logger.info("openid identifier = {}", id.getIdentifier());
        this.onAccessGranted(request, response);
        return;
      } catch (OpenIDException e) {
        throw new ServletException(e);
      }
    }

    try {
      logger.info("Send OpenId auth request.");
      AuthRequest authReq = this.consumer.authRequest(this.publicIdentifier, request, response);
      request.setAttribute("message", authReq);
      request.getRequestDispatcher(this.returnToUrl).forward(request, response);
    } catch (OpenIDException e) {
      throw new ServletException(e);
    }
  }
コード例 #15
0
ファイル: Redirector.java プロジェクト: dblaber/Ne8
 /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   if (request.getPathInfo().equals("/")) {
     response.getWriter().write("HomePage");
   } else {
     response.getWriter().write("Got: " + request.getPathInfo().substring(1));
   }
 }
コード例 #16
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    logger.debug("Request URL: " + request.getRequestURI());
    logger.debug("Request Path Info: " + request.getPathInfo());
    logger.debug("Request Param: " + request.getQueryString());

    RestRequest restRequest = null;
    try {
      String url = request.getPathInfo();
      if (request.getQueryString() != null) url += "?" + request.getQueryString();
      restRequest = new RestRequest(url, HttpMethod.POST.name());
    } catch (ServletException e) {
      response.setContentType(MimeType.TEXT_PLAIN);
      response.getWriter().write("Invalid URL!");
      return;
    }

    String serviceId = restRequest.getId();
    String format = restRequest.getFormat();

    for (String s : request.getParameterMap().keySet())
      logger.debug(s + " --- " + request.getParameterMap().get(s).toString());
    logger.debug("Id: " + serviceId);
    logger.debug("Format: " + format);

    // request.setCharacterEncoding(CharEncoding.ISO_8859_1);
    logger.info("Content-Type: " + request.getContentType());

    String formData = null;
    String inputLang = "";
    if (request.getContentType().startsWith(MimeType.APPLICATION_RDF_XML))
      inputLang = SerializationLang.XML;
    if (request.getContentType().startsWith(MimeType.TEXT_XML)) inputLang = SerializationLang.XML;
    else if (request.getContentType().startsWith(MimeType.APPLICATION_XML))
      inputLang = SerializationLang.XML;
    else if (request.getContentType().startsWith(MimeType.APPLICATION_RDF_N3))
      inputLang = SerializationLang.N3;
    if (request.getContentType().startsWith(MimeType.APPLICATION_FORM_URLENCODED)) {
      inputLang = SerializationLang.N3; // default for html forms
      formData = request.getParameter("rdf");
      logger.debug(formData);
    } else {
      response.setContentType(MimeType.TEXT_PLAIN);
      response.getWriter().write("The content type is neither rdf+xml nor rdf+n3");
      return;
    }

    InputStream in = request.getInputStream();

    if (formData != null) {
      in = new ByteArrayInputStream(formData.getBytes());
    }

    new PostRequestManager(serviceId, in, inputLang, format, response).HandleRequest();

    response.flushBuffer();
  }
コード例 #17
0
  @Override
  public boolean matches(HttpServletRequest request) {
    String path = request.getServletPath();
    if (request.getPathInfo() != null) {
      path += request.getPathInfo();
    }

    return !redirectPaths.contains(path);
  }
コード例 #18
0
 static void redirect(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
   if (request.getPathInfo() == null || request.getPathInfo().equals("/")) {
     response.sendRedirect(
         response.encodeRedirectURL(WebOPIConstants.MAIN_SERVELET_NAME)); // $NON-NLS-1$
   } else {
     response.sendError(HttpServletResponse.SC_NOT_FOUND);
   }
 }
コード例 #19
0
    private String getRequestPath(HttpServletRequest request) {
      String url = request.getServletPath();

      if (request.getPathInfo() != null) {
        url += request.getPathInfo();
      }

      return url;
    }
コード例 #20
0
  /**
   * 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
    }
  }
コード例 #21
0
 /** {@inheritDoc} */
 public String getPath() {
   String path = request.getContextPath();
   if (request.getPathInfo() != null) {
     path += request.getPathInfo();
   }
   if (path.charAt(0) == '/') {
     path = path.substring(1);
   }
   return path;
 }
コード例 #22
0
 private void handleNotFound(HttpServletRequest req, HttpServletResponse resp, int code)
     throws ServletException {
   String path = req.getPathInfo() == null ? "/" : req.getPathInfo();
   String msg =
       code == HttpServletResponse.SC_NOT_FOUND
           ? "No preferences found for path {0}"
           : "Invalid preference path {0}";
   handleException(
       resp, new Status(IStatus.ERROR, Activator.PI_SERVER_SERVLETS, NLS.bind(msg, path)), code);
 }
コード例 #23
0
 /** Redirect to HTTP port. */
 @Override
 protected void service(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   HttpClient client = HttpConnectionUtil.getClient(connectionTimeout);
   // setup POST
   HttpPost post = null;
   try {
     post = new HttpPost(postAcceptorURL);
     String path = req.getContextPath();
     if (path == null) {
       path = "";
     }
     log.debug("Path: {}", path);
     if (req.getPathInfo() != null) {
       path += req.getPathInfo();
     }
     log.debug("Path 2: {}", path);
     int reqContentLength = req.getContentLength();
     if (reqContentLength > 0) {
       log.debug("Request content length: {}", reqContentLength);
       IoBuffer reqBuffer = IoBuffer.allocate(reqContentLength);
       ServletUtils.copy(req, reqBuffer.asOutputStream());
       reqBuffer.flip();
       post.setEntity(new InputStreamEntity(reqBuffer.asInputStream(), reqContentLength));
       post.addHeader("Content-Type", REQUEST_TYPE);
       // get.setPath(path);
       post.addHeader("Tunnel-request", path);
       // execute the method
       HttpResponse response = client.execute(post);
       int code = response.getStatusLine().getStatusCode();
       log.debug("HTTP response code: {}", code);
       if (code == HttpStatus.SC_OK) {
         HttpEntity entity = response.getEntity();
         if (entity != null) {
           resp.setContentType(REQUEST_TYPE);
           // get the response as bytes
           byte[] bytes = EntityUtils.toByteArray(entity);
           IoBuffer resultBuffer = IoBuffer.wrap(bytes);
           resultBuffer.flip();
           ServletUtils.copy(resultBuffer.asInputStream(), resp.getOutputStream());
           resp.flushBuffer();
         }
       } else {
         resp.sendError(code);
       }
     } else {
       resp.sendError(HttpStatus.SC_BAD_REQUEST);
     }
   } catch (Exception ex) {
     log.error("", ex);
     if (post != null) {
       post.abort();
     }
   }
 }
コード例 #24
0
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    validateRequestType(servletRequest);
    validateResponseType(servletResponse);

    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;

    final String path =
        request.getContextPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());

    if (request.getMethod().equals("OPTIONS") || whitelisted(path)) {
      filterChain.doFilter(servletRequest, servletResponse);
      return;
    }

    final String header = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (header == null) {
      noHeader().writeResponse(response);
      return;
    }

    final String[] usernameAndPassword = extractCredential(header);
    if (usernameAndPassword == null) {
      badHeader().writeResponse(response);
      return;
    }

    final String username = usernameAndPassword[0];
    final String password = usernameAndPassword[1];

    switch (authManager.authenticate(username, password)) {
      case PASSWORD_CHANGE_REQUIRED:
        if (!passwordChangeWhitelist.matches(path)) {
          passwordChangeRequired(username, baseURL(request)).writeResponse(response);
          return;
        }
        // fall through
      case SUCCESS:
        filterChain.doFilter(
            new AuthorizedRequestWrapper(BASIC_AUTH, username, request), servletResponse);
        return;
      case TOO_MANY_ATTEMPTS:
        tooManyAttemptes().writeResponse(response);
        return;
      default:
        log.warn(
            "Failed authentication attempt for '%s' from %s", username, request.getRemoteAddr());
        invalidCredential().writeResponse(response);
        return;
    }
  }
コード例 #25
0
 protected void handleDocument(
     HttpServletRequest request, HttpServletResponse response, Document doc) throws IOException {
   if (request.getPathInfo().equalsIgnoreCase("/load")) getXmlScoreBoard().loadDocument(doc);
   else if (request.getPathInfo().equalsIgnoreCase("/merge"))
     getXmlScoreBoard().mergeDocument(doc);
   else
     response.sendError(
         HttpServletResponse.SC_NOT_FOUND, "Must specify to load or merge document");
   response.setContentType("text/plain");
   response.setStatus(HttpServletResponse.SC_OK);
 }
コード例 #26
0
ファイル: RestServlet.java プロジェクト: runningship/kuaiyi
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   if (req.getPathInfo() == null) {
     super.doGet(req, resp);
     return;
   }
   String data = req.getPathInfo().replace("/", "");
   req.setAttribute("qrCode", data);
   RequestDispatcher rd = req.getRequestDispatcher("/public/itemView.jsp");
   rd.forward(req, resp);
 }
コード例 #27
0
ファイル: AccueilController.java プロジェクト: venril/SIGDV
 /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   // TODO Auto-generated method stub
   if (request.getPathInfo().equals("/depovente/")) {
     // Collection<Produit> liste =produitdao.findAll();
     RequestDispatcher rd = request.getRequestDispatcher("/menuAccueil.jsp");
     rd.forward(request, response);
   }
   if (request.getPathInfo().equals("/depotvente/#")) {
     RequestDispatcher rd = request.getRequestDispatcher("/menuAccueil.jsp");
     rd.forward(request, response);
   }
 }
コード例 #28
0
ファイル: RWTServlet.java プロジェクト: oaperez/rap
 private void handleRequest(HttpServletRequest request, HttpServletResponse response)
     throws IOException, ServletException {
   if (!applicationContext.allowsRequests()) {
     response.sendError(SC_SERVICE_UNAVAILABLE);
   } else if (request.getPathInfo() == null) {
     // /context/servlet: no extra path info after servlet name
     handleValidRequest(request, response);
   } else if ("/".equals(request.getPathInfo()) && "".equals(request.getServletPath())) {
     // /context/: root servlet, in this case path info "/" is ok
     handleValidRequest(request, response);
   } else {
     response.sendError(SC_NOT_FOUND);
   }
 }
コード例 #29
0
ファイル: MovieServlet.java プロジェクト: dtcyganov/sf-movies
 private static Long getId(HttpServletRequest req) {
   if (req.getPathInfo() == null) {
     return null;
   }
   Matcher matcher = idPattern.matcher(req.getPathInfo());
   if (!matcher.matches()) {
     return null;
   }
   try {
     return Long.parseLong(matcher.group(1));
   } catch (NumberFormatException ignore) {
     return null;
   }
 }
コード例 #30
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 {
    // we expect a path in the form /resource/<prefix>/<suffix>.
    String pathInfo = request.getPathInfo();

    log.debug("Pathinfo: " + pathInfo);
    if (StringUtils.isEmpty(pathInfo) || StringUtils.countMatches(pathInfo, "/") < 2) {
      log.debug("Path does not contain the expected number of slashes.");
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    // remove trailing slash of the path info and split it.
    String[] path = request.getPathInfo().substring(1).split("/");

    String handle = path[0] + "/" + path[1];
    String dspaceURL = (new DSpace()).getConfigurationService().getProperty("dspace.url");

    // Prepare content negotiation
    int requestedMimeType = Negotiator.negotiate(request.getHeader(ACCEPT_HEADER_NAME));

    Context context = null;
    DSpaceObject dso = null;
    try {
      context = new Context(Context.READ_ONLY);
      dso = handleService.resolveToObject(context, handle);
    } catch (SQLException ex) {
      log.error("SQLException: " + ex.getMessage(), ex);
      context.abort();
      // probably a problem with the db connection => send Service Unavailable
      response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
      return;
    } catch (IllegalStateException ex) {
      log.error(
          "Cannot resolve handle " + handle + ". IllegalStateException:" + ex.getMessage(), ex);
      context.abort();
      response.sendError(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }
    if (dso == null) {
      log.info("Cannot resolve handle '" + handle + "' to dso. => 404");
      context.abort();
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    // close the context and send forward.
    context.abort();
    Negotiator.sendRedirect(response, handle, "", requestedMimeType, true);
  }