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.versatus.jwebshield.filter.SecurityFilter.java

private void sendSecurityReject(ServletResponse response) {
    try {//from  w  w  w  . ja va2  s  .  c o m
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
    } catch (IOException e) {
        // ignore
    }
}

From source file:org.jboss.additional.testsuite.jdkall.past.eap_6_4_x.clustering.cluster.web.ClusteredWebSimpleTestCase.java

/**
 * Test if the authentication status is successfully propagated between cluster nodes.
 *
 * @param baseURL1//w  w w .  j a v a2s  .  com
 * @param baseURL2
 * @throws IOException when an HTTP client problem occurs
 */
@Test
@InSequence(4)
@OperateOnDeployment(DEPLOYMENT_1)
public void testAuthnPropagation(
        @ArquillianResource(SimpleSecuredServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource(SimpleSecuredServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
        throws IOException {
    DefaultHttpClient client = HttpClientUtils.relaxedCookieHttpClient();

    final String servletPath = SimpleSecuredServlet.SERVLET_PATH.substring(1); // remove the leading slash

    try {
        // make request to a protected resource without authentication
        final HttpGet httpGet1 = new HttpGet(baseURL1.toString() + servletPath);
        HttpResponse response = client.execute(httpGet1);
        int statusCode = response.getStatusLine().getStatusCode();
        assertEquals("Unexpected HTTP response status code.", HttpServletResponse.SC_UNAUTHORIZED, statusCode);
        EntityUtils.consume(response.getEntity());

        // set credentials and retry the request
        final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1", "password1");
        client.getCredentialsProvider().setCredentials(new AuthScope(baseURL1.getHost(), baseURL1.getPort()),
                credentials);
        response = client.execute(httpGet1);
        statusCode = response.getStatusLine().getStatusCode();
        assertEquals("Unexpected HTTP response status code.", HttpServletResponse.SC_OK, statusCode);
        EntityUtils.consume(response.getEntity());

        waitForReplication(GRACE_TIME_TO_REPLICATE);

        // check on the 2nd server
        final HttpGet httpGet2 = new HttpGet(baseURL2.toString() + servletPath);
        response = client.execute(httpGet2);
        Assert.assertEquals("Unexpected HTTP response status code.", HttpServletResponse.SC_OK,
                response.getStatusLine().getStatusCode());
        EntityUtils.consume(response.getEntity());
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.konakart.actions.ipn.BarclaycardSmartPayApiNotificationAction.java

public String execute() {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();

    String httpAuthStr = null;//from  w ww  .  j  ava 2s .c om
    String httpUsername;
    String httpPassword;
    String pspReference = null;
    String merchantReference = null;
    String merchantAccountCode = null;
    String eventDate = null;
    String successString = null;
    boolean success = false;
    String paymentMethod = null;
    String value = null;
    String currency = null;
    String reason = null;

    String eventCode = null;
    String status = null;

    String sessionId = null;
    KKAppEng kkAppEng = null;

    if (log.isDebugEnabled()) {
        log.debug(BarclaycardSmartPayApi.BC_SPAY_API_GATEWAY_CODE + " Notification Action");
    }

    // Create these outside of try / catch since they are needed in the case of a general
    // exception
    IpnHistoryIf ipnHistory = new IpnHistory();
    ipnHistory.setOrderId(-1);
    ipnHistory.setModuleCode(BarclaycardSmartPayApi.BC_SPAY_API_GATEWAY_CODE);

    try {
        // Process the parameters sent in the callback
        StringBuffer sb = new StringBuffer();
        if (request != null) {
            Enumeration<String> en = request.getParameterNames();
            while (en.hasMoreElements()) {
                String paramName = en.nextElement();
                String paramValue = request.getParameter(paramName);
                if (sb.length() > 0) {
                    sb.append("\n");
                }
                sb.append(paramName);
                sb.append(" = ");
                sb.append(paramValue);

                // Capture important variables so that we can determine whether the transaction
                // was successful
                if (paramName != null) {
                    if (paramName.equalsIgnoreCase("eventCode")) {
                        eventCode = paramValue;
                    } else if (paramName.equalsIgnoreCase("pspReference")) {
                        pspReference = paramValue;
                    } else if (paramName.equalsIgnoreCase("merchantReference")) {
                        merchantReference = paramValue;
                    } else if (paramName.equalsIgnoreCase("merchantAccountCode")) {
                        merchantAccountCode = paramValue;
                    } else if (paramName.equalsIgnoreCase("eventDate")) {
                        eventDate = paramValue;
                    } else if (paramName.equalsIgnoreCase("success")) {
                        successString = paramValue;
                        success = Boolean.valueOf(successString);
                    } else if (paramName.equalsIgnoreCase("paymentMethod")) {
                        paymentMethod = paramValue;
                    } else if (paramName.equalsIgnoreCase("value")) {
                        value = paramValue;
                    } else if (paramName.equalsIgnoreCase("currency")) {
                        currency = paramValue;
                    } else if (paramName.equalsIgnoreCase("reason")) {
                        reason = paramValue;
                    }
                }
            }
        }

        if (log.isDebugEnabled()) {
            log.debug(BarclaycardSmartPayApi.BC_SPAY_API_GATEWAY_CODE + " Raw Notification Data:\n"
                    + sb.toString());
            log.debug("\n    merchantAccountCode       = " + merchantAccountCode + "\n"
                    + "    eventCode                 = " + eventCode + "\n" + "    eventDate                 = "
                    + eventDate + "\n" + "    merchantReference         = " + merchantReference + "\n"
                    + "    pspReference              = " + pspReference + "\n"
                    + "    paymentMethod             = " + paymentMethod + "\n"
                    + "    amount                    = " + value + "\n" + "    currency                  = "
                    + currency + "\n" + "    success                   = " + successString + "\n"
                    + "    reason                    = " + reason);
        }

        // If we didn't receive an eventCode, we log a warning and return
        if (eventCode == null) {
            log.warn("No eventCode returned by " + BarclaycardSmartPayApi.BC_SPAY_API_GATEWAY_CODE);
            return null;
        }

        status = eventCode;
        if (eventCode.equals("AUTHORISATION")) {
            if (success) {
                status += " successful";
            } else {
                status += " unsuccessful";
            }
        }

        // Fill more details of the IPN history class
        ipnHistory.setGatewayResult(status);
        ipnHistory.setGatewayFullResponse(sb.toString());
        ipnHistory.setGatewayTransactionId(pspReference);

        /*
         * Get the uuid from the request so that we can look up the SSO Token
         */
        if (merchantReference == null) {
            throw new Exception(
                    "The callback from BarclaycardSmartPayApi did not contain the 'merchantReference' parameter.");
        }

        // Get an instance of the KonaKart engine and look up the token
        kkAppEng = this.getKKAppEng(request, response);
        SSOTokenIf token = kkAppEng.getEng().getSSOToken(merchantReference, /* deleteToken */
                true);
        if (token == null) {
            throw new Exception("The SSOToken from the BarclaycardSmartPayApi callback is null");
        }

        /*
         * Use the session of the logged in user to initialise kkAppEng
         */
        try {
            kkAppEng.getEng().checkSession(token.getSessionId());
        } catch (KKException e) {
            throw new Exception(
                    "The SessionId from the SSOToken in the BarclaycardSmartPayApi Callback is not valid: "
                            + token.getSessionId());
        }

        // Log in the user
        kkAppEng.getCustomerMgr().loginBySession(token.getSessionId());
        sessionId = token.getSessionId();

        /*
         * Get the parameters from the token
         */
        String custom1 = token.getCustom1();
        String[] custom1Array = custom1.split("~");
        if (custom1Array == null || custom1Array.length != 3) {
            throw new Exception("Custom1 field of token doesn't contain expected data: " + token.getCustom1());
        }
        httpAuthStr = custom1Array[0];
        int orderId = Integer.parseInt(custom1Array[1]);
        String countryCode = custom1Array[2];
        httpUsername = token.getCustom2();
        httpPassword = token.getCustom3();

        if (countryCode == null) {
            log.warn("CountryCode not returned in the " + BarclaycardSmartPayHosted.BC_SPAY_HOSTED_GATEWAY_CODE
                    + " response");
        }

        ipnHistory.setOrderId(orderId);

        // Do HTTP Authentication if required
        if (httpAuthStr != null && Boolean.valueOf(httpAuthStr)) {
            // Get Authorization header
            String auth = null;

            if (request != null) {
                auth = request.getHeader("Authorization");
            }

            // Do we allow that user?
            if (!allowUser(auth, httpUsername, httpPassword)) {
                // Not allowed, so return "unauthorized"
                response.setContentType("text/plain");
                response.setHeader("WWW-Authenticate", "BASIC realm=\"Protected Page\"");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                log.warn("Notification from " + BarclaycardSmartPayApi.BC_SPAY_API_GATEWAY_CODE
                        + " could not be Authenticated");

                ipnHistory.setKonakartResultDescription(RET2_DESC);
                ipnHistory.setKonakartResultId(RET2);
                kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);
                return null;
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Accept Notification for " + BarclaycardSmartPayApi.BC_SPAY_API_GATEWAY_CODE);
        }

        // We always accept the Notification if we get this far
        response.setContentType("text/plain");
        response.getWriter().print("[accepted]\n");

        if (orderId < 0) {
            ipnHistory.setKonakartResultDescription(RET3_DESC);
            ipnHistory.setKonakartResultId(RET3);
            kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);
            return null;
        }

        // If it's not an AUTHORISATION event, we just throw it away
        if (!eventCode.equals("AUTHORISATION")) {
            if (log.isInfoEnabled()) {
                log.info("'" + eventCode + "' notification sent from "
                        + BarclaycardSmartPayApi.BC_SPAY_API_GATEWAY_CODE + " discarded");
            }
            return null;
        }

        // If we're about to set the order status to the current value we'll assume this is a
        // duplicate Notification from Barclaycard and not do any updates

        int currentOrderStatus = kkAppEng.getEng().getOrderStatus(sessionId, orderId);

        if (log.isDebugEnabled()) {
            log.debug("currentOrderStatus for orderId " + orderId + " = " + currentOrderStatus);
        }

        if ((success && currentOrderStatus == com.konakart.bl.OrderMgr.PAYMENT_RECEIVED_STATUS)
                || (!success && currentOrderStatus == com.konakart.bl.OrderMgr.PAYMENT_DECLINED_STATUS)) {
            if (log.isDebugEnabled()) {
                log.debug("Possible Duplicate '" + eventCode + "' notification sent from "
                        + BarclaycardSmartPayApi.BC_SPAY_API_GATEWAY_CODE + " discarded");
            }
            return null;
        }

        ipnHistory.setKonakartResultDescription(RET0_DESC);
        ipnHistory.setKonakartResultId(RET0);
        kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);

        return null;

    } catch (Exception e) {
        try {
            if (sessionId != null) {
                ipnHistory.setKonakartResultDescription(RET4_DESC);
                ipnHistory.setKonakartResultId(RET4);
                if (kkAppEng != null) {
                    kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);
                }
            }
        } catch (KKException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
        return null;
    } finally {
        if (sessionId != null && kkAppEng != null) {
            try {
                kkAppEng.getEng().logout(sessionId);
            } catch (KKException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.xpn.xwiki.user.impl.xwiki.MyFormAuthenticator.java

/**
 * Process any login information passed in parameter (username, password). Returns true if SecurityFilter should
 * abort further processing after the method completes (for example, if a redirect was sent as part of the login
 * processing).// www  .  j  a v  a2 s .c o  m
 * 
 * @param request
 * @param response
 * @return true if the filter should return after this method ends, false otherwise
 */
public boolean processLogin(String username, String password, String rememberme, SecurityRequestWrapper request,
        HttpServletResponse response, XWikiContext context) throws Exception {
    Principal principal = authenticate(username, password, context);
    if (principal != null) {
        // login successful
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("User " + principal.getName() + " has been logged-in");
        }

        // invalidate old session if the user was already authenticated, and they logged in as a different user
        if (request.getUserPrincipal() != null && !username.equals(request.getRemoteUser())) {
            request.getSession().invalidate();
        }

        // manage persistent login info, if persistent login management is enabled
        if (this.persistentLoginManager != null) {
            // did the user request that their login be persistent?
            if (rememberme != null) {
                // remember login
                this.persistentLoginManager.rememberLogin(request, response, username, password);
            } else {
                // forget login
                this.persistentLoginManager.forgetLogin(request, response);
            }
        }

        // make sure the Principal contains wiki name information
        if (!StringUtils.contains(principal.getName(), ':')) {
            principal = new SimplePrincipal(context.getDatabase() + ":" + principal.getName());
        }

        request.setUserPrincipal(principal);
        Boolean bAjax = (Boolean) context.get("ajax");
        if ((bAjax == null) || (!bAjax.booleanValue())) {
            String continueToURL = getContinueToURL(request);
            // This is the url that the user was initially accessing before being prompted for login.
            response.sendRedirect(response.encodeRedirectURL(continueToURL));
        }
    } else {
        // login failed
        // set response status and forward to error page
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("User " + username + " login has failed");
        }

        String returnCode = context.getWiki().Param("xwiki.authentication.unauthorized_code");
        int rCode = HttpServletResponse.SC_UNAUTHORIZED;
        if ((returnCode != null) && (!returnCode.equals(""))) {
            try {
                rCode = Integer.parseInt(returnCode);
            } catch (Exception e) {
                rCode = HttpServletResponse.SC_UNAUTHORIZED;
            }
        }
        response.setStatus(rCode); // TODO: Does this work? (200 in case of error)
    }

    return true;
}

From source file:com.sap.cloudlabs.connectivity.proxy.ProxyServlet.java

/**
 * Process response received from backend service and copy it to origin response of 
 * client.//  w  w w.  java  2s .  com
 * 
 * @param request
 *            origin request of this Web application
 * @param response
 *            origin response of this Web application; this is where the
 *            backend response is copied to
 * @param backendResponse
 *            the response of the backend service
 * @param proxyUrl
 *            the URL that should replace the <code>rewriteUrl</code>
 * @param rewriteUrl
 *            the URL that should be rewritten 
 */
private void processBackendResponse(HttpServletRequest request, HttpServletResponse response,
        HttpResponse backendResponse, String proxyUrl, String rewriteUrl) throws IOException, ServletException {
    // copy response status code
    int status = backendResponse.getStatusLine().getStatusCode();
    response.setStatus(status);
    LOGGER.debug("backend response status code: " + status);

    // filter the headers to suppress the authentication dialog (only for
    // 401 - unauthorized)
    List<String> blockedHeaders = null;
    if (status == HttpServletResponse.SC_UNAUTHORIZED && request.getHeader("authorization") != null
            && request.getHeader("suppress-www-authenticate") != null) {
        blockedHeaders = Arrays.asList(new String[] { "www-authenticate" });
    } else {
        // for rewriting the URLs in the response, content-length, content-encoding 
        // and transfer-encoding (for chunked content) headers are removed and handled specially.
        blockedHeaders = Arrays
                .asList(new String[] { "content-length", "transfer-encoding", "content-encoding" });
    }

    // copy backend response headers and content
    LOGGER.debug("backend response headers: ");
    for (Header header : backendResponse.getAllHeaders()) {
        if (!blockedHeaders.contains(header.getName().toLowerCase())) {
            response.addHeader(header.getName(), header.getValue());
            LOGGER.debug("    => " + header.getName() + ": " + header.getValue());
        } else {
            LOGGER.debug("    => " + header.getName() + ": blocked response header");
        }
    }

    handleContentEncoding(backendResponse);

    // pipe and return the response
    HttpEntity entity = backendResponse.getEntity();
    if (entity != null) {
        // rewrite URL in the content of the response to make sure that
        // internal URLs point to the proxy servlet as well

        // determine charset and content as String
        @SuppressWarnings("deprecation")
        String charset = EntityUtils.getContentCharSet(entity);
        String content = EntityUtils.toString(entity);

        LOGGER.debug("URL rewriting:");
        LOGGER.debug("    => rewriteUrl: " + rewriteUrl);
        LOGGER.debug("    => proxyUrl: " + proxyUrl);

        // replace the rewriteUrl with the targetUrl
        content = content.replaceAll(rewriteUrl, proxyUrl);

        // get the bytes and open a stream (by default HttpClient uses ISO-8859-1)
        byte[] contentBytes = charset != null ? content.getBytes(charset) : content.getBytes(ISO_8859_1);
        InputStream is = new ByteArrayInputStream(contentBytes);

        // set the new content length
        response.setContentLength(contentBytes.length);

        // return the modified content
        pipe(is, response.getOutputStream());
    }

}

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

@RequestMapping(method = RequestMethod.GET, value = "/itinerary")
public @ResponseBody List<ItineraryObject> getItineraries(HttpServletResponse response) throws Exception {
    try {/*  w  w w. ja  v  a  2  s .co m*/
        String userId = getUserId();
        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return null;
        }

        Map<String, Object> pars = new TreeMap<String, Object>();
        pars.put("userId", userId);
        List<ItineraryObject> res = domainStorage.searchDomainObjects(pars, ItineraryObject.class);

        return res;
    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return null;
}

From source file:org.dasein.cloud.cloudstack.CSMethod.java

public @Nonnull Document get(@Nonnull String url, @Nonnull String command)
        throws CloudException, InternalException {
    Logger wire = CSCloud.getLogger(CSMethod.class, "wire");
    Logger logger = CSCloud.getLogger(CSMethod.class, "std");

    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + CSMethod.class.getName() + ".get(" + url + ")");
    }/* ww w.  jav  a 2  s  .  c o  m*/
    if (wire.isDebugEnabled()) {
        wire.debug(
                "[" + (new Date()) + "] -------------------------------------------------------------------");
        wire.debug("");
    }
    HttpClient client = null;
    try {
        HttpGet get = new HttpGet(url);
        client = getClient(url);
        HttpResponse response;

        get.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        //get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
        if (wire.isDebugEnabled()) {
            wire.debug(get.getRequestLine().toString());
            for (Header header : get.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        try {
            APITrace.trace(provider, command);
            response = client.execute(get);
        } catch (IOException e) {
            logger.error("I/O error from server communications: " + e.getMessage());
            e.printStackTrace();
            throw new InternalException(e);
        }
        int status = response.getStatusLine().getStatusCode();
        if (logger.isDebugEnabled()) {
            logger.debug("get(): HTTP Status " + status);
        }
        if (wire.isDebugEnabled()) {
            Header[] headers = response.getAllHeaders();

            wire.debug(response.getStatusLine().toString());
            for (Header h : headers) {
                if (h.getValue() != null) {
                    wire.debug(h.getName() + ": " + h.getValue().trim());
                } else {
                    wire.debug(h.getName() + ":");
                }
            }
            wire.debug("");
        }
        try {
            if (status != HttpServletResponse.SC_OK) {
                HttpEntity entity = response.getEntity();
                String body = (entity == null ? null : EntityUtils.toString(entity));

                if (body == null) {
                    CSMethod.ParsedError p = new CSMethod.ParsedError();

                    p.code = status;
                    p.message = "No error information was provided";
                    throw new CSException(CloudErrorType.GENERAL, p);
                }
                if (body.contains("<html>")) {
                    if (status == HttpServletResponse.SC_FORBIDDEN
                            || status == HttpServletResponse.SC_UNAUTHORIZED) {
                        CSMethod.ParsedError p = new CSMethod.ParsedError();

                        p.code = status;
                        p.message = body;
                        throw new CSException(CloudErrorType.AUTHENTICATION, p);
                    } else if (status == 430 || status == 431 || status == 432 || status == 436) {
                        return null;
                    }
                    CSMethod.ParsedError p = new CSMethod.ParsedError();

                    p.code = status;
                    p.message = body;
                    throw new CSException(p);
                }
                throw new CSException(parseError(status, body));
            }
            HttpEntity entity = response.getEntity();

            return parseResponse(status, EntityUtils.toString(entity));
        } catch (NoHttpResponseException e) {
            throw new CloudException("No answer from endpoint: " + e.getMessage());
        } catch (IOException e) {
            throw new CloudException("IOException getting stream: " + e.getMessage());
        }
    } finally {
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("[" + (new Date())
                    + "] -------------------------------------------------------------------");
        }
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + CSMethod.class.getName() + ".get()");
        }
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
    }
}

From source file:org.dataconservancy.ui.api.ProjectController.java

/**
 * Handles the posting of a new project, this will add a new project to the
 * system. Note: Dates should be in the format dd mm yyyy
 *
 * @throws InvalidXmlException// w  w w.j a  v  a  2 s .  c om
 * @throws IOException
 */
@RequestMapping(method = { RequestMethod.POST })
public void handleProjectPostRequest(@RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestBody byte[] content, HttpServletRequest req, HttpServletResponse resp)
        throws BizInternalException, BizPolicyException, InvalidXmlException, IOException {

    // TODO Why doesn't spring do this?
    if (req.getContentType().contains("application/x-www-form-urlencoded")) {
        content = URLDecoder.decode(new String(content, "UTF-8"), "UTF-8").getBytes("UTF-8");
    }

    Project project = objectBuilder.buildProject(new ByteArrayInputStream(content));
    Person user = getAuthenticatedUser();

    if (user == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } else if (authorizationService.canCreateProject(user)) {
        projectBizService.updateProject(project, user);
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/xml");
        resp.setStatus(HttpStatus.SC_CREATED);

        Bop bop = new Bop();
        bop.addProject(project);
        objectBuilder.buildBusinessObjectPackage(bop, resp.getOutputStream());
    } else {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
}

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

@RequestMapping(value = "/service/dispatcher")
public Dispatcher serviceDispatcher(@RequestParam(name = "login") String login, HttpServletRequest request,
        HttpServletResponse response) {/*from   ww w .  jav a 2 s.com*/
    HttpSession httpSession = request.getSession();
    User user = (User) httpSession.getAttribute("user");

    if (!serviceUsers.checkUserOnline(user)) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

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

        return null;
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("user get dispacther. Session id : " + httpSession.getId() + ". User : " + user
                + ". URL : /service/dispatcher/typeMachine");
    }

    return serviceDispatcherName.getDispatcher(user);
}

From source file:com.moss.bdbadmin.jetty.BdbAdminJettyAdapter.java

public void handle(String target, final HttpServletRequest request, final HttpServletResponse response,
        int arg3) throws IOException, ServletException {

    target = request.getRequestURI(); // the target is automatically URLDecoded, we don't want this

    if (!target.startsWith(contextPath)) {
        return;//from  w w w .ja v a2  s . com
    }

    final IdProof assertion;
    {
        IdProof a = null;

        String value = request.getHeader(AuthenticationHeader.HEADER_NAME);
        if (value != null && value.length() > 0) {
            try {
                a = AuthenticationHeader.decode(value);
            } catch (Exception ex) {
                ex.printStackTrace();
                a = null;
            }
        } else {
            System.out.println("No assertion included in request header");
            a = null;
        }

        assertion = a;
    }

    final ServiceResource resource;
    {
        String path;
        if (target.length() >= contextPath.length()) {
            path = target.substring(contextPath.length()).trim();
        } else {
            path = target;
        }

        ServiceResource r = null;
        ;
        try {
            r = service.resolve(path);
        } catch (ResourcePathException ex) {
            ex.printStackTrace();
        }

        resource = r;
    }

    if (assertion == null || resource == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {
        abstract class Handler {
            abstract void handle() throws Exception;
        }

        Handler handler = resource.acceptVisitor(new ServiceResourceVisitor<Handler>() {
            public Handler visit(BdbMapResource map) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("OPTIONS".equals(request.getMethod())) {
                            byte[] data = service.map(assertion);
                            response.setHeader("Content-Length", Integer.toString(data.length));
                            response.getOutputStream().write(data);
                            response.setStatus(HttpServletResponse.SC_OK);
                        } else {
                            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }

            public Handler visit(BdbCategory category) {
                return null;
            }

            public Handler visit(BdbEnv env) {
                return null;
            }

            public Handler visit(final BdbDb db) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("GET".equals(request.getMethod())) {
                            byte[] data = service.dbInfo(assertion, db);
                            response.setHeader("Content-Length", Integer.toString(data.length));
                            response.getOutputStream().write(data);
                            response.setStatus(HttpServletResponse.SC_OK);
                        } else if ("DELETE".equals(request.getMethod())) {
                            service.clearDb(assertion, db);
                            response.setStatus(HttpServletResponse.SC_OK);
                        } else {
                            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }

            public Handler visit(final BdbEntityResource entity) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("OPTIONS".equals(request.getMethod())) {
                            byte[] data = service.entryInfo(assertion, entity);
                            if (data == null) {
                                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                            } else {
                                response.setHeader("Content-Length", Integer.toString(data.length));
                                response.getOutputStream().write(data);
                                response.setStatus(HttpServletResponse.SC_OK);
                            }
                        } else if ("GET".equals(request.getMethod())) {
                            byte[] data = service.getEntry(assertion, entity);
                            if (data == null) {
                                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                            } else {
                                response.setHeader("Content-Length", Integer.toString(data.length));
                                response.getOutputStream().write(data);
                                response.setStatus(HttpServletResponse.SC_OK);
                            }
                        } else if ("HEAD".equals(request.getMethod())) {
                            byte[] data = service.getEntry(assertion, entity);
                            if (data == null) {
                                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                            } else {
                                response.setStatus(HttpServletResponse.SC_OK);
                            }
                        } else if ("PUT".equals(request.getMethod())) {

                            byte[] input;
                            {
                                InputStream in = request.getInputStream();
                                ByteArrayOutputStream out = new ByteArrayOutputStream();

                                byte[] buffer = new byte[1023 * 10]; //10k buffer
                                for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) {
                                    out.write(buffer, 0, numRead);
                                }

                                in.close();
                                out.close();

                                input = out.toByteArray();
                            }

                            service.putEntry(assertion, entity, input);
                            response.setStatus(HttpServletResponse.SC_OK);
                        } else if ("DELETE".equals(request.getMethod())) {
                            if (service.deleteEntry(assertion, entity)) {
                                response.setStatus(HttpServletResponse.SC_OK);
                            } else {
                                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                            }
                        } else {
                            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }
        });

        if (handler == null) {
            System.out.println("Cannot perform any methods on requested path");
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        } else {
            try {
                handler.handle();
            } catch (IdProovingException ex) {
                ex.printStackTrace();
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            } catch (NotAuthorizedException ex) {
                ex.printStackTrace();
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            } catch (Exception ex) {
                throw new ServletException(ex);
            }
        }
    }

    response.getOutputStream().close();

    ((Request) request).setHandled(true);
}