Example usage for org.springframework.http HttpStatus UNAUTHORIZED

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

Introduction

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

Prototype

HttpStatus UNAUTHORIZED

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

Click Source Link

Document

401 Unauthorized .

Usage

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

@Test
@DirtiesContext/*from  w ww .ja  va 2s.co m*/
public void testMissingAccessTokenIdParamError() throws Exception {
    accessTokenIdResolver.setAccessTokenId(null);

    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.UNAUTHORIZED, e.getStatus());
        assertEquals(ErrorCode.MISSING_ACCESS_TOKEN_ID_PARAM, e.getErrorCode());
    }
}

From source file:info.raack.appliancelabeler.service.OAuthRequestProcessor.java

public <T, S> S processRequest(String uri, OAuthSecurityContext context, ResponseHandler<T, S> handler)
        throws OAuthUnauthorizedException {
    logger.debug("Attempting to request " + uri);

    String responseString = null;
    InputStream xmlInputStream = null;
    try {//from w  ww  .java 2  s .  c om
        if (context != null) {
            // set the current authentication context
            OAuthSecurityContextHolder.setContext(context);
        }

        // use the normal request processor for the currently logged in user
        byte[] bytes = oAuthRestTemplate.getForObject(URI.create(uri), byte[].class);

        responseString = new String(bytes);
        //logger.debug(new String(bytes));
        xmlInputStream = new ByteArrayInputStream(bytes);

        //logger.debug("response: " + new String(bytes));
        synchronized (this) {
            try {
                T item = (T) ((JAXBElement) u1.unmarshal(xmlInputStream)).getValue();
                return handler.extractValue(item);
            } catch (Exception e) {
                // don't do anything if we can't unmarshall with the teds.xsd - try the other one
                try {
                    xmlInputStream.close();
                } catch (Exception e2) {

                }

                xmlInputStream = new ByteArrayInputStream(bytes);
            }
            T item = (T) ((JAXBElement) u2.unmarshal(xmlInputStream)).getValue();
            return handler.extractValue(item);
        }

    } catch (HttpClientErrorException e2) {
        // if unauthorized - our credentials are bad or have been revoked - throw exception up the stack
        if (e2.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            throw new OAuthUnauthorizedException();
        } else {
            throw new RuntimeException(
                    "Unknown remote server error " + e2.getStatusCode() + " (" + e2.getStatusText()
                            + ") returned when requesting " + uri + "; " + e2.getResponseBodyAsString());
        }
    } catch (HttpServerErrorException e3) {
        throw new RuntimeException(
                "Unknown remote server error " + e3.getStatusCode() + " (" + e3.getStatusText()
                        + ") returned when requesting " + uri + "; " + e3.getResponseBodyAsString());
    } catch (Exception e) {
        throw new RuntimeException(
                "Could not request " + uri + (responseString != null ? " response was " + responseString : ""),
                e);
    } finally {
        try {
            if (xmlInputStream != null) {
                xmlInputStream.close();
            }
        } catch (Exception e) {
        }
    }
}

From source file:cloudserviceapi.app.controller.SRCrudService.java

@ApiOperation(httpMethod = "POST", value = "Resource to delete an Item", nickname = "delete")
@ApiImplicitParams({/*from   www.  j a v a  2  s  . co  m*/
        @ApiImplicitParam(name = "id", value = "Item unique id", required = true, dataType = "string", paramType = "body") //SR2#2 datatype has to be a string due to Apimatic (https://mail.google.com/mail/u/0/#inbox/15252575a5c9dd9f)
})
@ApiResponses(value = { @ApiResponse(code = 200, message = "Success"),
        @ApiResponse(code = 401, message = "Failure") })
@RequestMapping(value = "/delete", method = RequestMethod.POST, produces = { "application/json" })
@Secured("ROLE_ADMIN")
public @ResponseBody ResponseEntity<ServiceRegistry> delete(@RequestBody Long id) {
    System.out.println("REST request to delete ServiceRegistry: " + id);
    try {
        if (id > -1) {
            //caused: javax.persistence.PersistenceException: Problem with query <SELECT count(x) FROM ServiceRegistry x WHERE x.id = :id AND 1 = 1>: Unexpected expression type while parsing query: org.datanucleus.query.expression.Literal
            //repository.delete(id);
            (new ServiceRegistryDAO()).remove(id);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return new ResponseEntity<ServiceRegistry>(HttpStatus.UNAUTHORIZED);
    }

    return new ResponseEntity<ServiceRegistry>(HttpStatus.OK);
}

From source file:resources.RedSocialColaborativaRESTFUL.java

/**
 *
 * @param _newPasswordDTO/*from  w w  w  .ja  v  a  2s. c o m*/
 * @return
 * @throws NoSuchAlgorithmException
 */
@RequestMapping(value = "/perfil/password", method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")
public ResponseEntity<String> cambioPasswordUsuario(@RequestBody NewPasswordDTO _newPasswordDTO)
        throws NoSuchAlgorithmException {
    String usernameConectado = null;
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    if (principal instanceof UserDetails) {
        usernameConectado = ((UserDetails) principal).getUsername();

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        if (_newPasswordDTO.getPasswordActual() == null) {
            return new ResponseEntity<>(HttpStatus.CONFLICT);
        }

        if (!encoder.matches(_newPasswordDTO.getPasswordActual(), ((UserDetails) principal).getPassword())) {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
    }

    if (!_newPasswordDTO.getNewPassword().equals(_newPasswordDTO.getConfPassword())) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    red.setUsername(usernameConectado);

    red.cambiarPassword(_newPasswordDTO.getNewPassword());

    return new ResponseEntity<>(HttpStatus.OK);
}

From source file:md.ibanc.rm.controllers.request.RequestCustomersController.java

@RequestMapping(value = "/logout/customers", method = RequestMethod.POST)
public ResponseEntity<String> logoutCustomers(@Valid @RequestBody LogoutForm logoutForm,
        BindingResult bindingResult, HttpServletRequest request) {

    if (bindingResult.hasFieldErrors()) {
        return new ResponseEntity<>("Fail", HttpStatus.UNAUTHORIZED);
    }/*  w  w w  .  j a  va  2 s . c o m*/

    String guid = logoutForm.getGuidToken();
    String token = logoutForm.getGuidToken();

    customersService.logout(guid, token);

    return new ResponseEntity<>("Success", HttpStatus.OK);
}

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

@Test
public void testAuthenticateWithInvalidPassword() throws Exception {
    try {/*from   ww  w.j  av  a 2  s  .  com*/
        authenticationService.authenticate(DEFAULT_TENANT_NAME, ADMIN_USERNAME, INVALID_PASSWORD);
        fail("Exception " + ProfileRestServiceException.class.getName() + " expected");
    } catch (ProfileRestServiceException e) {
        assertEquals(HttpStatus.UNAUTHORIZED, e.getStatus());
        assertEquals(ErrorCode.BAD_CREDENTIALS, e.getErrorCode());
    }
}

From source file:org.venice.piazza.servicecontroller.controller.TaskManagedController.java

/**
 * Updates the Status for a Piazza Job./*from  ww w .ja  v a 2s  . c  o  m*/
 * 
 * @param userName
 *            The name of the user. Used for verification.
 * @param serviceId
 *            The ID of the Service containing the Job
 * @param jobId
 *            The ID of the Job to update
 * @param statusUpdate
 *            The update contents, including status, percentage, and possibly results.
 * @return Success or error.
 */
@RequestMapping(value = {
        "/service/{serviceId}/task/{jobId}" }, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<PiazzaResponse> updateServiceJobStatus(
        @RequestParam(value = "userName", required = true) String userName,
        @PathVariable(value = "serviceId") String serviceId, @PathVariable(value = "jobId") String jobId,
        @RequestBody StatusUpdate statusUpdate) {
    try {
        // Log the Request
        piazzaLogger.log(
                String.format("User %s Requesting to Update Job Status for Job %s for Task-Managed Service.",
                        userName, jobId),
                Severity.INFORMATIONAL);

        // Check for Access
        boolean canAccess = mongoAccessor.canUserAccessServiceQueue(serviceId, userName);
        if (!canAccess) {
            throw new ResourceAccessException("Service does not allow this user to access.");
        }

        // Simple Validation
        if ((statusUpdate.getStatus() == null) || (statusUpdate.getStatus().isEmpty())) {
            throw new HttpServerErrorException(HttpStatus.BAD_REQUEST,
                    "`status` property must be provided in Update payload.");
        }

        // Process the Update
        serviceTaskManager.processStatusUpdate(serviceId, jobId, statusUpdate);
        // Return Success
        return new ResponseEntity<>(new SuccessResponse("OK", "ServiceController"), HttpStatus.OK);
    } catch (Exception exception) {
        String error = String.format("Could not Update status for Job %s for Service %s : %s", jobId, serviceId,
                exception.getMessage());
        LOGGER.error(error, exception);
        piazzaLogger.log(error, Severity.ERROR, new AuditElement(userName, "failedToUpdateServiceJob", jobId));
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        if (exception instanceof ResourceAccessException) {
            status = HttpStatus.UNAUTHORIZED;
        } else if (exception instanceof InvalidInputException) {
            status = HttpStatus.NOT_FOUND;
        } else if (exception instanceof HttpServerErrorException) {
            status = ((HttpServerErrorException) exception).getStatusCode();
        }
        return new ResponseEntity<>(new ErrorResponse(error, "ServiceController"), status);
    }
}