org.eclipse.jetty.server.Response Java Examples

The following examples show how to use org.eclipse.jetty.server.Response. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EnvServlet.java    From s2g-zuul with MIT License 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // make a writable copy of the immutable System.getenv() map
    Map<String,String> envVarsMap = new TreeMap<String,String>(System.getenv());

    String jsonStr = JSON.toJSONString(envVarsMap);

    resp.addHeader("Access-Control-Allow-Origin", "*");
    resp.addHeader("Access-Control-Allow-Headers","Content-Type, Accept");
    resp.setContentType("application/json; charset=UTF-8");

    PrintWriter writer = resp.getWriter();
    try{
        writer.write(jsonStr);
        resp.setStatus(Response.SC_OK);
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}
 
Example #2
Source File: SpnegoAuthenticatorEx.java    From sql-layer with GNU Affero General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #3
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
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());
 }
 
Example #4
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #5
Source File: TlsCertificateAuthorityServiceHandler.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private void writeResponse(ObjectMapper objectMapper, HttpServletRequest request, HttpServletResponse response, TlsCertificateAuthorityResponse tlsCertificateAuthorityResponse,
                           int responseCode) throws IOException {
    if (logger.isInfoEnabled()) {
        logger.info(new StringBuilder("Returning code:").append(responseCode).append(" payload ").append(objectMapper.writeValueAsString(tlsCertificateAuthorityResponse))
                .append(" to ").append(request.getRemoteHost()).toString());
    }
    if (responseCode == Response.SC_OK) {
        objectMapper.writeValue(response.getWriter(), tlsCertificateAuthorityResponse);
        response.setStatus(responseCode);
    } else {
        response.setStatus(responseCode);
        response.setContentType("application/json");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        objectMapper.writeValue(response.getWriter(), tlsCertificateAuthorityResponse);
    }
}
 
Example #6
Source File: HttpErrorHandler.java    From rdf-delta with Apache License 2.0 6 votes vote down vote up
@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); 
}
 
Example #7
Source File: TlsCertificateAuthorityServiceHandler.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void writeResponse(ObjectMapper objectMapper, HttpServletRequest request, HttpServletResponse response, TlsCertificateAuthorityResponse tlsCertificateAuthorityResponse,
                           int responseCode) throws IOException {
    if (logger.isInfoEnabled()) {
        logger.info(new StringBuilder("Returning code:").append(responseCode).append(" payload ").append(objectMapper.writeValueAsString(tlsCertificateAuthorityResponse))
                .append(" to ").append(request.getRemoteHost()).toString());
    }
    if (responseCode == Response.SC_OK) {
        objectMapper.writeValue(response.getWriter(), tlsCertificateAuthorityResponse);
        response.setStatus(responseCode);
    } else {
        response.setStatus(responseCode);
        response.setContentType("application/json");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        objectMapper.writeValue(response.getWriter(), tlsCertificateAuthorityResponse);
    }
}
 
Example #8
Source File: BasicAuthFilter.java    From dropwizard-experiment with MIT License 6 votes vote down vote up
@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);
}
 
Example #9
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #10
Source File: Log4JAccessLogTest.java    From Poseidon with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: AccessHandler.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public void log( Request request, Response response ) {
  if( log.isTraceEnabled() ) {
    StringBuilder sb = new StringBuilder();
    TraceUtil.appendCorrelationContext(sb);
    sb.append('|')
        .append(request.getRemoteAddr())
        .append('|')
        .append(request.getMethod())
        .append('|')
        .append(request.getHttpURI())
        .append('|')
        .append(request.getContentLength())
        .append('|')
        .append(response.getStatus())
        .append('|')
        .append(response.getContentCount())
        .append('|')
        .append(System.currentTimeMillis() - request.getTimeStamp());
    log.trace(sb);
  }
}
 
Example #12
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #13
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #14
Source File: EnvServlet.java    From tcc-transaction with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // make a writable copy of the immutable System.getenv() map
    Map<String,String> envVarsMap = new TreeMap<String,String>(System.getenv());

    String jsonStr = JSON.toJSONString(envVarsMap);
    resp.setCharacterEncoding("utf-8");
    resp.addHeader("Access-Control-Allow-Origin", "*");
    resp.addHeader("Access-Control-Allow-Headers","Content-Type, Accept");
    resp.setContentType("application/json");

    PrintWriter writer = resp.getWriter();
    try{
        writer.write(jsonStr);
        resp.setStatus(Response.SC_OK);
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}
 
Example #15
Source File: TlsCertificateSigningRequestPerformerTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testOk() throws Exception {
    certificates.add(caCertificate);
    statusCode = Response.SC_OK;
    tlsCertificateAuthorityResponse = new TlsCertificateAuthorityResponse(testHmac, testSignedCsr);
    tlsCertificateSigningRequestPerformer.perform(keyPair);
}
 
Example #16
Source File: TlsCertificateSigningRequestPerformerTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoCertificate() throws Exception {
    certificates.add(caCertificate);
    statusCode = Response.SC_OK;
    tlsCertificateAuthorityResponse = new TlsCertificateAuthorityResponse(testHmac, null);
    try {
        tlsCertificateSigningRequestPerformer.perform(keyPair);
        fail("Expected IOE");
    } catch (IOException e) {
        assertEquals(TlsCertificateSigningRequestPerformer.EXPECTED_RESPONSE_TO_CONTAIN_CERTIFICATE, e.getMessage());
    }
}
 
Example #17
Source File: TlsCertificateAuthorityServiceHandler.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    try {
        TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = objectMapper.readValue(new BoundedReader(request.getReader(), 1024 * 1024), TlsCertificateAuthorityRequest.class);

        if (!tlsCertificateAuthorityRequest.hasHmac()) {
            writeResponse(objectMapper, request, response, new TlsCertificateAuthorityResponse(HMAC_FIELD_MUST_BE_SET), Response.SC_BAD_REQUEST);
            return;
        }

        if (!tlsCertificateAuthorityRequest.hasCsr()) {
            writeResponse(objectMapper, request, response, new TlsCertificateAuthorityResponse(CSR_FIELD_MUST_BE_SET), Response.SC_BAD_REQUEST);
            return;
        }

        JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = TlsHelper.parseCsr(tlsCertificateAuthorityRequest.getCsr());
        byte[] expectedHmac = TlsHelper.calculateHMac(token, jcaPKCS10CertificationRequest.getPublicKey());

        if (MessageDigest.isEqual(expectedHmac, tlsCertificateAuthorityRequest.getHmac())) {
            String dn = jcaPKCS10CertificationRequest.getSubject().toString();
            if (logger.isInfoEnabled()) {
                logger.info("Received CSR with DN " + dn);
            }
            X509Certificate x509Certificate = CertificateUtils.generateIssuedCertificate(dn, jcaPKCS10CertificationRequest.getPublicKey(),
                    CertificateUtils.getExtensionsFromCSR(jcaPKCS10CertificationRequest), caCert, keyPair, signingAlgorithm, days);
            writeResponse(objectMapper, request, response, new TlsCertificateAuthorityResponse(TlsHelper.calculateHMac(token, caCert.getPublicKey()),
                    TlsHelper.pemEncodeJcaObject(x509Certificate)), Response.SC_OK);
            return;
        } else {
            writeResponse(objectMapper, request, response, new TlsCertificateAuthorityResponse(FORBIDDEN), Response.SC_FORBIDDEN);
            return;
        }
    } catch (Exception e) {
        throw new ServletException("Server error");
    } finally {
        baseRequest.setHandled(true);
    }
}
 
Example #18
Source File: SearchModelTest.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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());

}
 
Example #19
Source File: TlsCertificateSigningRequestPerformerTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void test2CertSize() throws Exception {
    certificates.add(caCertificate);
    certificates.add(caCertificate);
    statusCode = Response.SC_OK;
    tlsCertificateAuthorityResponse = new TlsCertificateAuthorityResponse();
    try {
        tlsCertificateSigningRequestPerformer.perform(keyPair);
        fail("Expected IOE");
    } catch (IOException e) {
        assertEquals(TlsCertificateSigningRequestPerformer.EXPECTED_ONE_CERTIFICATE, e.getMessage());
    }
}
 
Example #20
Source File: TlsCertificateSigningRequestPerformerTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoHmac() throws Exception {
    certificates.add(caCertificate);
    statusCode = Response.SC_OK;
    tlsCertificateAuthorityResponse = new TlsCertificateAuthorityResponse(null, testSignedCsr);
    try {
        tlsCertificateSigningRequestPerformer.perform(keyPair);
        fail("Expected IOE");
    } catch (IOException e) {
        assertEquals(TlsCertificateSigningRequestPerformer.EXPECTED_RESPONSE_TO_CONTAIN_HMAC, e.getMessage());
    }
}
 
Example #21
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
public void testAdminRequired_NoUserSkipAdminCheck() throws Exception {
  String path = "/admin/blah";
  Request request = spy(new Request(null, null));
  doReturn("true").when(request).getAttribute("com.google.apphosting.internal.SkipAdminCheck");
  Response response = mock(Response.class);
  String output = runRequest(path, request, response);
  assertEquals("null: null", output);
}
 
Example #22
Source File: TlsCertificateSigningRequestPerformerTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void test0CertSize() throws Exception {
    statusCode = Response.SC_OK;
    tlsCertificateAuthorityResponse = new TlsCertificateAuthorityResponse();
    try {
        tlsCertificateSigningRequestPerformer.perform(keyPair);
        fail("Expected IOE");
    } catch (IOException e) {
        assertEquals(TlsCertificateSigningRequestPerformer.EXPECTED_ONE_CERTIFICATE, e.getMessage());
    }
}
 
Example #23
Source File: TlsCertificateSigningRequestPerformerTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testBadStatusCode() throws Exception {
    statusCode = Response.SC_FORBIDDEN;
    tlsCertificateAuthorityResponse = new TlsCertificateAuthorityResponse();
    try {
        tlsCertificateSigningRequestPerformer.perform(keyPair);
        fail("Expected IOE");
    } catch (IOException e) {
        assertTrue(e.getMessage().startsWith(TlsCertificateSigningRequestPerformer.RECEIVED_RESPONSE_CODE + statusCode));
    }
}
 
Example #24
Source File: AppEngineAuthenticationTest.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
public void testUserNotRequired_WithAdmin() throws Exception {
  // Add a logged in admin.
  helper.setEnvIsLoggedIn(true)
      .setEnvIsAdmin(true)
      .setEnvEmail(ADMIN_EMAIL)
      .setEnvAuthDomain(TEST_ENV_DOMAIN)
      .setUp();
  Request request = spy(new Request(null, null));
  Response response = mock(Response.class);
  String path = "/";
  String output = runRequest(path, request, response);
  assertEquals(String.format("%s: %s", ADMIN_EMAIL, ADMIN_EMAIL), output);
}
 
Example #25
Source File: AuthenticationFilter.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
   filterChain.doFilter(servletRequest, servletResponse);
   if (AuditLogger.isAnyLoggingEnabled()) {
      int status = ((Response) servletResponse).getStatus();
      //status 200 means that the user has been authenticated, anything else must be a failure
      if (status == 200) {
         HttpSession session = ((Request) servletRequest).getSession();
         AuditLogger.userSuccesfullyLoggedInAudit(session != null ? (Subject) session.getAttribute("subject") : null);
      } else {
         AuditLogger.userFailedLoggedInAudit("" + status);
      }
   }
}
 
Example #26
Source File: PatternConverterTest.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #27
Source File: Log4JAccessLog.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
/**
 * 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));
}
 
Example #28
Source File: JettyJSONErrorHandler.java    From heroic with Apache License 2.0 5 votes vote down vote up
@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());
    }
}
 
Example #29
Source File: CrossOriginConstraintSecurityHandler.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected boolean isAuthMandatory(Request baseRequest, Response baseResponse, Object constraintInfo) {
    if(constraintInfo == null) {
        return false;
    }
    if(isPreFlightRequest(baseRequest)) {
        return false;
    }
    return ((RoleInfo)constraintInfo).isChecked();
}
 
Example #30
Source File: ServletRuntime25Test.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void status_fromJetty() throws Exception {
  Response jettyResponse = new Response(null);
  Field field = Response.class.getDeclaredField("_status");
  field.setAccessible(true);
  field.set(jettyResponse, 400);
  assertThat(ServletRuntime.get().status(jettyResponse))
    .isEqualTo(400);
}