本文整理汇总了Java中play.libs.ws.WS类的典型用法代码示例。如果您正苦于以下问题:Java WS类的具体用法?Java WS怎么用?Java WS使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
WS类属于play.libs.ws包,在下文中一共展示了WS类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: notify
import play.libs.ws.WS; //导入依赖的package包/类
private void notify(String url) {
if (!url.isEmpty()) {
Logger.info("Send request to: " + url);
ObjectMapper mapper = new ObjectMapper();
ObjectNode json = mapper.createObjectNode();
JsonNode k = mapper.valueToTree(keys);
json.put("id", id)
.put("name", uploadFileName)
.put("bucket", GlobalParams.AWS_S3_BUCKET)
.put("type", type.getType())
.put("status", UploadStatus.READ.getType())
.put("keys", k);
Logger.info("Send post request: " + json);
WS.url(url).post(json);
}
}
示例2: custom
import play.libs.ws.WS; //导入依赖的package包/类
private Promise<Result> custom(
String moduleId,
String path,
Function<WSRequest, Promise<WSResponse>> prepareAndFireRequest) {
long userId = getUserIdForRequest();
if (!UserModuleActivationPersistency.doesActivationExist(userId,
moduleId)) {
return Promise
.pure(badRequestJson(AssistanceAPIErrors.moduleActivationNotActive));
}
ActiveAssistanceModule module = UserModuleActivationPersistency.activatedModuleEndpointsForUser(new String[]{moduleId})[0];
WSRequest request = WS.url(module.restUrl("/custom/" + path));
request.setHeader("ASSISTANCE-USER-ID", Long.toString(userId));
Promise<WSResponse> responsePromise = prepareAndFireRequest.apply(request);
return responsePromise.map((response) -> (Result) Results.status(response.getStatus(),
response.getBody()));
}
示例3: testsWithServer
import play.libs.ws.WS; //导入依赖的package包/类
@Test
public void testsWithServer() throws Exception {
final TestServer testServer = testServer(fakeApplication());
running(testServer, () -> {
try (final WSClient wsClient = WS.newClient(testServer.port())) {
final WSResponse wsResponse = wsClient
.url("/playbasics/show2")
.setQueryString("name=John")
.get().toCompletableFuture().get();
assertThat(wsResponse.getStatus()).isEqualTo(OK);
assertThat(wsResponse.getBody()).isEqualTo("Hello John!");
} catch (IOException | InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
});
}
开发者ID:commercetools,项目名称:commercetools-sunrise-java-training,代码行数:17,代码来源:MyControllerMixScopeTest.java
示例4: sendUserInput
import play.libs.ws.WS; //导入依赖的package包/类
public F.Promise<List<PaymentSchedule>> sendUserInput(CalculatorInput calcInput) {
String calculatorUrl = String.format("%s/%s", baseUrl, "paymentschedule");
Logger.debug(toJson(calcInput).toString());
F.Promise<WSResponse> result = WS.url(calculatorUrl).post(toJson(calcInput));
return result.map(r -> {
if (r.getStatus() != 200) {
return new ArrayList<PaymentSchedule>();
} else {
return Arrays.asList(fromJson(r.asJson(), PaymentSchedule[].class));
}
});
}
示例5: findAll
import play.libs.ws.WS; //导入依赖的package包/类
public static List<Todo> findAll(String accessToken) {
WSRequestHolder req = WS.url(OAUTH_RESOURCE_SERVER_URL + "/rest/todos");
req.setHeader("Authorization", "Bearer " + accessToken);
Promise<List<Todo>> jsonPromise = req.get().map(new Function<WSResponse, List<Todo>>() {
public List<Todo> apply(WSResponse response) {
JsonNode json = response.asJson();
ArrayNode results = (ArrayNode) json;
List<Todo> todos = new ArrayList<Todo>();
Iterator<JsonNode> it = results.iterator();
while (it.hasNext()) {
JsonNode node = it.next();
Todo todo = new Todo();
todo.setDescription(node.get("description").asText());
todos.add(todo);
}
return todos;
}
});
return jsonPromise.get(5000);
}
示例6: findByUsername
import play.libs.ws.WS; //导入依赖的package包/类
public static List<Todo> findByUsername(String accessToken, String username) {
WSRequestHolder req = WS.url(OAUTH_RESOURCE_SERVER_URL + "/rest/todos/" + username);
req.setHeader("Authorization", "Bearer " + accessToken);
Promise<List<Todo>> jsonPromise = req.get().map(new Function<WSResponse, List<Todo>>() {
public List<Todo> apply(WSResponse response) {
JsonNode json = response.asJson();
ArrayNode results = (ArrayNode) json;
List<Todo> todos = new ArrayList<Todo>();
Iterator<JsonNode> it = results.iterator();
while (it.hasNext()) {
JsonNode node = it.next();
Todo todo = new Todo();
todo.setId(node.get("id").asLong());
todo.setDescription(node.get("description").asText());
todo.setUsername(node.get("username").asText());
todos.add(todo);
}
return todos;
}
});
return jsonPromise.get(5000);
}
示例7: index
import play.libs.ws.WS; //导入依赖的package包/类
public static Promise<Result> index() {
if (session().get("access_token") == null) {
return Promise.pure(redirect(routes.Application.index().absoluteURL(request())));
}
String accessToken = session().get("access_token");
WSRequestHolder req = WS.url(OAUTH_URL + "/userinfo");
req.setHeader("Authorization", "Bearer " + accessToken);
// Get the JSON Response
Promise<Result> resultPromise = req.get().map(new Function<WSResponse, Result>() {
public Result apply(WSResponse response) {
if (200 == response.getStatus()) {
// get the user info
String username = response.asJson().get("username").textValue();
session().put("username", username);
return redirect(routes.Application.index().absoluteURL(request()));
}
// go back to authentication
return redirect(OAuthUtils.oAuthAuthorizeUrl());
}
});
return resultPromise;
}
示例8: getJsonFrom
import play.libs.ws.WS; //导入依赖的package包/类
protected static JsonNode getJsonFrom(String cookie, String url) {
Logger.info("Getting "+url);
while(true) {
try {
Promise<JsonNode> jsonPromise = WS.url(url).setRequestTimeout(timeout).setHeader("Cookie", cookie).get().map(
new Function<WSResponse, JsonNode>() {
public JsonNode apply(WSResponse response) {
JsonNode json = response.asJson();
return json;
}
}
);
return jsonPromise.get(timeout);
} catch( Exception e ) {
Logger.error("Exception while talking to W3ACT - sleeping for 15 seconds before retrying.",e);
try {
Thread.sleep(15*1000);
} catch (InterruptedException e1) {
Logger.error("Thread sleep was interrupted.",e);
}
}
}
}
示例9: testGetMeal
import play.libs.ws.WS; //导入依赖的package包/类
@Test
public void testGetMeal() {
running(testServer(Th.SERVER_PORT, fakeApplication(inMemoryDatabase())), new Runnable() {
public void run() {
JsonNode credentials = Th.createAccount(Th.TEST_EMAIL, Th.TEST_PASSWORD);
String token = WS
.url(Th.getFullUrl("/app/login"))
.post(credentials)
.get(Th.REQUEST_TIME_OUT_MILLISEC)
.getCookie(SecurityController.AUTH_TOKEN).getValue();
assertEquals(Http.Status.OK, WS
.url(Th.getFullUrl("/app/meals"))
.setHeader(SecurityController.AUTH_TOKEN_HEADER.toLowerCase(), token)
.get()
.get(Th.REQUEST_TIME_OUT_MILLISEC)
.getStatus());
}
});
}
示例10: testUserSignUp
import play.libs.ws.WS; //导入依赖的package包/类
@Test
public void testUserSignUp() {
running(testServer(Th.SERVER_PORT, fakeApplication(inMemoryDatabase())), new Runnable() {
public void run() {
JsonNode credentials = Json.newObject()
.put("email", Th.TEST_EMAIL)
.put("password", Th.TEST_PASSWORD);
assertEquals("{\"success\":{\"message\":\"User created successfully\"}}", WS
.url(Th.getFullUrl("/app/signup"))
.post(credentials)
.get(Th.REQUEST_TIME_OUT_MILLISEC)
.getBody());
assertEquals("{\"error\":{\"message\":\"User exists\"}}", WS
.url(Th.getFullUrl("/app/signup"))
.post(credentials)
.get(Th.REQUEST_TIME_OUT_MILLISEC)
.getBody());
}
});
}
示例11: testInvalidUserLogin
import play.libs.ws.WS; //导入依赖的package包/类
@Test
public void testInvalidUserLogin() {
running(testServer(Th.SERVER_PORT, fakeApplication(inMemoryDatabase())), new Runnable() {
public void run() {
Th.createAccount("[email protected]", "password");
String invalidEmail = "[email protected]";
String invalidPassword = "invalidpassword";
JsonNode invalidCredentials = Json.newObject()
.put("email", invalidEmail)
.put("password", invalidPassword);
assertEquals(Http.Status.UNAUTHORIZED, WS
.url(Th.getFullUrl("/app/login"))
.post(invalidCredentials)
.get(Th.REQUEST_TIME_OUT_MILLISEC)
.getStatus());
}
});
}
示例12: testApiCredentialsCanBeCreated
import play.libs.ws.WS; //导入依赖的package包/类
@Test
public void testApiCredentialsCanBeCreated() {
running(testServer(Th.SERVER_PORT, fakeApplication(inMemoryDatabase())), new Runnable() {
public void run() {
JsonNode credentials = Th.createAccount(Th.TEST_EMAIL, Th.TEST_PASSWORD);
String token = WS
.url(Th.getFullUrl("/app/login"))
.post(credentials)
.get(Th.REQUEST_TIME_OUT_MILLISEC)
.getCookie(SecurityController.AUTH_TOKEN).getValue();
assertEquals(Http.Status.OK, WS.url(Th.getFullUrl("/app/apikeys"))
.setHeader(SecurityController.AUTH_TOKEN_HEADER.toLowerCase(), token)
.post("")
.get(Th.REQUEST_TIME_OUT_MILLISEC)
.getStatus());
}
});
}
示例13: testUnAuthGetMeal
import play.libs.ws.WS; //导入依赖的package包/类
@Test
public void testUnAuthGetMeal() {
running(testServer(Th.SERVER_PORT, fakeApplication(inMemoryDatabase())), new Runnable() {
public void run() {
String url = String.format(
Th.getFullUrl("/api/meals?%s=%s&%s=%s"),
SecuredApi.API_USER,
"bogususer",
SecuredApi.API_SIGNATURE,
"bogussignature");
assertEquals(Http.Status.UNAUTHORIZED, WS
.url(url)
.get()
.get(Th.REQUEST_TIME_OUT_MILLISEC)
.getStatus());
}
});
}
示例14: oauthCallback
import play.libs.ws.WS; //导入依赖的package包/类
public static F.Promise<Result> oauthCallback(String code) {
String url = "https://login.salesforce.com/services/oauth2/token";
F.Promise<WSResponse> ws = WS.url(url)
.setQueryParameter("grant_type", "authorization_code")
.setQueryParameter("code", code)
.setQueryParameter("client_id", getConsumerKey())
.setQueryParameter("client_secret", getConsumerSecret())
.setQueryParameter("redirect_uri", getOauthCallbackUrl(Http.Context.current().request()))
.post("");
return ws.map(new F.Function<WSResponse, Result>() {
@Override
public Result apply(WSResponse response) throws Throwable {
JsonNode json = response.asJson();
String accessToken = json.get("access_token").asText();
String instanceUrl = json.get("instance_url").asText();
Http.Context.current().session().put(TOKEN, accessToken);
Http.Context.current().session().put(INSTANCE_URL, instanceUrl);
return redirect(routes.Application.index());
}
});
}
示例15: getLatLongPromise
import play.libs.ws.WS; //导入依赖的package包/类
/**
* Resolves the longitude and latitude for a given address ID
*
* @param addressId The address to resolve
* @return A promise with the longitude and latitude
*/
@InjectContext
// TODO: inject context probably does not work here
public static Promise<F.Tuple<Double, Double>> getLatLongPromise(int addressId) {
AddressDAO dao = DataAccess.getInjectedContext().getAddressDAO();
Address address = dao.getAddress(addressId);
if (address != null) {
return WS.url(ADDRESS_RESOLVER)
.setQueryParameter("street", address.getNum() + " " + address.getStreet())
.setQueryParameter("city", address.getCity())
.setQueryParameter("country", "Belgium")
// TODO: uncomment postalcode line, it's only commented for test data purposes
// .setQueryParameter("postalcode", address.getZip())
.setQueryParameter("format", "json").get().map(
response -> {
JsonNode node = response.asJson();
if (node.size() > 0) {
JsonNode first = node.get(0);
return new F.Tuple<>(first.get("lat").asDouble(), first.get("lon").asDouble());
} else return null;
}
);
} else throw new DataAccessException("Could not find address by ID");
}