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.venice.piazza.servicecontroller.controller.TaskManagedController.java

/**
 * Gets metadata for a specific Task-Managed Service.
 * /* ww  w .  j  ava2  s  .co  m*/
 * @param userName
 *            The name of the user. Used for verification.
 * @param serviceId
 *            The ID of the Service
 * @return Map containing information regarding the Task-Managed Service
 */
@RequestMapping(value = {
        "/service/{serviceId}/task/metadata" }, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getServiceQueueData(@RequestParam(value = "userName", required = true) String userName,
        @PathVariable(value = "serviceId") String serviceId) {
    try {
        // Log the Request
        piazzaLogger.log(String.format("User %s Requesting Task-Managed Service Information for Service %s",
                userName, serviceId), Severity.INFORMATIONAL);

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

        // Ensure this Service exists and is Task-Managed
        Service service = mongoAccessor.getServiceById(serviceId);
        if ((service.getIsTaskManaged() == null) || (service.getIsTaskManaged() == false)) {
            throw new InvalidInputException("The specified Service is not a Task-Managed Service.");
        }
        // Fill Map with Metadata
        Map<String, Object> response = mongoAccessor.getServiceQueueCollectionMetadata(serviceId);
        // Respond
        return new ResponseEntity<Map<String, Object>>(response, HttpStatus.OK);
    } catch (Exception exception) {
        String error = String.format("Could not retrieve Service Queue data for %s : %s", serviceId,
                exception.getMessage());
        LOGGER.error(error, exception);
        piazzaLogger.log(error, Severity.ERROR,
                new AuditElement(userName, "failedToRetrieveServiceQueueMetadata", serviceId));
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        if (exception instanceof ResourceAccessException) {
            status = HttpStatus.UNAUTHORIZED;
        } else if (exception instanceof InvalidInputException) {
            status = HttpStatus.NOT_FOUND;
        }
        return new ResponseEntity<String>(error, status);
    }
}

From source file:org.dataone.proto.trove.mn.rest.base.AbstractWebController.java

@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
@ExceptionHandler(InvalidToken.class)
public void handleException(InvalidToken exception, HttpServletRequest request, HttpServletResponse response) {
    handleBaseException((BaseException) exception, request, response);
}

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

@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<Void> handleUnAuthorizedException(UnauthorizedException ex, HttpServletResponse response)
        throws IOException {
    logger.debug("handling exception for: " + ex.getMessage());
    response.setStatus(HttpStatus.UNAUTHORIZED.value());
    response.sendError(HttpStatus.UNAUTHORIZED.value());
    return new ResponseEntity<Void>(null, getResponseHeaders(ex.getMessage(), null, null),
            HttpStatus.UNAUTHORIZED);/*from  ww w  .jav a  2 s. c  o  m*/
}

From source file:org.apigw.authserver.AuthorizationCodeProviderIntegrationtest.java

public void testInvalidScopeInTokenRequest() throws Exception {
    ResponseEntity<Void> response = helper.attemptToGetConfirmationPage(CLIENT_ID, REDIRECT_URL, "bogus");
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
}

From source file:com.jaspersoft.android.jaspermobile.test.acceptance.profile.ServersManagerPageTest.java

public void testPageShouldProperlyHandleUnAuthorized() {
    registerTestModule(new CommonTestModule() {
        @Override/*  w  w w .  j av  a  2s .c o  m*/
        protected void semanticConfigure() {
            bind(JsSpiceManager.class).toInstance(new JsSpiceManager() {
                @Override
                public <T> void execute(CachedSpiceRequest<T> cachedSpiceRequest,
                        final RequestListener<T> requestListener) {
                    HttpClientErrorException httpClientErrorException = new HttpClientErrorException(
                            HttpStatus.UNAUTHORIZED);
                    requestListener.onRequestFailure(new NetworkException(
                            "Exception occurred during invocation of web service.", httpClientErrorException));
                }
            });
        }
    });
    startActivityUnderTest();

    onView(withId(R.id.addProfile)).perform(click());

    onView(withId(R.id.aliasEdit)).perform(typeText(TEST_ALIAS));
    onView(withId(R.id.serverUrlEdit)).perform(typeText(TEST_SERVER_URL));
    onView(withId(R.id.organizationEdit)).perform(typeText("some invalid organization"));
    onView(withId(R.id.usernameEdit)).perform(typeText("some invalid username"));
    onView(withId(R.id.passwordEdit)).perform(typeText("some invalid password"));
    onView(withId(R.id.saveAction)).perform(click());

    FakeHttpLayerManager.clearHttpResponseRules();
    FakeHttpLayerManager.addHttpResponseRule(ApiMatcher.SERVER_INFO, TestResponses.get().notAuthorized());
    onView(withText(TEST_ALIAS)).perform(click());

    onOverflowView(getActivity(), withId(R.id.sdl__title)).check(matches(withText(R.string.error_msg)));
    onOverflowView(getActivity(), withId(R.id.sdl__message))
            .check(matches(withText(ExceptionRule.UNAUTHORIZED.getMessage())));
    onOverflowView(getActivity(), withId(R.id.sdl__negative_button)).perform(click());
}

From source file:org.apigw.authserver.AuthorizationCodeProviderIntegrationtest.java

@Test
public void testNoClientIdProvided() throws Exception {
    log.debug("testNoClientIdProvided");
    ResponseEntity<Void> response = helper.attemptToGetConfirmationPage(null, REDIRECT_URL, SCOPE);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
}

From source file:controller.PlayController.java

@ExceptionHandler(HttpSessionRequiredException.class)
@ResponseStatus(value = HttpStatus.UNAUTHORIZED, reason = "The session has expired")
public String handleSessionExpired() {
    return "sessionExpired";
}

From source file:com.appglu.impl.UserTemplateTest.java

@Test
public void logoutUnauthorized() {
    mockServer.expect(requestTo("http://localhost/appglu/v1/users/logout")).andExpect(method(HttpMethod.POST))
            .andExpect(header(UserSessionPersistence.X_APPGLU_SESSION_HEADER, "sessionId"))
            .andRespond(withStatus(HttpStatus.UNAUTHORIZED).body(compactedJson("data/user_unauthorized"))
                    .headers(responseHeaders));

    Assert.assertFalse(appGluTemplate.isUserAuthenticated());
    Assert.assertNull(appGluTemplate.getAuthenticatedUser());

    appGluTemplate.setUserSessionPersistence(new LoggedInUserSessionPersistence("sessionId", new User("test")));

    Assert.assertTrue(appGluTemplate.isUserAuthenticated());
    Assert.assertNotNull(appGluTemplate.getAuthenticatedUser());

    boolean succeed = userOperations.logout();
    Assert.assertFalse(succeed);// w w w .  j av  a  2s  .  c  om

    Assert.assertFalse(appGluTemplate.isUserAuthenticated());
    Assert.assertNull(appGluTemplate.getAuthenticatedUser());

    mockServer.verify();
}

From source file:org.dataone.proto.trove.mn.rest.base.AbstractWebController.java

@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
@ExceptionHandler(NotAuthorized.class)
public void handleException(NotAuthorized exception, HttpServletRequest request, HttpServletResponse response) {
    handleBaseException((BaseException) exception, request, response);
}