Example usage for javax.servlet.http HttpServletResponse SC_SERVICE_UNAVAILABLE

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

Introduction

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

Prototype

int SC_SERVICE_UNAVAILABLE

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

Click Source Link

Document

Status code (503) indicating that the HTTP server is temporarily overloaded, and unable to handle the request.

Usage

From source file:org.jahia.bin.errors.ErrorServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    WebUtils.setNoCacheHeaders(response);

    // check if the Basic Authentication is required
    Integer errorCode = (Integer) request.getAttribute("javax.servlet.error.status_code");

    if (errorCode == HttpServletResponse.SC_UNAUTHORIZED && getException(request) == null) {
        if (!response.containsHeader("WWW-Authenticate")) {
            response.setHeader("WWW-Authenticate", "BASIC realm=\"Secured Jahia tools\"");
        }/*from   www .  j a  v  a2  s . c o  m*/
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } else {
        if (errorCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE && StringUtils.equals(
                ErrorServlet.MAINTENANCE_MODE, (String) request.getAttribute("javax.servlet.error.message"))) {
            forwardToErrorPage("/errors/maintenance.jsp", request, response);
        } else if (errorCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE
                && StringUtils.equals(ErrorServlet.LICENSE_TERMS_VIOLATION_MODE,
                        (String) request.getAttribute("javax.servlet.error.message"))) {
            forwardToErrorPage("/errors/license.jsp", request, response);
        } else {
            // otherwise continue with processing of the error
            String method = request.getMethod();
            if (method.equals("GET") || method.equals("POST")) {
                process(request, response);
            } else {
                response.sendError(errorCode != null ? errorCode.intValue()
                        : HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        }
    }
}

From source file:org.eclipse.gyrex.http.jetty.internal.app.ApplicationHandlerCollection.java

@Override
public void handle(final String target, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    // don't do anything if already processed
    if (response.isCommitted() || baseRequest.isHandled())
        return;//  w ww .  j  a  v  a 2  s.c  o m

    final Iterator<Handler> handlers = this.handlers.iterator();
    if (!handlers.hasNext())
        return;

    final ThroughputMetric requestsMetric = metrics.getRequestsMetric();
    final long requestStart = requestsMetric.requestStarted();
    try {
        doHandle(target, baseRequest, request, response);
        if (response instanceof Response) {
            final int status = ((Response) response).getStatus();
            if (HttpStatus.isServerError(status)) {
                metrics.getRequestsMetric().requestFailed();
                metrics.error(status, ((Response) response).getReason());
            } else {
                metrics.getRequestsMetric().requestFinished(((Response) response).getContentCount(),
                        System.currentTimeMillis() - requestStart);
            }
        } else {
            metrics.getRequestsMetric().requestFinished(0, System.currentTimeMillis() - requestStart);
        }
    } catch (final EofException | RuntimeIOException | ContinuationThrowable e) {
        metrics.getRequestsMetric().requestFailed();
        throw e;
    } catch (final Exception e) {
        metrics.getRequestsMetric().requestFailed();

        final DispatcherType type = baseRequest.getDispatcherType();
        if (!(DispatcherType.REQUEST.equals(type) || DispatcherType.ASYNC.equals(type))) {
            if (e instanceof IOException)
                throw (IOException) e;
            if (e instanceof RuntimeException)
                throw (RuntimeException) e;
            if (e instanceof ServletException)
                throw (ServletException) e;
        }

        // handle or log exception
        else if (e instanceof RuntimeIOException)
            throw (RuntimeIOException) e;
        else if (e instanceof EofException)
            throw (EofException) e;
        else if ((e instanceof IOException) || (e instanceof UnavailableException)
                || (e instanceof IllegalStateException)) {
            if (Platform.inDebugMode()) {
                LOG.debug("Exception processing request {}: {}", request.getRequestURI(),
                        ExceptionUtils.getMessage(e), e);
                LOG.debug(request.toString());
            }
        } else {
            LOG.error("Exception processing request {}: {}",
                    new Object[] { request.getRequestURI(), ExceptionUtils.getRootCauseMessage(e), e });
            if (Platform.inDebugMode()) {
                LOG.debug(request.toString());
            }
        }

        // send error response if possible
        if (!response.isCommitted()) {
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE, e.getClass());
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, e);
            if (e instanceof UnavailableException) {
                final UnavailableException ue = (UnavailableException) e;
                if (ue.isPermanent()) {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
                } else {
                    response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
                }
            } else if (e instanceof IllegalStateException) {
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, e.getMessage());
            } else {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            }
        } else {
            // give up
            if (JettyDebug.debug) {
                LOG.debug("Response already committed for handling {}", ExceptionUtils.getMessage(e));
            }
        }
    } catch (final Error e) {
        metrics.getRequestsMetric().requestFailed();

        // only handle some errors
        if (!((e instanceof LinkageError) || (e instanceof AssertionError)))
            throw e;

        final DispatcherType type = baseRequest.getDispatcherType();
        if (!(DispatcherType.REQUEST.equals(type) || DispatcherType.ASYNC.equals(type)))
            throw e;

        LOG.error("Error processing request {}: {}",
                new Object[] { request.getRequestURI(), ExceptionUtils.getRootCauseMessage(e), e });
        if (JettyDebug.debug) {
            LOG.debug(request.toString());
        }

        // TODO httpResponse.getHttpConnection().forceClose();
        if (!response.isCommitted()) {
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE, e.getClass());
            request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } else {
            if (JettyDebug.debug) {
                LOG.debug("Response already committed for handling {}", ExceptionUtils.getMessage(e));
            }
        }
    }
}

From source file:org.jetbrains.webdemo.handlers.ServerHandler.java

private void forwardRequestToBackend(HttpServletRequest request, HttpServletResponse response,
        Map<String, String> postParameters) {
    final boolean hasoutbody = (request.getMethod().equals("POST"));

    try {/* w  w  w. j  a  v a  2s.c om*/
        final URL url = new URL("http://" + ApplicationSettings.BACKEND_URL + "/"
                + (request.getQueryString() != null ? "?" + request.getQueryString() : ""));
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        final Enumeration<String> headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            final String header = headers.nextElement();
            final Enumeration<String> values = request.getHeaders(header);
            while (values.hasMoreElements()) {
                final String value = values.nextElement();
                conn.addRequestProperty(header, value);
            }
        }

        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);
        conn.setUseCaches(false);
        conn.setDoOutput(hasoutbody);

        if (postParameters != null && !postParameters.isEmpty()) {
            conn.setRequestMethod("POST");
            try (OutputStream requestBody = conn.getOutputStream()) {
                boolean first = true;
                for (Map.Entry<String, String> entry : postParameters.entrySet()) {
                    if (entry.getValue() == null)
                        continue;
                    if (first) {
                        first = false;
                    } else {
                        requestBody.write('&');
                    }
                    requestBody.write(URLEncoder.encode(entry.getKey(), "UTF8").getBytes());
                    requestBody.write('=');
                    requestBody.write(URLEncoder.encode(entry.getValue(), "UTF8").getBytes());
                }
            }
        } else {
            conn.setRequestMethod("GET");
        }

        StringBuilder responseBody = new StringBuilder();
        if (conn.getResponseCode() >= 400) {
            StringBuilder serverMessage = new StringBuilder();
            try (InputStream errorStream = conn.getErrorStream()) {
                if (errorStream != null) {
                    byte[] buffer = new byte[1024];
                    while (true) {
                        final int read = errorStream.read(buffer);
                        if (read <= 0)
                            break;
                        serverMessage.append(new String(buffer, 0, read));
                    }
                }
            }

            switch (conn.getResponseCode()) {
            case HttpServletResponse.SC_NOT_FOUND:
                responseBody.append("Kotlin compile server not found");
                break;
            case HttpServletResponse.SC_SERVICE_UNAVAILABLE:
                responseBody.append("Kotlin compile server is temporary overloaded");
                break;
            default:
                responseBody = serverMessage;
                break;
            }
        } else {
            try (InputStream inputStream = conn.getInputStream()) {
                if (inputStream != null) {
                    byte[] buffer = new byte[1024];
                    while (true) {
                        final int read = inputStream.read(buffer);
                        if (read <= 0)
                            break;
                        responseBody.append(new String(buffer, 0, read));
                    }
                }
            }
        }
        writeResponse(request, response, responseBody.toString(), conn.getResponseCode());
    } catch (SocketTimeoutException e) {
        writeResponse(request, response, "Compile server connection timeout",
                HttpServletResponse.SC_GATEWAY_TIMEOUT);
    } catch (Exception e) {
        ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(e, "FORWARD_REQUEST_TO_BACKEND", "",
                "Can't forward request to Kotlin compile server");
        writeResponse(request, response, "Can't send your request to Kotlin compile server",
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

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

public void retweet(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");
    long statusId = Long.parseLong(request.getParameter("d"));

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

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

    try {
        Status status = null;

        // update user status
        status = twitter.retweetStatus(statusId);
        if (status == null) {
            log.error("Status is null.");
            // general error
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

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

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

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

        out.print(json.toString());

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

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

From source file:org.jitsi.videobridge.rest.HandlerImpl.java

/**
 * Lists the <tt>Conference</tt>s of (the associated) <tt>Videobridge</tt>.
 *
 * @param baseRequest the original unwrapped {@link Request} object
 * @param request the request either as the {@code Request} object or a
 * wrapper of that request/*from  ww  w . j  ava 2 s .c  o m*/
 * @param response the response either as the {@code Response} object or a
 * wrapper of that response
 * @throws IOException
 * @throws ServletException
 */
private void doGetConferencesJSON(Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    Videobridge videobridge = getVideobridge();

    if (videobridge == null) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else {
        Conference[] conferences = videobridge.getConferences();
        List<ColibriConferenceIQ> conferenceIQs = new ArrayList<>();

        for (Conference conference : conferences) {
            ColibriConferenceIQ conferenceIQ = new ColibriConferenceIQ();

            conferenceIQ.setID(conference.getID());
            conferenceIQs.add(conferenceIQ);
        }

        JSONArray conferencesJSONArray = JSONSerializer.serializeConferences(conferenceIQs);

        if (conferencesJSONArray == null)
            conferencesJSONArray = new JSONArray();

        response.setStatus(HttpServletResponse.SC_OK);
        conferencesJSONArray.writeJSONString(response.getWriter());
    }
}

From source file:org.oclc.oai.server.OAIHandler.java

/**
 * Peform the http GET action. Note that POST is shunted to here as well. The verb widget is taken from the request and
 * used to invoke an OAIVerb object of the corresponding kind to do the actual work of the verb.
 *
 * @param request  the servlet's request information
 * @param response the servlet's response information
 * @throws IOException an I/O error occurred
 *///from  w  w  w  . j a  v  a2s  .c  o  m
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Map attributes = getAttributes(request.getPathInfo());
    if (!filterRequest(request, response)) {
        return;
    }
    //      log.debug("attributes=" + attributes);
    Properties properties = (Properties) attributes.get("OAIHandler.properties");
    boolean monitor = false;
    if (properties.getProperty("OAIHandler.monitor") != null) {
        monitor = true;
    }
    boolean serviceUnavailable = isServiceUnavailable(properties);
    String extensionPath = properties.getProperty("OAIHandler.extensionPath", "/extension");

    Map serverVerbs = ServerVerb.getVerbs(properties);
    Map extensionVerbs = ServerVerb.getExtensionVerbs(properties);

    Transformer transformer = (Transformer) attributes.get("OAIHandler.transformer");

    boolean forceRender = false;
    if ("true".equals(properties.getProperty("OAIHandler.forceRender"))) {
        forceRender = true;
    }

    // try {
    request.setCharacterEncoding("UTF-8");
    // } catch (UnsupportedEncodingException e) {
    // e.printStackTrace();
    // throw new IOException(e.getMessage());
    // }
    Date then = null;
    if (monitor)
        then = new Date();
    if (debug) {
        Enumeration headerNames = request.getHeaderNames();
        System.out.println("OAIHandler.doGet: ");
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            System.out.print(headerName);
            System.out.print(": ");
            System.out.println(request.getHeader(headerName));
        }
    }
    if (serviceUnavailable) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "Sorry. This server is down for maintenance");
    } else {
        try {
            String userAgent = request.getHeader("User-Agent");
            if (userAgent == null) {
                userAgent = "";
            } else {
                userAgent = userAgent.toLowerCase();
            }
            Transformer serverTransformer = null;
            if (transformer != null) {

                // return HTML if the client is an old browser
                if (forceRender || userAgent.indexOf("opera") != -1
                        || (userAgent.startsWith("mozilla") && userAgent.indexOf("msie 6") == -1
                        /* && userAgent.indexOf("netscape/7") == -1 */)) {
                    serverTransformer = transformer;
                }
            }
            String result = getResult(attributes, request, response, serverTransformer, serverVerbs,
                    extensionVerbs, extensionPath);
            // log.debug("result=" + result);

            // if (serverTransformer) { // render on the server
            // response.setContentType("text/html; charset=UTF-8");
            // StringReader stringReader = new StringReader(getResult(request));
            // StreamSource streamSource = new StreamSource(stringReader);
            // StringWriter stringWriter = new StringWriter();
            // transformer.transform(streamSource, new StreamResult(stringWriter));
            // result = stringWriter.toString();
            // } else { // render on the client
            // response.setContentType("text/xml; charset=UTF-8");
            // result = getResult(request);
            // }

            Writer out = getWriter(request, response);
            out.write(result);
            out.close();
        } catch (FileNotFoundException e) {
            if (debug) {
                e.printStackTrace();
                System.out.println("SC_NOT_FOUND: " + e.getMessage());
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        } catch (TransformerException e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (OAIInternalServerError e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (SocketException e) {
            System.out.println(e.getMessage());
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (Throwable e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
    if (monitor) {
        StringBuffer reqUri = new StringBuffer(request.getRequestURI());
        String queryString = request.getQueryString(); // d=789
        if (queryString != null) {
            reqUri.append("?").append(queryString);
        }
        //Runtime rt = Runtime.getRuntime();
        //System.out.println(rt.freeMemory() + "/" + rt.totalMemory() + " " + ((new Date()).getTime() - then.getTime()) + "ms: " + reqUri.toString());
    }
}

From source file:de.innovationgate.wgpublisher.WGPRequestPath.java

protected WGPRequestPath(HttpServletRequest request, HttpServletResponse response, WGPDispatcher dispatcher)
        throws HttpErrorException, WGException, IOException, URIException {

    this.core = dispatcher.getCore();
    this.queryString = request.getQueryString();
    this.completeURL = buildCompleteURL(request);
    this.publisherURL = WGPDispatcher.getPublisherURL(request);

    // Extract the base part of the path - Redirect to start.jsp if no path information given
    this.basePath = this.getBasePath(request, dispatcher);
    if (this.basePath.equals("") || this.basePath.equals("/")) {
        if (core.getWgaConfiguration().getDefaultDatabase() == null) {
            this.pathType = TYPE_REDIRECT;
            this.resourcePath = this.publisherURL + this.core.getStartPageURL();
            return;
        } else {/*from  ww  w .  ja va 2s  . c om*/
            this.basePath = "/" + core.getWgaConfiguration().getDefaultDatabase();
        }
    }

    // Tokenize Path
    int tildeTokenPos = -1;
    java.util.StringTokenizer pathTokens = new StringTokenizer(this.basePath, "/");
    String token;
    while (pathTokens.hasMoreTokens()) {
        token = pathTokens.nextToken();
        this.pathElements.add(token);
        if (token.charAt(0) == '~') {
            tildeTokenPos = this.pathElements.size() - 1;
        }

    }

    if (this.pathElements.size() < 1) {
        this.pathType = TYPE_INVALID;
        return;
    }

    // Resolve database
    this.databaseKey = ((String) this.pathElements.get(0)).toLowerCase();
    ;
    this.database = (WGDatabase) core.getContentdbs().get(this.databaseKey);

    // if no database under this key, try to recognize a special path command
    if (this.database == null) {
        determineSpecialPathCommand();
        if (this.database == null) {
            return;
        }
    }

    // Check if we need to enforce secure app mode
    URL secureURL = enforceSecureAppMode(database, request);
    if (secureURL != null) {
        pathType = TYPE_REDIRECT;
        resourcePath = secureURL.toString();
        return;
    }

    // check if db is accessed via right protocol, host and port - Must be before login so it may get redirected to some certauth port
    URL currentURL = new URL(request.getRequestURL().toString());
    URL redirectURL = enforceRedirectionRules(database, currentURL);

    // currentURL differs from redirectURL - redirect necessary
    if (redirectURL != null && !dispatcher.isBrowserInterface(request.getSession())) {
        pathType = TYPE_REDIRECT;
        resourcePath = redirectURL.toString();
        return;
    }

    // Handle special db commands "login" and "logout". The only one not requiring to login to the database
    if (this.pathElements.size() == 2) {
        if ("login".equals(this.pathElements.get(1))) {
            this.pathType = TYPE_REDIRECT;
            String sourceURL = (request.getParameter("redirect") != null
                    ? dispatcher.getCore().getURLEncoder().decode(request.getParameter("redirect"))
                    : WGPDispatcher.getPublisherURL(request) + "/" + this.databaseKey);
            this.resourcePath = dispatcher.getLoginURL(request, database, sourceURL);
            this.appendQueryString = false;
            return;
        } else if ("logout".equals(this.pathElements.get(1))) {
            this.pathType = TYPE_LOGOUT;

            if (request.getParameter("redirect") != null) {
                this.resourcePath = request.getParameter("redirect");
                this.appendQueryString = false;
            } else {
                this.resourcePath = WGPDispatcher.getPublisherURL(request) + "/" + this.databaseKey;
            }
            return;
        }

    }

    // Open the database
    try {
        if (pathType == TYPE_STATICTML && "admintml".equals(getPathCommand())
                && dispatcher.isAdminLoggedIn(request)) {
            this.masterLogin = true;
        }

        // Prepare HTTP credentials if available
        String credentials = request.getHeader("Authorization");
        if (credentials != null && credentials.trim().toLowerCase().startsWith("basic")) {
            DBLoginInfo loginInfo = DBLoginInfo.createFromHttpCredentials(credentials);
            if (loginInfo != null) {
                // Look if ANY media key uses HTTP login. Only if so we accept this login
                if (isHttpLoginUsed(database)) {
                    request.setAttribute(REQATTRIB_HTTPLOGIN, loginInfo);
                }
            }
        }

        this.database = core.openContentDB(database, request, this.masterLogin);
    } catch (WGUnavailableException e) {
        throw new HttpErrorException(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "The website is currently unavailable: " + e.getMessage(), getDatabaseKey());
    } catch (de.innovationgate.wgpublisher.AuthenticationException e) {
        throw new HttpErrorException(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage(), null);
    } catch (AccessException e) {
        throw new HttpErrorException(HttpServletResponse.SC_FORBIDDEN, e.getMessage(), null);
    }

    if (!database.isSessionOpen()) {
        handleLoginFailure(request, response, dispatcher);
        this.proceedRequest = false;
        return;
    }

    // If request is static/admin tml we are done here
    if (pathType == TYPE_STATICTML) {
        return;
    }

    // If only database given, go to home page
    if (this.pathElements.size() == 1) {
        this.pathType = TYPE_GOTO_HOMEPAGE;
        setPermanentRedirect(core.getWgaConfiguration().isUsePermanentRedirect());
        return;
    }

    // Process tilde tokens
    if (tildeTokenPos != -1) {
        String tildeToken = (String) this.pathElements.get(tildeTokenPos);

        // Url to file attachment via ~file-Syntax
        if (tildeToken.equalsIgnoreCase("~file")) {
            this.pathType = TYPE_FILE;
            List<String> preTildeTokenElems = this.pathElements.subList(1, tildeTokenPos);
            this.containerKey = (String) preTildeTokenElems.get(preTildeTokenElems.size() - 1);
            this.fileName = WGUtils.serializeCollection(
                    this.pathElements.subList(tildeTokenPos + 1, this.pathElements.size()), "/");
            return;
        }

    }

    // Catch special db-related urls
    String elem1 = ((String) this.pathElements.get(1)).toLowerCase();
    int elementsSize = this.pathElements.size();
    if (elementsSize >= 3 && (elem1.equals("css"))) {
        this.pathType = TYPE_CSS;
        this.cssjsKey = this.database.toLowerCaseMeta(
                WGUtils.serializeCollection(this.pathElements.subList(2, this.pathElements.size()), "/"));
        return;
    } else if (elementsSize >= 3 && (elem1.equals("js"))) {
        this.pathType = TYPE_JS;
        this.cssjsKey = this.database.toLowerCaseMeta(
                WGUtils.serializeCollection(this.pathElements.subList(2, this.pathElements.size()), "/"));
        return;
    } else if (elementsSize >= 3 && elem1.equals("file")) {
        this.pathType = TYPE_FILE;
        int fileNameIndex = determineFileNameIndex(this.pathElements, 2);
        this.containerKey = this.database
                .toLowerCaseMeta(WGUtils.serializeCollection(this.pathElements.subList(2, fileNameIndex), ":"));
        this.fileName = WGUtils.serializeCollection(this.pathElements.subList(fileNameIndex, elementsSize),
                "/");
        return;
    }

    // Find out if we have a title path URL
    TitlePathManager tpm = (TitlePathManager) database.getAttribute(WGACore.DBATTRIB_TITLEPATHMANAGER);
    if (tpm != null && tpm.isGenerateTitlePathURLs()) {
        TitlePathManager.TitlePath url = tpm.parseTitlePathURL(pathElements.subList(1, pathElements.size()));
        if (url != null) {
            this.pathType = TYPE_TITLE_PATH;
            this.titlePathURL = url;
            this.mediaKey = core.getMediaKey(url.getMediaKey());
            if (url.getLanguage() == null) {
                completePath = false;
            }
        }
    }

    // Path identified as normal TML request, read media and layout key
    if (pathType == TYPE_UNKNOWN) {
        pathType = TYPE_TML;
        int elementIdx = this.readMediaKey(core, this.pathElements, 1);
        elementIdx = this.readLayoutKey(core, this.pathElements, elementIdx);
        if (elementIdx < this.pathElements.size()) {
            this.contentKey = this.database.toLowerCaseMeta((String) this.pathElements.get(elementIdx));
        }
        if (this.layoutKey == null && this.contentKey == null) {
            this.pathType = TYPE_INVALID;
        }
    }

    // Retrieve the content
    if (getPathType() == WGPRequestPath.TYPE_TITLE_PATH) {
        this.content = getContentByTitlePath(request);
        if (this.content == null) {
            pathType = TYPE_UNKNOWN_CONTENT;
        }

        // If content was retrieved with struct key we check if the title path is correct. If not we force redirection to the correct version (#00003145)
        else if (getTitlePathURL().getStructKey() != null) {
            List<String> correctTitlePath = tpm.buildTitlePath(this.content, mediaKey.getKey(),
                    new RequestLanguageChooser(this.database, request));
            if (correctTitlePath == null || !correctTitlePath.equals(getTitlePathURL().getEncodedTitles())) {
                completePath = false;
            }
        }

        // If title path is configured to include keys but the current tp has no key we force redirection to the version including a key (#00003304).
        else if (tpm.isIncludeKeys()) {
            completePath = false;
        }
    } else if (getPathType() == TYPE_TML) {
        if (this.contentKey != null) {
            URLID contentid = new URLID(this.contentKey, this.database);
            boolean isBI = WGPDispatcher.isBrowserInterface(request.getSession())
                    || WGPDispatcher.isAuthoringMode(database.getDbReference(), request.getSession());
            this.content = WGPDispatcher.getContentByAnyKey(contentid, database,
                    new RequestLanguageChooser(database, request), isBI);
            if (this.content != null) {
                // Look if we really used the parsed content URLID information.
                if (!contentid.isCompleteFormat()) {
                    completePath = false;
                }
                this.requestLanguage = content.getLanguage().getName();
            } else {
                pathType = TYPE_UNKNOWN_CONTENT;
            }
        }

        // Contextless request. If we have no request language we have no complete path and we must determine a language
        else {
            if (requestLanguage == null) {
                completePath = false;
                LanguageBehaviour langBehaviour = LanguageBehaviourTools.retrieve(database);
                WGLanguage lang = langBehaviour.requestSelectDatabaseLanguage(database, request);
                if (lang != null) {
                    this.requestLanguage = lang.getName();
                }

                // Fallback to the database default language
                else {
                    this.requestLanguage = database.getDefaultLanguage();
                }
            }
        }
    }
}

From source file:com.janrain.backplane.server.Backplane1Controller.java

@ExceptionHandler
@ResponseBody/*from w w  w .j  av a 2 s .  c o  m*/
public Map<String, String> handle(final BackplaneServerException bse, HttpServletResponse response) {
    logger.error("Backplane server error: " + bse.getMessage(), bpConfig.getDebugException(bse));
    response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    return new HashMap<String, String>() {
        {
            put(ERR_MSG_FIELD, bpConfig.isDebugMode() ? bse.getMessage() : "Service unavailable");
        }
    };
}

From source file:br.gov.lexml.server.LexMLOAIHandler.java

/**
 * Peform the http GET action. Note that POST is shunted to here as well. The verb widget is
 * taken from the request and used to invoke an OAIVerb object of the corresponding kind to do
 * the actual work of the verb./* w  w  w.java 2 s  .  com*/
 * 
 * @param request the servlet's request information
 * @param response the servlet's response information
 * @exception IOException an I/O error occurred
 */
@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    // Fora gerao do cookie de sesso
    // (necessrio para balanceamento de carga pelo pound do Prodasen)
    request.getSession();

    HashMap attributes = getAttributes(request.getPathInfo());
    if (!filterRequest(request, response)) {
        return;
    }
    log.debug("attributes = " + attributes);
    Properties properties = (Properties) attributes.get("OAIHandler.properties");
    boolean monitor = false;
    if (properties.getProperty("OAIHandler.monitor") != null) {
        monitor = true;
    }
    boolean serviceUnavailable = isServiceUnavailable(properties);
    String extensionPath = properties.getProperty("OAIHandler.extensionPath", "/extension");

    HashMap serverVerbs = ServerVerb.getVerbs(properties);
    HashMap extensionVerbs = ServerVerb.getExtensionVerbs(properties);

    Transformer transformer = (Transformer) attributes.get("OAIHandler.transformer");

    boolean forceRender = false;
    if ("true".equals(properties.getProperty("OAIHandler.forceRender"))) {
        forceRender = true;
    }

    request.setCharacterEncoding("UTF-8");

    Date then = null;
    if (monitor) {
        then = new Date();
    }
    if (debug) {
        Enumeration headerNames = request.getHeaderNames();
        log.debug("OAIHandler.doGet: ");
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            log.debug(headerName + ": " + request.getHeader(headerName));
        }
    }
    if (serviceUnavailable) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "Sorry. This server is down for maintenance");
    } else {
        try {
            String userAgent = request.getHeader("User-Agent");
            if (userAgent == null) {
                userAgent = "";
            } else {
                userAgent = userAgent.toLowerCase();
            }
            Transformer serverTransformer = null;
            if (transformer != null) {

                // return HTML if the client is an old browser
                if (forceRender || userAgent.indexOf("opera") != -1
                        || userAgent.startsWith("mozilla") && userAgent.indexOf("msie 6") == -1
                /* && userAgent.indexOf("netscape/7") == -1 */) {
                    serverTransformer = transformer;
                }
            }
            String result = LexMLOAIHandler.getResult(attributes, request, response, serverTransformer,
                    serverVerbs, extensionVerbs, extensionPath);

            Writer out = LexMLOAIHandler.getWriter(request, response);
            out.write(result);
            out.flush();
            IOUtils.closeQuietly(out);
        } catch (FileNotFoundException e) {
            log.error("Falha no processamento.", e);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        } catch (Throwable e) {
            log.error("Falha no processamento.", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
    if (monitor) {
        StringBuffer reqUri = new StringBuffer(request.getRequestURI());
        String queryString = request.getQueryString(); // d=789
        if (queryString != null) {
            reqUri.append("?").append(queryString);
        }
        Runtime rt = Runtime.getRuntime();
        log.debug(rt.freeMemory() + "/" + rt.totalMemory() + " " + (new Date().getTime() - then.getTime())
                + "ms: " + reqUri.toString());
    }
}

From source file:com.alfaariss.oa.sso.web.profile.web.WebProfile.java

/**
 * Process the WebSSO HTTP requests.//  w w w.java  2  s  . co  m
 * <br><br>
 * All requests require a session: 
 * <ol>
 *  <li>Request attribute ({@link ISession#ID_NAME}=<code>session</code>)</li>
 *   <li>Request parameter ({@link ISession#ID_NAME}=<code>session id</code>)</li>
 * </ol> 
 * 
 * <h4>The following session states are processed:</h4>
 * <dl>
 *  <dt>{@link SessionState#SESSION_CREATED}, {@link SessionState#PRE_AUTHZ_IN_PROGRESS}</dt>
 *  <dd>Perform pre authorization</dd>
 *  <dt>{@link SessionState#PRE_AUTHZ_OK}</dt>
 *  <dd>Check SSO TGT</dd>
 *  <dt>{@link SessionState#AUTHN_SELECTION_IN_PROGRESS}</dt>
 *  <dd>Perform authenctication profile selection</dd>
 *  <dt>{@link SessionState#AUTHN_SELECTION_OK}, {@link SessionState#AUTHN_IN_PROGRESS}</dt>
 *  <dd>Perform authenctication profile selection</dd>
 *  <dt><code>default</code></dt>
 *  <dd>All other states are redirected back to the profile used</dd>
 * </dl>
 * 
 * @see com.alfaariss.oa.api.IService#service(
 *  javax.servlet.http.HttpServletRequest, 
 *  javax.servlet.http.HttpServletResponse)
 */
@Override
public void service(HttpServletRequest oRequest, HttpServletResponse oResponse) throws OAException {
    ISession oSession = null;
    try {
        if (!_bStarted) //Check sso state
        {
            oResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }

        //Disable caching
        HttpUtils.setDisableCachingHttpHeaders(oRequest, oResponse);

        //retrieve session attribute (trusted)
        oSession = (ISession) oRequest.getAttribute(ISession.ID_NAME);

        if (oSession == null) //No session found yet
        {
            //Retrieve session id (not trusted)
            String sId = oRequest.getParameter(ISession.ID_NAME);
            if (sId != null) {
                //TODO session id as cookie? (Erwin)
                if (!SessionValidator.validateDefaultSessionId(sId)) {
                    _systemLogger.warn("Invalid session id in request: " + sId);
                    throw new UserException(UserEvent.REQUEST_INVALID);
                }
                oSession = _ssoService.getSession(sId);
            }
            if (oSession == null) //No session found
            {
                //Show default page
                _systemLogger.debug("No valid session found");
                handleStartPage(oRequest, oResponse);
            }
        }

        if (oSession != null) //Session found
        {
            //Check session expiration
            if (oSession.isExpired()) {
                throw new UserException(UserEvent.SESSION_EXPIRED);
            }

            //Check cancelled
            if (oRequest.getParameter("cancel") != null) {
                try {
                    oSession.setState(SessionState.USER_CANCELLED);
                    oSession.persist();
                    _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(),
                            UserEvent.USER_CANCELLED, this, null));
                } catch (OAException e) {
                    _systemLogger.warn("Could not store session");
                    //Wrap exception
                    throw new SSOException(e.getCode(), e);
                }
            }

            /* dopey adds: change locate from request */
            if (oRequest.getParameter(PARAMETER_LANGUAGE_LOCALE) != null) {
                String sNewLocale = oRequest.getParameter(PARAMETER_LANGUAGE_LOCALE);
                if (!sNewLocale.equals("")) {
                    oSession.setLocale(new Locale(sNewLocale));
                    oSession.persist();
                    _systemLogger.info("User changed session 'locale_language' to " + sNewLocale);
                }
            }
            /* end-of-locale-updates */

            RequestorPool oRequestorPool = _ssoService.getRequestorPool(oSession);
            if (oRequestorPool == null) {
                _systemLogger.warn(new SystemLogItem(oSession.getId(), SystemErrors.ERROR_INTERNAL,
                        "Could not retrieve requestor pool from session"));
                throw new SSOException(SystemErrors.ERROR_INTERNAL);
            }

            //switch state
            switch (oSession.getState()) {
            case SESSION_CREATED: {
                List<IAuthenticationProfile> listAuthNProfiles = _ssoService
                        .getAllAuthNProfiles(oRequestorPool);
                if (listAuthNProfiles.isEmpty()) {
                    //DD A requestor pool must be configured with one or more authN profiles 
                    _systemLogger.warn("Not one enabled authentication profile for requestor pool: "
                            + oRequestorPool.getID());
                    throw new SSOException(SystemErrors.ERROR_INTERNAL);
                }

                oSession.setAuthNProfiles(listAuthNProfiles);
                oSession.setState(SessionState.PRE_AUTHZ_IN_PROGRESS);

                if (oRequestorPool.isForcedAuthenticate()) {
                    oSession.setForcedAuthentication(true);
                    _systemLogger.debug("Forced by requestor pool: Force authentication");
                }

                handlePreAuthorization(oRequest, oResponse, oSession, oRequestorPool);
                break;
            }
            case PRE_AUTHZ_IN_PROGRESS: {
                handlePreAuthorization(oRequest, oResponse, oSession, oRequestorPool);
                break;
            }
            case PRE_AUTHZ_OK: {
                checkTGT(oRequest, oResponse, oSession, oRequestorPool);
                break;
            }
            case AUTHN_SELECTION_IN_PROGRESS: {
                handleAuthenticationSelection(oRequest, oResponse, oSession, oRequestorPool);
                break;
            }
            case AUTHN_SELECTION_OK:
            case AUTHN_IN_PROGRESS: {
                handleAuthentication(oRequest, oResponse, oSession, oRequestorPool,
                        oSession.getSelectedAuthNProfile());
                break;
            }
            case POST_AUTHZ_IN_PROGRESS: {
                //handle post authz
                handlePostAuthorization(oRequest, oResponse, oSession, oRequestorPool);
                break;
            }
            case POST_AUTHZ_OK:
            case POST_AUTHZ_FAILED:
            case PRE_AUTHZ_FAILED:
            case AUTHN_SELECTION_FAILED:
            case AUTHN_OK:
            case USER_CANCELLED:
            case AUTHN_FAILED:
            case AUTHN_NOT_SUPPORTED:
            case USER_BLOCKED:
            case USER_UNKNOWN:
            default: //Redirect to profile
            {
                _systemLogger.debug(
                        new SystemLogItem(oSession.getId(), SystemErrors.OK, "Redirect back to Profile"));
                oResponse.sendRedirect(oSession.getProfileURL());
                break;
            }
            }
        }
    } catch (UserException e) //User error
    {
        if (oSession != null)
            _eventLogger
                    .info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), e.getEvent(), this, null));
        else
            _eventLogger.info(new UserEventLogItem(null, null, null, e.getEvent(), null,
                    oRequest.getRemoteAddr(), null, this, null));

        if (!oResponse.isCommitted()) {
            try {
                oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } catch (IOException e1) {
                _systemLogger.warn("Could not send response", e1);
            }
        }
    } catch (SSOException e) //Internal error in websso
    {
        //Log to event logging
        if (oSession != null) {
            _eventLogger.info(new UserEventLogItem(oSession, oRequest.getRemoteAddr(), UserEvent.INTERNAL_ERROR,
                    this, null));
        } else {
            _eventLogger.info(new UserEventLogItem(null, null, null, UserEvent.INTERNAL_ERROR, null,
                    oRequest.getRemoteAddr(), null, this, null));
        }
        handleError(oRequest, oResponse, oSession, e, e.getCode());
    } catch (OAException e) //Internal error in methods
    {
        handleError(oRequest, oResponse, oSession, e, e.getCode());
    } catch (Exception e) //Internal error 
    {
        handleError(oRequest, oResponse, oSession, e, SystemErrors.ERROR_INTERNAL);
    }
}