Search in sources :

Example 36 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project openlmis-stockmanagement by OpenLMIS.

the class BaseReferenceDataServiceTest method shouldReturnNullIfEntityCannotBeFoundById.

@Test
public void shouldReturnNullIfEntityCannotBeFoundById() {
    // given
    BaseReferenceDataService<T> service = prepareService();
    UUID id = UUID.randomUUID();
    // when
    when(restTemplate.exchange(any(URI.class), eq(HttpMethod.GET), any(HttpEntity.class), eq(service.getResultClass()))).thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND));
    T found = service.findOne(id);
    // then
    verify(restTemplate).exchange(uriCaptor.capture(), eq(HttpMethod.GET), entityCaptor.capture(), eq(service.getResultClass()));
    URI uri = uriCaptor.getValue();
    String url = service.getServiceUrl() + service.getUrl() + id;
    assertThat(uri.toString(), is(equalTo(url)));
    assertThat(found, is(nullValue()));
    assertAuthHeader(entityCaptor.getValue());
    assertThat(entityCaptor.getValue().getBody(), is(nullValue()));
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpEntity(org.springframework.http.HttpEntity) UUID(java.util.UUID) URI(java.net.URI) BaseCommunicationServiceTest(org.openlmis.stockmanagement.service.BaseCommunicationServiceTest) Test(org.junit.Test)

Example 37 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project ArTEMiS by ls1intum.

the class JiraAuthenticationProvider method addUserToGroup.

/**
 * Adds a JIRA user to a JIRA group. Ignores "user is already a member of" errors.
 *
 * @param username The JIRA username
 * @param group The JIRA group name
 * @throws ArtemisAuthenticationException if JIRA returns an error
 */
@Override
public void addUserToGroup(String username, String group) throws ArtemisAuthenticationException {
    HttpHeaders headers = HeaderUtil.createAuthorization(JIRA_USER, JIRA_PASSWORD);
    Map<String, Object> body = new HashMap<>();
    body.put("name", username);
    HttpEntity<?> entity = new HttpEntity<>(body, headers);
    RestTemplate restTemplate = new RestTemplate();
    try {
        restTemplate.exchange(JIRA_URL + "/rest/api/2/group/user?groupname=" + group, HttpMethod.POST, entity, Map.class);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode().equals(HttpStatus.BAD_REQUEST) && e.getResponseBodyAsString().contains("user is already a member of")) {
            // ignore the error if the user is already in the group
            return;
        }
        log.error("Could not add JIRA user to group " + group, e);
        throw new ArtemisAuthenticationException("Error while adding user to JIRA group");
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) RestTemplate(org.springframework.web.client.RestTemplate) ArtemisAuthenticationException(de.tum.in.www1.artemis.exception.ArtemisAuthenticationException)

Example 38 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project ArTEMiS by ls1intum.

the class BitbucketService method createUser.

/**
 * Creates an user on Bitbucket
 *
 * @param username     The wanted Bitbucket username
 * @param password     The wanted passowrd in clear text
 * @param emailAddress The eMail address for the user
 * @param displayName  The display name (full name)
 * @throws BitbucketException
 */
public void createUser(String username, String password, String emailAddress, String displayName) throws BitbucketException {
    HttpHeaders headers = HeaderUtil.createAuthorization(BITBUCKET_USER, BITBUCKET_PASSWORD);
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(BITBUCKET_SERVER_URL + "/rest/api/1.0/admin/users").queryParam("name", username).queryParam("email", emailAddress).queryParam("emailAddress", emailAddress).queryParam("password", password).queryParam("displayName", displayName).queryParam("addToDefaultGroup", "true").queryParam("notify", "false");
    HttpEntity<?> entity = new HttpEntity<>(headers);
    RestTemplate restTemplate = new RestTemplate();
    log.debug("Creating Bitbucket user {} ({})", username, emailAddress);
    try {
        restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entity, Map.class);
    } catch (HttpClientErrorException e) {
        log.error("Could not create Bitbucket user " + username, e);
        throw new BitbucketException("Error while creating user");
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) BitbucketException(de.tum.in.www1.artemis.exception.BitbucketException) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) RestTemplate(org.springframework.web.client.RestTemplate)

Example 39 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project ArTEMiS by ls1intum.

the class BitbucketService method forkRepository.

/**
 * Uses the configured Bitbucket account to fork the given repository inside the project.
 *
 * @param baseProjectKey     The project key of the base project.
 * @param baseRepositorySlug The repository slug of the base repository.
 * @param username           The user for whom the repository is being forked.
 * @return The slug of the forked repository (i.e. its identifier).
 */
private Map<String, String> forkRepository(String baseProjectKey, String baseRepositorySlug, String username) throws BitbucketException {
    String forkName = String.format("%s-%s", baseRepositorySlug, username);
    Map<String, Object> body = new HashMap<>();
    body.put("name", forkName);
    body.put("project", new HashMap<>());
    ((Map) body.get("project")).put("key", baseProjectKey);
    HttpHeaders headers = HeaderUtil.createAuthorization(BITBUCKET_USER, BITBUCKET_PASSWORD);
    HttpEntity<?> entity = new HttpEntity<>(body, headers);
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<Map> response;
    try {
        response = restTemplate.exchange(BITBUCKET_SERVER_URL + "/rest/api/1.0/projects/" + baseProjectKey + "/repos/" + baseRepositorySlug, HttpMethod.POST, entity, Map.class);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode().equals(HttpStatus.CONFLICT)) {
            log.info("Repository already exists. Going to recover repository information...");
            Map<String, String> result = new HashMap<>();
            result.put("slug", forkName);
            result.put("cloneUrl", buildCloneUrl(baseProjectKey, forkName, username).toString());
            return result;
        } else {
            throw e;
        }
    } catch (Exception e) {
        log.error("Could not fork base repository for user " + username, e);
        throw new BitbucketException("Error while forking repository");
    }
    if (response != null && response.getStatusCode().equals(HttpStatus.CREATED)) {
        String slug = (String) response.getBody().get("slug");
        String cloneUrl = buildCloneUrl(baseProjectKey, forkName, username).toString();
        Map<String, String> result = new HashMap<>();
        result.put("slug", slug);
        result.put("cloneUrl", cloneUrl);
        return result;
    }
    return null;
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HashMap(java.util.HashMap) MalformedURLException(java.net.MalformedURLException) BitbucketException(de.tum.in.www1.artemis.exception.BitbucketException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) BitbucketException(de.tum.in.www1.artemis.exception.BitbucketException) RestTemplate(org.springframework.web.client.RestTemplate) HashMap(java.util.HashMap) Map(java.util.Map)

Example 40 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project ArTEMiS by ls1intum.

the class BitbucketService method userExists.

/**
 * Checks if an username exists on Bitbucket
 *
 * @param username the Bitbucket username to check
 * @return true if it exists
 * @throws BitbucketException
 */
private Boolean userExists(String username) throws BitbucketException {
    HttpHeaders headers = HeaderUtil.createAuthorization(BITBUCKET_USER, BITBUCKET_PASSWORD);
    HttpEntity<?> entity = new HttpEntity<>(headers);
    RestTemplate restTemplate = new RestTemplate();
    try {
        restTemplate.exchange(BITBUCKET_SERVER_URL + "/rest/api/1.0/users/" + username, HttpMethod.GET, entity, Map.class);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
            return false;
        }
        log.error("Could not check if user  " + username + " exists.", e);
        throw new BitbucketException("Could not check if user exists");
    }
    return true;
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) BitbucketException(de.tum.in.www1.artemis.exception.BitbucketException) RestTemplate(org.springframework.web.client.RestTemplate)

Aggregations

HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)113 HttpHeaders (org.springframework.http.HttpHeaders)31 Test (org.junit.Test)25 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)24 HashMap (java.util.HashMap)21 HttpServerErrorException (org.springframework.web.client.HttpServerErrorException)21 MediaType (org.springframework.http.MediaType)19 RestTemplate (org.springframework.web.client.RestTemplate)19 ParameterizedTypeReference (org.springframework.core.ParameterizedTypeReference)18 HttpEntity (org.springframework.http.HttpEntity)16 URI (java.net.URI)15 Map (java.util.Map)8 HttpStatus (org.springframework.http.HttpStatus)8 RestClientException (org.springframework.web.client.RestClientException)8 ResourceAccessException (org.springframework.web.client.ResourceAccessException)7 UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)6 Date (java.util.Date)5 List (java.util.List)5 OpenAppNamespaceDTO (com.ctrip.framework.apollo.openapi.dto.OpenAppNamespaceDTO)4 ArrayList (java.util.ArrayList)4