Example usage for org.springframework.http HttpStatus FORBIDDEN

List of usage examples for org.springframework.http HttpStatus FORBIDDEN

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus FORBIDDEN.

Prototype

HttpStatus FORBIDDEN

To view the source code for org.springframework.http HttpStatus FORBIDDEN.

Click Source Link

Document

403 Forbidden .

Usage

From source file:org.craftercms.profile.services.ProfileServiceIT.java

@Test
@DirtiesContext/*from   w  w w  .  j  a v a2s  .co m*/
public void testExpiredAccessTokenError() throws Exception {
    accessTokenIdResolver.setAccessTokenId(EXPIRED_ACCESS_TOKEN_ID);

    try {
        profileService.createProfile(DEFAULT_TENANT, AVASQUEZ_USERNAME, AVASQUEZ_PASSWORD1, AVASQUEZ_EMAIL1,
                true, AVASQUEZ_ROLES1, null, VERIFICATION_URL);
        fail("Exception " + ProfileRestServiceException.class.getName() + " expected");
    } catch (ProfileRestServiceException e) {
        assertEquals(HttpStatus.FORBIDDEN, e.getStatus());
        assertEquals(ErrorCode.EXPIRED_ACCESS_TOKEN, e.getErrorCode());
    }
}

From source file:com.goldengekko.meetr.service.sugarcrm.SugarCRMClient.java

@Override
public CursorPage<DmContact> getPage(int pageSize, String cursorKey) {
    LOG.debug("SugarCRM client, get contacts. Token:{}", token);

    // Check that we have a token
    if (null == this.token || null == token) {
        throw new RestException(ERR_SUGAR_INVALID_TOKEN, HttpStatus.FORBIDDEN,
                "Token missing, app must generate token first");
    }//www . j a v a2s  .c o  m

    // If the cursor is null start from the beginning
    if (null == cursorKey) {
        cursorKey = "0";
    }

    // The request
    // {"session":"f9psqc1rgd2iuri76u3v17aul1","module_name":"Contacts","query":"","order_by":"","offset":1,"select_fields":["id","name"],"link_name_to_fields_array":[],"max_results":2,"deleted":0,"Favorites":0}
    String data = String.format(
            "{\"session\":\"%s\",\"module_name\":\"Contacts\",\"query\":\"\",\"order_by\":\"\",\"offset\":%s,\"select_fields\":[\"id\",\"first_name\",\"last_name\",\"email\",\"phone_work\",\"primary_address_street\",\"primary_address_city\",\"primary_address_country\",\"primary_address_postalcode\"],\"link_name_to_fields_array\":[],\"max_results\":%s,\"deleted\":0,\"Favorites\":0}",
            this.token, cursorKey.toString(), pageSize);
    LOG.debug("get contacts with data:{}", data);

    SugarCRMContactsResponse contacts = TEMPLATE.execute(this.sugarCRMUrl + PARAM_TEMPLATE, HttpMethod.GET,
            new RequestCallback() {
                @Override
                public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException {
                    LOG.debug("Sending get contact request with url:{}",
                            clientHttpRequest.getURI().toURL().toExternalForm());
                }
            }, new ResponseExtractor<SugarCRMContactsResponse>() {
                @Override
                public SugarCRMContactsResponse extractData(ClientHttpResponse clientHttpResponse)
                        throws IOException {
                    LOG.debug("Response with http code:{}", clientHttpResponse.getStatusCode().value());

                    if (clientHttpResponse.getStatusCode() == HttpStatus.OK) {
                        SugarCRMContactsResponse response = MAPPER.readValue(clientHttpResponse.getBody(),
                                SugarCRMContactsResponse.class);
                        LOG.debug("Response:{}", response);
                        if (!response.hasError()) {
                            return response;
                        } else if (response.isTokenInvalid()) {
                            LOG.info("Get contacts failed, invalid token");
                            throw new RestException(ERR_SUGAR_INVALID_TOKEN, HttpStatus.FORBIDDEN,
                                    "SugarCRM get contacts failed, invalid token");
                        } else {
                            LOG.info("SugarCRM get contacts failed with unknown reason:{}",
                                    new StringHttpMessageConverter().read(String.class, clientHttpResponse));
                            throw new RestException(ERR_SUGAR_GET_CONTACTS_FAILED,
                                    HttpStatus.SERVICE_UNAVAILABLE,
                                    "SugarCRM get contacts failed with unknown reason");
                        }
                    } else {
                        // If the SugarCRM does not respond with 200 throw http 503
                        LOG.warn("SugarCRM is responding with http code:{}",
                                clientHttpResponse.getStatusCode().value());
                        throw new RestException(ERR_SUGAR_NOT_AVAILABLE, HttpStatus.SERVICE_UNAVAILABLE,
                                "SugarCRM request failed");
                    }
                }
            }, "get_entry_list", "json", "json", data);

    LOG.debug("Got number of contacts:{}", contacts.getResult_count());

    CursorPage<DmContact> page = convertToPage(contacts, pageSize);
    return page;
}

From source file:org.kew.rmf.reconciliation.ws.MatchController.java

/**
 * Downloads a match result file.// w w w . j  a v  a 2  s . c  o  m
 */
@RequestMapping(value = "/download/{fileName}", method = RequestMethod.GET)
public ResponseEntity<String> doDownload(@PathVariable String fileName, Model model) {
    logger.info("User attempting to download file named {}", fileName);

    // Check for the user trying to do something suspicious
    if (fileName.contains(File.separator)) {
        logger.error("User attempting to download file named {}", fileName);
        return new ResponseEntity<String>("Looks dodgy.", HttpStatus.FORBIDDEN);
    }

    // Put back the .csv, as Spring has chopped it off.
    File downloadFile = new File(tmpDir, fileName + ".csv");

    try {
        if (downloadFile.canRead()) {
            return new ResponseEntity<String>(FileUtils.readFileToString(downloadFile, "UTF-8"), HttpStatus.OK);
        } else {
            logger.warn("User attempted to download file {} but it doesn't exist", fileName);
            return new ResponseEntity<String>("This download does not exist", HttpStatus.NOT_FOUND);
        }
    } catch (IOException e) {
        logger.error("Exception when user attempted to download file {}", fileName);
        return new ResponseEntity<String>("Error retrieving download: " + e.getMessage(),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:plbtw.klmpk.barang.hilang.controller.UserController.java

@RequestMapping(method = RequestMethod.PUT, produces = "application/json")
public CustomResponseMessage updateUser(@RequestHeader String apiKey, @RequestBody UserRequest userRequest) {
    try {//www  . jav  a2s  .  c  o m
        if (!authApiKey(apiKey)) {
            return new CustomResponseMessage(HttpStatus.FORBIDDEN, "Please use your api key to authentication");
        }

        if (checkRateLimit(RATE_LIMIT, apiKey)) {
            return new CustomResponseMessage(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED,
                    "Please wait a while, you have reached your rate limit");
        }

        LogRequest temp = DependencyFactory.createLog(apiKey, "Put");

        Log log = new Log();
        log.setApiKey(temp.getApiKey());
        log.setStatus(temp.getStatus());
        log.setTimeRequest(temp.getTime_request());
        logService.addLog(log);

        User userUpdate = userService.getUser(userRequest.getId());
        userUpdate.setUsername(userRequest.getUsername());
        userUpdate.setAlamat(userRequest.getAlamat());
        userUpdate.setEmail(userRequest.getEmail());
        userUpdate.setNoHp(userRequest.getNoHp());
        userUpdate.setPassword(userRequest.getPassword());
        userService.updateUser(userUpdate);
        return new CustomResponseMessage(HttpStatus.CREATED, "Update User successfuly");
    } catch (Exception ex) {
        return new CustomResponseMessage(HttpStatus.BAD_REQUEST, ex.toString());
    }
}

From source file:org.craftercms.profile.services.ProfileServiceIT.java

@Test
@DirtiesContext//from  ww  w  .ja  v  a  2  s  . co  m
public void testUnallowedAccessTokenError() throws Exception {
    accessTokenIdResolver.setAccessTokenId(UNALLOWED_ACCESS_TOKEN_ID);

    try {
        profileService.createProfile(DEFAULT_TENANT, AVASQUEZ_USERNAME, AVASQUEZ_PASSWORD1, AVASQUEZ_EMAIL1,
                true, AVASQUEZ_ROLES1, null, VERIFICATION_URL);
        fail("Exception " + ProfileRestServiceException.class.getName() + " expected");
    } catch (ProfileRestServiceException e) {
        assertEquals(HttpStatus.FORBIDDEN, e.getStatus());
        assertEquals(ErrorCode.ACTION_DENIED, e.getErrorCode());
    }
}

From source file:plbtw.klmpk.barang.hilang.controller.BarangController.java

@RequestMapping(method = RequestMethod.DELETE, produces = "application/json")
public CustomResponseMessage deleteBarang(@RequestHeader String apiKey,
        @RequestBody BarangRequest barangRequest) {
    try {/* ww w . j a  v  a 2  s . c o m*/
        if (!authApiKey(apiKey)) {
            return new CustomResponseMessage(HttpStatus.FORBIDDEN, "Please use your api key to authentication");
        }

        if (checkRateLimit(RATE_LIMIT, apiKey)) {
            return new CustomResponseMessage(HttpStatus.BANDWIDTH_LIMIT_EXCEEDED,
                    "Please wait a while, you have reached your rate limit");
        }

        LogRequest temp = DependencyFactory.createLog(apiKey, "Delete");

        Log log = new Log();
        log.setApiKey(temp.getApiKey());
        log.setStatus(temp.getStatus());
        log.setTimeRequest(temp.getTime_request());
        logService.addLog(log);
        barangService.deleteBarang(barangRequest.getId());
        return new CustomResponseMessage(HttpStatus.CREATED, "Delete Barang successfull");
    } catch (NullPointerException ex) {
        return new CustomResponseMessage(HttpStatus.NOT_FOUND, "Data not found");
    } catch (Exception ex) {
        return new CustomResponseMessage(HttpStatus.BAD_REQUEST, ex.toString());
    }
}

From source file:org.mitre.oauth2.web.TokenAPI.java

@RequestMapping(value = "/refresh/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String getRefreshTokenById(@PathVariable("id") Long id, ModelMap m, Principal p) {

    OAuth2RefreshTokenEntity token = tokenService.getRefreshTokenById(id);

    if (token == null) {
        logger.error("refresh token not found: " + id);
        m.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        m.put(JsonErrorView.ERROR_MESSAGE, "The requested token with id " + id + " could not be found.");
        return JsonErrorView.VIEWNAME;
    } else if (!token.getAuthenticationHolder().getAuthentication().getName().equals(p.getName())) {
        logger.error("refresh token " + id + " does not belong to principal " + p.getName());
        m.put(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        m.put(JsonErrorView.ERROR_MESSAGE, "You do not have permission to view this token");
        return JsonErrorView.VIEWNAME;
    } else {/*from  w w w  .j  a v a  2s  . c o  m*/
        m.put(JsonEntityView.ENTITY, token);
        return TokenApiView.VIEWNAME;
    }
}

From source file:org.spring.data.gemfire.rest.GemFireRestInterfaceTest.java

@SuppressWarnings("deprecation")
private RestTemplate setErrorHandler(final RestTemplate restTemplate) {
    restTemplate.setErrorHandler(new ResponseErrorHandler() {
        private final Set<HttpStatus> errorStatuses = new HashSet<>();

        /* non-static */ {
            errorStatuses.add(HttpStatus.BAD_REQUEST);
            errorStatuses.add(HttpStatus.UNAUTHORIZED);
            errorStatuses.add(HttpStatus.FORBIDDEN);
            errorStatuses.add(HttpStatus.NOT_FOUND);
            errorStatuses.add(HttpStatus.METHOD_NOT_ALLOWED);
            errorStatuses.add(HttpStatus.NOT_ACCEPTABLE);
            errorStatuses.add(HttpStatus.REQUEST_TIMEOUT);
            errorStatuses.add(HttpStatus.CONFLICT);
            errorStatuses.add(HttpStatus.REQUEST_ENTITY_TOO_LARGE);
            errorStatuses.add(HttpStatus.REQUEST_URI_TOO_LONG);
            errorStatuses.add(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
            errorStatuses.add(HttpStatus.TOO_MANY_REQUESTS);
            errorStatuses.add(HttpStatus.INTERNAL_SERVER_ERROR);
            errorStatuses.add(HttpStatus.NOT_IMPLEMENTED);
            errorStatuses.add(HttpStatus.BAD_GATEWAY);
            errorStatuses.add(HttpStatus.SERVICE_UNAVAILABLE);
        }/*from  ww  w.j  a  v a 2 s  .  c o  m*/

        @Override
        public boolean hasError(final ClientHttpResponse response) throws IOException {
            return errorStatuses.contains(response.getStatusCode());
        }

        @Override
        public void handleError(final ClientHttpResponse response) throws IOException {
            System.err.printf("%1$d - %2$s%n", response.getRawStatusCode(), response.getStatusText());
            System.err.println(readBody(response));
        }

        private String readBody(final ClientHttpResponse response) throws IOException {
            BufferedReader responseBodyReader = null;

            try {
                responseBodyReader = new BufferedReader(new InputStreamReader(response.getBody()));

                StringBuilder buffer = new StringBuilder();
                String line;

                while ((line = responseBodyReader.readLine()) != null) {
                    buffer.append(line).append(System.getProperty("line.separator"));
                }

                return buffer.toString().trim();
            } finally {
                FileSystemUtils.close(responseBodyReader);
            }
        }
    });

    return restTemplate;
}

From source file:org.mitre.uma.web.ResourceSetRegistrationEndpoint.java

@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String deleteResourceSet(@PathVariable("id") Long id, Model m, Authentication auth) {
    ensureOAuthScope(auth, SystemScopeService.UMA_PROTECTION_SCOPE);

    ResourceSet rs = resourceSetService.getById(id);

    if (rs == null) {
        m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        m.addAttribute(JsonErrorView.ERROR, "not_found");
        return JsonErrorView.VIEWNAME;
    } else {//from www  .ja  v a2  s  .  co  m
        if (!auth.getName().equals(rs.getOwner())) {

            logger.warn("Unauthorized resource set request from bad user; expected " + rs.getOwner() + " got "
                    + auth.getName());

            // it wasn't issued to this user
            m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
            return JsonErrorView.VIEWNAME;
        } else if (auth instanceof OAuth2Authentication
                && !((OAuth2Authentication) auth).getOAuth2Request().getClientId().equals(rs.getClientId())) {

            logger.warn("Unauthorized resource set request from bad client; expected " + rs.getClientId()
                    + " got " + ((OAuth2Authentication) auth).getOAuth2Request().getClientId());

            // it wasn't issued to this client
            m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
            return JsonErrorView.VIEWNAME;
        } else {

            // user and client matched
            resourceSetService.remove(rs);

            m.addAttribute(HttpCodeView.CODE, HttpStatus.NO_CONTENT);
            return HttpCodeView.VIEWNAME;
        }

    }
}

From source file:org.mitre.uma.web.PolicyAPI.java

/**
 * Get a specific policy//ww  w . j a  v a2  s  .  c om
 * @param rsid
 * @param pid
 * @param m
 * @param auth
 * @return
 */
@RequestMapping(value = "/{rsid}" + POLICYURL
        + "/{pid}", method = RequestMethod.GET, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String getPolicy(@PathVariable(value = "rsid") Long rsid, @PathVariable(value = "pid") Long pid, Model m,
        Authentication auth) {

    ResourceSet rs = resourceSetService.getById(rsid);

    if (rs == null) {
        m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        return HttpCodeView.VIEWNAME;
    }

    if (!rs.getOwner().equals(auth.getName())) {
        logger.warn("Unauthorized resource set request from bad user; expected " + rs.getOwner() + " got "
                + auth.getName());

        // authenticated user didn't match the owner of the resource set
        m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
        return HttpCodeView.VIEWNAME;
    }

    for (Policy policy : rs.getPolicies()) {
        if (policy.getId().equals(pid)) {
            // found it!
            m.addAttribute(JsonEntityView.ENTITY, policy);
            return JsonEntityView.VIEWNAME;
        }
    }

    // if we made it this far, we haven't found it
    m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
    return HttpCodeView.VIEWNAME;
}