org.apache.commons.io.input.BoundedInputStream#org.eclipse.jetty.server.Response源码实例Demo

下面列出了org.apache.commons.io.input.BoundedInputStream#org.eclipse.jetty.server.Response 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

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);
    }
}
 
源代码2 项目: s2g-zuul   文件: EnvServlet.java
@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();
        }
    }
}
 
源代码3 项目: tcc-transaction   文件: EnvServlet.java
@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();
        }
    }
}
 
源代码4 项目: 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);
}
 
源代码5 项目: 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); 
}
 
源代码6 项目: 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;
}
 
源代码7 项目: 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);
}
 
源代码8 项目: knox   文件: AccessHandler.java
@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);
  }
}
 
/**
 * 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());
}
 
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());
 }
 
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);
}
 
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);
}
 
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);
}
 
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);
    }
}
 
源代码15 项目: judgels   文件: ActorChecker.java
public String check(@Nullable AuthHeader authHeader) {
    PerRequestActorProvider.clearJid();

    if (authHeader == null) {
        throw new NotAuthorizedException(Response.SC_UNAUTHORIZED);
    }

    String actorJid = actorExtractor.extractJid(authHeader)
            .orElseThrow(() -> new NotAuthorizedException(Response.SC_UNAUTHORIZED));

    PerRequestActorProvider.setJid(actorJid);

    return actorJid;
}
 
源代码16 项目: brave   文件: ServletRuntimeTest.java
@Test public void servlet25_status_doesntParseAnonymousTypes() {
  // while looks nice, this will overflow our cache
  Response jettyResponse = new Response(null, null) {
    @Override public int getStatus() {
      throw new AssertionError();
    }
  };
  assertThat(servlet25.status(jettyResponse))
    .isZero();
}
 
@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);
    }
}
 
@Test
public void testOk() throws Exception {
    certificates.add(caCertificate);
    statusCode = Response.SC_OK;
    tlsCertificateAuthorityResponse = new TlsCertificateAuthorityResponse(testHmac, testSignedCsr);
    tlsCertificateSigningRequestPerformer.perform(keyPair);
}
 
@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));
    }
}
 
@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());
    }
}
 
@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());
    }
}
 
@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());
    }
}
 
@Test
public void testBadHmac() throws Exception {
    certificates.add(caCertificate);
    statusCode = Response.SC_OK;
    tlsCertificateAuthorityResponse = new TlsCertificateAuthorityResponse("badHmac".getBytes(StandardCharsets.UTF_8), testSignedCsr);
    try {
        tlsCertificateSigningRequestPerformer.perform(keyPair);
        fail("Expected IOE");
    } catch (IOException e) {
        assertEquals(TlsCertificateSigningRequestPerformer.UNEXPECTED_HMAC_RECEIVED_POSSIBLE_MAN_IN_THE_MIDDLE, e.getMessage());
    }
}
 
@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());
    }
}
 
@Test
public void testSuccess() throws IOException, ServletException, GeneralSecurityException, CRMFException {
    tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest(testHmac, testPemEncodedCsr);
    tlsCertificateAuthorityServiceHandler.handle(null, baseRequest, httpServletRequest, httpServletResponse);
    assertEquals(Response.SC_OK, statusCode);
    assertArrayEquals(testCaHmac, getResponse().getHmac());
    X509Certificate certificate = TlsHelper.parseCertificate(new StringReader(getResponse().getPemEncodedCertificate()));
    assertEquals(certificateKeyPair.getPublic(), certificate.getPublicKey());
    assertEquals(new X500Name(requestedDn), new X500Name(certificate.getSubjectDN().toString()));
    certificate.verify(caCert.getPublicKey());
}
 
@Test
public void testNoCsr() throws IOException, ServletException {
    tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest(testHmac, null);
    tlsCertificateAuthorityServiceHandler.handle(null, baseRequest, httpServletRequest, httpServletResponse);
    assertEquals(Response.SC_BAD_REQUEST, statusCode);
    assertEquals(TlsCertificateAuthorityServiceHandler.CSR_FIELD_MUST_BE_SET, getResponse().getError());
}
 
@Test
public void testNoHmac() throws IOException, ServletException {
    tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest(null, testPemEncodedCsr);
    tlsCertificateAuthorityServiceHandler.handle(null, baseRequest, httpServletRequest, httpServletResponse);
    assertEquals(Response.SC_BAD_REQUEST, statusCode);
    assertEquals(TlsCertificateAuthorityServiceHandler.HMAC_FIELD_MUST_BE_SET, getResponse().getError());
}
 
@Test
public void testForbidden() throws IOException, ServletException, NoSuchAlgorithmException, CRMFException, NoSuchProviderException, InvalidKeyException {
    tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest("badHmac".getBytes(StandardCharsets.UTF_8), testPemEncodedCsr);
    tlsCertificateAuthorityServiceHandler.handle(null, baseRequest, httpServletRequest, httpServletResponse);
    assertEquals(Response.SC_FORBIDDEN, statusCode);
    assertEquals(TlsCertificateAuthorityServiceHandler.FORBIDDEN, getResponse().getError());
}
 
源代码29 项目: s2g-zuul   文件: StatusServlet.java
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    Map<String, String> props = new LinkedHashMap<String, String>();

    props.put("Server Start Time", new SimpleDateFormat("yyyy-MM-dd HH:ss").format(new Date(rb.getStartTime())));
    props.put("Server Up Time", TimeUtil.readableTimeInterval(rb.getUptime()));

    addJsonContent(props, "System ", operatingSystemStatsGetter.get().toJsonStr());
    addJsonContent(props, "Memory ", memoryStatsGetter.get().toJsonStr());
    addJsonContent(props, "Thread ", threadStatsGetter.get().toJsonStr());
    addJsonContent(props, "Class ", classStatsGetter.get().toJsonStr());
    addJsonContent(props, "GC(last Minute) ", statusInfo.getGCStats().toJsonStr());

    String jsonStr = JSON.toJSONString(props);

    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();
        }
    }
}
 
@Test
public void testNoHmac() throws IOException, ServletException {
    tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest(null, testPemEncodedCsr);
    tlsCertificateAuthorityServiceHandler.handle(null, baseRequest, httpServletRequest, httpServletResponse);
    assertEquals(Response.SC_BAD_REQUEST, statusCode);
    assertEquals(TlsCertificateAuthorityServiceHandler.HMAC_FIELD_MUST_BE_SET, getResponse().getError());
}