Example usage for org.springframework.web.client HttpClientErrorException HttpClientErrorException

List of usage examples for org.springframework.web.client HttpClientErrorException HttpClientErrorException

Introduction

In this page you can find the example usage for org.springframework.web.client HttpClientErrorException HttpClientErrorException.

Prototype

public HttpClientErrorException(HttpStatus statusCode, String statusText) 

Source Link

Document

Constructor with a status code and status text.

Usage

From source file:com.thecorpora.qbo.androidapk.rest.RESTClient.java

/**
 * /*from w  w  w  .  j av  a  2 s .  c  o m*/
 * We send the user name and password parameters to the robot.
 * 
 * We will get true if the access is allowed, false otherwise
 * 
 * @param userName user name
 * @param pwd password
 * @param aes_string string to encrypt userName and pwd
 * @return true if the access is allowed, false if not.
 */
public HttpCookie post_login(String userName, String pwd, String aes_string) {
    AESCipher aes = new AESCipher();

    byte[] bytesUserName = {};
    byte[] bytesPwd = {};
    try {
        bytesUserName = userName.getBytes("UTF-8");
        userName = aes.encrypt(bytesUserName, aes_string);

        bytesPwd = pwd.getBytes("UTF-8");
        pwd = aes.encrypt(bytesPwd, aes_string);

    } catch (UnsupportedEncodingException uee) {
        uee.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    ResponseEntity<String> response = mRest.login(userName, pwd);

    String cookie = response.getHeaders().getFirst("Set-Cookie");

    if (cookie == null)
        throw new HttpClientErrorException(response.getStatusCode(), "session cookie not found");

    mCookie = HttpCookie.parse(cookie).get(0);
    return mCookie;
}

From source file:com.muk.services.security.DefaultUaaLoginService.java

@Override
public String approveClient(String approvalQuery, String cookie) {
    final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(cfgService.getOauthServer());
    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));

    final StringTokenizer cookieTokenizer = new StringTokenizer(cookie, "; ");
    while (cookieTokenizer.hasMoreTokens()) {
        headers.add(HttpHeaders.COOKIE, cookieTokenizer.nextToken());
    }// w w w . ja  va  2s.  co m

    final MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    for (final String pair : approvalQuery.split("&")) {
        final String[] nv = pair.split("=");
        formData.add(nv[0], nv[1]);
    }
    formData.add("X-Uaa-Csrf", getCsrf(headers.get(HttpHeaders.COOKIE)));

    final UriComponents loginUri = uriBuilder.cloneBuilder().pathSegment("oauth").pathSegment("authorize")
            .build();

    final ResponseEntity<String> response = exchangeForType(loginUri.toUriString(), HttpMethod.POST, formData,
            headers, String.class);

    if (approvalQuery.contains("false")) {
        return null; // approval declined.
    }

    // accepted, but location contains error
    if (response.getHeaders().getLocation().getQuery().startsWith("error")) {
        throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED,
                response.getHeaders().getLocation().getQuery());
    }

    // accepted with related auth code
    return response.getHeaders().getLocation().getQuery().split("=")[1];
}

From source file:com.courtalon.gigaMvcGalerie.web.ImageController.java

@RequestMapping(value = "/images/save/{licenseId:[0-9]+}/{sourceId:[0-9]+}", method = RequestMethod.POST, produces = "application/json")
@ResponseBody//from w  w  w . ja  v a  2  s . c om
@JsonView(AssetOnly.class)
public Image save(@RequestBody Image image, @PathVariable("licenseId") int licenseId,
        @PathVariable("sourceId") int sourceId) {
    Image oldImage = getImageRepository().findOne(image.getId());
    if (oldImage == null) {
        throw new HttpClientErrorException(HttpStatus.NOT_FOUND,
                "pas d'image existante correspondant a l'edition");
    }
    if (oldImage.getLicense().getId() != licenseId) {
        oldImage.setLicense(getLicenseTypeRepository().findOne(licenseId));
    }
    if (oldImage.getSource().getId() != sourceId) {
        oldImage.setSource(getAssetSourceRepository().findOne(sourceId));
    }
    oldImage.setName(image.getName());
    oldImage.setDescription(image.getDescription());
    oldImage.setFileName(image.getFileName());
    return getImageRepository().save(oldImage);
}

From source file:com.oneops.controller.cms.CMSClientTest.java

@SuppressWarnings("unchecked")
@Test(priority = 14)// w w  w. j av a  2 s .  c  o  m
/** again with http error */
public void getWorkOrdersHttpErrTest() {
    CmsDeployment cmsDeployment = mock(CmsDeployment.class);
    when(cmsDeployment.getDeploymentId()).thenReturn(DPLMNT_ID);

    DelegateExecution delegateExecution = mock(DelegateExecution.class);
    when(delegateExecution.getVariable("dpmt")).thenReturn(cmsDeployment);
    //we rely on mock of restTemplate to give error  answer 
    RestTemplate httpErrorTemplate = mock(RestTemplate.class);
    when(httpErrorTemplate.getForObject(anyString(), any(java.lang.Class.class), anyLong(), anyInt()))
            .thenThrow(new HttpClientErrorException(HttpStatus.I_AM_A_TEAPOT, "mocking"));
    cc.setRestTemplate(httpErrorTemplate);
    cc.getWorkOrderIds(delegateExecution);
    //it would be nice to assert the exec was updated, but for now we
    //just let the test pass if the client swallows the http error
}

From source file:com.courtalon.gigaMvcGalerie.web.ImageController.java

@RequestMapping(value = "/images/saveunstage/{licenseId:[0-9]+}/{sourceId:[0-9]+}", method = RequestMethod.POST, produces = "application/json")
@ResponseBody//from   w w w . j a  va 2  s  .c o m
@JsonView(AssetOnly.class)
public Image saveUnStage(@RequestBody Image image, @PathVariable("licenseId") int licenseId,
        @PathVariable("sourceId") int sourceId) {
    Image oldImage = getImageRepository().findOneIncludingTags(image.getId());
    if (oldImage == null) {
        throw new HttpClientErrorException(HttpStatus.NOT_FOUND,
                "pas d'image existante correspondant a l'edition");
    }
    if (oldImage.getLicense().getId() != licenseId) {
        oldImage.setLicense(getLicenseTypeRepository().findOne(licenseId));
    }
    if (oldImage.getSource().getId() != sourceId) {
        oldImage.setSource(getAssetSourceRepository().findOne(sourceId));
    }
    oldImage.setName(image.getName());
    oldImage.setDescription(image.getDescription());
    oldImage.setFileName(image.getFileName());
    oldImage.removeTag(getTagRepository().findByLibelle(TagRepository.UPLOADED));
    return getImageRepository().save(oldImage);
}

From source file:com.courtalon.gigaMvcGalerie.web.ImageController.java

@RequestMapping(value = "/images/data", method = RequestMethod.POST, produces = "application/json")
@ResponseBody//w w  w.j av  a2s .  c o m
@JsonView(AssetOnly.class)
public Image upload(@RequestParam("file") MultipartFile file,
        @RequestParam("licenseId") Optional<Integer> licenseId,
        @RequestParam("sourceId") Optional<Integer> sourceId,
        @RequestParam("tagsId") Optional<List<Integer>> tagsId) {
    Image img = null;
    try {
        img = getImageRepository()
                .save(new Image(0, file.getOriginalFilename(), "", new Date(), file.getOriginalFilename(),
                        file.getContentType(), file.getSize(), DigestUtils.md5Hex(file.getInputStream())));

        getImageRepository().saveImageFile(img.getId(), file.getInputStream());
        img.addTag(getTagRepository().findByLibelleAndSystemTag(TagRepository.UPLOADED, true));
        img.setLicense(getLicenseTypeRepository().findOne(licenseId.orElse(LicenseType.NO_LICENSE_ID)));
        img.setSource(getAssetSourceRepository().findOne(sourceId.orElse(AssetSource.UNKOWN_SOURCE_ID)));
        final Image image = img;
        if (tagsId.isPresent()) {
            tagsId.get().forEach(id -> image.addTag(getTagRepository().findByIdAndSystemTag(id, false)));
        }
        getImageRepository().save(img);

    } catch (IOException e) {
        log.error(e);
        throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "could not save uploaded image");
    }
    return img;
}

From source file:com.courtalon.gigaMvcGalerie.web.ImageController.java

@RequestMapping(value = "/images/data/{id:[0-9]+}", method = RequestMethod.GET)
@ResponseBody/*from w  w  w  . j  a v a 2  s.c  o  m*/
public ResponseEntity<FileSystemResource> downloadImage(@PathVariable("id") int id) {
    Image img = imageRepository.findOne(id);
    if (img == null)
        throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "image not found");
    HttpHeaders respHeaders = new HttpHeaders();
    respHeaders.setContentType(MediaType.parseMediaType(img.getContentType()));
    respHeaders.setContentLength(img.getFileSize());
    respHeaders.setContentDispositionFormData("attachment", img.getFileName());

    Optional<File> f = getImageRepository().getImageFile(img.getId());
    if (f.isPresent()) {
        log.info("fichier pour image no " + id + " trouv");
        FileSystemResource fsr = new FileSystemResource(f.get());
        return new ResponseEntity<FileSystemResource>(fsr, respHeaders, HttpStatus.OK);
    } else {
        log.info("fichier pour image no " + id + " introuvable");
        throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "image file not found");
    }
}

From source file:com.oneops.controller.cms.CMSClientTest.java

@SuppressWarnings("unchecked")
@Test//from  www .  j ava2  s  .c o m
public void updateWoStateTestHttperr() {
    DelegateExecution delegateExecution = mock(DelegateExecution.class);
    CmsDeployment cmsDeployment = mock(CmsDeployment.class);
    when(delegateExecution.getVariable("dpmt")).thenReturn(cmsDeployment);
    when(delegateExecution.getId()).thenReturn("Id11");
    when(delegateExecution.getVariable("error-message")).thenReturn("mocked-error");

    CmsWorkOrderSimple cmsWorkOrderSimple = new CmsWorkOrderSimple();
    cmsWorkOrderSimple.setDpmtRecordId(0);
    cmsWorkOrderSimple.setDeploymentId(66);
    cmsWorkOrderSimple.setComments("mockito-mock-comments");

    RestTemplate httpErrorTemplate = mock(RestTemplate.class);
    when(httpErrorTemplate.getForObject(anyString(), any(java.lang.Class.class), anyLong(), anyInt()))
            .thenThrow(new HttpClientErrorException(HttpStatus.I_AM_A_TEAPOT, "mocking"));
    cc.setRestTemplate(httpErrorTemplate);
    cc.updateWoState(delegateExecution, cmsWorkOrderSimple, "failed"); //also to do complete

}

From source file:com.daon.identityx.controller.SimpleController.java

@RequestMapping(value = "policies/{id}", method = RequestMethod.GET, consumes = { "application/json" })
@ResponseStatus(HttpStatus.OK)//from  w  ww . j  a v a 2 s .  c  o m
public @ResponseBody GetPolicyResponse getPolicy(@RequestHeader("Session-Id") String sessionId,
        @PathVariable("id") String id) {

    logger.info("***** Received request to get the policy: {} for session: {} ", id, sessionId);
    long start = System.currentTimeMillis();
    Audit anAudit = new Audit(AuditAction.GET_POLICY);
    try {
        Session session = this.validateSession(sessionId);
        Account account = this.getAccountRepository().findById(session.getAccountId());
        anAudit.setAccountId(account.getId());
        GetPolicyResponse res = new GetPolicyResponse();
        if (id.equalsIgnoreCase("reg")) {
            res.setPolicyInfo(getIdentityXServices().getRegistrationPolicyInfo());
        } else if (id.equalsIgnoreCase("auth")) {
            res.setPolicyInfo(getIdentityXServices().getAuthenticationPolicyInfo());
        } else {
            throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "Policy " + id);
        }
        return res;
    } finally {
        anAudit.setDuration(System.currentTimeMillis() - start);
        anAudit.setCreatedDTM(new Timestamp(System.currentTimeMillis()));
        this.getAuditRepository().save(anAudit);
        logger.info("***** Sending response to the request to getPolicy - duration: {}ms",
                (System.currentTimeMillis() - start));
    }
}