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:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static int invalidTokenResponse(String message, Throwable t, EPADLogger log) {
    return warningResponse(HttpServletResponse.SC_UNAUTHORIZED, message, t, log);
}

From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static int invalidTokenResponse(String message, EPADLogger log) {
    return warningResponse(HttpServletResponse.SC_UNAUTHORIZED, message, log);
}

From source file:edu.stanford.epad.epadws.xnat.XNATSessionOperations.java

private static XNATSessionResponse getXNATSessionID(String username, String password) {
    String xnatSessionURL = buildXNATSessionURL();
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(xnatSessionURL);
    String authString = buildAuthorizationString(username, password);
    XNATSessionResponse xnatSessionResponse;
    int xnatStatusCode;

    try {/*w  ww  .j  a  v  a 2s  .c  om*/
        log.info("Invoking XNAT session service for user " + username + " at " + xnatSessionURL);
        method.setRequestHeader("Authorization", "Basic " + authString);
        xnatStatusCode = client.executeMethod(method);
        log.info("Successfully invoked XNAT session service for user " + username + "; status code = "
                + xnatStatusCode);
    } catch (IOException e) {
        log.warning("Error calling XNAT session service for user " + username, e);
        xnatStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    try {
        if (xnatStatusCode == HttpServletResponse.SC_OK) {
            try {
                StringBuilder sb = new StringBuilder();
                InputStreamReader isr = null;
                try {
                    isr = new InputStreamReader(method.getResponseBodyAsStream());
                    int read = 0;
                    char[] chars = new char[128];
                    while ((read = isr.read(chars)) > 0) {
                        sb.append(chars, 0, read);
                    }
                } finally {
                    IOUtils.closeQuietly(isr);
                }
                String jsessionID = sb.toString();
                xnatSessionResponse = new XNATSessionResponse(HttpServletResponse.SC_OK, jsessionID);
                log.debug("Session ID " + jsessionID + " generated for user " + username); // TODO temp
            } catch (IOException e) {
                log.warning(LOGIN_EXCEPTION_MESSAGE, e);
                xnatSessionResponse = new XNATSessionResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        LOGIN_EXCEPTION_MESSAGE + ": " + e.getMessage());
            }
        } else if (xnatStatusCode == HttpServletResponse.SC_UNAUTHORIZED) {
            log.warning(XNAT_UNAUTHORIZED_MESSAGE);
            xnatSessionResponse = new XNATSessionResponse(xnatStatusCode, XNAT_UNAUTHORIZED_MESSAGE);
        } else {
            log.warning(XNAT_LOGIN_ERROR_MESSAGE + "; XNAT status code = " + xnatStatusCode);
            xnatSessionResponse = new XNATSessionResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    XNAT_LOGIN_ERROR_MESSAGE + "; XNAT status code = " + xnatStatusCode);
        }
    } finally {
        method.releaseConnection();
    }
    return xnatSessionResponse;
}

From source file:org.openrepose.common.auth.openstack.AuthenticationServiceClient.java

@Override
public AuthGroups getGroups(String userId, String tracingHeader) throws AuthServiceException {
    final Map<String, String> headers = new HashMap<>();

    AuthGroups authGroups;/*w  w w .j  a va  2 s.co m*/

    try {
        headers.put(ACCEPT_HEADER, MediaType.APPLICATION_XML);
        headers.put(AUTH_TOKEN_HEADER, getAdminToken(tracingHeader, false));
        if (tracingHeader != null) {
            headers.put(CommonHttpHeader.TRACE_GUID.toString(), tracingHeader);
        }

        ServiceClientResponse serviceResponse = akkaServiceClient.get(GROUPS_PREFIX + userId,
                targetHostUri + "/users/" + userId + "/RAX-KSGRP", headers);

        switch (serviceResponse.getStatus()) {
        case HttpServletResponse.SC_OK:
            authGroups = getAuthGroups(serviceResponse);
            break;
        case HttpServletResponse.SC_UNAUTHORIZED:
            LOG.error("Unable to get groups for user: " + serviceResponse.getStatus()
                    + " :admin token expired. Retrieving new admin token and retrying groups retrieval...");

            headers.put(AUTH_TOKEN_HEADER, getAdminToken(tracingHeader, true));

            serviceResponse = akkaServiceClient.get(GROUPS_PREFIX + userId,
                    targetHostUri + "/users/" + userId + "/RAX-KSGRP", headers);

            if (serviceResponse.getStatus() == HttpServletResponse.SC_ACCEPTED) {
                authGroups = getAuthGroups(serviceResponse);
            } else {
                delegationMessage.set("Unable to get groups for user id: " + userId + ". Status code: "
                        + serviceResponse.getStatus());
                LOG.error("Still unable to get groups: " + serviceResponse.getStatus());
                throw new AuthServiceException("Unable to retrieve groups for user. Response from "
                        + targetHostUri + ": " + serviceResponse.getStatus());

            }
            break;
        case HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE:
        case FilterDirector.SC_TOO_MANY_REQUESTS: // (413 | 429)
            delegationMessage.set("Unable to get groups for user id: " + userId + ". Status code: "
                    + serviceResponse.getStatus());
            throw buildAuthServiceOverLimitException(serviceResponse);
        default:
            delegationMessage.set("Unable to get groups for user id: " + userId + ". Status code: "
                    + serviceResponse.getStatus());
            LOG.error("Unable to get groups for user id: " + userId + " Status code: "
                    + serviceResponse.getStatus());
            throw new AuthServiceException("Unable to retrieve groups for user. Response from " + targetHostUri
                    + ": " + serviceResponse.getStatus());
        }
    } catch (AkkaServiceClientException e) {
        throw new AuthServiceException("Unable to get groups.", e);
    }

    return authGroups;
}

From source file:de.tu_dortmund.ub.api.paia.auth.PaiaAuthEndpoint.java

/**
 * PAIAauth services: Prfe jeweils die scopes und liefere die Daten
 *///from   w  w w .j  a va 2s.  co m
private void provideService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        String service, String access_token, String requestBody, String format, String language,
        String redirect_url) throws IOException {

    ObjectMapper mapper = new ObjectMapper();

    switch (service) {

    case "login": {

        if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) {

            AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class);
            // init Authorization Service
            authorizationInterface.init(this.config);

            // if access_token not equals "" >> delete token + new login
            if (!access_token.equals("")) {

                // AuthorizationInterface.revokeToken()
                try {

                    boolean isRevoked = authorizationInterface.revokeToken(access_token);
                } catch (AuthorizationException e) {

                    // TODO correct error handling
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!");
                }

                // delete cookie
                Cookie cookie = new Cookie("PaiaService", null);
                if (this.config.getProperty("service.cookie.domain") != null
                        && !this.config.getProperty("service.cookie.domain").equals("")) {
                    cookie.setDomain(this.config.getProperty("service.cookie.domain"));
                }
                cookie.setMaxAge(0);
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);

                // cleanup variable
                access_token = "";
            }

            // analyse on request data
            LoginRequest loginRequest = null;
            try {

                loginRequest = mapper.readValue(requestBody, LoginRequest.class);

                if (httpServletRequest.getParameter("redirect_url") != null
                        && !httpServletRequest.getParameter("redirect_url").equals("")) {

                    redirect_url = httpServletRequest.getParameter("redirect_url");
                }
            } catch (Exception e) {

                if (requestBody != null && !requestBody.equals("")) {

                    String[] params = requestBody.split("&");

                    if (params.length > 1) {

                        loginRequest = new LoginRequest();

                        for (String param : params) {

                            if (param.startsWith("grant_type")) {
                                loginRequest.setGrant_type(param.split("=")[1]);
                            } else if (param.startsWith("username")) {
                                loginRequest.setUsername(param.split("=")[1]);
                            } else if (param.startsWith("password")) {
                                loginRequest.setPassword(param.split("=")[1]);
                            } else if (param.startsWith("scope")) {
                                loginRequest.setScope(param.split("=")[1]);
                            } else if (param.startsWith("format")) {
                                format = param.split("=")[1];
                                this.logger.info("format = " + format);
                            } else if (param.startsWith("redirect_url")) {
                                redirect_url = URLDecoder.decode(param.split("=")[1], "UTF-8");
                                this.logger.info("redirect_url = " + redirect_url);
                            } else {
                                // Tu nix
                            }
                        }
                    }
                } else if (httpServletRequest.getParameter("grant_type") != null
                        && !httpServletRequest.getParameter("grant_type").equals("")
                        && httpServletRequest.getParameter("username") != null
                        && !httpServletRequest.getParameter("username").equals("")
                        && httpServletRequest.getParameter("password") != null
                        && !httpServletRequest.getParameter("password").equals("")) {

                    loginRequest = new LoginRequest();
                    loginRequest.setGrant_type(httpServletRequest.getParameter("grant_type"));
                    loginRequest.setUsername(httpServletRequest.getParameter("username"));
                    loginRequest.setPassword(httpServletRequest.getParameter("password"));
                    if (httpServletRequest.getParameter("scope") != null
                            && !httpServletRequest.getParameter("scope").equals("")) {
                        loginRequest.setScope(httpServletRequest.getParameter("scope"));
                    }
                    if (httpServletRequest.getParameter("redirect_url") != null
                            && !httpServletRequest.getParameter("redirect_url").equals("")) {

                        redirect_url = httpServletRequest.getParameter("redirect_url");
                    }
                } else {
                    loginRequest = null;
                }
            }

            // do login
            if (loginRequest != null && loginRequest.getUsername() != null && loginRequest.getPassword() != null
                    && loginRequest.getGrant_type() != null
                    && loginRequest.getGrant_type().equals("password")) {

                String scope = "read_patron read_fees read_items write_items"; // TODO config-properties
                if (loginRequest.getScope() != null && !loginRequest.getScope().equals("")) {

                    scope = loginRequest.getScope();
                }

                // AuthorizationInterface.getToken()
                String responseJson = "";
                try {

                    responseJson = authorizationInterface.getToken(scope, loginRequest.getUsername(),
                            loginRequest.getPassword());
                } catch (AuthorizationException e) {

                    // TODO correct error handling
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!");
                }

                if (!responseJson.equals("")) {

                    LoginResponse loginResponse = mapper.readValue(responseJson, LoginResponse.class);

                    // anpassen des loginResponse
                    loginResponse.setRefresh_token(null);
                    loginResponse.setRefresh_expires_in(null);
                    loginResponse.setPatron(loginRequest.getUsername());

                    httpServletResponse.setHeader("Access-Control-Allow-Origin",
                            this.config.getProperty("Access-Control-Allow-Origin"));
                    httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control"));
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);

                    // add cookie
                    StringWriter stringWriter = new StringWriter();
                    mapper.writeValue(stringWriter, loginResponse);
                    Cookie cookie = new Cookie("PaiaService",
                            URLEncoder.encode(stringWriter.toString(), "UTF-8"));
                    if (this.config.getProperty("service.cookie.domain") != null
                            && !this.config.getProperty("service.cookie.domain").equals("")) {
                        cookie.setDomain(this.config.getProperty("service.cookie.domain"));
                    }
                    cookie.setMaxAge(-1);
                    cookie.setPath("/");
                    httpServletResponse.addCookie(cookie);

                    // extent redirect_url
                    this.logger.info("redirect_url: " + redirect_url);
                    if (redirect_url.startsWith(this.config.getProperty("service.base_url") + "/core")) {

                        if (redirect_url.endsWith("core/")) {
                            redirect_url += loginResponse.getPatron();
                        } else if (redirect_url.endsWith("core")) {
                            redirect_url += "/" + loginResponse.getPatron();
                        } else if (redirect_url.contains("/patronid/")) {

                            redirect_url = redirect_url.replaceAll("/patronid/",
                                    "/" + loginResponse.getPatron() + "/");
                        } else {
                            // nix
                        }
                    }
                    this.logger.info("redirect_url: " + redirect_url);

                    // XML-Ausgabe mit JAXB
                    if (format.equals("xml")) {

                        try {

                            JAXBContext context = JAXBContext.newInstance(LoginResponse.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(loginResponse, httpServletResponse.getWriter());
                        } catch (JAXBException e) {
                            this.logger.error(e.getMessage(), e.getCause());
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering the results.");
                        }
                    }

                    // JSON-Ausgabe mit Jackson
                    if (format.equals("json")) {

                        httpServletResponse.setContentType("application/json;charset=UTF-8");
                        mapper.writeValue(httpServletResponse.getWriter(), loginResponse);
                    }

                    // html >> redirect
                    if (format.equals("html")) {

                        // if QueryString contains redirect_url and value of it contains /paia/core/ >> expand URL with username
                        if (redirect_url.contains("/paia/core/")) {

                            // TODO redirect_url += loginResponse.getPatron();
                        }
                        this.logger.info("redirect_url = " + redirect_url);

                        httpServletResponse.sendRedirect(redirect_url);
                    }
                } else {

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config
                            .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2"));
                    requestError.setCode(HttpServletResponse.SC_FORBIDDEN);
                    requestError.setDescription(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.uri"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }
            }
            // else Baue HTML-Seite mit login-Formular mittels XSLT
            else {

                httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAIA auth\"");
                httpServletResponse.setContentType("application/json");
                httpServletResponse.setHeader("Access-Control-Allow-Origin",
                        config.getProperty("Access-Control-Allow-Origin"));
                httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control"));

                // Error handling mit suppress_response_codes=true
                if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                }
                // Error handling mit suppress_response_codes=false (=default)
                else {
                    httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
                }

                // Json fr Response body
                RequestError requestError = new RequestError();
                requestError.setError(this.config
                        .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2"));
                requestError.setCode(HttpServletResponse.SC_FORBIDDEN);
                requestError.setDescription(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.description"));
                requestError.setErrorUri(this.config
                        .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.uri"));

                if (format.equals("html")) {

                    if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) {

                        try {
                            ObjectToHtmlTransformation htmlTransformation = Lookup
                                    .lookup(ObjectToHtmlTransformation.class);
                            // init transformator
                            htmlTransformation.init(this.config);

                            HashMap<String, String> parameters = new HashMap<String, String>();
                            parameters.put("lang", language);
                            parameters.put("redirect_url", redirect_url);

                            //String provider = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + this.config.getProperty("service.endpoint.auth") + "/" + service;
                            String provider = this.config.getProperty("service.base_url")
                                    + this.config.getProperty("service.endpoint.auth") + "/" + service;
                            parameters.put("formURL", provider);

                            httpServletResponse.setContentType("text/html;charset=UTF-8");
                            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                            httpServletResponse.getWriter()
                                    .println(htmlTransformation.transform(new Document(), parameters));
                        } catch (TransformationException e) {
                            e.printStackTrace();
                            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Internal Server Error: Error while rendering a HTML message.");
                        }
                    } else {
                        this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON.");
                        format = "json";
                    }
                }

                // XML-Ausgabe mit JAXB
                if (format.equals("xml")) {

                    try {

                        JAXBContext context = JAXBContext.newInstance(RequestError.class);
                        Marshaller m = context.createMarshaller();
                        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                        // Write to HttpResponse
                        httpServletResponse.setContentType("application/xml;charset=UTF-8");
                        m.marshal(requestError, httpServletResponse.getWriter());
                    } catch (JAXBException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering the results.");
                    }
                }

                // JSON-Ausgabe mit Jackson
                if (format.equals("json")) {

                    httpServletResponse.setContentType("application/json;charset=UTF-8");
                    mapper.writeValue(httpServletResponse.getWriter(), requestError);
                }
            }
        } else {

            this.logger.error(HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": Config Error!");

            // Error handling mit suppress_response_codes=true
            if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            }
            // Error handling mit suppress_response_codes=false (=default)
            else {
                httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            }

            // Json fr Response body
            RequestError requestError = new RequestError();
            requestError.setError(this.config
                    .getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
            requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            requestError.setDescription(this.config.getProperty(
                    "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
            requestError.setErrorUri(this.config.getProperty(
                    "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

            this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
        }

        break;
    }
    case "logout": {

        if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) {

            AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class);
            // init Authorization Service
            authorizationInterface.init(this.config);

            if (!access_token.equals("")) {

                // AuthorizationInterface.revokeToken()
                try {

                    boolean isRevoked = authorizationInterface.revokeToken(access_token);
                } catch (AuthorizationException e) {

                    // TODO correct error handling
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!");
                }
            }

            httpServletResponse.setHeader("Access-Control-Allow-Origin",
                    config.getProperty("Access-Control-Allow-Origin"));
            httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control"));
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);

            // delete cookie
            Cookie cookie = new Cookie("PaiaService", null);
            if (this.config.getProperty("service.cookie.domain") != null
                    && !this.config.getProperty("service.cookie.domain").equals("")) {
                cookie.setDomain(this.config.getProperty("service.cookie.domain"));
            }
            cookie.setMaxAge(0);
            cookie.setPath("/");
            httpServletResponse.addCookie(cookie);

            // html >> redirect
            if (format.equals("html")) {

                if (httpServletRequest.getParameter("redirect_url") != null
                        && !httpServletRequest.getParameter("redirect_url").equals("")) {

                    redirect_url = httpServletRequest.getParameter("redirect_url");
                } else {

                    redirect_url = this.config.getProperty("service.auth.logout.redirect.default");
                }

                httpServletResponse.sendRedirect(redirect_url);
            }

            if (format.equals("json")) {
                httpServletResponse.setContentType("application/json;charset=UTF-8");
                httpServletResponse.getWriter().println("{\"logged out\":\"true\"}");
            }

            if (format.equals("xml")) {
                httpServletResponse.setContentType("application/xml;charset=UTF-8");
                httpServletResponse.getWriter().println(
                        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><logout status=\"true\" />");
            }

        } else {

            this.logger.error(HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": Config Error!");

            // Error handling mit suppress_response_codes=true
            if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            }
            // Error handling mit suppress_response_codes=false (=default)
            else {
                httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            }

            // Json fr Response body
            RequestError requestError = new RequestError();
            requestError.setError(this.config
                    .getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE)));
            requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            requestError.setDescription(this.config.getProperty(
                    "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description"));
            requestError.setErrorUri(this.config.getProperty(
                    "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri"));

            this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
        }

        break;
    }
    case "change": {

        // build ChangeRequest object
        ChangeRequest changeRequest = mapper.readValue(requestBody, ChangeRequest.class);

        // check token ...
        boolean isAuthorized = false;

        if (access_token != null && !access_token.equals("")) {

            if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) {

                AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class);
                // init Authorization Service
                authorizationInterface.init(this.config);

                try {

                    isAuthorized = authorizationInterface.isTokenValid(httpServletResponse, service,
                            changeRequest.getPatron(), access_token);
                } catch (AuthorizationException e) {

                    // TODO correct error handling
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!");
                }
            } else {

                // TODO correct error handling
                this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": "
                        + "Authorization Interface not implemented!");
            }
        }

        this.logger.debug("Authorization: " + access_token + " - " + isAuthorized);

        if (!isAuthorized) {

            // Authorization
            this.authorize(httpServletRequest, httpServletResponse, format);
        } else {

            if (Lookup.lookupAll(LibraryManagementSystem.class).size() > 0) {

                LibraryManagementSystem libraryManagementSystem = Lookup.lookup(LibraryManagementSystem.class);
                // init ILS
                libraryManagementSystem.init(this.config);

                // exists patron?
                // use LibraryManagementSystem.patron(): failed = Exception!
                try {

                    Patron patron = libraryManagementSystem.patron(changeRequest.getPatron(), false);

                    boolean isChanged = libraryManagementSystem.changePassword(changeRequest);

                    if (isChanged) {

                        // E-Mail to user
                        Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf"));

                        try {

                            if (this.config.getProperty("isTestMode") != null
                                    && !Boolean.parseBoolean(this.config.getProperty("isTestMode"))) {
                                mailer.postMail(patron.getEmail(),
                                        this.config.getProperty("service.mailer.change.subject"),
                                        this.config.getProperty("service.mailer.change.message"));
                            } else {
                                mailer.postMail(this.config.getProperty("service.mailer.change.subject"),
                                        this.config.getProperty("service.mailer.change.message"));
                            }

                        } catch (MessagingException e1) {

                            this.logger.error(e1.getMessage(), e1.getCause());
                        }

                        this.logger.info("Password changed. Mail send to '" + patron.getEmail() + "'.");

                        // 200 OK
                        if (format.equals("html")) {

                            format = "json"; // TODO or what else?
                        }

                        Patron responsePatron = new Patron();
                        responsePatron.setUsername(patron.getUsername());
                        responsePatron.setStatus(patron.getStatus());
                        responsePatron.setEmail(new InternetAddress(patron.getEmail()));

                        if (format.equals("json")) {

                            httpServletResponse.setContentType("application/json;charset=UTF-8");
                            mapper.writeValue(httpServletResponse.getWriter(), responsePatron);
                        }

                        if (format.equals("xml")) {

                            JAXBContext context = JAXBContext.newInstance(Patron.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(responsePatron, httpServletResponse.getWriter());
                        }
                    } else {

                        // 401 UNAUTHORIZED
                        this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": Wrong old password!");

                        // Error handling mit suppress_response_codes=true
                        if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        }
                        // Error handling mit suppress_response_codes=false (=default)
                        else {
                            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                        }

                        // Json fr Response body
                        RequestError requestError = new RequestError();
                        requestError.setError(this.config
                                .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED)));
                        requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED);
                        requestError.setDescription(this.config.getProperty("error."
                                + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description"));
                        requestError.setErrorUri(this.config.getProperty(
                                "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri"));

                        this.sendRequestError(httpServletResponse, requestError, format, language,
                                redirect_url);
                    }
                } catch (LibraryManagementSystemException e) {

                    // 401 UNAUTHORIZED
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": " + e.getMessage());

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config
                            .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED)));
                    requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED);
                    requestError.setDescription(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                } catch (Exception e) {

                    this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
                    requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    requestError.setDescription(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description"));
                    requestError.setErrorUri(this.config.getProperty("error."
                            + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }
            } else {

                this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!");

                // Error handling mit suppress_response_codes=true
                if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                }
                // Error handling mit suppress_response_codes=false (=default)
                else {
                    httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }

                // Json fr Response body
                RequestError requestError = new RequestError();
                requestError.setError(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
                requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                requestError.setDescription(this.config.getProperty("error."
                        + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description"));
                requestError.setErrorUri(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri"));

                this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
            }
        }

        break;
    }
    case "renew": {

        if (Lookup.lookupAll(LibraryManagementSystem.class).size() > 0) {

            LibraryManagementSystem libraryManagementSystem = Lookup.lookup(LibraryManagementSystem.class);
            // init ILS
            libraryManagementSystem.init(this.config);

            // exists patron?
            // use LibraryManagementSystem.patron(): failed = Exception!
            try {

                // build NewPasswordRequest object
                NewPasswordRequest newPasswordRequest = mapper.readValue(requestBody, NewPasswordRequest.class);

                Patron patron = libraryManagementSystem.patron(newPasswordRequest.getPatron(), true);

                if (patron.getEmail() != null && !patron.getEmail().equals("")) {

                    boolean isRenewed = libraryManagementSystem.renewPassword(newPasswordRequest, patron);

                    if (isRenewed) {

                        // E-Mail to user
                        Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf"));

                        try {

                            if (this.config.getProperty("isTestMode") != null
                                    && !Boolean.parseBoolean(this.config.getProperty("isTestMode"))) {
                                mailer.postMail(patron.getEmail(),
                                        this.config.getProperty("service.mailer.renew.subject"),
                                        this.config.getProperty("service.mailer.renew.message"));
                            } else {
                                mailer.postMail(this.config.getProperty("service.mailer.renew.subject"),
                                        this.config.getProperty("service.mailer.renew.message"));
                            }

                        } catch (MessagingException e1) {

                            this.logger.error(e1.getMessage(), e1.getCause());
                        }

                        this.logger.info("Password resetted. Mail send to '" + patron.getEmail() + "'.");

                        // 200 OK
                        if (format.equals("html")) {

                            format = "json"; // TODO or what else?
                        }

                        Patron responsePatron = new Patron();
                        responsePatron.setUsername(patron.getUsername());
                        responsePatron.setStatus(patron.getStatus());
                        responsePatron.setEmail(new InternetAddress(patron.getEmail()));

                        if (format.equals("json")) {

                            httpServletResponse.setContentType("application/json;charset=UTF-8");
                            mapper.writeValue(httpServletResponse.getWriter(), responsePatron);
                        }

                        if (format.equals("xml")) {

                            JAXBContext context = JAXBContext.newInstance(Patron.class);
                            Marshaller m = context.createMarshaller();
                            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            // Write to HttpResponse
                            httpServletResponse.setContentType("application/xml;charset=UTF-8");
                            m.marshal(responsePatron, httpServletResponse.getWriter());
                        }
                    } else {

                        // 401 SC_UNAUTHORIZED
                        this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": Wrong usergroup!");

                        // Error handling mit suppress_response_codes=true
                        if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        }
                        // Error handling mit suppress_response_codes=false (=default)
                        else {
                            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                        }

                        // Json fr Response body
                        RequestError requestError = new RequestError();
                        requestError.setError(this.config
                                .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED)));
                        requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED);
                        requestError.setDescription(this.config.getProperty("error."
                                + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description"));
                        requestError.setErrorUri(this.config.getProperty(
                                "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri"));

                        this.sendRequestError(httpServletResponse, requestError, format, language,
                                redirect_url);
                    }
                } else {

                    // 401 SC_UNAUTHORIZED
                    this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": No E-Mail-Address exists!");

                    // Error handling mit suppress_response_codes=true
                    if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                    }
                    // Error handling mit suppress_response_codes=false (=default)
                    else {
                        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    }

                    // Json fr Response body
                    RequestError requestError = new RequestError();
                    requestError.setError(this.config
                            .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED)));
                    requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED);
                    requestError.setDescription(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description"));
                    requestError.setErrorUri(this.config.getProperty(
                            "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri"));

                    this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
                }
            } catch (LibraryManagementSystemException e) {

                e.printStackTrace();

                // 400 SC_BAD_REQUEST
                this.logger.error(HttpServletResponse.SC_BAD_REQUEST + ": " + e.getMessage());

                // Error handling mit suppress_response_codes=true
                if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                }
                // Error handling mit suppress_response_codes=false (=default)
                else {
                    httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                }

                // Json fr Response body
                RequestError requestError = new RequestError();
                requestError.setError(this.config
                        .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST)));
                requestError.setCode(HttpServletResponse.SC_BAD_REQUEST);
                requestError.setDescription(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description"));
                requestError.setErrorUri(this.config
                        .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri"));

                this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
            } catch (Exception e) {

                this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!");

                // Error handling mit suppress_response_codes=true
                if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                }
                // Error handling mit suppress_response_codes=false (=default)
                else {
                    httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }

                // Json fr Response body
                RequestError requestError = new RequestError();
                requestError.setError(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
                requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                requestError.setDescription(this.config.getProperty("error."
                        + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description"));
                requestError.setErrorUri(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri"));

                this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
            }
        } else {

            this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!");

            // Error handling mit suppress_response_codes=true
            if (httpServletRequest.getParameter("suppress_response_codes") != null) {
                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            }
            // Error handling mit suppress_response_codes=false (=default)
            else {
                httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }

            // Json fr Response body
            RequestError requestError = new RequestError();
            requestError.setError(this.config
                    .getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
            requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            requestError.setDescription(this.config.getProperty("error."
                    + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description"));
            requestError.setErrorUri(this.config.getProperty(
                    "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri"));

            this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
        }

        break;
    }
    default: {

        this.logger.error(HttpServletResponse.SC_BAD_REQUEST + "Unknown function! (" + service + ")");

        // Error handling mit suppress_response_codes=true
        if (httpServletRequest.getParameter("suppress_response_codes") != null
                && !httpServletRequest.getParameter("suppress_response_codes").equals("")) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        }
        // Error handling mit suppress_response_codes=false (=default)
        else {
            httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

        // Json fr Response body
        RequestError requestError = new RequestError();
        requestError.setError(
                this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST)));
        requestError.setCode(HttpServletResponse.SC_BAD_REQUEST);
        requestError.setDescription(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description"));
        requestError.setErrorUri(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri"));

        this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url);
    }
    }
}

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

public void getTweets(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");

    Twitter twitter = twitterLogic.getTwitterAuthForUser(userToken, userSecret);
    if (twitter == null) {
        // no connection
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;//  www.  j a v  a  2s  . com
    }

    String cacheKey = userToken;
    Element element = null;

    // force refresh
    boolean force = Boolean.parseBoolean(request.getParameter("force"));
    if (force) {
        log.debug("force refresh for " + userToken);
        // remove tweets cache
        tweetsCache.remove(cacheKey);
    } else {
        element = tweetsCache.get(cacheKey);
    }

    if (element == null) {
        synchronized (tweetsCache) {
            // if it is still null after acquiring lock
            element = tweetsCache.get(cacheKey);

            if (element == null) {
                log.debug("cache miss: getting tweets for " + userToken);
                System.out.println("Last refreshed: " + Calendar.getInstance().getTime());

                try {
                    ResponseList<Status> friendStatus = twitter.getFriendsTimeline();

                    long maxId = Long.MIN_VALUE;

                    JSONObject json = new JSONObject();

                    lastRefreshed = Calendar.getInstance().getTime().toString();

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

                    User currentUser = twitter.showUser(twitter.getId());
                    Status lastUserStatus = currentUser.getStatus();
                    if (lastUserStatus == null) {
                        json.element("lastStatusUpdate", "unable to retrieve last status");
                    } else {
                        Date lastStatusUpdate = lastUserStatus.getCreatedAt();
                        json.element("lastStatusUpdate", lastStatusUpdate.toString());
                    }

                    for (Status status : friendStatus) {
                        maxId = Math.max(maxId, status.getId());
                        json.accumulate("statusList", getStatusJSON(twitter, status));
                    }

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

                    out.print(json.toString());

                    element = new Element(cacheKey,
                            new TweetsCacheElement(System.currentTimeMillis(), maxId, json));

                    tweetsCache.put(element);

                    return;

                } 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);
                    }

                    return;
                }
            }
        }
    }

    // tweets available in cache
    log.debug("cache hit: getting tweets for " + userToken);

    TweetsCacheElement tweets = (TweetsCacheElement) element.getObjectValue();

    // if just refreshed too quickly, don't request update, just use
    // whatever in cache
    long period = System.currentTimeMillis() - tweets.getLastRefresh();
    System.out.println("Already refreshed: " + (period / 1000) + " second(s) ago");

    if (period < 2 * 60 * 1000) {
        log.debug("refreshed too quickly: " + (period / 1000) + " seconds");
        JSONObject json = tweets.getResult();
        lastRefreshed = Calendar.getInstance().getTime().toString();
        json.element("lastRefreshed", lastRefreshed.toString());
        out.print(json.toString());
        return;
    }

    // get new updates since the last id
    long maxId = tweets.lastId;
    try {
        JSONObject json = tweets.getResult();

        ResponseList<Status> friendStatus = twitter.getFriendsTimeline(new Paging(maxId));

        tweets.setLastRefresh(System.currentTimeMillis());

        log.debug(String.format("Got %d new tweets", friendStatus.size()));

        if (friendStatus.size() > 0) {
            JSONArray newTweets = new JSONArray();

            lastRefreshed = Calendar.getInstance().getTime().toString();
            json.element("lastRefreshed", lastRefreshed.toString());

            for (Status status : friendStatus) {
                maxId = Math.max(maxId, status.getId());
                newTweets.add(getStatusJSON(twitter, status));
            }

            if (log.isDebugEnabled()) {
                log.debug("new tweets:\n" + newTweets.toString(2));
            }

            json.getJSONArray("statusList").addAll(0, newTweets);

            tweets.setLastId(maxId);

            User currentUser = twitter.showUser(twitter.getId());
            Status lastUserStatus = currentUser.getStatus();
            if (lastUserStatus == null) {
                json.element("lastStatusUpdate", "unable to retrieve last status");
            } else {
                Date lastStatusUpdate = lastUserStatus.getCreatedAt();
                json.element("lastStatusUpdate", lastStatusUpdate.toString());
            }
        }

        out.print(json.toString());

    } catch (TwitterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        log.error(e);
    }
}

From source file:com.google.nigori.server.NigoriServlet.java

/**
 * Handle initial request from client and dispatch to appropriate handler or return error message.
 *///from  w  ww  .j  a  v  a2 s  . c o  m
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {
        addCorsHeaders(resp);
        // Subset of path managed by this servlet; e.g. if URI is "/nigori/get" and servlet path
        // is "/nigori, then we want to retrieve "get" as the request type
        int startIndex = req.getServletPath().length() + 1;
        String requestURI = req.getRequestURI();
        if (requestURI.length() <= startIndex) {
            ServletException s = new ServletException(HttpServletResponse.SC_BAD_REQUEST,
                    "No request type specified.\n" + supportedTypes + "\n");
            log.fine(s.toString());
            s.writeHttpResponse(resp);
            return;
        }
        String requestType = requestURI.substring(startIndex);
        String requestMimetype = req.getContentType();
        RequestHandlerType handlerType = new RequestHandlerType(requestMimetype, requestType);

        RequestHandler handler = handlers.get(handlerType);
        if (handler == null) {
            throw new ServletException(HttpServletResponse.SC_NOT_ACCEPTABLE,
                    "Unsupported request pair: " + handlerType + "\n" + supportedTypes + "\n");
        }
        try {
            handler.handle(req, resp);
        } catch (NotFoundException e) {
            ServletException s = new ServletException(HttpServletResponse.SC_NOT_FOUND,
                    e.getLocalizedMessage());
            log.fine(s.toString());
            s.writeHttpResponse(resp);
        } catch (UnauthorisedException e) {
            ServletException s = new ServletException(HttpServletResponse.SC_UNAUTHORIZED,
                    "Authorisation failed: " + e.getLocalizedMessage());
            log.warning(s.toString());
            s.writeHttpResponse(resp);
        } catch (IOException ioe) {
            throw new ServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Internal error sending data to client");
        } catch (MessageLibrary.JsonConversionException jce) {
            throw new ServletException(HttpServletResponse.SC_BAD_REQUEST,
                    "JSON format error: " + jce.getMessage());
        } catch (RuntimeException re) {
            log.severe(re.toString());
            throw new ServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, re.toString());
        }

    } catch (ServletException e) {
        log.severe(e.toString());
        e.writeHttpResponse(resp);
    }
}

From source file:de.tu_dortmund.ub.api.paaa.PaaaEndpoint.java

/**
 * @param httpServletRequest/*from w w  w.ja  v  a 2 s.  c  o m*/
 * @param httpServletResponse
 * @throws ServletException
 * @throws java.io.IOException
 */
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    ObjectMapper mapper = new ObjectMapper();

    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "PathInfo = "
            + httpServletRequest.getPathInfo());
    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "QueryString = "
            + httpServletRequest.getQueryString());

    String patronid = "";
    String service = "";
    String accept = "";
    String authorization = "";

    String format = "json";

    String path = httpServletRequest.getPathInfo();
    String[] params = path.substring(1, path.length()).split("/");

    if (params.length == 1) {
        patronid = params[0];
        service = "patron";
    } else if (params.length == 2) {
        patronid = params[0];
        service = params[1];
    }

    if (patronid.equals("patronid")) {
        patronid = "";
    }

    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Patron: " + patronid);
    this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Service: " + service);

    if (httpServletRequest.getParameter("format") != null
            && !httpServletRequest.getParameter("format").equals("")) {

        format = httpServletRequest.getParameter("format");
    } else {

        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerNameKey = headerNames.nextElement();

            if (headerNameKey.equals("Accept")) {

                this.logger.debug("headerNameKey = " + httpServletRequest.getHeader(headerNameKey));

                if (httpServletRequest.getHeader(headerNameKey).contains("text/html")) {
                    format = "html";
                } else if (httpServletRequest.getHeader(headerNameKey).contains("application/xml")) {
                    format = "xml";
                } else if (httpServletRequest.getHeader(headerNameKey).contains("application/json")) {
                    format = "json";
                }
            }
        }
    }

    this.logger.info("format = " + format);

    if (!format.equals("json") && !format.equals("xml")) {

        this.logger.error("[" + this.config.getProperty("service.name") + "] "
                + HttpServletResponse.SC_BAD_REQUEST + ": " + format + " not implemented!");

        // Error handling mit suppress_response_codes=true
        if (httpServletRequest.getParameter("suppress_response_codes") != null) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        }
        // Error handling mit suppress_response_codes=false (=default)
        else {
            httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

        // Json fr Response body
        RequestError requestError = new RequestError();
        requestError.setError(
                this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST)));
        requestError.setCode(HttpServletResponse.SC_BAD_REQUEST);
        requestError.setDescription(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description"));
        requestError.setErrorUri(this.config
                .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri"));

        this.sendRequestError(httpServletResponse, requestError, format);
    } else {
        // PAAA - function
        if (service.equals("signup") || service.equals("newpatron") || service.equals("updatepatron")
                || service.equals("blockpatron") || service.equals("unblockpatron")
                || service.equals("newfee")) {

            // get 'Accept' and 'Authorization' from Header;
            Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
            while (headerNames.hasMoreElements()) {

                String headerNameKey = (String) headerNames.nextElement();
                this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "headerNameKey = "
                        + headerNameKey + " / headerNameValue = "
                        + httpServletRequest.getHeader(headerNameKey));

                if (headerNameKey.equals("Accept")) {
                    accept = httpServletRequest.getHeader(headerNameKey);
                }
                if (headerNameKey.equals("Authorization")) {
                    authorization = httpServletRequest.getHeader(headerNameKey);
                }
            }

            this.logger.debug("[" + this.config.getProperty("service.name") + "] " + "Accept: " + accept);
            this.logger.debug(
                    "[" + this.config.getProperty("service.name") + "] " + "Authorization: " + authorization);

            // if not exists token: read request parameter
            if (authorization.equals("") && httpServletRequest.getParameter("access_token") != null
                    && !httpServletRequest.getParameter("access_token").equals("")) {
                authorization = httpServletRequest.getParameter("access_token");
            }

            // if not exists token
            if (authorization.equals("")) {

                // if exists PaiaService-Cookie: read content
                Cookie[] cookies = httpServletRequest.getCookies();

                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        if (cookie.getName().equals("PaaaService")) {

                            String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
                            this.logger.info(value);
                            LoginResponse loginResponse = mapper.readValue(value, LoginResponse.class);

                            // A C H T U N G: ggf. andere patronID im Cookie als in Request (UniAccount vs. BibAccount)
                            if (loginResponse.getPatron().equals(patronid)) {
                                authorization = loginResponse.getAccess_token();
                            }

                            break;
                        }
                    }
                }
            }

            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

            // check token ...
            boolean isAuthorized = false;

            if (!authorization.equals("")) {

                if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) {

                    AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class);
                    // init Authorization Service
                    authorizationInterface.init(this.config);

                    try {

                        isAuthorized = authorizationInterface.isTokenValid(httpServletResponse, service,
                                patronid, authorization);
                    } catch (AuthorizationException e) {

                        // TODO correct error handling
                        this.logger.error("[" + config.getProperty("service.name") + "] "
                                + HttpServletResponse.SC_UNAUTHORIZED + "!");
                    }
                } else {

                    // TODO correct error handling
                    this.logger.error("[" + this.config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": "
                            + "Authorization Interface not implemented!");
                }
            }

            this.logger.debug("[" + config.getProperty("service.name") + "] " + "Authorization: "
                    + authorization + " - " + isAuthorized);

            // ... - if not is authorized - against DFN-AAI service
            if (!isAuthorized) {

                // TODO if exists OpenAM-Session-Cookie: read content
                this.logger.debug("[" + config.getProperty("service.name") + "] " + "Authorization: "
                        + authorization + " - " + isAuthorized);
            }

            if (isAuthorized) {

                // execute query
                this.provideService(httpServletRequest, httpServletResponse, format, patronid, authorization,
                        service);
            } else {

                // Authorization
                this.authorize(httpServletRequest, httpServletResponse, format);
            }
        } else {

            this.logger.error("[" + this.config.getProperty("service.name") + "] "
                    + HttpServletResponse.SC_METHOD_NOT_ALLOWED + ": " + "POST for '" + service
                    + "' not allowed!");

            httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
            httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
            httpServletResponse.setContentType("application/json");

            // Error handling mit suppress_response_codes=true
            if (httpServletRequest.getParameter("suppress_response_codes") != null
                    && !httpServletRequest.getParameter("suppress_response_codes").equals("")) {
                httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            }
            // Error handling mit suppress_response_codes=false (=default)
            else {
                httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }

            // Json fr Response body
            RequestError requestError = new RequestError();
            requestError.setError(this.config
                    .getProperty("error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED)));
            requestError.setCode(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            requestError.setDescription(this.config.getProperty(
                    "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".description"));
            requestError.setErrorUri(this.config.getProperty(
                    "error." + Integer.toString(HttpServletResponse.SC_METHOD_NOT_ALLOWED) + ".uri"));

            StringWriter json = new StringWriter();
            mapper.writeValue(json, requestError);
            this.logger.debug("[" + this.config.getProperty("service.name") + "] " + json);

            // send response
            httpServletResponse.getWriter().println(json);
        }
    }
}

From source file:com.mirth.connect.connectors.ws.WebServiceReceiver.java

private com.sun.net.httpserver.Authenticator createAuthenticator() throws ConnectorTaskException {
    final Authenticator authenticator;
    try {/*from  w ww  .jav a  2s  . c o  m*/
        authenticator = authenticatorProvider.getAuthenticator();
    } catch (Exception e) {
        throw new ConnectorTaskException("Unable to create authenticator.", e);
    }

    return new com.sun.net.httpserver.Authenticator() {
        @Override
        public Result authenticate(final HttpExchange exch) {
            String remoteAddress = StringUtils
                    .trimToEmpty(exch.getRemoteAddress().getAddress().getHostAddress());
            int remotePort = exch.getRemoteAddress().getPort();
            String localAddress = StringUtils.trimToEmpty(exch.getLocalAddress().getAddress().getHostAddress());
            int localPort = exch.getLocalAddress().getPort();
            String protocol = StringUtils.trimToEmpty(exch.getProtocol());
            String method = StringUtils.trimToEmpty(exch.getRequestMethod());
            String requestURI = StringUtils.trimToEmpty(exch.getRequestURI().toString());
            Map<String, List<String>> headers = exch.getRequestHeaders();

            Map<String, List<String>> queryParameters = new LinkedHashMap<String, List<String>>();
            for (NameValuePair nvp : URLEncodedUtils.parse(exch.getRequestURI(), "UTF-8")) {
                List<String> list = queryParameters.get(nvp.getName());
                if (list == null) {
                    list = new ArrayList<String>();
                    queryParameters.put(nvp.getName(), list);
                }
                list.add(nvp.getValue());
            }

            EntityProvider entityProvider = new EntityProvider() {
                @Override
                public byte[] getEntity() throws IOException {
                    byte[] entity = (byte[]) exch.getAttribute(ATTRIBUTE_NAME);
                    if (entity == null) {
                        entity = IOUtils.toByteArray(exch.getRequestBody());
                        exch.setAttribute(ATTRIBUTE_NAME, entity);
                        exch.setStreams(new ByteArrayInputStream(entity), exch.getResponseBody());
                    }
                    return entity;
                }
            };

            RequestInfo requestInfo = new RequestInfo(remoteAddress, remotePort, localAddress, localPort,
                    protocol, method, requestURI, headers, queryParameters, entityProvider);

            try {
                AuthenticationResult result = authenticator.authenticate(requestInfo);

                for (Entry<String, List<String>> entry : result.getResponseHeaders().entrySet()) {
                    if (StringUtils.isNotBlank(entry.getKey()) && entry.getValue() != null) {
                        for (int i = 0; i < entry.getValue().size(); i++) {
                            if (i == 0) {
                                exch.getResponseHeaders().set(entry.getKey(), entry.getValue().get(i));
                            } else {
                                exch.getResponseHeaders().add(entry.getKey(), entry.getValue().get(i));
                            }
                        }
                    }
                }

                switch (result.getStatus()) {
                case CHALLENGED:
                    return new com.sun.net.httpserver.Authenticator.Retry(HttpServletResponse.SC_UNAUTHORIZED);
                case SUCCESS:
                    String username = StringUtils.trimToEmpty(result.getUsername());
                    String realm = StringUtils.trimToEmpty(result.getRealm());
                    return new com.sun.net.httpserver.Authenticator.Success(new HttpPrincipal(username, realm));
                case FAILURE:
                default:
                    return new com.sun.net.httpserver.Authenticator.Failure(
                            HttpServletResponse.SC_UNAUTHORIZED);

                }
            } catch (Throwable t) {
                logger.error("Error in HTTP authentication for " + connectorProperties.getName() + " ("
                        + connectorProperties.getName() + " \"Source\" on channel " + getChannelId() + ").", t);
                eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), null,
                        ErrorEventType.DESTINATION_CONNECTOR, "Source", connectorProperties.getName(),
                        "Error in HTTP authentication for " + connectorProperties.getName(), t));
                return new com.sun.net.httpserver.Authenticator.Failure(
                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        }
    };
}