当前位置: 首页>>代码示例>>Java>>正文


Java WSResponse类代码示例

本文整理汇总了Java中play.libs.ws.WSResponse的典型用法代码示例。如果您正苦于以下问题:Java WSResponse类的具体用法?Java WSResponse怎么用?Java WSResponse使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


WSResponse类属于play.libs.ws包,在下文中一共展示了WSResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: parseMessageResponse

import play.libs.ws.WSResponse; //导入依赖的package包/类
/**
 * Parse an incoming response back from a GCM send action.
 *
 * @param response PlatformMessageResult The WSResponse back from google which
 *                 should contain a json success / fail map.
 * @return GcmResponse result from google for gcm message.
 */
private GcmResponse parseMessageResponse(WSResponse response) {
    if (response.getAllHeaders().containsKey("Retry-After")) {
        throw new PlatformEndpointException(500, response.getBody());

    } else if (response.getStatus() != 200) {
        throw new PlatformEndpointException(response.getStatus(), response.getBody());
    }

    GcmResponse gcmResponse = new Gson().fromJson(response.getBody(), GcmResponse.class);
    Logger.debug(String.format("\n" +
                    "[%1$d] canonical ids.\n" +
                    "[%2$d] successful message recipients.\n" +
                    "[%3$d] failed message recipients.",
            gcmResponse.canonicalIdCount, gcmResponse.successCount, gcmResponse.failCount));
    return gcmResponse;
}
 
开发者ID:splendidbits,项目名称:play-pushservices,代码行数:24,代码来源:GcmMessageDispatcher.java

示例2: sendMessage

import play.libs.ws.WSResponse; //导入依赖的package包/类
/**
 * Send a message and get a synchronous application response in return.
 *
 * @param message    the message or message part to send.
 * @param recipients blocks of 1000 recipients inside a collection.
 * @return WSResponse google request response.
 */
@Nonnull
private CompletionStage<WSResponse> sendMessage(@Nonnull Message message, @Nonnull List<Recipient> recipients) {
    String jsonBody = new GsonBuilder()
            .registerTypeAdapter(Message.class, new GcmMessageSerializer(recipients))
            .create()
            .toJson(message);

    return mWsClient
            .url(message.credentials.platformType.url)
            .setContentType("application/json")
            .setHeader("Authorization", String.format("key=%s", message.credentials.authKey))
            .setRequestTimeout(ENDPOINT_REQUEST_TIMEOUT_SECONDS)
            .setFollowRedirects(true)
            .post(jsonBody);
}
 
开发者ID:splendidbits,项目名称:play-pushservices,代码行数:23,代码来源:GcmMessageDispatcher.java

示例3: pingAsync

import play.libs.ws.WSResponse; //导入依赖的package包/类
public CompletionStage<Status> pingAsync() {
    WSRequest request = wsClient.url(storageAdapterWebserviceUrl + "/status");
    request.setRequestTimeout(Duration.ofSeconds(10));
    CompletionStage<WSResponse> responsePromise = request.get();

    return responsePromise.handle((result, error) -> {
        if (error != null) {
            return new Status(false, error.getMessage());
        } else {
            if (result.getStatus() == 200) {
                return new Status(true, "Alive and well");
            } else {
                return new Status(false, result.getStatusText());
            }
        }
    });
}
 
开发者ID:Azure,项目名称:device-telemetry-java,代码行数:18,代码来源:KeyValueClient.java

示例4: listFacilities

import play.libs.ws.WSResponse; //导入依赖的package包/类
@Restrict({@Group("STUDENT")})
public CompletionStage<Result> listFacilities(Optional<String> organisation) throws MalformedURLException {
    if (!organisation.isPresent()) {
        return wrapAsPromise(badRequest());
    }
    URL url = parseExternalUrl(organisation.get());
    WSRequest request = wsClient.url(url.toString());
    Function<WSResponse, Result>  onSuccess = response -> {
        JsonNode root = response.asJson();
        if (response.getStatus() != 200) {
            return internalServerError(root.get("message").asText("Connection refused"));
        }
        return ok(root);
    };
    return request.get().thenApplyAsync(onSuccess);
}
 
开发者ID:CSCfi,项目名称:exam,代码行数:17,代码来源:FacilityController.java

示例5: listOrganisations

import play.libs.ws.WSResponse; //导入依赖的package包/类
@Restrict({@Group("STUDENT")})
public CompletionStage<Result> listOrganisations() throws MalformedURLException {
    URL url = parseUrl();
    WSRequest request = wsClient.url(url.toString());
    String localRef = ConfigFactory.load().getString("sitnet.integration.iop.organisationRef");

    Function<WSResponse, Result>  onSuccess = response -> {
        JsonNode root = response.asJson();
        if (response.getStatus() != 200) {
            return internalServerError(root.get("message").asText("Connection refused"));
        }
        if (root instanceof ArrayNode) {
            ArrayNode node = (ArrayNode) root;
            for (JsonNode n : node) {
                ((ObjectNode) n).put("homeOrg", n.get("_id").asText().equals(localRef));
            }
        }
        return ok(root);
    };
    return request.get().thenApplyAsync(onSuccess);
}
 
开发者ID:CSCfi,项目名称:exam,代码行数:22,代码来源:OrganisationController.java

示例6: downloadCourses

import play.libs.ws.WSResponse; //导入依赖的package包/类
private CompletionStage<List<Course>> downloadCourses(URL url) {
    WSRequest request = wsClient.url(url.toString().split("\\?")[0]);
    if (url.getQuery() != null) {
        request = request.setQueryString(url.getQuery());
    }
    RemoteFunction<WSResponse, List<Course>> onSuccess = response -> {
        int status = response.getStatus();
        if (status == STATUS_OK) {
            return parseCourses(response.asJson());
        }
        Logger.info("Non-OK response received for URL: {}. Status: {}", url, status);
        throw new RemoteException(String.format("sitnet_remote_failure %d %s", status, response.getStatusText()));
    };
    return request.get().thenApplyAsync(onSuccess).exceptionally(t -> {
        Logger.error("Connection error occurred", t);
        return Collections.emptyList();
    });
}
 
开发者ID:CSCfi,项目名称:exam,代码行数:19,代码来源:ExternalCourseHandlerImpl.java

示例7: send

import play.libs.ws.WSResponse; //导入依赖的package包/类
private void send(ExamEnrolment enrolment) throws IOException {
    String ref = enrolment.getReservation().getExternalRef();
    Logger.debug("Sending back assessment for reservation " + ref);
    URL url = parseUrl(ref);
    WSRequest request = wsClient.url(url.toString());
    ExternalExam ee = enrolment.getExternalExam();
    Function<WSResponse, Void> onSuccess = response -> {
        if (response.getStatus() != 201) {
            Logger.error("Failed in sending assessment for reservation " + ref);
        } else {
            ee.setSent(DateTime.now());
            ee.update();
            Logger.info("Assessment for reservation " + ref + " processed successfully");
        }
        return null;
    };
    String json = Ebean.json().toJson(ee, PathProperties.parse("(*, creator(id))"));
    ObjectMapper om = new ObjectMapper();
    JsonNode node = om.readTree(json);
    request.post(node).thenApplyAsync(onSuccess);
}
 
开发者ID:CSCfi,项目名称:exam,代码行数:22,代码来源:AssessmentSenderActor.java

示例8: processWebResponses

import play.libs.ws.WSResponse; //导入依赖的package包/类
private List<ModuleInformationCard> processWebResponses(List<WSResponse> responses) {
    ObjectMapper objMapper = new ObjectMapper();

    return responses.parallelStream()
            .filter((w) -> w != null)
            .map((wsr) -> {
                ModuleInformationCard card = null;

                if (wsr.getStatus() == 200) {
                    JsonNode json = wsr.asJson();
                    try {
                        card = objMapper.treeToValue(json, ModuleInformationCard.class);
                    } catch (Exception e) {

                        Logger.error("Couldn't parse response from module REST server. Expected JSON but got: " + json, e);
                    }
                } else {
                    Logger.error("Errornous response from module REST server: " + wsr.getBody());
                }

                return card;
            })
            .filter((c) -> c != null)
            .collect(Collectors.toList());
}
 
开发者ID:Telecooperation,项目名称:assistance-platform-server,代码行数:26,代码来源:CurrentModuleInformationAggregator.java

示例9: custom

import play.libs.ws.WSResponse; //导入依赖的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()));
}
 
开发者ID:Telecooperation,项目名称:assistance-platform-server,代码行数:22,代码来源:CustomAssistanceProxy.java

示例10: testsWithServer

import play.libs.ws.WSResponse; //导入依赖的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

示例11: sendUserInput

import play.libs.ws.WSResponse; //导入依赖的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));
            }
        });
    }
 
开发者ID:hmrc,项目名称:self-service-time-to-pay-frontend-java,代码行数:17,代码来源:SelfAssessmentConnector.java

示例12: findAll

import play.libs.ws.WSResponse; //导入依赖的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);
}
 
开发者ID:tcompiegne,项目名称:oauth2-client-samples,代码行数:24,代码来源:TodoService.java

示例13: findByUsername

import play.libs.ws.WSResponse; //导入依赖的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);
}
 
开发者ID:tcompiegne,项目名称:oauth2-client-samples,代码行数:26,代码来源:TodoService.java

示例14: index

import play.libs.ws.WSResponse; //导入依赖的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;
}
 
开发者ID:tcompiegne,项目名称:oauth2-client-samples,代码行数:27,代码来源:UserInfo.java

示例15: getJsonFrom

import play.libs.ws.WSResponse; //导入依赖的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);
	}
    }
}
   }
 
开发者ID:ukwa,项目名称:ukwa,代码行数:24,代码来源:W3ACTCache.java


注:本文中的play.libs.ws.WSResponse类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。