Example usage for javax.servlet.http HttpServletRequest getServerName

List of usage examples for javax.servlet.http HttpServletRequest getServerName

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getServerName.

Prototype

public String getServerName();

Source Link

Document

Returns the host name of the server to which the request was sent.

Usage

From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 *
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @param httpServletRequest Request object pertaining to the proxied HTTP request
 * @throws IOException      Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 *//*from w ww.  ja v a 2 s  . c o  m*/
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    getCredential(httpServletRequest.getParameter("servername"));
    if (credentials != null) {
        httpClient.getParams().setAuthenticationPreemptive(true);
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    httpMethodProxyRequest.setFollowRedirects(true);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    String response = httpMethodProxyRequest.getResponseBodyAsString();

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES
            /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        if (followRedirects) {
            if (stringLocation.contains("jsessionid")) {
                Cookie cookie = new Cookie("JSESSIONID",
                        stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11));
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL");
            } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) {
                Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie");
                String[] cookieDetails = header.getValue().split(";");
                String[] nameValue = cookieDetails[0].split("=");

                Cookie cookie = new Cookie(nameValue[0], nameValue[1]);
                cookie.setPath("/");
                //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath());
                httpServletResponse.addCookie(cookie);
            }
            httpServletResponse.sendRedirect(stringLocation
                    .replace(getProxyHostAndPort(httpServletRequest) + this.getProxyPath(), stringMyHostName));
            return;
        }
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header
                header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    if (isBodyParameterGzipped(responseHeaders)) {
        debug("GZipped: true");
        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            response = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(STRING_LOCATION_HEADER, response);
        } else {
            response = new String(ungzip(httpMethodProxyRequest.getResponseBody()));
        }
        httpServletResponse.setContentLength(response.length());
    }

    // Send the content to the client
    if (intProxyResponseCode == 200)
        httpServletResponse.getWriter().write(response);
    else
        httpServletResponse.getWriter().write(intProxyResponseCode);
}

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

/**
 * PAAA services/*from w  w w  . ja v  a  2  s  .  co  m*/
 */
private void provideService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        String format, String patronid, String token, String service) throws IOException {

    String baseurl = httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort();
    this.logger.info("[" + config.getProperty("service.name") + "] " + "baseurl = " + baseurl);

    ObjectMapper mapper = new ObjectMapper();

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

        try {
            IntegratedLibrarySystem integratedLibrarySystem = Lookup.lookup(IntegratedLibrarySystem.class);
            // init ILS
            integratedLibrarySystem.init(this.config);

            switch (service) {

            case "signup": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2create = mapper.readValue(jb.toString(), Patron.class);
                if (patron2create.getAccount() == null || patron2create.getAccount().equals("")) {
                    if (!patronid.equals("")) {
                        patron2create.setAccount(patronid);
                    } else {
                        patron2create.setAccount(UUID.randomUUID().toString());
                    }
                }

                patron = integratedLibrarySystem.signup(patron2create);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

                    Block block = new Block();
                    LocalDateTime timePoint = LocalDateTime.now();
                    block.setDate(timePoint.getYear() + "-"
                            + (timePoint.getMonthValue() < 10 ? "0" + timePoint.getMonthValue()
                                    : timePoint.getMonthValue())
                            + "-" + (timePoint.getDayOfMonth() < 10 ? "0" + timePoint.getDayOfMonth()
                                    : timePoint.getDayOfMonth()));
                    block.setKey("93");
                    integratedLibrarySystem.blockpatron(patron, block);

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

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

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

                    // 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"));

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

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

                break;
            }
            case "newpatron": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2create = mapper.readValue(jb.toString(), Patron.class);
                patron2create.setAccount(patronid);

                patron = integratedLibrarySystem.newpatron(patron2create);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

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

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

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

                    // 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"));

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

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

                break;
            }
            case "updatepatron": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2update = mapper.readValue(jb.toString(), Patron.class);
                patron2update.setAccount(patronid);

                // TODO Was tun bei nderung des 'status'?

                patron = integratedLibrarySystem.updatepatron(patron2update);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

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

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

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

                    // 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"));

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

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

                break;
            }
            case "blockpatron": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2block = new Patron();
                patron2block.setAccount(patronid);
                Block block = mapper.readValue(jb.toString(), Block.class);

                patron = integratedLibrarySystem.blockpatron(patron2block, block);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

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

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

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

                    // 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"));

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

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

                break;
            }
            case "unblockpatron": {

                Patron patron = null;

                // read Patron
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                Patron patron2unblock = new Patron();
                patron2unblock.setAccount(patronid);
                Block block = mapper.readValue(jb.toString(), Block.class);

                patron = integratedLibrarySystem.unblockpatron(patron2unblock, block);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

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

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

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

                    // 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"));

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

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

                break;
            }
            case "deletepatron": {

                Patron patron = null;

                Patron patron2delete = new Patron();
                patron2delete.setAccount(patronid);

                patron = integratedLibrarySystem.deletepatron(patron2delete);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");

                if (patron != null) {

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

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

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

                    // 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"));

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

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

                break;
            }
            case "newfee": {

                Patron patron = null;
                Fee resultFee = null;

                patron = new Patron();
                patron.setAccount(patronid);

                // read Fee
                StringBuffer jb = new StringBuffer();
                String line = null;
                try {
                    BufferedReader reader = httpServletRequest.getReader();
                    while ((line = reader.readLine()) != null)
                        jb.append(line);
                } catch (Exception e) {
                    /*report an error*/ }

                this.logger.debug("[" + config.getProperty("service.name") + "] " + "Fee = " + jb);

                Fee fee = mapper.readValue(jb.toString(), Fee.class);

                resultFee = integratedLibrarySystem.newfee(patron, fee);

                this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '"
                        + service + "' event for patron '" + patronid + "' >>> success!");
                StringWriter stringWriter = new StringWriter();
                mapper.writeValue(stringWriter, resultFee);
                this.logger.debug(
                        "[" + config.getProperty("service.name") + "] " + "Fee: " + stringWriter.toString());

                if (patron != null) {

                    StringWriter json = new StringWriter();
                    mapper.writeValue(json, resultFee);
                    this.logger.debug(json);

                    // If request contains parameter 'redirect_uri', then redirect mit access_token and patronid
                    if (httpServletRequest.getParameter("redirect_uri") != null) {
                        this.logger.debug("[" + config.getProperty("service.name") + "] " + "REDIRECT? "
                                + httpServletRequest.getParameter("redirect_uri"));

                        httpServletResponse.sendRedirect(httpServletRequest.getParameter("redirect_uri")
                                + "&patron=" + patronid + "&token=" + token);
                    } else {
                        httpServletResponse.setContentType("application/json");
                        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
                        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                        httpServletResponse.getWriter().println(json);
                    }
                } else {
                    this.logger.error("[" + config.getProperty("service.name") + "] "
                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": ILS!");

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

                    // 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"));

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

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

                break;
            }
            default: {
                // TODO: keine gltige Funktion
            }
            }
        } catch (ILSException e) {

            this.logger.info("[" + config.getProperty("service.name") + "] " + token + " performed '" + service
                    + "' event for patron '" + patronid + "' >>> failed!");
            this.logger.error("[" + config.getProperty("service.name") + "] "
                    + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": ILS Error! " + e.getMessage());

            // TODO e.getMessage = 403
            if (e.getMessage().equals("403")) {

                // TODO >> properties
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                httpServletResponse.setContentType("application/json");
                httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                // 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)));
                requestError.setCode(HttpServletResponse.SC_FORBIDDEN);
                requestError.setDescription(this.config.getProperty(
                        "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".description"));
                requestError.setErrorUri(this.config
                        .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".uri"));

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

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

                // Mail to Bib-IT wg. Socket-Error
                try {

                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);

                    Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf"));
                    mailer.postMail(
                            "[" + this.config.getProperty("service.name") + "] ILS Error! " + e.getMessage(),
                            sw.toString());

                } catch (MessagingException | IOException e1) {

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

                // TODO >> properties
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer");
                httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAAA\"");
                httpServletResponse.setContentType("application/json");
                httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

                // 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"));

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

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

        this.logger.error("[" + config.getProperty("service.name") + "] "
                + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!");

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

        // 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"));

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

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

}

From source file:org.xmlactions.web.conceal.HttpPager.java

public SessionExecContext setupExecContext(HttpServletRequest request, HttpServletResponse response)
        throws IOException, FileUploadException {

    ApplicationContext applicationContext = getApplicationContext(request.getSession(true).getServletContext());

    SessionExecContext execContext = (SessionExecContext) applicationContext
            .getBean(ActionConst.EXEC_CONTEXT_BEAN_REF);

    new CreateHandyParams(execContext);

    // Make it available for the scope of this request.
    RequestExecContext.set(execContext);

    execContext.setApplicationContext(applicationContext);

    execContext.put(ActionConst.WEB_REAL_PATH_BEAN_REF, realPath);
    execContext.put(ActionConst.PAGE_NAMESPACE_BEAN_REF, nameSpace);

    execContext.setSession(request.getSession(true));
    execContext.loadFromPersistence();/*from   w  w w.j a va 2  s . c  o m*/
    execContext.addNamedMap(IExecContext.PERSISTENCE_MAP, execContext.getPersistenceMap());
    new CreateUserParams(execContext);

    // FIXME - will want to remove the addNamedMap("request")
    Map<String, Object> params = new HtmlRequestMapper(-1).getRequestParamsAsMap(request);
    if (params != null) {
        execContext.addNamedMap(PagerWebConst.REQUEST, params);
    }
    List<HttpParam> paramList = new HtmlRequestMapper(-1).getRequestParamsAsVector(request);
    if (paramList != null) {
        execContext.put(PagerWebConst.REQUEST_LIST, paramList);
    }
    String pageName = request.getServletPath();
    // remove the leading slash/
    execContext.put(PagerWebConst.PAGE_NAME, (pageName.length() > 1 ? pageName.substring(1) : pageName));
    execContext.put(PagerWebConst.PAGE_URI, request.getRequestURI());
    execContext.put(PagerWebConst.PAGE_URL, request.getRequestURL().toString());
    execContext.put(PagerWebConst.PAGE_SERVER_NAME, request.getServerName());
    String appName = getAppName(request.getRequestURI());
    execContext.put(PagerWebConst.PAGE_APP_NAME, appName);
    if (StringUtils.isEmpty(appName)) {
        execContext.put(ActionConst.WEB_ROOT_BEAN_REF, "");
    } else {
        execContext.put(ActionConst.WEB_ROOT_BEAN_REF, "/" + appName);
    }
    execContext.put(PagerWebConst.HTTP_REQUEST, request);
    execContext.put(PagerWebConst.HTTP_RESPONSE, response);
    execContext.put(PagerWebConst.HTTP_SESSION, request.getSession(true));
    execContext.put(PagerWebConst.EXEC_CONTEXT, execContext);

    // log.debug(((PropertyContainer)
    // webApplicationContext.getBean("readOnlyProperties")).get("user.home"));
    log.debug("nameSpace:" + nameSpace);
    log.debug("Real Path:" + realPath);
    log.debug("bean count:" + execContext.getApplicationContext().getBeanDefinitionCount());
    for (String beanName : applicationContext.getBeanDefinitionNames()) {
        log.debug("bean:" + beanName);
        execContext.put(beanName, applicationContext.getBean(beanName));
    }

    execContext.addNamedMap(PagerWebConst.REQUEST_HEADERS, HttpSessionInfo.getRequestHeaders(request));

    log.info("ExecContext size:" + execContext.size());

    return execContext;
}

From source file:com.joseflavio.uxiamarelo.servlet.UxiAmareloServlet.java

@Override
protected void doPost(HttpServletRequest requisicao, HttpServletResponse resposta)
        throws ServletException, IOException {

    String tipo = requisicao.getContentType();
    if (tipo == null || tipo.isEmpty())
        tipo = "text/plain";

    String codificacao = requisicao.getCharacterEncoding();
    if (codificacao == null || codificacao.isEmpty())
        codificacao = "UTF-8";

    resposta.setCharacterEncoding(codificacao);
    PrintWriter saida = resposta.getWriter();

    try {/*from  www . j  a va2 s.  co  m*/

        JSON json;

        if (tipo.contains("json")) {
            json = new JSON(IOUtils.toString(requisicao.getInputStream(), codificacao));
        } else {
            json = new JSON();
        }

        Enumeration<String> parametros = requisicao.getParameterNames();

        while (parametros.hasMoreElements()) {
            String chave = parametros.nextElement();
            String valor = URLDecoder.decode(requisicao.getParameter(chave), codificacao);
            json.put(chave, valor);
        }

        if (tipo.contains("multipart")) {

            Collection<Part> arquivos = requisicao.getParts();

            if (!arquivos.isEmpty()) {

                File diretorio = new File(uxiAmarelo.getDiretorio());

                if (!diretorio.isAbsolute()) {
                    diretorio = new File(requisicao.getServletContext().getRealPath("") + File.separator
                            + uxiAmarelo.getDiretorio());
                }

                if (!diretorio.exists())
                    diretorio.mkdirs();

                String diretorioStr = diretorio.getAbsolutePath();

                String url = uxiAmarelo.getDiretorioURL();

                if (uxiAmarelo.isDiretorioURLRelativo()) {
                    String url_esquema = requisicao.getScheme();
                    String url_servidor = requisicao.getServerName();
                    int url_porta = requisicao.getServerPort();
                    String url_contexto = requisicao.getContextPath();
                    url = url_esquema + "://" + url_servidor + ":" + url_porta + url_contexto + "/" + url;
                }

                if (url.charAt(url.length() - 1) == '/') {
                    url = url.substring(0, url.length() - 1);
                }

                Map<String, List<JSON>> mapa_arquivos = new HashMap<>();

                for (Part arquivo : arquivos) {

                    String chave = arquivo.getName();
                    String nome_original = getNome(arquivo, codificacao);
                    String nome = nome_original;

                    if (nome == null || nome.isEmpty()) {
                        try (InputStream is = arquivo.getInputStream()) {
                            String valor = IOUtils.toString(is, codificacao);
                            valor = URLDecoder.decode(valor, codificacao);
                            json.put(chave, valor);
                            continue;
                        }
                    }

                    if (uxiAmarelo.getArquivoNome().equals("uuid")) {
                        nome = UUID.randomUUID().toString();
                    }

                    while (new File(diretorioStr + File.separator + nome).exists()) {
                        nome = UUID.randomUUID().toString();
                    }

                    arquivo.write(diretorioStr + File.separator + nome);

                    List<JSON> lista = mapa_arquivos.get(chave);

                    if (lista == null) {
                        lista = new LinkedList<>();
                        mapa_arquivos.put(chave, lista);
                    }

                    lista.add((JSON) new JSON().put("nome", nome_original).put("endereco", url + "/" + nome));

                }

                for (Entry<String, List<JSON>> entrada : mapa_arquivos.entrySet()) {
                    List<JSON> lista = entrada.getValue();
                    if (lista.size() > 1) {
                        json.put(entrada.getKey(), lista);
                    } else {
                        json.put(entrada.getKey(), lista.get(0));
                    }
                }

            }

        }

        String copaiba = (String) json.remove("copaiba");
        if (StringUtil.tamanho(copaiba) == 0) {
            throw new IllegalArgumentException("copaiba = nome@classe@metodo");
        }

        String[] copaibaParam = copaiba.split("@");
        if (copaibaParam.length != 3) {
            throw new IllegalArgumentException("copaiba = nome@classe@metodo");
        }

        String comando = (String) json.remove("uxicmd");
        if (StringUtil.tamanho(comando) == 0)
            comando = null;

        if (uxiAmarelo.isCookieEnviar()) {
            Cookie[] cookies = requisicao.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    String nome = cookie.getName();
                    if (uxiAmarelo.cookieBloqueado(nome))
                        continue;
                    if (!json.has(nome)) {
                        try {
                            json.put(nome, URLDecoder.decode(cookie.getValue(), "UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            json.put(nome, cookie.getValue());
                        }
                    }
                }
            }
        }

        if (uxiAmarelo.isEncapsulamentoAutomatico()) {
            final String sepstr = uxiAmarelo.getEncapsulamentoSeparador();
            final char sep0 = sepstr.charAt(0);
            for (String chave : new HashSet<>(json.keySet())) {
                if (chave.indexOf(sep0) == -1)
                    continue;
                String[] caminho = chave.split(sepstr);
                if (caminho.length > 1) {
                    Util.encapsular(caminho, json.remove(chave), json);
                }
            }
        }

        String resultado;

        if (comando == null) {
            try (CopaibaConexao cc = uxiAmarelo.conectarCopaiba(copaibaParam[0])) {
                resultado = cc.solicitar(copaibaParam[1], json.toString(), copaibaParam[2]);
                if (resultado == null)
                    resultado = "";
            }
        } else if (comando.equals("voltar")) {
            resultado = json.toString();
            comando = null;
        } else {
            resultado = "";
        }

        if (comando == null) {

            resposta.setStatus(HttpServletResponse.SC_OK);
            resposta.setContentType("application/json");

            saida.write(resultado);

        } else if (comando.startsWith("redirecionar")) {

            resposta.sendRedirect(Util.obterStringDeJSON("redirecionar", comando, resultado));

        } else if (comando.startsWith("base64")) {

            String url = comando.substring("base64.".length());

            resposta.sendRedirect(url + Base64.getUrlEncoder().encodeToString(resultado.getBytes("UTF-8")));

        } else if (comando.startsWith("html_url")) {

            HttpURLConnection con = (HttpURLConnection) new URL(
                    Util.obterStringDeJSON("html_url", comando, resultado)).openConnection();
            con.setRequestProperty("User-Agent", "Uxi-amarelo");

            if (con.getResponseCode() != HttpServletResponse.SC_OK)
                throw new IOException("HTTP = " + con.getResponseCode());

            resposta.setStatus(HttpServletResponse.SC_OK);
            resposta.setContentType("text/html");

            try (InputStream is = con.getInputStream()) {
                saida.write(IOUtils.toString(is));
            }

            con.disconnect();

        } else if (comando.startsWith("html")) {

            resposta.setStatus(HttpServletResponse.SC_OK);
            resposta.setContentType("text/html");

            saida.write(Util.obterStringDeJSON("html", comando, resultado));

        } else {

            throw new IllegalArgumentException(comando);

        }

    } catch (Exception e) {

        resposta.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resposta.setContentType("application/json");

        saida.write(Util.gerarRespostaErro(e).toString());

    }

    saida.flush();

}

From source file:com.boylesoftware.web.impl.AbstractRouterConfiguration.java

@Override
public String getRouteURI(final HttpServletRequest request, final String routeId, final URIType type,
        final String... uriParams) {

    // find mapping
    final RouteImpl mapping = this.mappingsById.get(routeId);
    if (mapping == null)
        throw new IllegalArgumentException("No mapping for route id " + routeId + ".");

    // check number of provided URI parameters
    final int numURIParams = mapping.getNumURIParams();
    if (numURIParams != uriParams.length)
        throw new IllegalArgumentException(
                "Number of URI parameters does" + " not match the route mapping's URI pattern.");

    // build the URI
    try (final PooledStringBuffer buf = StringBufferPool.get()) {

        // build server root relative URI
        final String uriTmpl = mapping.getURITemplate();
        final String relativeURI = (numURIParams > 0 ? this.replaceURIPlaceholders(uriTmpl, uriParams, buf)
                : uriTmpl);//from w ww.j  av a2 s  .c  om

        // determine if SSL is needed
        final boolean needsSSL = ((type == URIType.FORCE_SSL) || (type == URIType.FORCE_ABSOLUTE_SSL)
                || ((type == URIType.DEFAULT) && ((mapping.getSecurityMode() != SecurityMode.DEFAULT)
                        || this.isAuthenticationRequired(relativeURI))));

        // is server root relative URI OK?
        final boolean secureRequest = request.isSecure();
        final boolean authedRequest = (request.getAttribute(Attributes.AUTHED_USER) != null);
        if ((type != URIType.FORCE_ABSOLUTE_PLAIN) && (type != URIType.FORCE_ABSOLUTE_SSL)
                && ((!needsSSL && !(secureRequest && ((type == URIType.FORCE_PLAIN) || !authedRequest)))
                        || (needsSSL && secureRequest)))
            return relativeURI;

        // build full URL
        final StringBuilder urlSB = buf.getStringBuilder();
        urlSB.setLength(0);
        if (needsSSL)
            urlSB.append("https://");
        else
            urlSB.append("http://");
        urlSB.append(request.getServerName());
        final int httpsPort = this.webapp.getHTTPSPort();
        final int httpPort = this.webapp.getHTTPPort();
        if (needsSSL && (httpsPort != 443))
            urlSB.append(':').append(httpsPort);
        else if (!needsSSL && (httpPort != 80))
            urlSB.append(':').append(httpPort);
        urlSB.append(relativeURI);

        // return it
        return urlSB.toString();
    }
}

From source file:com.squid.kraken.v4.auth.OAuth2LoginServlet.java

/**
 * Perform the login action via API calls.
 *
 * @param request//from  w w  w .  jav a2 s  . com
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void login(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, URISyntaxException {
    String responseType = request.getParameter(RESPONSE_TYPE);
    if (responseType == null) {
        responseType = RESPONSE_TYPE_TOKEN;
    }
    String customerId = request.getParameter(CUSTOMER_ID);

    // create a POST method to execute the login request
    HttpPost post;
    List<NameValuePair> values = new ArrayList<NameValuePair>();
    if (responseType.equals(RESPONSE_TYPE_TOKEN)) {
        post = new HttpPost(privateServerURL + V4_RS_AUTH_TOKEN);
    } else {
        post = new HttpPost(privateServerURL + V4_RS_AUTH_CODE);
    }
    if (StringUtils.isNotBlank(customerId)) {
        values.add(new BasicNameValuePair(CUSTOMER_ID, customerId));
    }
    if (request.getParameter(CLIENT_ID) != null) {
        values.add(new BasicNameValuePair(CLIENT_ID, request.getParameter(CLIENT_ID)));
    }

    // get login and pwd either from the request or from the session
    HttpSession session = request.getSession(false);
    String login = request.getParameter(LOGIN);
    if ((session != null) && (login == null)) {
        login = (String) session.getAttribute(LOGIN);
        session.setAttribute(LOGIN, null);
    }
    String password = request.getParameter(PASSWORD);
    if ((session != null) && (password == null)) {
        password = (String) session.getAttribute(PASSWORD);
        session.setAttribute(PASSWORD, null);
    }

    boolean isSso = false;
    String redirectUri = null;
    if (request.getParameter(REDIRECT_URI) != null) {
        redirectUri = request.getParameter(REDIRECT_URI).trim();
        values.add(new BasicNameValuePair(REDIRECT_URI, redirectUri));
        isSso = isSso(request, redirectUri);
    }

    if (isSso == false && ((login == null) || (password == null))) {
        showLogin(request, response);
    } else {
        if (isSso == false) {
            values.add(new BasicNameValuePair(LOGIN, login));
            values.add(new BasicNameValuePair(PASSWORD, password));
        } else {
            String uri = request.getScheme() + "://" + request.getServerName()
                    + ("http".equals(request.getScheme()) && request.getServerPort() == 80
                            || "https".equals(request.getScheme()) && request.getServerPort() == 443 ? ""
                                    : ":" + request.getServerPort());
            post = new HttpPost(uri + V4_RS_SSO_TOKEN);
            if (values != null) {
                URL url = new URL(redirectUri);
                values = getQueryPairs(getRedirectParameters(url.getQuery()));
            }
        }
        post.setEntity(new UrlEncodedFormEntity(values));
        try {
            String redirectUrl = redirectUri;
            // T489 remove any trailing #
            if (redirectUrl.endsWith("#")) {
                redirectUrl = redirectUrl.substring(0, redirectUrl.length() - 1);
            }
            if (responseType.equals(RESPONSE_TYPE_TOKEN)) {
                // token type
                // execute the login request
                AccessToken token = RequestHelper.processRequest(AccessToken.class, request, post);
                String tokenId = token.getId().getTokenId();
                // redirect URL
                if (redirectUrl.contains(ACCESS_TOKEN_PARAM_PATTERN)) {
                    // replace access_token parameter pattern
                    redirectUrl = StringUtils.replace(redirectUrl, ACCESS_TOKEN_PARAM_PATTERN, tokenId);
                } else {
                    // append access_token anchor
                    redirectUrl += (!redirectUrl.contains("?")) ? "?" : "&";
                    redirectUrl += ACCESS_TOKEN + "=" + tokenId;
                }
            } else {
                // auth code type
                // execute the login request
                AuthCode codeObj = RequestHelper.processRequest(AuthCode.class, request, post);
                String code = codeObj.getCode();
                if (redirectUrl.contains(AUTH_CODE_PARAM_PATTERN)) {
                    // replace code parameter pattern
                    redirectUrl = StringUtils.replace(redirectUrl, AUTH_CODE_PARAM_PATTERN, code);
                } else {
                    // append code param
                    redirectUrl += (!redirectUrl.contains("?")) ? "?" : "&";
                    redirectUrl += AUTH_CODE + "=" + code;
                }
            }
            response.sendRedirect(redirectUrl);
        } catch (ServerUnavailableException e1) {
            // Authentication server unavailable
            logger.error(e1.getLocalizedMessage());
            request.setAttribute(KRAKEN_UNAVAILABLE, Boolean.TRUE);
            showLogin(request, response);
            return;
        } catch (ServiceException e2) {
            WebServicesException exception = e2.getWsException();
            if (exception != null) {
                if (exception.getCustomers() != null) {
                    // multiple customers found
                    request.setAttribute(DUPLICATE_USER_ERROR, Boolean.TRUE);
                    request.setAttribute(CUSTOMERS_LIST, exception.getCustomers());
                    // save the credentials for later use
                    request.getSession().setAttribute(LOGIN, login);
                    request.getSession().setAttribute(PASSWORD, password);
                } else {
                    String errorMessage = exception.getError();
                    if (!errorMessage.contains("Password")) {
                        request.setAttribute(ERROR, exception.getError());
                    } else {
                        request.setAttribute(ERROR, Boolean.TRUE);
                    }
                }
            } else {
                request.setAttribute(ERROR, Boolean.TRUE);
            }
            // forward to login page
            showLogin(request, response);
            return;
        } catch (SSORedirectException error) {
            response.sendRedirect(error.getRedirectURL());
        }

    }
}

From source file:freeciv.servlet.ProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse An object by which we can send the proxied
 *                             response back to the client
 * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 */// w w  w .  j a v a 2 s.  com
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {

    httpMethodProxyRequest.setFollowRedirects(false);
    String port = "" + httpServletRequest.getSession().getAttribute("civserverport");
    String host = "" + httpServletRequest.getSession().getAttribute("civserverhost");
    String username = "" + httpServletRequest.getSession().getAttribute("username");
    httpMethodProxyRequest.addRequestHeader("civserverport", port);
    httpMethodProxyRequest.addRequestHeader("civserverhost", host);
    httpMethodProxyRequest.addRequestHeader("username", username);
    int intProxyResponseCode = 0;
    // Execute the request
    try {
        intProxyResponseCode = client.executeMethod(httpMethodProxyRequest);
    } catch (IOException ioErr) {
        //- If an I/O (transport) error occurs. Some transport exceptions can be recovered from. 
        //- If a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        httpServletResponse.setStatus(502);
        outputStreamClientResponse
                .write("Freeciv web client proxy not responding (most likely died).".getBytes());
        httpMethodProxyRequest.releaseConnection();
        return;
    }

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            httpMethodProxyRequest.releaseConnection();
            throw new ServletException("Recieved status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        httpServletResponse.sendRedirect(
                stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName));
        httpMethodProxyRequest.releaseConnection();
        return;
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        httpMethodProxyRequest.releaseConnection();
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        httpServletResponse.setHeader(header.getName(), header.getValue());
    }

    // Send the content to the client
    InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);
    OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
    int intNextByte;
    while ((intNextByte = bufferedInputStream.read()) != -1) {
        outputStreamClientResponse.write(intNextByte);
    }
    httpMethodProxyRequest.releaseConnection();
}

From source file:com.redhat.rhn.frontend.action.user.CreateUserAction.java

/** {@inheritDoc} */
public ActionForward execute(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
        HttpServletResponse response) {//from  w  ww .  j  a  va  2s. c  o  m

    RequestContext requestContext = new RequestContext(request);

    DynaActionForm form = (DynaActionForm) formIn;

    /*
     * If the usepam checkbox has been checked, the password fields aren't required.
     * Since password is required in the db and since in all other cases it is required,
     * we'll trick the validation by doing all of the manipulation before validating
     * the form.
     *
     * Also, if the user for some reason does want to set a default password to stick
     * in the db (even though it won't be used), we'll just validate it like a regular
     * password and allow it.
     */
    if (form.get("usepam") != null && ((Boolean) form.get("usepam")).booleanValue()) {
        String hash = MD5Crypt.crypt("" + System.currentTimeMillis());
        if (form.get(UserActionHelper.DESIRED_PASS) == null
                || form.get(UserActionHelper.DESIRED_PASS).equals("")) {
            form.set(UserActionHelper.DESIRED_PASS, hash);
        }
        if (form.get(UserActionHelper.DESIRED_PASS_CONFIRM) == null
                || form.get(UserActionHelper.DESIRED_PASS_CONFIRM).equals("")) {
            form.set(UserActionHelper.DESIRED_PASS_CONFIRM, hash);
        }
    }

    // Validate the form
    ActionErrors verrors = RhnValidationHelper.validateDynaActionForm(this, form);
    if (!verrors.isEmpty()) {
        RhnValidationHelper.setFailedValidation(request);
        return returnError(mapping, request, verrors);
    }

    // Create the user and do some more validation
    CreateUserCommand command = getCommand();
    ActionErrors errors = populateCommand(form, command);
    if (!errors.isEmpty()) {
        return returnError(mapping, request, errors);
    }

    String accountType = (String) form.get(ACCOUNT_TYPE);
    if (!validateAccountType(accountType)) {
        return returnError(mapping, request, errors);
    }

    ActionMessages msgs = new ActionMessages();

    if (accountType.equals(TYPE_INTO_ORG)) {
        User user = createIntoOrg(requestContext, command, (String) form.get(UserActionHelper.DESIRED_PASS),
                msgs);
        User orgAdmin = requestContext.getCurrentUser();
        saveMessages(request, msgs);
        command.publishNewUserEvent(orgAdmin, orgAdmin.getOrg().getActiveOrgAdmins(), request.getServerName(),
                (String) form.get(UserActionHelper.DESIRED_PASS));

        user.setTimeZone(UserManager.getTimeZone(((Integer) form.get("timezone")).intValue()));
        String preferredLocale = form.getString("preferredLocale");
        if (preferredLocale != null && preferredLocale.equals("none")) {
            preferredLocale = null;
        }
        user.setPreferredLocale(preferredLocale);
        user.setReadOnly(form.get("readonly") != null ? true : false);
        UserManager.storeUser(user);

        return getStrutsDelegate().forwardParam(mapping.findForward(SUCCESS_INTO_ORG), "uid",
                String.valueOf(user.getId()));

    } else if (accountType.equals(TYPE_CREATE_SAT)) {
        User user = createSatUser(requestContext, command, msgs);
        saveMessages(request, msgs);
        pxtDelegate.updateWebUserId(request, response, user.getId());
        return mapping.findForward(SUCCESS_SAT);
    }

    // we're screwed if we get this far
    return mapping.findForward(FAILURE);
}