Example usage for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED

List of usage examples for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED.

Prototype

int SC_UNAUTHORIZED

To view the source code for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED.

Click Source Link

Document

Status code (401) indicating that the request requires HTTP authentication.

Usage

From source file:com.almende.eve.transport.http.AgentServlet.java

/**
 * Get an agents web interface Usage: GET /servlet/{agentId}.
 * //from   w w  w  . j  a v a2s .c  om
 * @param req
 *            the req
 * @param resp
 *            the resp
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final String uri = req.getRequestURI();
    String agentId;
    try {
        agentId = httpTransport.getAgentId(new URI(uri));
    } catch (URISyntaxException e) {
        throw new ServletException(AGENTURLWARNING, e);
    }
    String resource = httpTransport.getAgentResource(uri);

    // if no agentId is found, return generic information on servlet usage
    if (agentId == null || agentId.equals("")) {
        resp.getWriter().write(getServletDocs());
        resp.setContentType("text/plain");
        return;
    }

    // check if the agent exists
    try {
        if (!host.hasAgent(agentId)) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Agent with id '" + agentId + "' not found.");
            return;
        }
    } catch (final Exception e) {
        throw new ServletException(e);
    }

    // If this is a handshake request, handle it.
    if (handleHandShake(req, resp)) {
        return;
    }

    try {
        if (host.getAgent(agentId).hasPrivate() && !handleSession(req, resp)) {
            if (!resp.isCommitted()) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
            return;
        }
    } catch (final Exception e1) {
        LOG.log(Level.WARNING, "", e1);
    }
    // get the resource name from the end of the url
    if (resource == null || resource.equals("")) {
        if (!uri.endsWith("/") && !resp.isCommitted()) {
            final String redirect = uri + "/";
            resp.sendRedirect(redirect);
            return;
        }
        resource = "index.html";
    }
    final String extension = resource.substring(resource.lastIndexOf('.') + 1);

    if (resource.equals("events")) {
        //TODO: fix this again.
    } else {
        // load the resource
        final String mimetype = StreamingUtil.getMimeType(extension);
        final String filename = RESOURCES + resource;
        final InputStream is = this.getClass().getResourceAsStream(filename);
        if (is != null) {
            StreamingUtil.streamBinaryData(is, mimetype, resp);
        } else {
            throw new ServletException("Resource '" + resource + "' not found");
        }
    }
}

From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.filter.JWSAuthenticationProcessFilterTest.java

@Test
public void testJWSAuthenticationFilterFailInvalidSignature() throws Exception {

    String a = "eyJhbGciOiJSUzI1NiJ9.aHR0cDovL2xvY2FsaG9zdDo4MDgw.g1naD_1vfSoXXC-KlOLbzQSmfCyO4JySqAyAC4RSGvEHO2v2V0coWjtzIEkCJ-d-JA_xyxc1me7L3q5PC8zx3IGayIgphqx2KO8CddY0RKTkbP6I3WaKZ3LhzTUZiO9MY5ATmTCYT05HWp9zgW-QAhdqTexzLPS5t1rszkmir0U";
    String content = "";
    String requestURL = "http://someserver:8080";
    ServletInputStream emptyContent = new DelegatingServletInputStream(
            new ByteArrayInputStream(content.getBytes()));
    ArgumentCaptor<Integer> errorCode = ArgumentCaptor.forClass(Integer.class);
    when(request.getHeader(JWSAuthenticationProcessingFilter.JWS_AUTH_HEADER))
            .thenReturn(JWSAuthenticationProcessingFilter.JWS_AUTH_HEADER_TOKEN_MARK + a);
    when(request.getInputStream()).thenReturn(emptyContent);
    when(request.getRequestURL()).thenReturn(new StringBuffer(requestURL));
    //test/*from   w ww .j  a  v  a2 s.  c  om*/
    myJWSFilter.doFilter(request, response, chain);
    verify(chain, times(0)).doFilter(any(ServletRequest.class), any(ServletResponse.class));
    verify(response, times(1)).sendError(errorCode.capture());//check sendError is not set
    int errorCodeValue = errorCode.getValue().intValue();
    logger.info("Response error:{}", errorCodeValue);
    Assert.assertEquals("sendError should be:", HttpServletResponse.SC_UNAUTHORIZED, errorCodeValue);

}

From source file:org.jboss.as.test.integration.security.picketlink.SAML2KerberosAuthenticationTestCase.java

/**
 * Test for SPNEGO working.//from  www.  j  ava2  s  .  c o m
 *
 * @throws Exception
 */
@Test
@OperateOnDeployment(SERVICE_PROVIDER_NAME)
public void testNegotiateHttpHeader(@ArquillianResource URL webAppURL,
        @ArquillianResource @OperateOnDeployment(IDENTITY_PROVIDER_NAME) URL idpURL) throws Exception {

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        final HttpGet httpGet = new HttpGet(webAppURL.toURI());
        final HttpResponse response = httpClient.execute(httpGet);

        assertThat("Unexpected status code.", response.getStatusLine().getStatusCode(),
                equalTo(HttpServletResponse.SC_UNAUTHORIZED));

        final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
        assertThat("WWW-Authenticate header is present", authnHeaders, notNullValue());
        assertThat("WWW-Authenticate header is non-empty", authnHeaders.length, not(equalTo(0)));

        final Set<? super String> authnHeaderValues = new HashSet<String>();
        for (final Header header : authnHeaders) {
            authnHeaderValues.add(header.getValue());
        }

        Matcher<String> matcherContainsString = containsString("Negotiate");
        Matcher<Iterable<? super String>> matcherAnyContainsNegotiate = hasItem(matcherContainsString);
        assertThat("WWW-Authenticate [Negotiate] header is missing", authnHeaderValues,
                matcherAnyContainsNegotiate);

        consumeResponse(response);
    }
}

From source file:com.iorga.iraj.security.AbstractSecurityFilter.java

protected boolean handleParsedDate(final Date parsedDate, final S securityContext,
        final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) throws IOException {
    final Date localDate = new Date();
    // By default, we check that the time shifting is less than 15mn
    if (Math.abs(parsedDate.getTime() - localDate.getTime()) > TIME_SHIFT_ALLOWED_MILLISECONDS) {
        sendError(HttpServletResponse.SC_UNAUTHORIZED, "Date too far from local time", httpResponse,
                "Got " + parsedDate + ", local date is " + localDate);
        return false;
    } else {//from   w  w  w.  ja  v a 2  s .co m
        return true;
    }
}

From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java

public void updateUserStatus(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();

    String userToken = request.getParameter("u");
    String userSecret = request.getParameter("s");
    String userStatus = request.getParameter("t");
    String statusId = request.getParameter("d");

    log.debug("userStatus: " + userStatus);
    log.debug("statusId: " + statusId);

    Twitter twitter = twitterLogic.getTwitterAuthForUser(userToken, userSecret);
    if (twitter == null) {
        // no connection
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;/*from  w  ww .j  a v  a 2 s .  c o m*/
    }

    try {
        Status status = null;

        // update user status
        if (StringUtils.isNotBlank(statusId)) {
            status = twitter.updateStatus(userStatus, Long.parseLong(statusId));
        } else {
            status = twitter.updateStatus(userStatus);
        }
        if (status == null) {
            log.error("Status is null.");
            // general error
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        JSONObject json = new JSONObject();
        JSONObject statusJSON = getStatusJSON(twitter, status);

        User currentUser = twitter.showUser(twitter.getId());
        Status lastUserStatus = currentUser.getStatus();

        // return as an array even though only it contains only one element, 
        // so we can reuse the same Trimpath template (Denny)
        JSONArray statusList = new JSONArray();
        statusList.add(statusJSON);
        json.put("statusList", statusList);
        lastRefreshed = Calendar.getInstance().getTime().toString();

        if (lastRefreshed == null) {
            json.element("lastRefreshed", "unable to retrieve last refreshed");
        } else {
            json.element("lastRefreshed", lastRefreshed.toString());
        }

        if (lastUserStatus == null) {
            json.element("lastStatusUpdate", "unable to retrieve last status");
        } else {
            Date lastStatusUpdate = lastUserStatus.getCreatedAt();
            json.element("lastStatusUpdate", lastStatusUpdate.toString());

        }

        if (log.isDebugEnabled()) {
            log.debug(json.toString(2));
        }

        out.print(json.toString());

    } catch (TwitterException e) {
        log.error("GetTweets: " + e.getStatusCode() + ": " + e.getClass() + e.getMessage());

        if (e.getStatusCode() == 401) {
            //invalid credentials
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        } else if (e.getStatusCode() == -1) {
            //no connection
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        } else {
            //general error
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:eu.trentorise.smartcampus.communicatorservice.controller.NotificationController.java

@RequestMapping(method = RequestMethod.POST, value = "app/{capp}/notification/sync")
public @ResponseBody ResponseEntity<SyncData> syncDataByApp(@PathVariable("capp") String capp,
        HttpServletRequest request, HttpServletResponse response, @RequestParam long since,
        @RequestBody Map<String, Object> obj) throws IOException, ClassNotFoundException, DataException {
    String userId = getUserId();//from w w w . j  a  v a  2 s .co  m
    if (userId == null) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
    SyncDataRequest syncReq = Util.convertRequest(obj, since);
    SyncData out = notificationManager.synchronizeByApp(userId, capp, syncReq.getSyncData());
    return new ResponseEntity<SyncData>(out, HttpStatus.OK);
}

From source file:org.dasein.cloud.ibm.sce.compute.vm.SCEVirtualMachine.java

@Override
public boolean isSubscribed() throws CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new SCEConfigException("No context was specified for this request");
    }//from   ww w . jav  a2 s .  com
    try {
        ExtendedRegion region = provider.getDataCenterServices().getRegion(ctx.getRegionId());

        return (region != null && region.isCompute());
    } catch (CloudException e) {
        if (e.getHttpCode() == HttpServletResponse.SC_FORBIDDEN
                || e.getHttpCode() == HttpServletResponse.SC_UNAUTHORIZED) {
            return false;
        }
        throw e;
    }
}

From source file:eionet.webq.web.interceptor.CdrAuthorizationInterceptorTest.java

private void assertThatResponseIsBasicAuthorizationCommence(MockHttpServletResponse response) {
    assertThat(response.getHeader("WWW-Authenticate"), containsString("Basic"));
    assertThat(response.getStatus(), equalTo(HttpServletResponse.SC_UNAUTHORIZED));
}

From source file:airport.web.controller.ServicesController.java

@JsonIgnore
@RequestMapping(value = "/service/dispatcher/delflight")
public boolean serviceDispatcherDelFlights(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(name = "runawayId") int runawayId) {
    HttpSession httpSession = request.getSession();
    User user = (User) httpSession.getAttribute("user");

    if (serviceUsers.checkUserOnline(user)) {
        String numberFlight = request.getParameter("numberFlight");

        Flight flight = new Flight();
        flight.setFlightNumber(numberFlight);

        if (serviceDispatcher.getFlightState(numberFlight).equals("")) {
            serviceStatistics.incAmountTakenOffPlane(user);
        } else {// www. ja v  a2 s.c  o  m
            serviceStatistics.incAmoubtLendedPlane(user);
        }

        boolean result = serviceDispatcher.delFlight(flight, runawayId);

        if (LOG.isInfoEnabled()) {
            LOG.info("user del flight. Session id : " + httpSession.getId() + ". User : " + user
                    + ". URL : /service/dispatcher/delflight");
        }

        return result;
    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        if (LOG.isInfoEnabled()) {
            LOG.info("the user isn't authorized. Session id : " + httpSession.getId()
                    + ". URL : /service/dispatcher/delflight");
        }

        return false;
    }
}