Search in sources :

Example 96 with HttpClientErrorException

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

the class PermissionService method checkUserToken.

private ResultDto<Boolean> checkUserToken(String rightName, UUID program, UUID facility, UUID warehouse) {
    UserDto user = authenticationHelper.getCurrentUser();
    RightDto right = authenticationHelper.getRight(rightName);
    try {
        return userReferenceDataService.hasRight(user.getId(), right.getId(), program, facility, warehouse);
    } catch (HttpClientErrorException httpException) {
        throw new PermissionMessageException(new Message(ERROR_PERMISSION_CHECK_FAILED, httpException.getMessage()), httpException);
    }
}
Also used : RightDto(org.openlmis.stockmanagement.dto.referencedata.RightDto) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) Message(org.openlmis.stockmanagement.util.Message) UserDto(org.openlmis.stockmanagement.dto.referencedata.UserDto) PermissionMessageException(org.openlmis.stockmanagement.exception.PermissionMessageException)

Example 97 with HttpClientErrorException

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

the class PermissionServiceTest method shouldThrowPermissionMessageExceptionWhenUserReferenceDataServiceThrows4xx.

@Test
public void shouldThrowPermissionMessageExceptionWhenUserReferenceDataServiceThrows4xx() {
    exception.expect(PermissionMessageException.class);
    exception.expectMessage(ERROR_PERMISSION_CHECK_FAILED);
    when(userReferenceDataService.hasRight(userId, rightId, null, null, null)).thenThrow(new HttpClientErrorException(HttpStatus.BAD_REQUEST));
    permissionService.canCreateStockCardTemplate();
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) Test(org.junit.Test)

Example 98 with HttpClientErrorException

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

the class BitbucketService method addUserToGroups.

/**
 * Adds an Bitbucket user to (multiple) Bitbucket groups
 *
 * @param username The Bitbucket username
 * @param groups   Names of Bitbucket groups
 * @throws BitbucketException
 */
public void addUserToGroups(String username, List<String> groups) throws BitbucketException {
    HttpHeaders headers = HeaderUtil.createAuthorization(BITBUCKET_USER, BITBUCKET_PASSWORD);
    Map<String, Object> body = new HashMap<>();
    body.put("user", username);
    body.put("groups", groups);
    HttpEntity<?> entity = new HttpEntity<>(body, headers);
    RestTemplate restTemplate = new RestTemplate();
    log.debug("Adding Bitbucket user {} to groups {}", username, groups);
    try {
        restTemplate.exchange(BITBUCKET_SERVER_URL + "/rest/api/1.0/admin/users/add-groups", HttpMethod.POST, entity, Map.class);
    } catch (HttpClientErrorException e) {
        log.error("Could not add Bitbucket user " + username + " to groups" + groups, e);
        throw new BitbucketException("Error while adding Bitbucket user to groups");
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) BitbucketException(de.tum.in.www1.artemis.exception.BitbucketException) HashMap(java.util.HashMap) RestTemplate(org.springframework.web.client.RestTemplate)

Example 99 with HttpClientErrorException

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

the class JiraAuthenticationProvider method getUsernameForEmail.

/**
 * Checks if an JIRA user for the given email address exists.
 *
 * @param email The JIRA user email address
 * @return Optional String of JIRA username
 * @throws ArtemisAuthenticationException
 */
@Override
public Optional<String> getUsernameForEmail(String email) throws ArtemisAuthenticationException {
    HttpHeaders headers = HeaderUtil.createAuthorization(JIRA_USER, JIRA_PASSWORD);
    HttpEntity<?> entity = new HttpEntity<>(headers);
    RestTemplate restTemplate = new RestTemplate();
    try {
        ResponseEntity<ArrayList> authenticationResponse = restTemplate.exchange(JIRA_URL + "/rest/api/2/user/search?username=" + email, HttpMethod.GET, entity, ArrayList.class);
        ArrayList results = authenticationResponse.getBody();
        if (results.size() == 0) {
            // no result
            return Optional.empty();
        }
        Map firstResult = (Map) results.get(0);
        return Optional.of((String) firstResult.get("name"));
    } catch (HttpClientErrorException e) {
        log.error("Could not get JIRA username for email address " + email, e);
        throw new ArtemisAuthenticationException("Error while checking eMail address");
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) RestTemplate(org.springframework.web.client.RestTemplate) ArtemisAuthenticationException(de.tum.in.www1.artemis.exception.ArtemisAuthenticationException)

Example 100 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project perun by CESNET.

the class PerunCLI method call.

private static void call(PerunCommand command, String[] cliArgs) throws ParseException {
    // prepare CLI options
    // first options common to all commands
    Options options = new Options();
    options.addOption(Option.builder(PERUN_URL_OPTION).required(false).hasArg().longOpt(PERUN_URL_VARIABLE).desc("Perun base URL").build());
    options.addOption(Option.builder(PERUN_USER_OPTION).required(false).hasArg().longOpt(PERUN_USER_VARIABLE).desc("HTTP Basic Auth user/password").build());
    options.addOption(Option.builder(DEBUG_OPTION).required(false).hasArg(false).longOpt("debug").desc("debugging output").build());
    options.addOption(Option.builder(HELP_OPTION).required(false).hasArg(false).longOpt("help").desc("print options").build());
    // then options specific to the command
    command.addOptions(options);
    // parse options
    CommandLine commandLine;
    try {
        commandLine = new DefaultParser().parse(options, cliArgs);
    } catch (MissingOptionException ex) {
        printHelp(command, options);
        return;
    }
    if (commandLine.hasOption(HELP_OPTION)) {
        printHelp(command, options);
        return;
    }
    if (commandLine.hasOption(DEBUG_OPTION)) {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        ch.qos.logback.classic.Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
        rootLogger.setLevel(Level.DEBUG);
    }
    // find URL
    String perunUrl = System.getenv(PERUN_URL_VARIABLE);
    if (commandLine.hasOption(PERUN_URL_OPTION)) {
        perunUrl = commandLine.getOptionValue(PERUN_URL_OPTION);
    }
    if (perunUrl == null)
        perunUrl = "https://perun.cesnet.cz/krb/rpc";
    // find user and password
    String user = System.getenv(PERUN_USER_VARIABLE);
    if (commandLine.hasOption(PERUN_USER_OPTION)) {
        user = commandLine.getOptionValue(PERUN_USER_OPTION);
    }
    PerunRPC perunRPC;
    if (user == null) {
        perunRPC = new PerunRPC(perunUrl, null, null, new KerberosRestTemplate(null, "-"));
    } else {
        int slash = user.indexOf('/');
        if (slash == -1) {
            System.err.println("the username and password must be separated by the '/' character");
            System.exit(1);
        }
        String username = user.substring(0, slash);
        String password = user.substring(slash + 1);
        perunRPC = new PerunRPC(perunUrl, username, password);
    }
    // execute the command
    HttpClientErrorException hce = null;
    try {
        command.executeCommand(new CommandContext(perunRPC, commandLine));
    } catch (HttpClientErrorException e1) {
        // normal RestTemplate throws this exception on status 400
        hce = e1;
    } catch (RestClientException e2) {
        if (e2.getCause() instanceof HttpClientErrorException) {
            // KerberosRestTemplate throws the exception wrapped
            hce = (HttpClientErrorException) e2.getCause();
        } else {
            // something other went wrong
            throw e2;
        }
    }
    if (hce != null) {
        PerunException pe = PerunException.to(hce);
        System.err.println(pe.getMessage());
        System.exit(1);
    }
}
Also used : Options(org.apache.commons.cli.Options) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) PerunException(cz.metacentrum.perun.openapi.PerunException) LoggerContext(ch.qos.logback.classic.LoggerContext) PerunRPC(cz.metacentrum.perun.openapi.PerunRPC) CommandLine(org.apache.commons.cli.CommandLine) KerberosRestTemplate(org.springframework.security.kerberos.client.KerberosRestTemplate) RestClientException(org.springframework.web.client.RestClientException) MissingOptionException(org.apache.commons.cli.MissingOptionException) DefaultParser(org.apache.commons.cli.DefaultParser)

Aggregations

HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)109 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