下面列出了org.springframework.boot.context.embedded.jetty.JettyServerCustomizer#org.eclipse.jetty.http.HttpMethod 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public AboutLRSResponse about() {
HTTPRequest request = new HTTPRequest();
request.setMethod(HttpMethod.GET.asString());
request.setResource("about");
HTTPResponse response = makeSyncRequest(request);
int status = response.getStatus();
AboutLRSResponse lrsResponse = new AboutLRSResponse(request, response);
if (status == 200) {
lrsResponse.setSuccess(true);
try {
lrsResponse.setContent(new About(response.getContent()));
} catch (Exception ex) {
lrsResponse.setErrMsg("Exception: " + ex.toString());
lrsResponse.setSuccess(false);
}
}
else {
lrsResponse.setSuccess(false);
}
return lrsResponse;
}
@Test
public void testRedirect() throws IOException, ServerAuthException {
JwtAuthenticator authenticator = new JwtAuthenticator(TOKEN_PROVIDER, JWT_TOKEN);
HttpServletRequest request = mock(HttpServletRequest.class);
expect(request.getMethod()).andReturn(HttpMethod.GET.asString());
expect(request.getQueryString()).andReturn(null);
expect(request.getHeader(HttpHeader.AUTHORIZATION.asString())).andReturn(null);
expect(request.getCookies()).andReturn(new Cookie[] {});
expect(request.getRequestURL()).andReturn(new StringBuffer(CRUISE_CONTROL_ENDPOINT));
HttpServletResponse response = mock(HttpServletResponse.class);
response.sendRedirect(TOKEN_PROVIDER.replace(JwtAuthenticator.REDIRECT_URL, CRUISE_CONTROL_ENDPOINT));
expectLastCall().andVoid();
replay(request, response);
Authentication actualAuthentication = authenticator.validateRequest(request, response, true);
verify(request, response);
assertEquals(Authentication.SEND_CONTINUE, actualAuthentication);
}
private LRSResponse deleteDocument(String resource, Map<String, String> queryParams) {
HTTPRequest request = new HTTPRequest();
request.setMethod(HttpMethod.DELETE.asString());
request.setResource(resource);
request.setQueryParams(queryParams);
HTTPResponse response = makeSyncRequest(request);
LRSResponse lrsResponse = new LRSResponse(request, response);
if (response.getStatus() == 204) {
lrsResponse.setSuccess(true);
}
else {
lrsResponse.setSuccess(false);
}
return lrsResponse;
}
private LRSResponse updateDocument(String resource, Map<String, String> queryParams, Document document) {
HTTPRequest request = new HTTPRequest();
request.setMethod(HttpMethod.POST.asString());
request.setResource(resource);
request.setQueryParams(queryParams);
request.setContentType(document.getContentType());
request.setContent(document.getContent());
if (document.getEtag() != null) {
request.setHeaders(new HashMap<String, String>());
request.getHeaders().put("If-Match", document.getEtag());
}
HTTPResponse response = makeSyncRequest(request);
LRSResponse lrsResponse = new LRSResponse(request, response);
if (response.getStatus() == 204) {
lrsResponse.setSuccess(true);
}
else {
lrsResponse.setSuccess(false);
}
return lrsResponse;
}
@Bean
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory(
@Value("${server.port:8080}") final String port,
@Value("${jetty.threadPool.maxThreads:200}") final String maxThreads,
@Value("${jetty.threadPool.minThreads:8}") final String minThreads,
@Value("${jetty.threadPool.idleTimeout:60000}") final String idleTimeout) {
final JettyEmbeddedServletContainerFactory factory =
new JettyEmbeddedServletContainerFactory(Integer.valueOf(port));
factory.addServerCustomizers((JettyServerCustomizer) server -> {
final QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class);
threadPool.setMaxThreads(Integer.valueOf(maxThreads));
threadPool.setMinThreads(Integer.valueOf(minThreads));
threadPool.setIdleTimeout(Integer.valueOf(idleTimeout));
final GzipHandler gzipHandler = new GzipHandler();
gzipHandler.addIncludedMethods(HttpMethod.POST.asString());
gzipHandler.setHandler(server.getHandler());
gzipHandler.setSyncFlush(true);
server.setHandler(gzipHandler);
});
return factory;
}
private void verifyEphemeralErrorsAreNotRetried(HttpMethod[] methods, Map<String, String> params)
throws IOException
{
proxy = TestUtils.startRequestFailingProxy(3, requests);
String uri = "http://localhost:" + httpMockWebServer.getPort() + "/test";
for (HttpMethod method : methods) {
runWorkflow(folder, "acceptance/http/http.dig",
ImmutableMap.<String, String>builder()
.putAll(params)
.put("test_uri", uri)
.put("http.method", method.asString())
.put("http.proxy.enabled", "true")
.put("http.proxy.host", "localhost")
.put("http.proxy.port", Integer.toString(proxy.getListenAddress().getPort()))
.build(),
ImmutableMap.of(),
1);
assertThat(requests.keySet().stream().anyMatch(k -> k.startsWith(method.asString())), is(true));
}
assertThat(httpMockWebServer.getRequestCount(), is(0));
}
private void verifyEphemeralErrorsAreRetried(HttpMethod[] methods, Map<String, String> params)
throws IOException
{
proxy = TestUtils.startRequestFailingProxy(3, requests);
String uri = "http://localhost:" + httpMockWebServer.getPort() + "/test";
for (HttpMethod method : methods) {
runWorkflow(folder, "acceptance/http/http.dig",
ImmutableMap.<String, String>builder()
.putAll(params)
.put("test_uri", uri)
.put("http.method", method.asString())
.put("http.proxy.enabled", "true")
.put("http.proxy.host", "localhost")
.put("http.proxy.port", Integer.toString(proxy.getListenAddress().getPort()))
.build(),
ImmutableMap.of(),
0);
assertThat(requests.keySet().stream().anyMatch(k -> k.startsWith(method.asString())), is(true));
}
assertThat(requests.size(), is(methods.length));
assertThat(httpMockWebServer.getRequestCount(), is(methods.length));
}
private static ArrayNode fetchDynRealmsFromElasticsearch(final String userKey) throws Exception {
String body =
'{'
+ " \"query\": {"
+ " \"match\": {\"_id\": \"" + userKey + "\"}"
+ " }"
+ '}';
HttpClient httpClient = new HttpClient();
httpClient.start();
ContentResponse response = httpClient.newRequest("http://localhost:9200/master_user/_search").
method(HttpMethod.GET).
header(HttpHeader.CONTENT_TYPE, MediaType.APPLICATION_JSON).
content(new InputStreamContentProvider(IOUtils.toInputStream(body))).
send();
assertEquals(HttpStatus.OK_200, response.getStatus());
return (ArrayNode) OBJECT_MAPPER.readTree(response.getContent()).
get("hits").get("hits").get(0).get("_source").get("dynRealms");
}
private void executeReceiveRequest(URI url, HttpHeaders headers, SockJsResponseListener listener) {
if (logger.isTraceEnabled()) {
logger.trace("Starting XHR receive request, url=" + url);
}
Request httpRequest = this.httpClient.newRequest(url).method(HttpMethod.POST);
addHttpHeaders(httpRequest, headers);
httpRequest.send(listener);
}
@Override
public void handle(
String target,
Request baseRequest,
HttpServletRequest request,
HttpServletResponse response
)
throws IOException, ServletException {
metrics.getRequestsMeter().mark();
if (!target.equals(s3Configuration.getLocalDownloadPath())) {
metrics.getClientErrorsMeter().mark();
response.sendError(404);
return;
}
if (!request.getMethod().equalsIgnoreCase(HttpMethod.POST.name())) {
metrics.getClientErrorsMeter().mark();
response.sendError(405);
return;
}
Optional<ArtifactDownloadRequest> artifactOptional = readDownloadRequest(request);
if (!artifactOptional.isPresent()) {
metrics.getClientErrorsMeter().mark();
response.sendError(400);
return;
}
Continuation continuation = ContinuationSupport.getContinuation(request);
continuation.suspend(response);
if (artifactOptional.get().getTimeoutMillis().isPresent()) {
continuation.setTimeout(artifactOptional.get().getTimeoutMillis().get());
}
downloaderCoordinator.register(continuation, artifactOptional.get());
}
@Test
public void baseTest() throws Exception {
mockResponse(HttpStatus.OK_200);
String result = HttpRequestBuilder.getFrom(URL).getContentAsString();
assertEquals("Some content", result);
verify(httpClientMock).newRequest(URL);
verify(requestMock).method(HttpMethod.GET);
verify(requestMock).send();
}
@Override
public ActivityLRSResponse retrieveActivity(Activity activity) {
HTTPRequest request = new HTTPRequest();
request.setMethod(HttpMethod.GET.asString());
request.setResource("activities");
request.setQueryParams(new HashMap<String, String>());
request.getQueryParams().put("activityId", activity.getId().toString());
HTTPResponse response = makeSyncRequest(request);
int status = response.getStatus();
ActivityLRSResponse lrsResponse = new ActivityLRSResponse(request, response);
if (status == 200) {
lrsResponse.setSuccess(true);
try {
lrsResponse.setContent(new Activity(new StringOfJSON(response.getContent())));
} catch (Exception ex) {
lrsResponse.setErrMsg("Exception: " + ex.toString());
lrsResponse.setSuccess(false);
}
}
else {
lrsResponse.setSuccess(false);
}
return lrsResponse;
}
@Override
public ClientResponse executeRequest(String url) throws Exception {
httpClient.start();
ContentResponse contentResponse = httpClient.newRequest(url)
.method(HttpMethod.GET)
.header(HEADER_KEY_CLIENT_TYPE, getClientType().getValue())
.send();
httpClient.stop();
return new ClientResponse(contentResponse.getContentAsString(), contentResponse.getStatus());
}
@Test
public void executeRequest() throws Exception {
Request request = mock(Request.class);
ContentResponse contentResponse = mock(ContentResponse.class);
when(httpClient.newRequest(anyString())).thenReturn(request);
when(request.method(any(HttpMethod.class))).thenReturn(request);
when(request.header(anyString(), anyString())).thenReturn(request);
when(request.send()).thenReturn(contentResponse);
when(contentResponse.getContentAsString()).thenReturn("hello");
when(contentResponse.getStatus()).thenReturn(200);
ArgumentCaptor<String> urlCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> headerKeyCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> headerValueCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<HttpMethod> httpMethodCaptor = ArgumentCaptor.forClass(HttpMethod.class);
ClientResponse clientResponse = victim.executeRequest(HTTP_URL);
assertThat(clientResponse.getStatusCode()).isEqualTo(200);
assertThat(clientResponse.getResponseBody()).isEqualTo("hello");
verify(request, times(1)).header(headerKeyCaptor.capture(), headerValueCaptor.capture());
assertThat(headerKeyCaptor.getValue()).isEqualTo(HEADER_KEY_CLIENT_TYPE);
assertThat(headerValueCaptor.getValue()).isEqualTo(JETTY_REACTIVE_HTTP_CLIENT.getValue());
verify(request, times(1)).method(httpMethodCaptor.capture());
assertThat(httpMethodCaptor.getValue()).isEqualTo(HttpMethod.GET);
verify(httpClient, times(1)).newRequest(urlCaptor.capture());
assertThat(urlCaptor.getValue()).isEqualTo(HTTP_URL);
verify(httpClient, times(1)).start();
verify(httpClient, times(1)).stop();
}
@Test
public void testSuccessfulLogin() throws Exception {
UserStore testUserStore = new UserStore();
testUserStore.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[]{USER_ROLE});
TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER);
JwtLoginService loginService = new JwtLoginService(new UserStoreAuthorizationService(testUserStore), tokenAndKeys.publicKey(), null);
Authenticator.AuthConfiguration configuration = mock(Authenticator.AuthConfiguration.class);
expect(configuration.getLoginService()).andReturn(loginService);
expect(configuration.getIdentityService()).andReturn(new DefaultIdentityService());
expect(configuration.isSessionRenewedOnAuthentication()).andReturn(true);
Request request = niceMock(Request.class);
expect(request.getMethod()).andReturn(HttpMethod.GET.asString());
expect(request.getHeader(HttpHeader.AUTHORIZATION.asString())).andReturn(null);
request.setAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE, tokenAndKeys.token());
expectLastCall().andVoid();
expect(request.getCookies()).andReturn(new Cookie[] {new Cookie(JWT_TOKEN, tokenAndKeys.token())});
expect(request.getAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE)).andReturn(tokenAndKeys.token());
HttpServletResponse response = mock(HttpServletResponse.class);
replay(configuration, request, response);
JwtAuthenticator authenticator = new JwtAuthenticator(TOKEN_PROVIDER, JWT_TOKEN);
authenticator.setConfiguration(configuration);
UserAuthentication authentication = (UserAuthentication) authenticator.validateRequest(request, response, true);
verify(configuration, request, response);
assertNotNull(authentication);
assertTrue(authentication.getUserIdentity().getUserPrincipal() instanceof JwtUserPrincipal);
JwtUserPrincipal userPrincipal = (JwtUserPrincipal) authentication.getUserIdentity().getUserPrincipal();
assertEquals(TEST_USER, userPrincipal.getName());
assertEquals(tokenAndKeys.token(), userPrincipal.getSerializedToken());
}
public void updateHealthStatus(HealthCheck.Status status) throws Exception {
logger.trace("Updating health of {}", serviceProps.getServiceName());
ContentResponse httpResponse = httpClient.newRequest(getHealthCheckUri(status)).method(HttpMethod.PUT).send();
if (httpResponse.getStatus() != 200) {
logger.warn("Received {} trying to update health", httpResponse.getStatus());
}
}
public boolean restoreRequest() {
HttpSession session = myRequest.getSession(false);
if (session == null) return false;
synchronized (session) {
String j_uri = (String) session.getAttribute(FormAuthenticator.__J_URI);
if (j_uri != null) {
// check if the request is for the same url as the original and restore
// params if it was a post
StringBuffer buf = myRequest.getRequestURL();
if (myRequest.getQueryString() != null)
buf.append("?").append(myRequest.getQueryString());
if (j_uri.equals(buf.toString())) {
String method = (String)session.getAttribute(JettyHttpFacade.__J_METHOD);
myRequest.setMethod(HttpMethod.valueOf(method.toUpperCase()), method);
MultivaluedHashMap<String, String> j_post = (MultivaluedHashMap<String, String>) session.getAttribute(CACHED_FORM_PARAMETERS);
if (j_post != null) {
myRequest.setContentType("application/x-www-form-urlencoded");
MultiMap<String> map = new MultiMap<String>();
for (String key : j_post.keySet()) {
for (String val : j_post.getList(key)) {
map.add(key, val);
}
}
restoreFormParameters(map, myRequest);
}
session.removeAttribute(FormAuthenticator.__J_URI);
session.removeAttribute(JettyHttpFacade.__J_METHOD);
session.removeAttribute(FormAuthenticator.__J_POST);
}
return true;
}
}
return false;
}
protected String sendRequest(String path, String data, HttpMethod method) throws Exception {
String url = getServiceUrl(path);
Request request = httpClient.newRequest(url).method(method).
header(HttpHeader.CONTENT_TYPE, "application/json");
if (data != null) {
request.content(new StringContentProvider(data));
}
ContentResponse response = request.send();
return response.getContentAsString();
}
private boolean verifyRegistrationInConsul() {
String registryServer = serviceProps.getRegistryServer();
if (StringUtils.isBlank(registryServer)) {
return false;
}
String url = "http://" + registryServer + "/v1/catalog/service/" +
serviceProps.getServiceName();
try {
ContentResponse httpResponse = httpClient.newRequest(url).
method(HttpMethod.GET).header(HttpHeader.CONTENT_TYPE, "application/json").send();
if (httpResponse.getStatus() != 200) {
return false;
}
JsonArray pods = new JsonParser().parse(httpResponse.getContentAsString()).getAsJsonArray();
Iterator<JsonElement> iter = pods.iterator();
while (iter.hasNext()) {
JsonElement pod = iter.next();
String serviceId = pod.getAsJsonObject().get("ServiceID").getAsString();
if (serviceProps.getServiceInstanceId().equals(serviceId)) {
return true;
}
}
} catch (Exception ex) {
logger.warn("Caught exception verifying registration", ex);
}
return false;
}
private boolean sendRegistration(JsonObject request) {
try {
ContentResponse httpResponse = httpClient.newRequest(getRegistrationUri()).
content(new StringContentProvider(request.toString())).
method(HttpMethod.PUT).header(HttpHeader.CONTENT_TYPE, "application/json").send();
if (httpResponse.getStatus() == 200) {
return true;
}
} catch (Exception ex) {
logger.warn("Caught exception sending registration {}", request.toString(), ex);
}
return false;
}
private ProfileKeysLRSResponse getProfileKeys(String resource, HashMap<String, String> queryParams) {
HTTPRequest request = new HTTPRequest();
request.setMethod(HttpMethod.GET.asString());
request.setResource(resource);
request.setQueryParams(queryParams);
HTTPResponse response = makeSyncRequest(request);
ProfileKeysLRSResponse lrsResponse = new ProfileKeysLRSResponse(request, response);
if (response.getStatus() == 200) {
lrsResponse.setSuccess(true);
try {
Iterator it = Mapper.getInstance().readValue(response.getContent(), ArrayNode.class).elements();
lrsResponse.setContent(new ArrayList<String>());
while (it.hasNext()) {
lrsResponse.getContent().add(it.next().toString());
}
} catch (Exception ex) {
lrsResponse.setErrMsg("Exception: " + ex.toString());
lrsResponse.setSuccess(false);
}
}
else {
lrsResponse.setSuccess(false);
}
return lrsResponse;
}
private void executeReceiveRequest(URI url, HttpHeaders headers, SockJsResponseListener listener) {
if (logger.isTraceEnabled()) {
logger.trace("Starting XHR receive request, url=" + url);
}
Request httpRequest = this.httpClient.newRequest(url).method(HttpMethod.POST);
addHttpHeaders(httpRequest, headers);
httpRequest.send(listener);
}
@Override
public PersonLRSResponse retrievePerson(Agent agent) {
HTTPRequest request = new HTTPRequest();
request.setMethod(HttpMethod.GET.asString());
request.setResource("agents");
request.setQueryParams(new HashMap<String, String>());
request.getQueryParams().put("agent", agent.toJSON(this.getVersion(), this.usePrettyJSON()));
HTTPResponse response = makeSyncRequest(request);
int status = response.getStatus();
PersonLRSResponse lrsResponse = new PersonLRSResponse(request, response);
if (status == 200) {
lrsResponse.setSuccess(true);
try {
lrsResponse.setContent(new Person(new StringOfJSON(response.getContent())));
} catch (Exception ex) {
lrsResponse.setErrMsg("Exception: " + ex.toString());
lrsResponse.setSuccess(false);
}
}
else {
lrsResponse.setSuccess(false);
}
return lrsResponse;
}
public OutStream initOutStream(String baseUrl,
UpdateRequest updateRequest,
String collection) throws IOException {
String contentType = requestWriter.getUpdateContentType();
final ModifiableSolrParams origParams = new ModifiableSolrParams(updateRequest.getParams());
// The parser 'wt=' and 'version=' params are used instead of the
// original params
ModifiableSolrParams requestParams = new ModifiableSolrParams(origParams);
requestParams.set(CommonParams.WT, parser.getWriterType());
requestParams.set(CommonParams.VERSION, parser.getVersion());
String basePath = baseUrl;
if (collection != null)
basePath += "/" + collection;
if (!basePath.endsWith("/"))
basePath += "/";
OutputStreamContentProvider provider = new OutputStreamContentProvider();
Request postRequest = httpClient
.newRequest(basePath + "update"
+ requestParams.toQueryString())
.method(HttpMethod.POST)
.header(HttpHeader.CONTENT_TYPE, contentType)
.content(provider);
decorateRequest(postRequest, updateRequest);
InputStreamResponseListener responseListener = new InputStreamResponseListener();
postRequest.send(responseListener);
boolean isXml = ClientUtils.TEXT_XML.equals(requestWriter.getUpdateContentType());
OutStream outStream = new OutStream(collection, origParams, provider, responseListener,
isXml);
if (isXml) {
outStream.write("<stream>".getBytes(FALLBACK_CHARSET));
}
return outStream;
}
/**
* Factory method to create a {@link HttpMethod}-object according to the given String <code>httpMethodString</code>
*
* @param httpMethodString the name of the {@link HttpMethod} to create
* @throws IllegalArgumentException if <code>httpMethod</code> is none of <code>GET</code>, <code>PUT</code>,
* <code>POST</POST> or <code>DELETE</code>
*/
public static HttpMethod createHttpMethod(String httpMethodString) {
// @formatter:off
return Optional.ofNullable(HttpMethod.fromString(httpMethodString))
.filter(m -> m == GET || m == POST || m == PUT || m == DELETE)
.orElseThrow(() -> new IllegalArgumentException("Given HTTP Method '" + httpMethodString + "' is unknown"));
// @formatter:on
}
/**
* Factory method to create a {@link HttpMethod}-object according to the given String <code>httpMethodString</code>
*
* @param httpMethodString the name of the {@link HttpMethod} to create
* @throws IllegalArgumentException if <code>httpMethod</code> is none of <code>GET</code>, <code>PUT</code>,
* <code>POST</POST> or <code>DELETE</code>
*/
public static HttpMethod createHttpMethod(String httpMethodString) {
// @formatter:off
return Optional.ofNullable(HttpMethod.fromString(httpMethodString))
.filter(m -> m == GET || m == POST || m == PUT || m == DELETE)
.orElseThrow(() -> new IllegalArgumentException("Given HTTP Method '" + httpMethodString + "' is unknown"));
// @formatter:on
}
@Test
public void testPostWithContentType() throws Exception {
ArgumentCaptor<ContentProvider> argumentCaptor = ArgumentCaptor.forClass(ContentProvider.class);
mockResponse(HttpStatus.OK_200);
String result = HttpRequestBuilder.postTo(URL).withContent("{json: true}", "application/json")
.getContentAsString();
assertEquals("Some content", result);
// verify just the content-type to be added to the request
verify(requestMock).method(HttpMethod.POST);
verify(requestMock).content(argumentCaptor.capture(), ArgumentMatchers.eq("application/json"));
}
@Test
public void baseTest() throws Exception {
mockResponse(HttpStatus.OK_200);
String result = HttpUtil.executeUrl("GET", URL, 500);
assertEquals("Some content", result);
verify(httpClientMock).newRequest(URL);
verify(requestMock).method(HttpMethod.GET);
verify(requestMock).timeout(500, TimeUnit.MILLISECONDS);
verify(requestMock).send();
}
@Test
public void testCreateHttpMethod() {
assertEquals(HttpMethod.GET, HttpUtil.createHttpMethod("GET"));
assertEquals(HttpMethod.PUT, HttpUtil.createHttpMethod("PUT"));
assertEquals(HttpMethod.POST, HttpUtil.createHttpMethod("POST"));
assertEquals(HttpMethod.DELETE, HttpUtil.createHttpMethod("DELETE"));
}
@Before
public void setUp() throws Exception {
initMocks(this);
Field httpClientFactory = HttpUtil.class.getDeclaredField("httpClientFactory");
httpClientFactory.setAccessible(true);
httpClientFactory.set(null, clientFactoryMock);
when(clientFactoryMock.getCommonHttpClient()).thenReturn(httpClientMock);
when(httpClientMock.newRequest(URL)).thenReturn(requestMock);
when(requestMock.method(any(HttpMethod.class))).thenReturn(requestMock);
when(requestMock.timeout(anyLong(), any(TimeUnit.class))).thenReturn(requestMock);
when(requestMock.send()).thenReturn(contentResponseMock);
}