下面列出了org.springframework.http.ResponseEntity#getStatusCodeValue ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void getUser() throws Exception {
try {
ResponseEntity<Collection<UserVO>> response
= restTemplate.exchange(
userEndpoint + "?name=z",
HttpMethod.GET,
null,
new ParameterizedTypeReference<Collection<UserVO>>() {
}, (Object) "restaurants");
LOG.info("Response status: {}", response.getStatusCode());
LOG.info("Response headers: {}", response.getHeaders());
LOG.info("Response body: {}", response.getBody());
if (response.getStatusCodeValue() == 200) {
response.getBody().forEach((UserVO userVO) -> {
LOG.info("UserVO: {}", userVO);
});
}
} catch (org.springframework.web.client.HttpClientErrorException.NotFound ex) {
LOG.info(ex.getMessage());
}
}
public void getUser() throws Exception {
try {
ResponseEntity<Collection<UserVO>> response
= restTemplate.exchange(
userEndpoint + "?name=z",
HttpMethod.GET,
null,
new ParameterizedTypeReference<Collection<UserVO>>() {
}, (Object) "restaurants");
LOG.info("Response status: {}", response.getStatusCode());
LOG.info("Response headers: {}", response.getHeaders());
LOG.info("Response body: {}", response.getBody());
if (response.getStatusCodeValue() == 200) {
response.getBody().forEach((UserVO userVO) -> {
LOG.info("UserVO: {}", userVO);
});
}
} catch (org.springframework.web.client.HttpClientErrorException.NotFound ex) {
LOG.info(ex.getMessage());
}
}
public void getUser() throws Exception {
try {
ResponseEntity<Collection<UserVO>> response
= restTemplate.exchange(
userEndpoint + "?name=z",
HttpMethod.GET,
null,
new ParameterizedTypeReference<Collection<UserVO>>() {
}, (Object) "restaurants");
LOG.info("Response status: {}", response.getStatusCode());
LOG.info("Response headers: {}", response.getHeaders());
LOG.info("Response body: {}", response.getBody());
if (response.getStatusCodeValue() == 200) {
response.getBody().forEach((UserVO userVO) -> {
LOG.info("UserVO: {}", userVO);
});
}
} catch (org.springframework.web.client.HttpClientErrorException.NotFound ex) {
LOG.info(ex.getMessage());
}
}
@Override
public void validate(TokenType type, String token) {
final String url = getURI(getZosmfServiceId()) + ZOSMF_INFO_END_POINT;
final HttpHeaders headers = new HttpHeaders();
headers.add(ZOSMF_CSRF_HEADER, "");
headers.add(HttpHeaders.COOKIE, type.getCookieName() + "=" + token);
try {
ResponseEntity<String> response = restTemplateWithoutKeystore.exchange(
url,
HttpMethod.GET,
new HttpEntity<>(null, headers),
String.class);
if (response.getStatusCode().is2xxSuccessful()) return;
if (response.getStatusCodeValue() == 401) {
throw new TokenNotValidException("Token is not valid.");
}
apimlLog.log("org.zowe.apiml.security.serviceUnavailable", url, response.getStatusCodeValue());
throw new ServiceNotAccessibleException("Could not get an access to z/OSMF service.");
} catch (RuntimeException re) {
throw handleExceptionOnCall(url, re);
}
}
private void testAuthzRequest(String user, String path, String method, int code) {
try {
// We use HTTP basic authentication for authentication in this test client.
// Username is user.
// Password is "123".
// You can customize your own authentication like OAuth, Apache Shiro, Spring Security, etc.
String plainCredentials = user + ":123";
String base64Credentials = Base64.getEncoder().encodeToString(plainCredentials.getBytes());
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Credentials);
ResponseEntity<String> result = testRestTemplate.exchange(path, HttpMethod.resolve(method), new HttpEntity<>(headers), String.class);
int myCode = result.getStatusCodeValue();
if (myCode != code) {
fail(String.format("%s, %s, %s: %d, supposed to be %d", user, path, method, myCode, code));
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Requests an access token for the configured Keycloak client.
* @return new Keycloak context holding the access token
*/
private KeycloakContext openAuthorizationContext() {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED + ";charset=" + keycloakConfiguration.getCharset());
HttpEntity<String> request = new HttpEntity<String>(
"client_id=" + keycloakConfiguration.getClientId()
+ "&client_secret=" + keycloakConfiguration.getClientSecret()
+ "&grant_type=client_credentials",
headers);
try {
ResponseEntity<String> response = restTemplate
.postForEntity(keycloakConfiguration.getKeycloakIssuerUrl() + "/protocol/openid-connect/token", request, String.class);
if (!response.getStatusCode().equals(HttpStatus.OK)) {
throw new IdentityProviderException("Could not connect to " + keycloakConfiguration.getKeycloakIssuerUrl()
+ ": HTTP status code " + response.getStatusCodeValue());
}
JsonObject json = parseAsJsonObject(response.getBody());
String accessToken = getJsonString(json, "access_token");
String tokenType = getJsonString(json, "token_type");
String refreshToken = getJsonString(json, "refresh_token");
long expiresInMillis = getJsonLong(json, "expires_in") * 1000;
return new KeycloakContext(accessToken, tokenType, expiresInMillis, refreshToken, keycloakConfiguration.getCharset());
} catch (RestClientException rce) {
LOG.requestTokenFailed(rce);
throw new IdentityProviderException("Unable to get access token from Keycloak server", rce);
} catch (JsonException je) {
LOG.requestTokenFailed(je);
throw new IdentityProviderException("Unable to get access token from Keycloak server", je);
}
}
@Override
public ClientResponse executeRequest(String url) {
HttpHeaders headers = new HttpHeaders();
headers.add(HEADER_KEY_CLIENT_TYPE, getClientType().getValue());
HttpEntity<String> entity = new HttpEntity<>(null, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
return new ClientResponse(response.getBody(), response.getStatusCodeValue());
}
public void sendCloudEventsToOptimize(String messageArrayJsonString) {
log.debug("Try to ingest event into Optimize\n"+messageArrayJsonString);
// prepare request
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set(HttpHeaders.AUTHORIZATION, optimizeIngestionAccessToken);
HttpEntity<String> request = new HttpEntity<String>(messageArrayJsonString, headers);
try {
// Use Optimize Event Ingestion API, see https://docs.camunda.org/optimize/latest/technical-guide/event-ingestion-rest-api/
ResponseEntity<String> response = rest.postForEntity( //
optimizeIngestionEndpoint, //
request, //
String.class);
if (response.getStatusCodeValue()==204) {
log.debug("Ingested event into Optimize\nMessages:"+messageArrayJsonString+"\nResponse:"+response);
} else {
// Actually errors should be lead to exceptions in Spring already - but just to be sure!
throw new IllegalArgumentException("Could not ingest event into Optimize, response code: " + response.getStatusCodeValue());
}
} catch (Exception ex) {
// Just log the problem and move on
log.error("Could not ingest event into Optimize\n"+messageArrayJsonString, ex);
// This leads to this event being missing in optimize
// but I don't care for this demo and prefer to move on when something is wired
// Not the best real-life strategy!
}
}
protected Integer determineStatusCode(Exception ex, HttpServletRequest request, String viewName) {
Integer statusCode = super.determineStatusCode(request, viewName);
if(statusCode==null){
ResponseEntity<Object> reponse = responseEntityExceptionHandler.handleException(ex, webRequest);
statusCode = reponse.getStatusCodeValue();
}
return statusCode;
}
@Test
public void checkAuthorizationUsersTest() {
String o ="Example object";
String[] roles = {"STUDENT"};
Collection<User> u = new ArrayList<User>();
u.add(new User("user3", "Mock6666", "mock", null,roles));
u.add(new User("user1", "Mock6666", "mock", null,roles));
u.add(new User("user2", "Mock6666", "mock", null,roles));
ResponseEntity <Object> r = service.checkAuthorizationUsers(null, u);
int status1 = r.getStatusCodeValue();
int expected1 = HttpStatus.BAD_REQUEST.value();
Assert.assertEquals("failure - expected HTTP status "+expected1, expected1, status1);
ResponseEntity <Object> r2 = service.checkAuthorizationUsers(o, u);
int status2 = r2.getStatusCodeValue();
int expected2 = HttpStatus.UNAUTHORIZED.value();
Assert.assertTrue("failure login - expected HTTP status "+
expected2 +
" but was: "+status2,
status2==expected2);
u.add(user.getLoggedUser());
ResponseEntity <Object> r3 = service.checkAuthorizationUsers(o, u);
Assert.assertEquals("Expeceted null", null, r3);
}
/**
* Requests groups of a specific user.
* @param query the group query - including a userId criteria
* @return list of matching groups
*/
public List<Group> requestGroupsByUserId(KeycloakGroupQuery query) {
String userId = query.getUserId();
List<Group> groupList = new ArrayList<>();
StringBuilder resultLogger = new StringBuilder();
if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
resultLogger.append("Keycloak group query results: [");
}
try {
// get Keycloak specific userID
String keyCloakID;
try {
keyCloakID = getKeycloakUserID(userId);
} catch (KeycloakUserNotFoundException e) {
// user not found: empty search result
return groupList;
}
// get groups of this user
ResponseEntity<String> response = restTemplate.exchange(
keycloakConfiguration.getKeycloakAdminUrl() + "/users/" + keyCloakID + "/groups?max=" + getMaxQueryResultSize(),
HttpMethod.GET, keycloakContextProvider.createApiRequestEntity(), String.class);
if (!response.getStatusCode().equals(HttpStatus.OK)) {
throw new IdentityProviderException(
"Unable to read user groups from " + keycloakConfiguration.getKeycloakAdminUrl()
+ ": HTTP status code " + response.getStatusCodeValue());
}
JsonArray searchResult = parseAsJsonArray(response.getBody());
for (int i = 0; i < searchResult.size(); i++) {
JsonObject keycloakGroup = getJsonObjectAtIndex(searchResult, i);
Group group = transformGroup(keycloakGroup);
// client side check of further query filters
if (!matches(query.getId(), group.getId())) continue;
if (!matches(query.getIds(), group.getId())) continue;
if (!matches(query.getName(), group.getName())) continue;
if (!matchesLike(query.getNameLike(), group.getName())) continue;
if (!matches(query.getType(), group.getType())) continue;
// authenticated user is always allowed to query his own groups
// otherwise READ authentication is required
boolean isAuthenticatedUser = isAuthenticatedUser(userId);
if (isAuthenticatedUser || isAuthorized(READ, GROUP, group.getId())) {
groupList.add(group);
if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
resultLogger.append(group);
resultLogger.append(" based on ");
resultLogger.append(keycloakGroup.toString());
resultLogger.append(", ");
}
}
}
} catch (HttpClientErrorException hcee) {
// if userID is unknown server answers with HTTP 404 not found
if (hcee.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
return groupList;
}
throw hcee;
} catch (RestClientException rce) {
throw new IdentityProviderException("Unable to query groups of user " + userId, rce);
} catch (JsonException je) {
throw new IdentityProviderException("Unable to query groups of user " + userId, je);
}
if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
resultLogger.append("]");
KeycloakPluginLogger.INSTANCE.groupQueryResult(resultLogger.toString());
}
// sort groups according to query criteria
if (query.getOrderingProperties().size() > 0) {
groupList.sort(new GroupComparator(query.getOrderingProperties()));
}
// paging
if ((query.getFirstResult() > 0) || (query.getMaxResults() < Integer.MAX_VALUE)) {
groupList = groupList.subList(query.getFirstResult(),
Math.min(groupList.size(), query.getFirstResult() + query.getMaxResults()));
}
// group queries in Keycloak do not consider the max attribute within the search request
return truncate(groupList, keycloakConfiguration.getMaxResultSize());
}
/**
* Requests groups.
* @param query the group query - not including a userId criteria
* @return list of matching groups
*/
public List<Group> requestGroupsWithoutUserId(KeycloakGroupQuery query) {
List<Group> groupList = new ArrayList<>();
StringBuilder resultLogger = new StringBuilder();
if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
resultLogger.append("Keycloak group query results: [");
}
try {
// get groups according to search criteria
ResponseEntity<String> response = null;
if (!StringUtils.isEmpty(query.getId())) {
response = requestGroupById(query.getId());
} else {
String groupFilter = createGroupSearchFilter(query); // only pre-filter of names possible
response = restTemplate.exchange(keycloakConfiguration.getKeycloakAdminUrl() + "/groups" + groupFilter, HttpMethod.GET,
keycloakContextProvider.createApiRequestEntity(), String.class);
}
if (!response.getStatusCode().equals(HttpStatus.OK)) {
throw new IdentityProviderException(
"Unable to read groups from " + keycloakConfiguration.getKeycloakAdminUrl()
+ ": HTTP status code " + response.getStatusCodeValue());
}
JsonArray searchResult = null;
if (!StringUtils.isEmpty(query.getId())) {
searchResult = parseAsJsonArray(response.getBody());
} else {
// for non ID queries search in subgroups as well
searchResult = flattenSubGroups(parseAsJsonArray(response.getBody()), new JsonArray());
}
for (int i = 0; i < searchResult.size(); i++) {
JsonObject keycloakGroup = getJsonObjectAtIndex(searchResult, i);
Group group = transformGroup(keycloakGroup);
// client side check of further query filters
if (!matches(query.getIds(), group.getId())) continue;
if (!matches(query.getName(), group.getName())) continue;
if (!matchesLike(query.getNameLike(), group.getName())) continue;
if (!matches(query.getType(), group.getType())) continue;
if (isAuthorized(READ, GROUP, group.getId())) {
groupList.add(group);
if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
resultLogger.append(group);
resultLogger.append(" based on ");
resultLogger.append(keycloakGroup.toString());
resultLogger.append(", ");
}
}
}
} catch (RestClientException rce) {
throw new IdentityProviderException("Unable to query groups", rce);
} catch (JsonException je) {
throw new IdentityProviderException("Unable to query groups", je);
}
if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
resultLogger.append("]");
KeycloakPluginLogger.INSTANCE.groupQueryResult(resultLogger.toString());
}
// sort groups according to query criteria
if (query.getOrderingProperties().size() > 0) {
groupList.sort(new GroupComparator(query.getOrderingProperties()));
}
// paging
if ((query.getFirstResult() > 0) || (query.getMaxResults() < Integer.MAX_VALUE)) {
groupList = groupList.subList(query.getFirstResult(),
Math.min(groupList.size(), query.getFirstResult() + query.getMaxResults()));
}
// group queries in Keycloak do not consider the max attribute within the search request
return truncate(groupList, keycloakConfiguration.getMaxResultSize());
}
/**
* Requests users of a specific group.
* @param query the user query - including a groupId criteria
* @return list of matching users
*/
public List<User> requestUsersByGroupId(KeycloakUserQuery query) {
String groupId = query.getGroupId();
List<User> userList = new ArrayList<>();
StringBuilder resultLogger = new StringBuilder();
if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
resultLogger.append("Keycloak user query results: [");
}
try {
// get Keycloak specific groupID
String keyCloakID;
try {
keyCloakID = getKeycloakGroupID(groupId);
} catch (KeycloakGroupNotFoundException e) {
// group not found: empty search result
return userList;
}
// get members of this group
ResponseEntity<String> response = restTemplate.exchange(
keycloakConfiguration.getKeycloakAdminUrl() + "/groups/" + keyCloakID + "/members?max=" + getMaxQueryResultSize(),
HttpMethod.GET, keycloakContextProvider.createApiRequestEntity(), String.class);
if (!response.getStatusCode().equals(HttpStatus.OK)) {
throw new IdentityProviderException(
"Unable to read group members from " + keycloakConfiguration.getKeycloakAdminUrl()
+ ": HTTP status code " + response.getStatusCodeValue());
}
JsonArray searchResult = parseAsJsonArray(response.getBody());
for (int i = 0; i < searchResult.size(); i++) {
JsonObject keycloakUser = getJsonObjectAtIndex(searchResult, i);
if (keycloakConfiguration.isUseEmailAsCamundaUserId() &&
StringUtils.isEmpty(getJsonString(keycloakUser, "email"))) {
continue;
}
if (keycloakConfiguration.isUseUsernameAsCamundaUserId() &&
StringUtils.isEmpty(getJsonString(keycloakUser, "username"))) {
continue;
}
UserEntity user = transformUser(keycloakUser);
// client side check of further query filters
if (!matches(query.getId(), user.getId())) continue;
if (!matches(query.getIds(), user.getId())) continue;
if (!matches(query.getEmail(), user.getEmail())) continue;
if (!matchesLike(query.getEmailLike(), user.getEmail())) continue;
if (!matches(query.getFirstName(), user.getFirstName())) continue;
if (!matchesLike(query.getFirstNameLike(), user.getFirstName())) continue;
if (!matches(query.getLastName(), user.getLastName())) continue;
if (!matchesLike(query.getLastNameLike(), user.getLastName())) continue;
if(isAuthenticatedUser(user) || isAuthorized(READ, USER, user.getId())) {
userList.add(user);
if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
resultLogger.append(user);
resultLogger.append(" based on ");
resultLogger.append(keycloakUser.toString());
resultLogger.append(", ");
}
}
}
} catch (HttpClientErrorException hcee) {
// if groupID is unknown server answers with HTTP 404 not found
if (hcee.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
return userList;
}
throw hcee;
} catch (RestClientException rce) {
throw new IdentityProviderException("Unable to query members of group " + groupId, rce);
} catch (JsonException je) {
throw new IdentityProviderException("Unable to query members of group " + groupId, je);
}
if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
resultLogger.append("]");
KeycloakPluginLogger.INSTANCE.userQueryResult(resultLogger.toString());
}
// sort users according to query criteria
if (query.getOrderingProperties().size() > 0) {
userList.sort(new UserComparator(query.getOrderingProperties()));
}
// paging
if ((query.getFirstResult() > 0) || (query.getMaxResults() < Integer.MAX_VALUE)) {
userList = userList.subList(query.getFirstResult(),
Math.min(userList.size(), query.getFirstResult() + query.getMaxResults()));
}
return userList;
}
/**
* Requests users.
* @param query the user query - not including a groupId criteria
* @return list of matching users
*/
public List<User> requestUsersWithoutGroupId(KeycloakUserQuery query) {
List<User> userList = new ArrayList<>();
StringBuilder resultLogger = new StringBuilder();
if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
resultLogger.append("Keycloak user query results: [");
}
try {
// get members of this group
ResponseEntity<String> response = null;
if (!StringUtils.isEmpty(query.getId())) {
response = requestUserById(query.getId());
} else {
// Create user search filter
String userFilter = createUserSearchFilter(query);
response = restTemplate.exchange(keycloakConfiguration.getKeycloakAdminUrl() + "/users" + userFilter, HttpMethod.GET,
keycloakContextProvider.createApiRequestEntity(), String.class);
}
if (!response.getStatusCode().equals(HttpStatus.OK)) {
throw new IdentityProviderException(
"Unable to read users from " + keycloakConfiguration.getKeycloakAdminUrl()
+ ": HTTP status code " + response.getStatusCodeValue());
}
JsonArray searchResult = parseAsJsonArray(response.getBody());
for (int i = 0; i < searchResult.size(); i++) {
JsonObject keycloakUser = getJsonObjectAtIndex(searchResult, i);
if (keycloakConfiguration.isUseEmailAsCamundaUserId() &&
StringUtils.isEmpty(getJsonString(keycloakUser, "email"))) {
continue;
}
if (keycloakConfiguration.isUseUsernameAsCamundaUserId() &&
StringUtils.isEmpty(getJsonString(keycloakUser, "username"))) {
continue;
}
UserEntity user = transformUser(keycloakUser);
// client side check of further query filters
// beware: looks like most attributes are treated as 'like' queries on Keycloak
// and must therefore be seen as a sort of pre-filter only
if (!matches(query.getId(), user.getId())) continue;
if (!matches(query.getEmail(), user.getEmail())) continue;
if (!matches(query.getFirstName(), user.getFirstName())) continue;
if (!matches(query.getLastName(), user.getLastName())) continue;
if (!matches(query.getIds(), user.getId())) continue;
if (!matchesLike(query.getEmailLike(), user.getEmail())) continue;
if (!matchesLike(query.getFirstNameLike(), user.getFirstName())) continue;
if (!matchesLike(query.getLastNameLike(), user.getLastName())) continue;
if(isAuthenticatedUser(user) || isAuthorized(READ, USER, user.getId())) {
userList.add(user);
if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
resultLogger.append(user);
resultLogger.append(" based on ");
resultLogger.append(keycloakUser.toString());
resultLogger.append(", ");
}
}
}
} catch (RestClientException rce) {
throw new IdentityProviderException("Unable to query users", rce);
} catch (JsonException je) {
throw new IdentityProviderException("Unable to query users", je);
}
if (KeycloakPluginLogger.INSTANCE.isDebugEnabled()) {
resultLogger.append("]");
KeycloakPluginLogger.INSTANCE.userQueryResult(resultLogger.toString());
}
// sort users according to query criteria
if (query.getOrderingProperties().size() > 0) {
userList.sort(new UserComparator(query.getOrderingProperties()));
}
// paging
if ((query.getFirstResult() > 0) || (query.getMaxResults() < Integer.MAX_VALUE)) {
userList = userList.subList(query.getFirstResult(),
Math.min(userList.size(), query.getFirstResult() + query.getMaxResults()));
}
return userList;
}
public static Response toResponse(ResponseEntity responseEntity, MediaType defaultContentType) {
return new BuiltResponse(responseEntity.getStatusCodeValue(),
addContentTypeIfMissing(toJaxRsHeaders(responseEntity.getHeaders()), defaultContentType),
responseEntity.getBody(),
new Annotation[0]);
}
public RestTemplateResponse(ResponseEntity<String> response) {
this.body = response.getBody();
this.status = response.getStatusCodeValue();
this.message = response.getStatusCode().getReasonPhrase();
this.headers = response.getHeaders();
}
public RestResponse(ResponseEntity<?> response) {
this.status = response.getStatusCodeValue();
this.entity = response.getBody();
}
@Test
public void checkBackendLoggedTest() {
ResponseEntity<Object> r = service.checkBackendLogged();
Assert.assertEquals("Expeceted null", null, r);
user.setLoggedUser(null);
ResponseEntity<Object> r2 = service.checkBackendLogged();
int status2 = r2.getStatusCodeValue();
int expected2 = HttpStatus.UNAUTHORIZED.value();
Assert.assertTrue("failure login - expected HTTP status "+
expected2 +
" but was: "+status2,
status2==expected2);
user.setLoggedUser(null);
}
@SuppressWarnings("unchecked")
@Override
public Object handleResponse(M invokeMethod, ResponseEntity<?> responseEntity, Class<?> actualResponseType){
Object response = responseEntity.getBody();
if(responseEntity.getStatusCode().is2xxSuccessful()){
ApiResponsable<?> baseResponse = null;
if(ApiResponsable.class.isInstance(response)){
baseResponse = (ApiResponsable<?>) response;
} else if (Result.class.isAssignableFrom(actualResponseType)) {
Result result = (Result) response;
baseResponse = new DataResultApiResponsableAdaptor(result);
} else if (Map.class.isAssignableFrom(actualResponseType)){
//reponseType have not define errcode and errmsg
Map<String, ?> map = (Map<String, ?>) response;
if (hasResultCodeField(map)) {
baseResponse = createBaseResponseByMap(map);
if(!invokeMethod.isReturnVoid()){
// response = map2Bean(map, invokeMethod.getMethodReturnType());
response = handleResponseMap(map, invokeMethod.getMethodReturnType());
}
} else if (invokeMethod.isReturnVoid()) {
//返回值为void,并且请求没有返回错误,则返回null
return null;
}
else {
// response = map2Bean(map, invokeMethod.getMethodReturnType());
response = handleResponseMap(map, invokeMethod.getMethodReturnType());
}
} else {
if(logger.isDebugEnabled()){
logger.debug("Non-WechatResponse type: {}", response.getClass());
}
}
if(baseResponse!=null && !baseResponse.isSuccess() && invokeMethod.isAutoThrowIfErrorCode()){
logger.error("api[{}] error response: {}", invokeMethod.getMethod().getName(), baseResponse);
/*throw WechatErrors.byErrcode(baseResponse.getErrcode())
.map(err->new ApiClientException(err, invokeMethod.getMethod(), null))
.orElse(new ApiClientException(ErrorTypes.of(baseResponse.getErrcode().toString(),
baseResponse.getErrmsg(),
responseEntity.getStatusCodeValue())
));*/
throw translateToApiClientException(invokeMethod, baseResponse, responseEntity);
// throw new ApiClientException(ErrorTypes.of(baseResponse.getErrcode().toString(), baseResponse.getErrmsg(), responseEntity.getStatusCodeValue()));
}
if(invokeMethod.isReturnVoid()){
//返回值为void,并且请求没有返回错误,则返回null
return null;
}
return response;
}
throw new RestClientException("error response: " + responseEntity.getStatusCodeValue());
}
@Test
public void checkAuthorizationTest() {
String o ="Example object";
String[] roles = {"STUDENT"};
User u = new User("FailUser", "Mock6666", "mock", null,roles);
ResponseEntity <Object> r = service.checkAuthorization(null, u);
int status1 = r.getStatusCodeValue();
int expected1 = HttpStatus.NOT_MODIFIED.value();
Assert.assertEquals("failure - expected HTTP status "+expected1, expected1, status1);
ResponseEntity <Object> r2 = service.checkAuthorization(o, u);
int status2 = r2.getStatusCodeValue();
int expected2 = HttpStatus.UNAUTHORIZED.value();
Assert.assertTrue("failure login - expected HTTP status "+
expected2 +
" but was: "+status2,
status2==expected2);
ResponseEntity <Object> r3 = service.checkAuthorization(o, user.getLoggedUser());
Assert.assertEquals("Expeceted null", null, r3);
}