Java 类org.eclipse.jetty.server.Response 实例源码

项目:gitplex-mit    文件:AssetServlet.java   
@Override
protected void putHeaders(HttpServletResponse response, HttpContent content, long contentLength) {
    super.putHeaders(response, content, contentLength);
    HttpFields fields = ((Response) response).getHttpFields();
    if (requestHolder.get().getDispatcherType() == DispatcherType.ERROR) {
        /*
         * Do not cache error page and also makes sure that error page is not eligible for 
         * modification check. That is, error page will be always retrieved.
         */
           fields.put(HttpHeader.CACHE_CONTROL, "must-revalidate,no-cache,no-store");
    } else if (requestHolder.get().getRequestURI().equals("/favicon.ico")) {
        /*
         * Make sure favicon request is cached. Otherwise, it will be requested for every 
         * page request.
         */
        fields.put(HttpHeader.CACHE_CONTROL, "max-age=86400,public");
    }
}
项目:hdfs-mesos    文件:HttpServer.java   
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response_) throws IOException {
    Response response = (Response) response_;
    int code = response.getStatus();

    String error = response.getReason() != null ? response.getReason() : "";
    PrintWriter writer = response.getWriter();

    if (request.getAttribute("jsonResponse") != null) {
        response.setContentType("application/json; charset=utf-8");

        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("error", error);

        writer.println("" + new JSONObject(map));
    } else {
        response.setContentType("text/plain; charset=utf-8");
        writer.println(code + " - " + error);
    }

    writer.flush();
    baseRequest.setHandled(true);
}
项目:micrometer    文件:JettyStatisticsMetricsTest.java   
@Test
void stats() throws IOException, ServletException {
    Request baseReq = mock(Request.class);
    HttpChannelState s = new HttpChannelState(null){};
    when(baseReq.getHttpChannelState()).thenReturn(s);
    Response resp = mock(Response.class);
    when(baseReq.getResponse()).thenReturn(resp);
    when(resp.getContentCount()).thenReturn(772L);

    handler.handle("/testUrl", baseReq, new MockHttpServletRequest(), new MockHttpServletResponse());

    assertThat(registry.mustFind("jetty.requests").functionTimer().count()).isEqualTo(1L);
    assertThat(registry.mustFind("jetty.responses.size").functionCounter().count()).isEqualTo(772.0);
}
项目:kit    文件:DefaultServlet.java   
protected void putHeaders(HttpServletResponse response, HttpContent content, long contentLength)
{
    if (response instanceof Response)
    {
        Response r = (Response)response;
        r.putHeaders(content, contentLength, _etags);
        HttpFields f = r.getHttpFields();
        if (_acceptRanges)
            f.put(ACCEPT_RANGES);

        if (_cacheControl != null)
            f.put(_cacheControl);
    }
    else
    {
        Response.putHeaders(response, content, contentLength, _etags);
        if (_acceptRanges)
            response.setHeader(ACCEPT_RANGES.getName(), ACCEPT_RANGES.getValue());

        if (_cacheControl != null)
            response.setHeader(_cacheControl.getName(), _cacheControl.getValue());
    }
}
项目:rdf-delta    文件:HttpErrorHandler.java   
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
    if ( request.getMethod().equals(METHOD_POST)) {
        response.setContentType(WebContent.contentTypeTextPlain);
        response.setCharacterEncoding(WebContent.charsetUTF8) ;

        String reason=(response instanceof Response)?((Response)response).getReason():null;
        String msg = String.format("%03d %s\n", response.getStatus(), reason) ;
        response.getOutputStream().write(msg.getBytes(StandardCharsets.UTF_8)) ;

        response.getOutputStream().flush() ;
        baseRequest.setHandled(true);
        return;
    }
    super.handle(target, baseRequest, request, response); 
}
项目:vespa    文件:AccessLogRequestLog.java   
@Override
public void log(final Request request, final Response response) {
    final AccessLogEntry accessLogEntryFromServletRequest = (AccessLogEntry) request.getAttribute(
            JDiscHttpServlet.ATTRIBUTE_NAME_ACCESS_LOG_ENTRY);
    final AccessLogEntry accessLogEntry;
    if (accessLogEntryFromServletRequest != null) {
        accessLogEntry = accessLogEntryFromServletRequest;
    } else {
        accessLogEntry = new AccessLogEntry();
        populateAccessLogEntryFromHttpServletRequest(request, accessLogEntry);
    }

    final long startTime = request.getTimeStamp();
    final long endTime = System.currentTimeMillis();
    accessLogEntry.setTimeStamp(startTime);
    accessLogEntry.setDurationBetweenRequestResponse(endTime - startTime);
    accessLogEntry.setReturnedContentSize(response.getContentCount());
    accessLogEntry.setStatusCode(response.getStatus());

    accessLog.log(accessLogEntry);
}
项目:sql-layer    文件:SpnegoAuthenticatorEx.java   
@Override
public Authentication validateRequest(ServletRequest request, ServletResponse response, boolean mandatory) throws ServerAuthException {
    Authentication result = super.validateRequest(request, response, mandatory);
    if ((result == Authentication.UNAUTHENTICATED) &&
        mandatory &&
        !DeferredAuthentication.isDeferred((HttpServletResponse)response)) {
        LOG.debug("SpengoAuthenticatorEx: unauthenticated -> forbidden");
        try {
            ((HttpServletResponse)response).sendError(Response.SC_FORBIDDEN,
                                                      "negotiation failure");
        }
        catch (IOException ex) {
            throw new ServerAuthException(ex);
        }
        result = Authentication.SEND_FAILURE;
    }
    return result;
}
项目:http-digest-auth    文件:JettyErrorHandler.java   
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
{
    String method = request.getMethod();

    if ( !method.equals(HttpMethod.GET.asString())
         && !method.equals(HttpMethod.POST.asString())
         && !method.equals(HttpMethod.HEAD.asString()) )
        return ;

    response.setContentType(MimeTypes.Type.TEXT_PLAIN_UTF_8.asString()) ;
    ServletOps.setNoCache(response) ;

    ByteArrayOutputStream bytes = new ByteArrayOutputStream(1024) ;
    try ( Writer writer = IO.asUTF8(bytes) ) {
        String reason=(response instanceof Response)?((Response)response).getReason():null;
        handleErrorPage(request, writer, response.getStatus(), reason) ;
        writer.flush();
        response.setContentLength(bytes.size()) ;
        // Copy :-(
        response.getOutputStream().write(bytes.toByteArray()) ;
    }
}
项目:Poseidon    文件:Log4JAccessLogTest.java   
@Before
public void setup() throws Exception {
    // Create mock objects
    mockLog4jContextFactory = mock(Log4jContextFactory.class);
    whenNew(Log4jContextFactory.class).withNoArguments().thenReturn(mockLog4jContextFactory);
    mockLoggerContext = mock(LoggerContext.class);
    mockLogger = mock(Logger.class);
    when(mockLog4jContextFactory.getContext(anyString(), any(ClassLoader.class), any(), anyBoolean(), any(URI.class), anyString())).thenReturn(mockLoggerContext);
    when(mockLoggerContext.getRootLogger()).thenReturn(mockLogger);
    mockRequest = mock(Request.class);
    mockResponse = mock(Response.class);
    mockAccessLog = mock(AccessLog.class);
    whenNew(AccessLog.class).withArguments(mockRequest, mockResponse).thenReturn(mockAccessLog);

    // Create actual objects
    enabledSupplier = () -> true;
    disabledSupplier = () -> false;
    failedAccessLog = new TestLog4JAccessLog(NON_EXISTING_FILE_PATH, enabledSupplier);
    String filePath = getClass().getClassLoader().getResource(ACCESS_CONFIG_FILE_PATH).getPath();
    enabledAccessLog = new TestLog4JAccessLog(filePath, enabledSupplier);
    disabledAccessLog = new TestLog4JAccessLog(filePath, disabledSupplier);
}
项目:CryptMeme    文件:I2PRequestLog.java   
protected void logExtended(Request request, 
                           Response response, 
                           Writer writer) throws IOException 
{
    String referer = request.getHeader(HttpHeaders.REFERER);
    if (referer == null) 
        writer.write("\"-\" ");
    else 
    {
        writer.write('"');
        writer.write(referer);
        writer.write("\" ");
    }

    String agent = request.getHeader(HttpHeaders.USER_AGENT);
    if (agent == null)
        writer.write("\"-\" ");
    else
    {
        writer.write('"');
        writer.write(agent);
        writer.write('"');
    }          
}
项目:appengine-java-vm-runtime    文件:AppEngineAuthenticationTest.java   
/**
 * Fire one request at the security handler (and by extension to the AuthServlet behind it).
 *
 * @param path The path to hit.
 * @param request The request object to use.
 * @param response The response object to use. Must be created by Mockito.mock()
 * @return Any data written to response.getWriter()
 * @throws IOException
 * @throws ServletException
 */
private String runRequest(String path, Request request, Response response)
    throws IOException, ServletException {
  //request.setMethod(/*HttpMethod.GET,*/ "GET");
  HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path);
  HttpFields httpf = new HttpFields();
  MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
  request.setMetaData(metadata);

  // request.setServerName(SERVER_NAME);
 // request.setAuthority(SERVER_NAME,9999);
 //// request.setPathInfo(path);
 //// request.setURIPathQuery(path);
  request.setDispatcherType(DispatcherType.REQUEST);
  doReturn(response).when(request).getResponse();

  ByteArrayOutputStream output = new ByteArrayOutputStream();
  try (PrintWriter writer = new PrintWriter(output)) {
    when(response.getWriter()).thenReturn(writer);
    securityHandler.handle(path, request, request, response);
  }
  return new String(output.toByteArray());
}
项目:appengine-java-vm-runtime    文件:AppEngineAuthenticationTest.java   
private String runRequest2(String path, Request request, Response response)
     throws IOException, ServletException {
   //request.setMethod(/*HttpMethod.GET,*/ "GET");
   HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path);
   HttpFields httpf = new HttpFields();
   MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
//   request.setMetaData(metadata);

   // request.setServerName(SERVER_NAME);
  // request.setAuthority(SERVER_NAME,9999);
  //// request.setPathInfo(path);
  //// request.setURIPathQuery(path);
   request.setDispatcherType(DispatcherType.REQUEST);
   doReturn(response).when(request).getResponse();

   ByteArrayOutputStream output = new ByteArrayOutputStream();
   try (PrintWriter writer = new PrintWriter(output)) {
     when(response.getWriter()).thenReturn(writer);
     securityHandler.handle(path, request, request, response);
   }
   return new String(output.toByteArray());
 }
项目:appengine-java-vm-runtime    文件:AppEngineAuthenticationTest.java   
public void testUserRequired_NoUser() throws Exception {
  String path = "/user/blah";
  Request request = spy(new Request(null, null));
  //request.setServerPort(9999);
      HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path);
  HttpFields httpf = new HttpFields();
  MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
  request.setMetaData(metadata);
 // request.setAuthority(SERVER_NAME,9999);
  Response response = mock(Response.class);
  String output = runRequest(path, request, response);
  // Verify that the servlet never was run (there is no output).
  assertEquals("", output);
  // Verify that the request was redirected to the login url.
  String loginUrl = UserServiceFactory.getUserService()
      .createLoginURL(String.format("http://%s%s", SERVER_NAME + ":9999", path));
  verify(response).sendRedirect(loginUrl);
}
项目:appengine-java-vm-runtime    文件:AppEngineAuthenticationTest.java   
public void testUserRequired_PreserveQueryParams() throws Exception {
  String path = "/user/blah";

  Request request = new Request(null, null);
  // request.setServerPort(9999);
      HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path,"foo=baqr","foo=bar","foo=barff");
  HttpFields httpf = new HttpFields();
  MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
  request.setMetaData(metadata);
  MultiMap<String> queryParameters = new MultiMap<> ();
  queryParameters.add("ffo", "bar");
  request.setQueryParameters(queryParameters);
      request = spy(request);

 /// request.setAuthority(SERVER_NAME,9999);
  request.setQueryString("foo=bar");
  Response response = mock(Response.class);
  String output = runRequest2(path, request, response);
  // Verify that the servlet never was run (there is no output).
  assertEquals("", output);
  // Verify that the request was redirected to the login url.
  String loginUrl = UserServiceFactory.getUserService()
      .createLoginURL(String.format("http://%s%s?foo=bar", SERVER_NAME + ":9999", path));
  verify(response).sendRedirect(loginUrl);
}
项目:appengine-java-vm-runtime    文件:AppEngineAuthenticationTest.java   
public void testAdminRequired_NoUser() throws Exception {
  String path = "/admin/blah";
  Request request = spy(new Request(null, null));
  //request.setServerPort(9999);
  HttpURI uri  =new HttpURI("http", SERVER_NAME,9999, path);
  HttpFields httpf = new HttpFields();
  MetaData.Request metadata = new MetaData.Request("GET", uri, HttpVersion.HTTP_2, httpf);
  request.setMetaData(metadata);
//  request.setAuthority(SERVER_NAME,9999);
  Response response = mock(Response.class);
  String output = runRequest(path, request, response);
  // Verify that the servlet never was run (there is no output).
  assertEquals("", output);
  // Verify that the request was redirected to the login url.
  String loginUrl = UserServiceFactory.getUserService()
      .createLoginURL(String.format("http://%s%s", SERVER_NAME + ":9999", path));
  verify(response).sendRedirect(loginUrl);
}
项目:jooby    文件:JettyHandler.java   
private static ServletUpgrade upgrade(final Request baseRequest, final HttpServletRequest request,
    final HttpServletResponse response, final WebSocketServerFactory webSocketServerFactory) {
  return new ServletUpgrade() {
    @SuppressWarnings("unchecked")
    @Override
    public <T> T upgrade(final Class<T> type) throws Exception {
      if (type == NativeWebSocket.class
          && webSocketServerFactory.isUpgradeRequest(request, response)
          && webSocketServerFactory.acceptWebSocket(request, response)) {
        String key = JettyWebSocket.class.getName();
        NativeWebSocket ws = (NativeWebSocket) request.getAttribute(key);
        if (ws != null) {
          request.removeAttribute(key);
          return (T) ws;
        }
      } else if (type == Sse.class) {
        return (T) new JettySse(baseRequest, (Response) response);
      } else if (type == NativePushPromise.class) {
        return (T) new JettyPush(baseRequest);
      }
      throw new UnsupportedOperationException("Not Supported: " + type);
    }
  };
}
项目:jooby    文件:JettySseTest.java   
@Test
public void send() throws Exception {
  byte[] bytes = {0};
  CountDownLatch latch = new CountDownLatch(1);
  new MockUnit(Request.class, Response.class, HttpOutput.class)
    .expect(httpOutput)
    .expect(write(bytes))
    .run(unit -> {
      new JettySse(unit.get(Request.class),
        unit.get(Response.class))
        .send(Optional.of("1"), bytes).whenComplete((id, x) -> {
        if (x == null) {
          assertEquals("1", id.get());
          latch.countDown();
        }
      });
      latch.await();
    });
}
项目:jooby    文件:JettySseTest.java   
@Test
public void sendFailure() throws Exception {
  byte[] bytes = {0};
  IOException cause = new IOException("intentional error");
  CountDownLatch latch = new CountDownLatch(1);
  new MockUnit(Request.class, Response.class, HttpOutput.class)
    .expect(httpOutput)
    .expect(unit -> {
      HttpOutput output = unit.get(HttpOutput.class);
      output.write(bytes);
      expectLastCall().andThrow(cause);
    })
    .run(unit -> {
      new JettySse(unit.get(Request.class),
        unit.get(Response.class))
        .send(Optional.of("1"), bytes).whenComplete((id, x) -> {
        if (x != null) {
          assertEquals(cause, x);
          latch.countDown();
        }
      });
      latch.await();
    });
}
项目:jooby    文件:JettyResponseTest.java   
@Test
public void sendBytes() throws Exception {
  byte[] bytes = "bytes".getBytes();
  new MockUnit(ServletServletRequest.class, Request.class, Response.class, HttpOutput.class)
      .expect(servletRequest)
      .expect(unit -> {
        HttpOutput output = unit.get(HttpOutput.class);
        output.sendContent(unit.capture(ByteBuffer.class));

        Response rsp = unit.get(Response.class);
        rsp.setHeader("Transfer-Encoding", null);
        expect(rsp.getHttpOutput()).andReturn(output);
      })
      .run(unit -> {
        new JettyResponse(unit.get(ServletServletRequest.class), unit.get(Response.class))
            .send(bytes);
      }, unit -> {
        assertArrayEquals(bytes, unit.captured(ByteBuffer.class).iterator().next().array());
      });
}
项目:jooby    文件:JettyResponseTest.java   
@Test
public void sendBuffer() throws Exception {
  byte[] bytes = "bytes".getBytes();
  ByteBuffer buffer = ByteBuffer.wrap(bytes);
  new MockUnit(ServletServletRequest.class, Request.class, Response.class, HttpOutput.class)
      .expect(servletRequest)
      .expect(unit -> {
        HttpOutput output = unit.get(HttpOutput.class);
        output.sendContent(eq(buffer));

        Response rsp = unit.get(Response.class);
        expect(rsp.getHttpOutput()).andReturn(output);
      })
      .run(unit -> {
        new JettyResponse(unit.get(ServletServletRequest.class), unit.get(Response.class))
            .send(buffer);
      });
}
项目:jooby    文件:JettyResponseTest.java   
@Test
public void sendInputStream() throws Exception {
  new MockUnit(ServletServletRequest.class, Request.class, Response.class, HttpOutput.class,
      InputStream.class, AsyncContext.class)
          .expect(servletRequest)
          .expect(unit -> {
            unit.mockStatic(Channels.class);
            ReadableByteChannel channel = unit.mock(ReadableByteChannel.class);
            expect(Channels.newChannel(unit.get(InputStream.class))).andReturn(channel);

            HttpOutput output = unit.get(HttpOutput.class);
            output.sendContent(eq(channel), isA(JettyResponse.class));

            Response rsp = unit.get(Response.class);
            expect(rsp.getHttpOutput()).andReturn(output);
          })
          .expect(startAsync)
          .run(unit -> {
            new JettyResponse(unit.get(ServletServletRequest.class), unit.get(Response.class))
                .send(unit.get(InputStream.class));
          });
}
项目:jooby    文件:JettyResponseTest.java   
@Test
public void sendSmallFileChannel() throws Exception {
  FileChannel channel = newFileChannel(1);
  new MockUnit(ServletServletRequest.class, Request.class, Response.class, HttpOutput.class,
      AsyncContext.class)
          .expect(servletRequest)
          .expect(unit -> {
            HttpOutput output = unit.get(HttpOutput.class);
            output.sendContent(eq(channel));

            Response rsp = unit.get(Response.class);
            expect(rsp.getBufferSize()).andReturn(2);
            expect(rsp.getHttpOutput()).andReturn(output);
          })
          .run(unit -> {
            new JettyResponse(unit.get(ServletServletRequest.class), unit.get(Response.class))
                .send(channel);
          });
}
项目:jooby    文件:JettyResponseTest.java   
@Test
public void sendLargeFileChannel() throws Exception {
  FileChannel channel = newFileChannel(10);
  new MockUnit(ServletServletRequest.class, Request.class, Response.class, HttpOutput.class,
      AsyncContext.class)
          .expect(servletRequest)
          .expect(unit -> {
            HttpOutput output = unit.get(HttpOutput.class);
            output.sendContent(eq(channel), isA(JettyResponse.class));

            Response rsp = unit.get(Response.class);
            expect(rsp.getBufferSize()).andReturn(5);
            expect(rsp.getHttpOutput()).andReturn(output);
          })
          .expect(startAsync)
          .run(unit -> {
            new JettyResponse(unit.get(ServletServletRequest.class), unit.get(Response.class))
                .send(channel);
          });
}
项目:jooby    文件:JettyResponseTest.java   
@Test
public void end() throws Exception {
  new MockUnit(ServletServletRequest.class, Request.class, Response.class, HttpOutput.class)
      .expect(servletRequest)
      .expect(unit -> {
        HttpOutput output = unit.get(HttpOutput.class);
        output.close();

        Response rsp = unit.get(Response.class);
        expect(rsp.getHttpOutput()).andReturn(output);
      })
      .expect(noAsyncStarted)
      .run(unit -> {
        new JettyResponse(unit.get(ServletServletRequest.class), unit.get(Response.class))
            .end();
      });
}
项目:dropwizard-experiment    文件:BasicAuthFilter.java   
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    String header = request.getHeader(HttpHeaders.AUTHORIZATION);

    if (header != null && header.startsWith("Basic ")) {
        String decoded = new String(BaseEncoding.base64().decode(header.substring(header.indexOf(" ") + 1)));

        if (decoded.contains(":")) {
            String username = decoded.substring(0, decoded.indexOf(":"));
            String password = decoded.substring(decoded.indexOf(":") + 1, decoded.length());

            if (username.equals(this.username) && password.equals(this.password)) {
                chain.doFilter(request, response);
                return;
            } else {
                log.info("Incorrect admin login with username '{}'.", username);
            }
        }
    }

    response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Administration\"");
    response.sendError(Response.SC_UNAUTHORIZED);
}
项目:cxf-server    文件:CommonRequestLog.java   
/**
 * Get the response status
 *
 * @param request the request.
 * @param response the response.
 * @return the status code ex. 200, or 'Async'.
 */
protected String getStatus(Request request, Response response) {
  StringBuilder buf = new StringBuilder();

  if (request.getAsyncContinuation().isInitial()) {
    int status = response.getStatus();
    if (status <= 0)
      status = HttpStatus.NOT_FOUND_404;
    buf.append((char) ('0' + ((status / 100) % 10)));
    buf.append((char) ('0' + ((status / 10) % 10)));
    buf.append((char) ('0' + (status % 10)));
  } else
    buf.append("Async");

  return buf.toString();
}
项目:restfb-example-chatbot    文件:AbstractFacebookBotServlet.java   
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  if ("subscribe".equals(req.getParameter("hub.mode")) //
      && Config.getInstance().getBotTokenVerify().equals(req.getParameter("hub.verify_token"))) {
    resp.getWriter().append(req.getParameter("hub.challenge"));
  } else {
    resp.setStatus(Response.SC_BAD_REQUEST);
  }
}
项目:vespa    文件:Cookie.java   
public static List<String> toSetCookieHeaderAll(Iterable<? extends Cookie> cookies) {
    // Ugly, bot Jetty does not provide a dedicated cookie parser (will be included in Jetty 10)
    Response response = new Response(null, null);
    for (Cookie cookie : cookies) {
        response.addSetRFC6265Cookie(
                cookie.getName(),
                cookie.getValue(),
                cookie.getDomain(),
                cookie.getPath(),
                cookie.getMaxAge(TimeUnit.SECONDS),
                cookie.isSecure(),
                cookie.isHttpOnly());
    }
    return new ArrayList<>(response.getHeaders("Set-Cookie"));
}
项目:athenz    文件:AthenzRequestLog.java   
@Override
public void logExtended(StringBuilder b, Request request, Response response)
        throws IOException {

    super.logExtended(b, request, response);

    Object principal = request.getAttribute(REQUEST_PRINCIPAL);
    if (principal == null) {
        b.append(" \"-\" ");
    } else {
        b.append(" \"");
        b.append(principal.toString());
        b.append("\" ");
    }

    long requestLength = request.getContentLengthLong();
    if (requestLength >= 0) {
        if (requestLength > 99999) {
            b.append(requestLength);
        } else {
            if (requestLength > 9999) {
                b.append((char) ('0' + ((requestLength / 10000) % 10)));
            }
            if (requestLength > 999) {
                b.append((char) ('0' + ((requestLength / 1000) % 10)));
            }
            if (requestLength > 99) {
                b.append((char) ('0' + ((requestLength / 100) % 10)));
            }
            if (requestLength > 9) {
                b.append((char) ('0' + ((requestLength / 10) % 10)));
            }
            b.append((char) ('0' + (requestLength) % 10));
        }
    } else {
        b.append('-');
    }
}
项目:keywhiz    文件:XsrfProtection.java   
public NewCookie generate(String session) {
  checkArgument(!session.isEmpty());
  String cookieValue = SHA512.hashString(session, UTF_8).toString();

  // HttpOnly MUST NOT be present for this cookie.
  HttpCookie cookie = new HttpCookie(config.getName(), cookieValue, config.getDomain(),
      config.getPath(), -1, config.isHttpOnly(), config.isSecure());
  Response response = new Response(null, null);
  response.addCookie(cookie);
  return NewCookie.valueOf(response.getHttpFields().getStringField(HttpHeader.SET_COOKIE));
}
项目:keywhiz    文件:AuthenticatedEncryptedCookieFactory.java   
/**
 * Produces a cookie string for a given value and expiration.
 *
 * @param value value of new cookie.
 * @param expiration expiration time of cookie.
 * @return serialized cookie with given value and expiration.
 */
public NewCookie cookieFor(String value, ZonedDateTime expiration) {
  long maxAge = Duration.between(ZonedDateTime.now(clock), expiration).getSeconds();

  HttpCookie cookie = new HttpCookie(config.getName(), value, config.getDomain(),
      config.getPath(), maxAge, config.isHttpOnly(), config.isSecure());

  Response response = new Response(null, null);
  response.addCookie(cookie);
  return NewCookie.valueOf(response.getHttpFields().getStringField(HttpHeader.SET_COOKIE));
}
项目:keywhiz    文件:AuthenticatedEncryptedCookieFactory.java   
/**
 * Produces an expired cookie string, used to update/overwrite an existing cookie.
 *
 * @return serialized expired cookie with matching parameters to authenticating cookie.
 */
public NewCookie getExpiredSessionCookie() {
  HttpCookie cookie = new HttpCookie(config.getName(), "expired", config.getDomain(), config.getPath(),
      0, config.isHttpOnly(), config.isSecure());

  Response response = new Response(null, null);
  response.addCookie(cookie);
  return NewCookie.valueOf(response.getHttpFields().getStringField(HttpHeader.SET_COOKIE));
}
项目:sql-layer    文件:CrossOriginConstraintSecurityHandler.java   
@Override
protected boolean isAuthMandatory(Request baseRequest, Response baseResponse, Object constraintInfo) {
    if(constraintInfo == null) {
        return false;
    }
    if(isPreFlightRequest(baseRequest)) {
        return false;
    }
    return ((RoleInfo)constraintInfo).isChecked();
}
项目:bartleby    文件:RequestLogImpl.java   
@Override
public void log(Request jettyRequest, Response jettyResponse) {
  JettyServerAdapter adapter = new JettyServerAdapter(jettyRequest,
          jettyResponse);
  IAccessEvent accessEvent = new AccessEvent(jettyRequest, jettyResponse,
          adapter);
  if (getFilterChainDecision(accessEvent) == FilterReply.DENY) {
    return;
  }
  aai.appendLoopOnAppenders(accessEvent);
}
项目:heroic    文件:JettyJSONErrorHandler.java   
@Override
public void handle(
    String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response
) throws IOException {
    baseRequest.setHandled(true);
    response.setContentType(CONTENT_TYPE);

    final String message;
    final javax.ws.rs.core.Response.Status status;

    if (response instanceof Response) {
        final Response r = (Response) response;
        status = javax.ws.rs.core.Response.Status.fromStatusCode(r.getStatus());
    } else {
        status = javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
    }

    final Throwable cause = (Throwable) request.getAttribute(Dispatcher.ERROR_EXCEPTION);

    if (cause != null && cause.getMessage() != null) {
        message = cause.getMessage();
    } else if (cause instanceof NullPointerException) {
        message = "NPE";
    } else {
        message = status.getReasonPhrase();
    }

    final InternalErrorMessage info = new InternalErrorMessage(message, status);

    response.setStatus(status.getStatusCode());

    try (final ByteArrayOutputStream output = new ByteArrayOutputStream(4096)) {
        final OutputStreamWriter writer = new OutputStreamWriter(output, Charsets.UTF_8);
        mapper.writeValue(writer, info);
        response.setContentLength(output.size());
        output.writeTo(response.getOutputStream());
    }
}
项目:Poseidon    文件:Log4JAccessLog.java   
/**
 * Generates access log statement. If async logging is enabled,
 * jetty thread won't be blocked till log is written to disk.
 *
 * Access log can be dynamically disabled by returning false from supplier.
 *
 * @param request jetty's request
 * @param response jetty's response
 */
@Override
public final void log(Request request, Response response) {
    if (!isEnabled()) {
        return;
    }

    // Instead of generating the access log line here directly, we form AccessLog object with values
    // copied from request and response and log this object using various converters.
    // Hence access log pattern is configurable and extensible.
    logger.log(Level.INFO, new AccessLog(request, response));
}
项目:Poseidon    文件:PatternConverterTest.java   
@Before
public void setup() {
    // Create mock objects
    mockRequest = mock(Request.class);
    mockResponse = mock(Response.class);
    when(mockRequest.getMethod()).thenReturn(METHOD);
    when(mockRequest.getRequestURI()).thenReturn(URI);
    when(mockRequest.getQueryString()).thenReturn(QUERY);
    when(mockRequest.getProtocol()).thenReturn(PROTOCOL);
    when(mockRequest.getRemoteHost()).thenReturn(REMOTE_HOST);
    when(mockResponse.getStatus()).thenReturn(STATUS);
    when(mockResponse.getContentCount()).thenReturn(CONTENT_LENGTH);
    when(mockRequest.getTimeStamp()).thenReturn(REQUEST_TIME);
    when(mockRequest.getHeaderNames()).thenReturn(Collections.enumeration((HEADERS.keySet())));
    when(mockRequest.getHeader(anyString())).thenAnswer(invocation -> HEADERS.get(invocation.getArguments()[0]));

    // Static mocks
    mockStatic(System.class);
    when(System.currentTimeMillis()).thenReturn(RESPONSE_TIME);

    // Create actual objects
    contentLengthConverter = ContentLengthPatternConverter.newInstance(null);
    elapsedTimeConverter = ElapsedTimePatternConverter.newInstance(null);
    remoteHostConverter = RemoteHostPatternConverter.newInstance(null);
    requestHeaderConverter = RequestHeaderPatternConverter.newInstance(null);
    requestHeaderCaseConverter = RequestHeaderPatternConverter.newInstance(new String[] {HEADER_KEY1.toUpperCase() });
    requestHeaderNAConverter = RequestHeaderPatternConverter.newInstance(new String[] { NON_EXISTING_HEADER });
    requestLineConverter = RequestLinePatternConverter.newInstance(null);
    statusCodePatternConverter = StatusCodePatternConverter.newInstance(null);
    logEvent = new Log4jLogEvent.Builder().setMessage(new AccessLog(mockRequest, mockResponse)).build();
    noLogEvent = new Log4jLogEvent.Builder().setMessage(new SimpleMessage()).build();
}
项目:gerrit    文件:HttpLog.java   
@Override
public void log(Request req, Response rsp) {
  final LoggingEvent event =
      new LoggingEvent( //
          Logger.class.getName(), // fqnOfCategoryClass
          log, // logger
          TimeUtil.nowMs(), // when
          Level.INFO, // level
          "", // message text
          "HTTPD", // thread name
          null, // exception information
          null, // current NDC string
          null, // caller location
          null // MDC properties
          );

  String uri = req.getRequestURI();
  uri = redactQueryString(uri, req.getQueryString());

  String user = (String) req.getAttribute(GetUserFilter.REQ_ATTR_KEY);
  if (user != null) {
    event.setProperty(P_USER, user);
  }

  set(event, P_HOST, req.getRemoteAddr());
  set(event, P_METHOD, req.getMethod());
  set(event, P_RESOURCE, uri);
  set(event, P_PROTOCOL, req.getProtocol());
  set(event, P_STATUS, rsp.getStatus());
  set(event, P_CONTENT_LENGTH, rsp.getContentCount());
  set(event, P_REFERER, req.getHeader("Referer"));
  set(event, P_USER_AGENT, req.getHeader("User-Agent"));

  async.append(event);
}
项目:robe    文件:SearchModelTest.java   
@Test
public void getterSetter() {
    SearchModel model = new SearchModel();

    String[] fields = new String[]{"field1", "field2"};
    model.setFields(fields);
    assertArrayEquals(fields, model.getFields());

    Integer offset = 0;
    model.setOffset(offset);
    Assert.assertEquals(offset, model.getOffset());

    Integer limit = 10;
    model.setLimit(limit);
    Assert.assertEquals(limit, model.getLimit());

    String q = "query";
    model.setQ(q);
    Assert.assertEquals(q, model.getQ());

    String[] sort = new String[]{"field1+", "field2-"};
    model.setSort(sort);
    assertArrayEquals(sort, model.getSort());

    long totalCount = 30;
    model.setTotalCount(totalCount);
    Assert.assertEquals(totalCount, model.getTotalCount(), 0);

    HttpServletResponse httpServletResponse = new Response(null, null);

    model.setResponse(httpServletResponse);
    Assert.assertEquals(httpServletResponse, model.getResponse());

    String[][] filter = new String[][]{new String[]{"field1", "=", "val"}};
    model.setFilter(filter);
    assertArrayEquals(filter, model.getFilter());

}
项目:CoVisor    文件:JSONRPCAPI.java   
@Override
public void handle(final String target, final Request baseRequest,
        final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {

    if (baseRequest.getAuthentication() == null
            || baseRequest.getAuthentication().equals(
                    Authentication.UNAUTHENTICATED)) {
        response.sendError(Response.SC_UNAUTHORIZED, "Permission denied.");
        baseRequest.setHandled(true);

        return;
    }
    if (target.equals("/status")) {
        this.monitoringService.handle(request, response);

    } else if (target.equals("/tenant")) {
        this.tenantService.handle(request, response);

    } else if (target.equals("/admin")) {
        this.adminService.handle(request, response);

    } else {
        response.sendError(Response.SC_NOT_FOUND, target
                + " is not a service offered by OVX");

    }
    baseRequest.setHandled(true);
}