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.xwiki.authentication.ntlm.NTLMAuthServiceImpl.java

/**
 * {@inheritDoc}//from w ww. ja va 2 s  .  c o  m
 * 
 * @see com.xpn.xwiki.user.impl.xwiki.XWikiAuthServiceImpl#showLogin(com.xpn.xwiki.XWikiContext)
 */
public void showLogin(XWikiContext context) throws XWikiException {
    if ("1".equals(getConfig().getParam("validate", "1", context))) {
        LOG.debug("showLogin");

        String realm = getConfig().getParam("realm", "XWiki NTLM", context);

        context.getResponse().setHeader("WWW-Authenticate", "NTLM");
        context.getResponse().addHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");

        context.getResponse().setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        context.getResponse().setStatus(401);

        try {
            context.getResponse().setContentLength("NTLM and BASIS authentication".length());
            context.getResponse().getOutputStream().write("NTLM and BASIS authentication".getBytes());
            context.setFinished(true);
        } catch (IOException e) {
            LOG.error("Failed to write page", e);
        }
    } else {
        super.showLogin(context);
    }
}

From source file:lucee.runtime.net.rpc.server.RPCServer.java

/**
 * Configure the servlet response status code and maybe other headers
 * from the fault info.//from   ww  w .j a  va2 s.c o  m
 * @param response response to configure
 * @param fault what went wrong
 */
private void configureResponseFromAxisFault(HttpServletResponse response, AxisFault fault) {
    // then get the status code
    // It's been suggested that a lack of SOAPAction
    // should produce some other error code (in the 400s)...
    int status = getHttpServletResponseStatus(fault);
    if (status == HttpServletResponse.SC_UNAUTHORIZED) {
        response.setHeader("WWW-Authenticate", "Basic realm=\"AXIS\"");
    }
    response.setStatus(status);
}

From source file:eu.trentorise.smartcampus.mobility.controller.rest.JourneyPlannerController.java

@RequestMapping(method = RequestMethod.POST, value = "/recurrent/replan/{itineraryId}")
public @ResponseBody RecurrentJourney planRecurrentJourney(HttpServletResponse response,
        @RequestBody(required = false) RecurrentJourneyParameters parameters, @PathVariable String itineraryId)
        throws Exception {
    try {/* w  ww .j  a  va 2s. c o m*/
        String userId = getUserId();
        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return null;
        }

        Map<String, Object> pars = new TreeMap<String, Object>();
        pars.put("clientId", itineraryId);
        RecurrentJourneyObject res = domainStorage.searchDomainObject(pars, RecurrentJourneyObject.class);

        if (res != null) {
            if (!userId.equals(res.getUserId())) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return null;
            } else {
                RecurrentJourney oldJourney = res.getData();
                return smartPlannerHelper.replanRecurrent(parameters, oldJourney);
            }
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

    } catch (ConnectorException e0) {
        response.setStatus(e0.getCode());
    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    return null;
}

From source file:info.raack.appliancelabeler.web.MainController.java

@RequestMapping(value = "/currentuser", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.NO_CONTENT)/*from  w w  w.ja  v a2s. co  m*/
public void masqueradeAsUser(@RequestParam("userId") String newUserId, HttpServletRequest request,
        HttpServletResponse response) {
    String userId = getUserId(request, response, true);

    // TODO - remove hardcoding for me, put admin login in property file
    if (userId != null && userId.equals("track16")) {
        userDetails.setMasqueradeUserId(newUserId);
    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:com.linuxbox.enkive.web.StatsServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("StatsServlet doGet started");
    }// w  ww  .  j ava  2s  . c om

    try {
        try {
            Date endTimestamp = null;
            Date startTimestamp = null;
            boolean noDate = true;
            // Get a DateRange for ts.min & ts.max
            if (req.getParameter(tsMax) != null) {
                noDate = false;
                if (!req.getParameter(tsMax).equals("")) {
                    try {
                        endTimestamp = new Date(NUMERIC_SEARCH_FORMAT.parse(req.getParameter(tsMax)).getTime()
                                + 1000 * 60 * 60 * 24);
                    } catch (ParseException e) {
                        endTimestamp = new Date();
                        LOGGER.error("Error Parsing Date: " + req.getParameter(tsMax), e);
                    }
                }
            } else {
                endTimestamp = new Date();
            }
            if (req.getParameter(tsMin) != null) {
                noDate = false;

                if (!req.getParameter(tsMin).equals("")) {
                    try {
                        startTimestamp = NUMERIC_SEARCH_FORMAT.parse(req.getParameter(tsMin));
                    } catch (ParseException e) {
                        startTimestamp = new Date(0L);
                        LOGGER.error("Error Parsing Date: " + req.getParameter(tsMin), e);
                    }
                }
            } else {
                startTimestamp = new Date(0L);
            }

            String[] serviceNames = req.getParameterValues(STAT_GATHERER_NAME);
            Integer grainType = null;

            if (req.getParameter(CONSOLIDATION_TYPE) != null) {
                grainType = Integer.parseInt(req.getParameter(CONSOLIDATION_TYPE));
            }
            List<StatsQuery> queryList = null;
            List<StatsFilter> filterList = null;

            if (serviceNames == null) {
                LOGGER.error("no valid data input", new NullPointerException());
            }

            if (serviceNames != null) {
                queryList = new LinkedList<StatsQuery>();
                filterList = new LinkedList<StatsFilter>();
                for (String serviceName : serviceNames) {

                    // building query
                    StatsQuery query = new MongoStatsQuery(serviceName, grainType, STAT_INTERVAL,
                            startTimestamp, endTimestamp);
                    // TODO
                    StatsFilter filter = null;
                    String[] keys = req.getParameterValues(serviceName);
                    // building filter
                    if (keys != null) {
                        List<String> temp = new ArrayList<String>(Arrays.asList(keys));
                        filter = new MongoStatsFilter(serviceName, temp);
                    } else {
                        filter = new MongoStatsFilter(serviceName, null);
                    }
                    queryList.add(query);
                    filterList.add(filter);
                }
            }

            List<Map<String, Object>> result = null;

            if (noDate) {// no date range means get instant data
                Map<String, List<String>> gatheringStats = new HashMap<String, List<String>>();
                for (StatsFilter tempFilter : filterList) {
                    if (tempFilter.keys != null) {
                        List<String> keys = new LinkedList<String>(tempFilter.keys.keySet());
                        gatheringStats.put(tempFilter.gathererName, keys);
                    } else {
                        gatheringStats.put(tempFilter.gathererName, null);
                    }
                }
                List<RawStats> tempRawStats = client.gatherData(gatheringStats);
                result = createListOfMaps();
                for (RawStats stats : tempRawStats) {
                    Map<String, Object> statsMap = stats.toMap();
                    result.add(statsMap);
                }
            } else {// output query data as formatted json
                List<Map<String, Object>> stats = client.queryStatistics(queryList, filterList);
                result = createListOfMaps();
                for (String name : serviceNames) {
                    List<Map<String, Object>> serviceStats = createListOfMaps();
                    // populate service data
                    for (Map<String, Object> data : stats) {
                        if (data.get(STAT_GATHERER_NAME).equals(name)) {
                            serviceStats.add(data);
                        }
                    }
                    Map<String, Object> consolidatedMap = createMap();
                    consolidatedMap.put(name,
                            consolidateMaps(serviceStats, client.getAttributes(name).getKeys()));
                    result.add(consolidatedMap);
                }
            }

            try {
                // 6. return data from query
                JSONObject statistics = new JSONObject();

                statistics.put("results", new JSONArray(result.toArray()));
                LOGGER.debug("Statistical Data: " + statistics);
                resp.getWriter().write(statistics.toString());
            } catch (IOException e) {
                // FIXME: NOAHCODE Why is this calling respondError and
                // throwing an exception, the catch of which calls
                // respondError again?
                respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp);
                throw new CannotRetrieveException("could not create JSON for message attachment", e);
            } catch (JSONException e) {
                // FIXME: NOAHCODE Why is this calling respondError and
                // throwing an exception, the catch of which calls
                // respondError again?
                respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp);
                throw new CannotRetrieveException("could not create JSON for message attachment", e);
            }
        } catch (CannotRetrieveException e) {
            respondError(HttpServletResponse.SC_UNAUTHORIZED, null, resp);
            LOGGER.error("CannotRetrieveException", e);
        } catch (NullPointerException e) {
            respondError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, resp);
            LOGGER.error("NullException thrown", e);
        }
    } catch (IOException e) {
        LOGGER.error("IOException thrown", e);
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("StatsServlet doGet finished");
    }
}

From source file:org.opencastproject.adminui.endpoint.AbstractEventEndpoint.java

@DELETE
@Path("{eventId}")
@Produces(MediaType.APPLICATION_JSON)//from w  w  w  .ja v  a  2 s .  com
@RestQuery(name = "deleteevent", description = "Delete a single event.", returnDescription = "Ok if the event has been deleted.", pathParameters = {
        @RestParameter(name = "eventId", isRequired = true, description = "The id of the event to delete.", type = STRING), }, reponses = {
                @RestResponse(responseCode = SC_OK, description = "The event has been deleted."),
                @RestResponse(responseCode = HttpServletResponse.SC_NOT_FOUND, description = "The event could not be found."),
                @RestResponse(responseCode = HttpServletResponse.SC_UNAUTHORIZED, description = "If the current user is not authorized to perform this action") })
public Response deleteEvent(@PathParam("eventId") String id) throws NotFoundException, UnauthorizedException {
    if (!removeEvent(id))
        return Response.serverError().build();

    return Response.ok().build();
}

From source file:com.esri.gpt.control.rest.ManageDocumentServlet.java

/**
 * Processes the HTTP request./*from   w  w w.  j av  a  2  s  . com*/
 * @param request the HTTP request
 * @param response HTTP response
 * @param context request context
 * @param method the method to executeUpdate GET|PUT|POST|DELETE
 * @throws ServletException if the request cannot be handled
 * @throws IOException if an I/O error occurs while handling the request 
 */
private void execute(HttpServletRequest request, HttpServletResponse response, String method)
        throws ServletException, IOException {

    RequestContext context = null;
    try {
        String msg = "HTTP " + method + ", " + request.getRequestURL().toString();
        if ((request.getQueryString() != null) && (request.getQueryString().length() > 0)) {
            msg += "?" + request.getQueryString();
        }
        getLogger().fine(msg);

        String sEncoding = request.getCharacterEncoding();
        if ((sEncoding == null) || (sEncoding.trim().length() == 0)) {
            request.setCharacterEncoding("UTF-8");
        }
        context = RequestContext.extract(request);

        //redirect to new method for list parameter without any authentication
        if (method.equals("GET") && request.getParameter("list") != null) {
            this.executeGetList(request, response, context);
            return;
        }
        if (method.equals("GET") && request.getParameter("download") != null) {
            this.executeGetPackage(request, response, context);
            return;
        }

        /// estabish the publisher
        StringAttributeMap params = context.getCatalogConfiguration().getParameters();
        String autoAuthenticate = Val.chkStr(params.getValue("BaseServlet.autoAuthenticate"));
        if (!autoAuthenticate.equalsIgnoreCase("false")) {
            Credentials credentials = getCredentials(request);
            if (credentials != null) {
                this.authenticate(context, credentials);
            }
        }
        Publisher publisher = new Publisher(context);

        // executeUpdate the appropriate action
        if (method.equals("GET")) {
            this.executeGet(request, response, context, publisher);
        } else if (method.equals("POST")) {
            this.executePost(request, response, context, publisher);
        } else if (method.equals("PUT")) {
            this.executePut(request, response, context, publisher);
        } else if (method.equals("DELETE")) {
            this.executeDelete(request, response, context, publisher);
        }

    } catch (CredentialsDeniedException e) {
        String sRealm = this.getRealm(context);
        response.setHeader("WWW-Authenticate", "Basic realm=\"" + sRealm + "\"");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    } catch (NotAuthorizedException e) {
        String sRealm = this.getRealm(context);
        response.setHeader("WWW-Authenticate", "Basic realm=\"" + sRealm + "\"");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    } catch (ValidationException e) {
        String sMsg = e.toString();
        if (sMsg.contains("XSD violation.")) {
            sMsg = "XSD violation.";
        } else if (sMsg.contains("Invalid metadata document.")) {
            sMsg = "Invalid metadata document.";
        } else {
            sMsg = "Invalid metadata document.";
        }
        String json = Val.chkStr(request.getParameter("errorsAsJson"));
        if (json.length() > 0) {
            json = Val.escapeXmlForBrowser(json);
            FacesContextBroker fcb = new FacesContextBroker(request, response);
            MessageBroker msgBroker = fcb.extractMessageBroker();

            ArrayList<String> validationMessages = new ArrayList<String>();
            e.getValidationErrors().buildMessages(msgBroker, validationMessages, true);

            StringBuilder sb = new StringBuilder();
            sb.append(json).append(" = {\r\n");
            sb.append("message: \"").append(Val.escapeStrForJson(sMsg)).append("\",\r\n");
            sb.append("code: 409,\r\n");
            sb.append("errors: [\r\n");
            for (int i = 0; i < validationMessages.size(); i++) {
                if (i > 0) {
                    sb.append(",\r\n");
                }
                sb.append("\"").append(Val.escapeStrForJson(validationMessages.get(i))).append("\"");
            }
            if (validationMessages.size() > 0) {
                sb.append("\r\n");
            }
            sb.append("]}");

            LOGGER.log(Level.SEVERE, sb.toString());
            response.getWriter().print(sb.toString());
        } else {
            response.sendError(409, sMsg);
        }
    } catch (ServletException e) {
        String sMsg = e.getMessage();
        int nCode = Val.chkInt(sMsg.substring(0, 3), 500);
        sMsg = Val.chkStr(sMsg.substring(4));
        String json = Val.chkStr(request.getParameter("errorsAsJson"));
        if (json.length() > 0) {
            json = Val.escapeXmlForBrowser(json);
            StringBuilder sb = new StringBuilder();
            sb.append(json).append(" = {\r\n");
            sb.append("message: \"").append(Val.escapeStrForJson(sMsg)).append("\",\r\n");
            sb.append("code: ").append(nCode).append(",\r\n");
            sb.append("errors: [\r\n");
            sb.append("\"").append(Val.escapeStrForJson(sMsg)).append("\"");
            sb.append("]}");

            LOGGER.log(Level.SEVERE, sb.toString());
            response.getWriter().print(sb.toString());
        } else {
            response.sendError(nCode, sMsg);
        }
    } catch (Throwable t) {
        String sMsg = t.toString();
        String json = Val.chkStr(request.getParameter("errorsAsJson"));
        if (json.length() > 0) {
            json = Val.escapeXmlForBrowser(json);
            StringBuilder sb = new StringBuilder();
            sb.append(json).append(" = {\r\n");
            sb.append("message: \"").append(Val.escapeStrForJson(sMsg)).append("\",\r\n");
            sb.append("code: ").append(500).append(",\r\n");
            sb.append("errors: [\r\n");
            sb.append("\"").append(Val.escapeStrForJson(sMsg)).append("\"");
            sb.append("]}");

            LOGGER.log(Level.SEVERE, sb.toString());
            response.getWriter().print(sb.toString());
        } else if (sMsg.contains("The document is owned by another user:")) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "The document is owned by another user.");
        } else {
            //String sErr = "Exception occured while processing servlet request.";
            //getLogger().log(Level.SEVERE,sErr,t);
            //response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
            //    sMsg + sErr);
        }
    } finally {
        if (context != null)
            context.onExecutionPhaseCompleted();
    }
}

From source file:org.openremote.modeler.service.impl.TemplateServiceImpl.java

public List<Template> getTemplatesByKeywordsAndPage(String keywords, int page) {
    String newKeywords = keywords;
    if (keywords == null || keywords.trim().length() == 0) {
        newKeywords = TemplateService.NO_KEYWORDS;
    }//from ww  w . j a v  a  2  s. c  o  m
    List<Template> templates = new ArrayList<Template>();
    String restURL = configuration.getBeehiveRESTRootUrl() + "templates/keywords/" + newKeywords + "/page/"
            + page;

    HttpGet httpGet = new HttpGet(restURL);
    httpGet.setHeader("Accept", "application/json");
    this.addAuthentication(httpGet);
    HttpClient httpClient = new DefaultHttpClient();

    try {
        HttpResponse response = httpClient.execute(httpGet);

        if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
            if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) {
                throw new NotAuthenticatedException(
                        "User " + userService.getCurrentUser().getUsername() + " not authenticated! ");
            }
            throw new BeehiveNotAvailableException("Beehive is not available right now! ");
        }

        InputStreamReader reader = new InputStreamReader(response.getEntity().getContent());
        BufferedReader buffReader = new BufferedReader(reader);
        StringBuilder sb = new StringBuilder();
        String line = "";

        while ((line = buffReader.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }

        String result = sb.toString();
        TemplateList templateList = buildTemplateListFromJson(result);
        List<TemplateDTO> dtoes = templateList.getTemplates();

        for (TemplateDTO dto : dtoes) {
            templates.add(dto.toTemplate());
        }
    } catch (IOException e) {
        throw new BeehiveNotAvailableException(
                "Failed to get template list, The beehive is not available right now ", e);
    }

    return templates;
}

From source file:com.aimluck.eip.modules.actions.ALSessionValidator.java

protected void requireAuth(HttpServletResponse hres) throws IOException {
    hres.setHeader("WWW-Authenticate", "BASIC realm=\"Aipo\"");
    hres.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}

From source file:com.vmware.identity.samlservice.AuthnRequestState.java

/**
 * Perform authentication if needed and prepare a Document with a saml token
 * in it. Should not throw, but will set ValidationResult on exception. -
 * 401 UNAUTHORIZED if more auth data is needed - Response:Responder,
 * Internal processing error for unexpected exceptions - ...
 *
 * @param tenant/*from   w w  w  .j  av a  2s  . c  o  m*/
 * @return
 */
public Document authenticate(String tenant, AuthenticationFilter<AuthnRequestState> authenticator) {
    Document retval = null;

    log.debug("authenticate, tenant " + tenant);

    Validate.notNull(this.idmAccessor);
    Validate.notNull(this.authnRequest);
    Validate.notNull(authenticator);

    // authentication call
    try {
        this.idmAccessor.setTenant(tenant);
        authenticator.authenticate(this);
    } catch (SamlServiceException e) {
        // more auth data is required
        log.error("Caught Saml Service Exception from authenticate " + e.toString());
        if (this.getValidationResult() == null || this.getValidationResult().isValid()) {
            this.validationResult = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized",
                    null);
        }
        return null;
    } catch (Exception e) {
        // unexpected processing error
        log.error("Caught Exception from authenticate " + e.toString());
        if (this.getValidationResult() == null || this.getValidationResult().isValid()) {
            this.validationResult = new ValidationResult(OasisNames.RESPONDER);
        }
        return null;
    }

    if (this.getPrincipalId() == null || this.getIdentityFormat() == null || this.getSessionId() == null) {
        // assume that user could not be authenticated and validation result
        // was set by other code
        return null;
    }

    // get our token authority
    try {
        if (!this.isProxying) {
            this.idmAccessor.setTenant(tenant);
            retval = createToken();
        }
    } catch (SamlServiceException e) {
        log.error("Caught Saml Service Exception in creating token." + e);
        this.validationResult = new ValidationResult(OasisNames.RESPONDER);
    } catch (com.vmware.identity.saml.SystemException e) {
        log.error("Caught SystemException in creating token. ", e);
        if (e.getCause() instanceof IDMReferralException) {
            this.validationResult = new ValidationResult(HttpServletResponse.SC_NOT_IMPLEMENTED,
                    "LdapReferralNotSupported", null);
        } else {
            this.validationResult = new ValidationResult(OasisNames.RESPONDER);
        }
    }

    return retval;
}