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:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java

/**
 * <pre>/*from w  ww. j a v a2  s . c om*/
 * RHEV Manager  API   .
 * </pre>
 * @param api RHEV Manager API (/api, /api/vms )
 * @param body xml contents
 * @param clazz ? Target Object Class
 * @return
 * @throws RestClientException
 * @throws Exception
 */
public synchronized <T> T submit(String api, HttpMethod method, Object body, String rootElementName,
        Class<T> clazz) throws RestClientException, Exception {
    Assert.isTrue(StringUtils.isNotEmpty(api), "api must not be null");
    Assert.notNull(clazz, "clazz must not be null.");

    // Multi RHEV Manager        ? ?? HostnameVerifier ??,
    // ??    ? ?.(java.io.IOException: HTTPS hostname wrong:  should be <{host}>)
    //init();

    try {
        RestTemplate rt = new RestTemplate();

        ResponseEntity<?> response = rt.exchange(new URI(getUrl(api)), method,
                setHTTPEntity(body, rootElementName), clazz);

        logger.debug("[Request URL] : {}", getUrl(api));
        logger.debug("[Response] : {}", response);

        if (response.getStatusCode().equals(HttpStatus.BAD_REQUEST)
                || response.getStatusCode().equals(HttpStatus.UNAUTHORIZED)
                || response.getStatusCode().equals(HttpStatus.PAYMENT_REQUIRED)
                || response.getStatusCode().equals(HttpStatus.FORBIDDEN)
                || response.getStatusCode().equals(HttpStatus.METHOD_NOT_ALLOWED)
                || response.getStatusCode().equals(HttpStatus.NOT_ACCEPTABLE)
                || response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)
                || response.getStatusCode().equals(HttpStatus.NOT_IMPLEMENTED)
                || response.getStatusCode().equals(HttpStatus.BAD_GATEWAY)
                || response.getStatusCode().equals(HttpStatus.SERVICE_UNAVAILABLE)
                || response.getStatusCode().equals(HttpStatus.GATEWAY_TIMEOUT)) {
            throw new Exception(response.getStatusCode().value() + " " + response.getStatusCode().toString());
        }

        return clazz.cast(response.getBody());
    } catch (RestClientException e) {
        logger.error("RestClientException has occurred.", e);
        throw e;
    } catch (Exception e) {
        logger.error("Unhandled Exception has occurred.", e);
        throw e;
    }
}

From source file:net.maritimecloud.identityregistry.controllers.UserController.java

/**
 * Deletes a User//w  ww.j a  v a2s  .  co  m
 * 
 * @return a reply...
 * @throws McBasicRestException 
 */
@RequestMapping(value = "/api/org/{orgMrn}/user/{userMrn}", method = RequestMethod.DELETE)
@ResponseBody
@PreAuthorize("hasRole('USER_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)")
public ResponseEntity<?> deleteUser(HttpServletRequest request, @PathVariable String orgMrn,
        @PathVariable String userMrn) throws McBasicRestException {
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        // Check that the entity being deleted belongs to the organization
        if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn).equals(MrnUtil.getOrgShortNameFromEntityMrn(userMrn))) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS,
                    request.getServletPath());
        }
        User user = this.entityService.getByMrn(userMrn);
        if (user == null) {
            throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.USER_NOT_FOUND,
                    request.getServletPath());
        }
        if (user.getIdOrganization().compareTo(org.getId()) == 0) {
            this.entityService.delete(user.getId());
            // Remove user from keycloak if created there.
            if (org.getIdentityProviderAttributes() == null || org.getIdentityProviderAttributes().isEmpty()) {
                keycloakAU.init(KeycloakAdminUtil.USER_INSTANCE);
                keycloakAU.deleteUser(user.getEmail());
            }
            return new ResponseEntity<>(HttpStatus.OK);
        }
        throw new McBasicRestException(HttpStatus.FORBIDDEN, MCIdRegConstants.MISSING_RIGHTS,
                request.getServletPath());
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:net.maritimecloud.identityregistry.controllers.EntityController.java

/**
 * Revokes certificate for the entity identified by the given ID
 *
 * @return a reply.../*from w  w w  .  ja va  2  s. c  o  m*/
 * @throws McBasicRestException
 */
protected ResponseEntity<?> revokeEntityCert(HttpServletRequest request, String orgMrn, String entityMrn,
        Long certId, CertificateRevocation input) throws McBasicRestException {
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        // Check that the entity being queried belongs to the organization
        if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn)
                .equals(MrnUtil.getOrgShortNameFromEntityMrn(entityMrn))) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS,
                    request.getServletPath());
        }
        T entity = this.entityService.getByMrn(entityMrn);
        if (entity == null) {
            throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ENTITY_NOT_FOUND,
                    request.getServletPath());
        }
        if (entity.getIdOrganization().compareTo(org.getId()) == 0) {
            Certificate cert = this.certificateService.getCertificateById(certId);
            T certEntity = getCertEntity(cert);
            if (certEntity != null && certEntity.getId().compareTo(entity.getId()) == 0) {
                this.revokeCertificate(cert.getId(), input, request);
                return new ResponseEntity<>(HttpStatus.OK);
            }
        }
        throw new McBasicRestException(HttpStatus.FORBIDDEN, MCIdRegConstants.MISSING_RIGHTS,
                request.getServletPath());
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:org.eclipse.cft.server.core.internal.CloudErrorUtil.java

/**
 * check 403 error due to invalid credentials
 * @param t//from  ww  w .  j a  v a  2s .  com
 * @return true if 403. False otherwise
 */
public static boolean isForbiddenException(Throwable t) {
    return isHttpException(t, HttpStatus.FORBIDDEN);
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java

@Test
public void simpleAuthenticationFlowTest() throws Exception {
    // Login first
    TestLoginInfo loginInfo = login();// w w  w  . j av a2  s.  c om

    // Calling protected remotelog service
    RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO();
    logRequestVO.setMessage("Test mesage!");
    logRequestVO.setLogLevel("DEBUG");
    HttpHeaders headers = new HttpHeaders();
    headers.set("Cookie", loginInfo.getJsessionid());
    HttpEntity<RemoteLogRequestVO> entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);

    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl("http://localhost:" + port + baseApiPath + remoteLogEndpointPath);
    // Try without token first - It should be 'Forbidden'
    // http://springinpractice.com/2012/04/08/sending-cookies-with-resttemplate      
    ResponseEntity<String> responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.POST, entityRemotelog, String.class);
    assertEquals(HttpStatus.FORBIDDEN, responseEntityRemotelog.getStatusCode());

    // Try now with the CSRF token - It should work well
    // This implies passing JSESSIONID and CSRF Token
    headers.set(DEFAULT_CSRF_HEADER_NAME, loginInfo.getXsrfToken());
    entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);
    responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
            entityRemotelog, String.class);
    assertEquals(HttpStatus.OK, responseEntityRemotelog.getStatusCode());

    // Calling here logout
    builder = UriComponentsBuilder
            .fromHttpUrl("http://localhost:" + port + basicAuthenticationLogoutEndpointPath);
    HttpEntity<Void> entityLogout = new HttpEntity<Void>(headers);
    responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
            entityLogout, String.class);
    assertEquals(HttpStatus.OK, responseEntityRemotelog.getStatusCode());

    // Try to call remotelog again (after logout)
    // This implies passing JSESSIONID and CSRF Token - We expect this not to work as the CSRF token has been removed and the session invalidated
    entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers);
    responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST,
            entityRemotelog, String.class);
    assertEquals(HttpStatus.FORBIDDEN, responseEntityRemotelog.getStatusCode());
}

From source file:com.hemou.android.account.AccountUtils.java

/**
 * Is the given {@link Exception} due to a 401 Unauthorized API response?
 * //  w w w  .  ja v  a2  s .  c o m
 * @param e
 * @return true if 401, false otherwise
 */
public static boolean isUnauthorized(final Exception e) {
    Log.e(TAG, "Exception occured[" + Thread.currentThread().getId() + "]:{type:" + e.getClass().getName() + ","
            + e.getLocalizedMessage() + "}");
    String errorMess = e.getMessage();

    if (!StringUtils.isEmpty(errorMess) && (errorMess.contains("The authorization has expired")
            || errorMess.contains("401 Unauthorized") || errorMess.contains("403 Forbidden")))
        return true;

    if (e instanceof NotAuthorizedException) {
        Log.e(TAG, "?...");
        return true;
    }
    //      if (e instanceof ResourceAccessException)
    //         return true;
    if (e instanceof HttpClientErrorException) {
        HttpClientErrorException expt = (HttpClientErrorException) e;
        HttpStatus status = expt.getStatusCode();
        if (Arrays.asList(HttpStatus.UNAUTHORIZED, HttpStatus.NETWORK_AUTHENTICATION_REQUIRED,
                HttpStatus.NON_AUTHORITATIVE_INFORMATION, HttpStatus.PROXY_AUTHENTICATION_REQUIRED,
                //403??????
                HttpStatus.FORBIDDEN).contains(status))
            return true;
    }

    return false;
}

From source file:net.maritimecloud.identityregistry.controllers.ServiceController.java

/**
 * Deletes a Service/*from www. j a v  a  2s. com*/
 * 
 * @return a reply...
 * @throws McBasicRestException 
 */
@RequestMapping(value = "/api/org/{orgMrn}/service/{serviceMrn}", method = RequestMethod.DELETE)
@ResponseBody
@PreAuthorize("hasRole('SERVICE_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)")
public ResponseEntity<?> deleteService(HttpServletRequest request, @PathVariable String orgMrn,
        @PathVariable String serviceMrn) throws McBasicRestException {
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        // Check that the entity being deleted belongs to the organization
        if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn)
                .equals(MrnUtil.getOrgShortNameFromEntityMrn(serviceMrn))) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS,
                    request.getServletPath());
        }
        Service service = this.entityService.getByMrn(serviceMrn);
        if (service == null) {
            throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ENTITY_NOT_FOUND,
                    request.getServletPath());
        }
        if (service.getIdOrganization().compareTo(org.getId()) == 0) {
            // Delete the keycloak client for the service if needed
            if (service.getOidcAccessType() != null && !service.getOidcAccessType().trim().isEmpty()
                    && service.getOidcRedirectUri() != null && !service.getOidcRedirectUri().trim().isEmpty()) {
                keycloakAU.init(KeycloakAdminUtil.BROKER_INSTANCE);
                keycloakAU.deleteClient(service.getMrn());
            }
            this.entityService.delete(service.getId());
            return new ResponseEntity<>(HttpStatus.OK);
        }
        throw new McBasicRestException(HttpStatus.FORBIDDEN, MCIdRegConstants.MISSING_RIGHTS,
                request.getServletPath());
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:de.zib.gndms.dspace.service.SliceServiceImpl.java

@RequestMapping(value = "/_{subspace}/_{sliceKind}/_{sliceId}/files", method = RequestMethod.POST)
@Secured("ROLE_USER")
public ResponseEntity<Integer> setFileContents(@PathVariable final String subspaceId,
        @PathVariable final String sliceKind, @PathVariable final String sliceId,
        @RequestParam("files") final List<MultipartFile> files, @RequestHeader("DN") final String dn) {
    GNDMSResponseHeader headers = setHeaders(subspaceId, sliceKind, sliceId, dn);

    try {//from ww  w  . j a v  a 2  s .c  o m
        Subspace space = subspaceProvider.get(subspaceId);
        Slice slice = findSliceOfKind(subspaceId, sliceKind, sliceId);
        String path = space.getPathForSlice(slice);

        final long sliceMaxSize = slice.getTotalStorageSize();

        for (MultipartFile file : files) {
            long sliceSize = sliceProvider.getDiskUsage(subspaceId, sliceId);
            if (sliceSize >= sliceMaxSize)
                throw new IOException(
                        "Slice " + sliceId + " has reached maximum size of " + sliceMaxSize + " Bytes");

            File newFile = new File(path + File.separatorChar + file.getOriginalFilename());

            if (newFile.exists()) {
                logger.warn("File " + newFile + "will be overwritten.");
            }

            file.transferTo(newFile);
        }
        return new ResponseEntity<Integer>(0, headers, HttpStatus.OK);
    } catch (NoSuchElementException ne) {
        logger.warn(ne.getMessage(), ne);
        return new ResponseEntity<Integer>(0, headers, HttpStatus.NOT_FOUND);
    } catch (FileNotFoundException e) {
        logger.warn(e.getMessage(), e);
        return new ResponseEntity<Integer>(0, headers, HttpStatus.FORBIDDEN);
    } catch (IOException e) {
        logger.warn(e.getMessage(), e);
        return new ResponseEntity<Integer>(0, headers, HttpStatus.FORBIDDEN);
    }
}

From source file:de.steilerdev.myVerein.server.controller.admin.EventManagementController.java

/**
 * This function saves an event. The function is invoked by POSTint the parameters to the URI /api/admin/event.
 * @param eventFlag This flag either stores the ID of the event, or true, if a new event is created.
 * @param eventName The name of the event.
 * @param eventDescription The description of the event.
 * @param startDate The start date, formatted according to the pattern d/MM/y, defined within the Java 8 DateTimeFormatter.
 * @param startTime The start time, formatted according to the pattern H:m, defined within the Java 8 DateTimeFormatter.
 * @param endDate The end date, formatted according to the pattern d/MM/y, defined within the Java 8 DateTimeFormatter.
 * @param endTime The end time, formatted according to the pattern H:m, defined within the Java 8 DateTimeFormatter.
 * @param location The name of the location of the event.
 * @param locationLat The latitude of the location of the event.
 * @param locationLng The longitude of the location of the event.
 * @param invitedDivisions A comma separated list of invited divisions.
 * @param currentUser The currently logged in user.
 * @return An HTTP response with a status code together with a JSON map object, containing an 'errorMessage', or a 'successMessage' respectively. If the operation was successful the id of the event is accessible via 'eventID'.
 *//*  w  ww.j  a va 2s.c o m*/
@RequestMapping(method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<Map<String, String>> saveEvent(@RequestParam String eventFlag,
        @RequestParam String eventName, @RequestParam String eventDescription, @RequestParam String startDate,
        @RequestParam String startTime, @RequestParam String endDate, @RequestParam String endTime,
        @RequestParam String location, @RequestParam String locationLat, @RequestParam String locationLng,
        @RequestParam String invitedDivisions, @CurrentUser User currentUser) {
    logger.trace("[" + currentUser + "] Saving event");
    Map<String, String> responseMap = new HashMap<>();
    Event event;
    if (eventFlag.isEmpty()) {
        logger.warn("[" + currentUser + "] The event flag is empty");
        responseMap.put("errorMessage", "The event flag is not allowed to be empty");
        return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
    } else if (eventFlag.equals("true")) {
        logger.debug("[" + currentUser + "] A new event is created");
        event = new Event();
    } else {
        logger.debug("[" + currentUser + "] The event with id " + eventFlag + " is altered");
        event = eventRepository.findEventById(eventFlag);
        if (event == null) {
            logger.warn("[" + currentUser + "] Unable to find the specified event with id " + eventFlag);
            responseMap.put("errorMessage", "Unable to find the specified event");
            return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
        } else if (!currentUser.isAllowedToAdministrate(event)) {
            logger.warn(
                    "[" + currentUser + "] The user is not allowed to alter the selected event " + eventFlag);
            responseMap.put("errorMessage", "You are not allowed to edit the selected event");
            return new ResponseEntity<>(responseMap, HttpStatus.FORBIDDEN);
        }
    }

    event.setName(eventName);
    event.setDescription(eventDescription);

    if (startDate.isEmpty() || startTime.isEmpty() || endDate.isEmpty() || endTime.isEmpty()) {
        logger.warn("[" + currentUser + "] The date and times defining the event (ID " + eventFlag
                + ") are not allowed to be empty.");
        responseMap.put("errorMessage", "The date and times defining the event are not allowed to be empty");
        return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
    } else {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/y'T'H:m");
        try {
            event.setStartDateTime(LocalDateTime.parse(startDate + "T" + startTime, formatter));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format " + startDate + "T" + startTime);
            responseMap.put("errorMessage", "Unrecognized date or time format within start time");
            return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
        }

        try {
            event.setEndDateTime(LocalDateTime.parse(endDate + "T" + endTime, formatter));
        } catch (DateTimeParseException e) {
            logger.warn("[" + currentUser + "] Unrecognized date format " + endDate + "T" + endTime);
            responseMap.put("errorMessage", "Unrecognized date or time format within end time");
            return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
        }
    }

    event.setLocation(location);

    if (!locationLat.isEmpty()) {
        try {
            event.setLocationLat(Double.parseDouble(locationLat));
        } catch (NumberFormatException e) {
            logger.warn("[" + currentUser + "] Unable to paste lat " + locationLat);
            responseMap.put("errorMessage", "Unable to parse latitude coordinate");
            return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
        }
    }

    if (!locationLng.isEmpty()) {
        try {
            event.setLocationLng(Double.parseDouble(locationLng));
        } catch (NumberFormatException e) {
            logger.warn("[" + currentUser + "] Unable to paste lng " + locationLng);
            responseMap.put("errorMessage", "Unable to parse longitude coordinate");
            return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
        }
    }

    if (!invitedDivisions.isEmpty()) {
        String[] divArray = invitedDivisions.split(",");
        for (String division : divArray) {
            Division div = divisionRepository.findByName(division);
            if (div == null) {
                logger.warn("[" + currentUser + "] Unrecognized division (" + division + ")");
                responseMap.put("errorMessage", "Division " + division + " does not exist");
                return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
            }
            event.addDivision(div);
        }
        event.updateInvitedUser(divisionRepository);
    } else if (event.getInvitedDivision() != null && !event.getInvitedDivision().isEmpty()) {
        event.updateInvitedUser(divisionRepository);
    }

    //Updating several fields.
    event.setEventAdmin(currentUser);
    event.setLastChanged(LocalDateTime.now());
    event.updateMultiDate();
    try {
        eventRepository.save(event);
        logger.info("[" + currentUser + "] Successfully saved event " + eventFlag);
        responseMap.put("successMessage", "Successfully saved the event");
        responseMap.put("eventID", event.getId());
        return new ResponseEntity<>(responseMap, HttpStatus.OK);
    } catch (ConstraintViolationException e) {
        logger.warn(
                "[" + currentUser + "] A database constraint was violated while saving the event " + eventFlag);
        responseMap.put("errorMessage", "A database constraint was violated while saving the event");
        return new ResponseEntity<>(responseMap, HttpStatus.BAD_REQUEST);
    }
}

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

/**
 * Delete a specific policy//from  w  w  w.  j  a v a  2 s.c  om
 * @param rsid
 * @param pid
 * @param m
 * @param auth
 * @return
 */
@RequestMapping(value = "/{rsid}" + POLICYURL
        + "/{pid}", method = RequestMethod.DELETE, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String deleteResourceSet(@PathVariable("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);
        m.addAttribute(JsonErrorView.ERROR, "not_found");
        return JsonErrorView.VIEWNAME;
    }

    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;
    }

    for (Policy policy : rs.getPolicies()) {
        if (policy.getId().equals(pid)) {
            // found it!
            rs.getPolicies().remove(policy);
            resourceSetService.update(rs, rs);

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

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

}