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:be.fedict.eid.idp.sp.protocol.openid.AuthenticationRequestServlet.java

/**
 * {@inheritDoc}//w ww  .  ja  v  a 2s.c  o m
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String spDestination;
    String userIdentifier;
    String languages;

    AuthenticationRequestService service = this.authenticationRequestServiceLocator.locateService();
    if (null != service) {
        userIdentifier = service.getUserIdentifier();
        spDestination = service.getSPDestination();
        languages = service.getPreferredLanguages();
    } else {
        userIdentifier = this.userIdentifier;
        if (null != this.spDestination) {
            spDestination = this.spDestination;
        } else {
            spDestination = request.getScheme() + "://" + request.getServerName() + ":"
                    + request.getServerPort() + request.getContextPath() + this.spDestinationPage;
        }
        languages = this.languages;
    }

    try {
        LOG.debug("discovering the identity...");
        LOG.debug("user identifier: " + userIdentifier);
        List discoveries = this.consumerManager.discover(userIdentifier);
        LOG.debug("associating with the IdP...");
        DiscoveryInformation discovered = this.consumerManager.associate(discoveries);
        request.getSession().setAttribute("openid-disc", discovered);

        LOG.debug("SP destination: " + spDestination);

        AuthRequest authRequest = this.consumerManager.authenticate(discovered,
                getReturnTo(spDestination, request.getSession()), spDestination);

        /*
         * We also piggy-back an attribute fetch request.
         */
        FetchRequest fetchRequest = FetchRequest.createFetchRequest();

        // required attributes
        fetchRequest.addAttribute(OpenIDAXConstants.AX_FIRST_NAME_PERSON_TYPE, true);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_LAST_NAME_PERSON_TYPE, true);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_NAME_PERSON_TYPE, true);

        // optional attributes
        fetchRequest.addAttribute(OpenIDAXConstants.AX_GENDER_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_POSTAL_CODE_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_POSTAL_ADDRESS_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_CITY_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_NATIONALITY_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_PLACE_OF_BIRTH_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_BIRTHDATE_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_CARD_NUMBER_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_CARD_VALIDITY_BEGIN_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_CARD_VALIDITY_END_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_PHOTO_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_RRN_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_CERT_AUTHN_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_AGE_TYPE, false);

        authRequest.addExtension(fetchRequest, "ax");

        /*
         * Piggy back UI Extension if any languages were specified
         */
        if (null != languages) {
            UserInterfaceMessage uiMessage = new UserInterfaceMessage();
            uiMessage.setLanguages(languages);
            authRequest.addExtension(uiMessage, "ui");
        }

        LOG.debug("redirecting to producer with authn request...");
        response.sendRedirect(authRequest.getDestinationUrl(true));
    } catch (OpenIDException e) {
        throw new ServletException("OpenID error: " + e.getMessage(), e);
    }
}

From source file:com.osbitools.ws.shared.auth.SamlSecurityProvider.java

public String getDefServiceLocationUrl(HttpServletRequest req) {
    return "http:" + (req.isSecure() ? "s" : "") + "//" + req.getServerName() + ":" + req.getServerPort()
            + req.getContextPath();/*from  w ww . j  av  a  2  s  .  c  o m*/
}

From source file:com.boylesoftware.web.Router.java

/**
 * Send request for user authentication, which can be a redirect to the
 * login page, or the 401 HTTP code.//www  .  j  a  va2  s.  com
 *
 * @param webapp The web-application.
 * @param request The HTTP request.
 * @param response The HTTP response.
 *
 * @throws ServletException If an error happens.
 */
private void sendRequestForAuthentication(final AbstractWebApplication webapp, final HttpServletRequest request,
        final HttpServletResponse response) throws ServletException {

    LooseCannon.heel();

    final String loginPageURI = webapp.getRouterConfiguration().getLoginPageURI();
    if (loginPageURI != null) {

        try (final PooledStringBuffer buf = StringBufferPool.get()) {
            final StringBuilder sb = buf.getStringBuilder();

            sb.append(request.getRequestURI());
            final String queryString = request.getQueryString();
            if (queryString != null)
                sb.append('?').append(queryString);
            final String targetURI = sb.toString();
            sb.setLength(0);

            sb.append("https://").append(request.getServerName());

            final int httpsPort = webapp.getHTTPSPort();
            if (httpsPort != 443)
                sb.append(':').append(httpsPort);

            sb.append(StringUtils.emptyIfNull(request.getContextPath())).append(loginPageURI).append('?')
                    .append(Authenticator.TARGET_URI).append('=');

            try {
                sb.append(URLEncoder.encode(targetURI, "UTF-8"));
            } catch (final UnsupportedEncodingException e) {
                throw new ServletException("UTF-8 is unsupported.", e);
            }

            response.setStatus(HttpServletResponse.SC_SEE_OTHER);
            response.setHeader("Location", sb.toString());
        }

    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        // TODO: configure realm in the application configuration
        response.setHeader("WWW-Authenticate", "Basic realm=\"Application\"");
    }
}

From source file:com.tasktop.c2c.server.web.proxy.ajp.AjpProtocol.java

public void forward(HttpServletRequest request, HttpServletResponse response) throws IOException {
    debug(request, "forward");

    Packet packet = new Packet();
    packet.reset();//from   ww  w  .ja va 2  s .  c om
    // AJP13_FORWARD_REQUEST
    packet.write(Type.REQUEST_FORWARD.code);
    packet.write(computeMethod(request.getMethod()).code);
    packet.write(request.getProtocol());
    packet.write(request.getRequestURI());
    packet.write(request.getRemoteAddr());
    packet.write(request.getRemoteAddr());
    packet.write(request.getServerName());
    packet.write(request.getServerPort());
    packet.write(request.isSecure());

    // request headers
    Map<String, String> headers = new HashMap<String, String>();
    @SuppressWarnings("rawtypes")
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement().toString();
        String headerValue = request.getHeader(headerName);
        headerValue = headerFilter.processRequestHeader(headerName, headerValue);
        if (headerValue != null) {
            headers.put(headerName, headerValue);
        }
    }
    packet.write(headers.size());
    for (Map.Entry<String, String> header : headers.entrySet()) {
        HttpRequestHeader headerType = HttpRequestHeader.fromHeaderName(header.getKey());
        if (headerType != null) {
            packet.write(headerType.code);
        } else {
            packet.write(header.getKey());
        }
        String headerValue = header.getValue();
        packet.write(headerValue == null ? "" : headerValue);
    }

    // request attributes
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        packet.write(Attribute.REMOTE_USER.code);
        packet.write(authentication.getName());
    }

    String queryString = request.getQueryString();
    if (queryString != null) {
        packet.write(Attribute.QUERY_STRING.code);
        packet.write(queryString);
    }

    // packet terminator
    packet.write((byte) 0xff);

    final Object socketKey = new AjpPoolableConnectionFactory.Key(proxyHost, proxyPort);
    Socket connection;

    try {
        connection = allocateSocket(socketKey);
        debug("allocated", connection);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RuntimeException(e);
    }

    boolean invalidate = true;
    try {
        OutputStream outputStream = connection.getOutputStream();
        InputStream inputStream = connection.getInputStream();
        packet.write(outputStream);
        packet.reset();

        int bytesWritten = 0;

        int contentLength = request.getContentLength();
        if (contentLength == -1) { // Unknown content length
            contentLength = Integer.MAX_VALUE;
        }
        ServletInputStream requestInput = request.getInputStream();

        OutputStream responseOutput = null;
        boolean reuse = false;

        if (request.getHeader("Content-Length") != null) {
            bytesWritten += processRequestBody(packet, outputStream, bytesWritten, contentLength, requestInput,
                    contentLength);
            debug("sent [" + bytesWritten + "] initial body bytes", connection);
        }

        for (;; packet.reset()) {
            debug("reading packet", connection);
            packet.read(inputStream);

            Type packetType = Type.fromCode(packet.readByte());
            debug("received " + packetType, connection);
            if (packetType == Type.END_RESPONSE) {
                reuse = packet.readBoolean();
                break;
            }
            switch (packetType) {
            case GET_BODY_CHUNK:
                int requestedSize = packet.readInt();
                packet.reset();
                int chunkSize = processRequestBody(packet, outputStream, bytesWritten, contentLength,
                        requestInput, requestedSize);
                bytesWritten += chunkSize;
                debug("sent [" + chunkSize + "] bytes of body chunk", connection);
                break;
            case SEND_HEADERS: {
                response.reset();
                int httpStatusCode = packet.readInt();
                packet.readString(); // status message, not used
                response.setStatus(httpStatusCode);
                int headerCount = packet.readInt();
                for (int x = 0; x < headerCount; ++x) {
                    byte b = packet.readByte();
                    packet.unreadByte();
                    String headerName;
                    if (b == ((byte) 0xA0)) {
                        int headerCode = packet.readInt();
                        headerName = HttpResponseHeader.fromCode(headerCode).headerName;
                    } else {
                        headerName = packet.readString();
                    }
                    String headerValue = packet.readString();
                    headerValue = headerFilter.processResponseHeader(headerName, headerValue);
                    if (headerValue != null) {
                        response.setHeader(headerName, headerValue);
                    }
                }
            }
                break;
            case SEND_BODY_CHUNK:
                if (responseOutput == null) {
                    responseOutput = response.getOutputStream();
                }
                packet.copy(responseOutput);
                break;
            }
        }

        // ORDER DEPENDENCY: this should come last
        invalidate = !reuse;

        if (responseOutput != null) {
            responseOutput.close();
        }
    } finally {
        if (!shareConnections) {
            invalidate = true;
        }
        deallocateSocket(socketKey, connection, invalidate);
        debug("released " + (invalidate ? "invalidate" : "reuse"), connection);
    }
}

From source file:it.jugpadova.blo.EventBo.java

/**
 * Ajax method for a full text search on events.
 *
 * @param searchQuery The text to search
 * @param maxResults The max number of results. No limit if maxResults <= 0.
 *//*from  www .j  av a  2 s .  com*/
@RemoteMethod
public void fullTextSearch(String searchQuery, boolean pastEvents, String locale, int maxResults) {
    if (StringUtils.isNotBlank(searchQuery)) {
        WebContext wctx = WebContextFactory.get();
        HttpServletRequest req = wctx.getHttpServletRequest();
        ScriptSession session = wctx.getScriptSession();
        Util util = new Util(session);
        java.text.DateFormat dateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.SHORT,
                new Locale(locale));
        java.lang.String baseUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                + req.getContextPath();
        List<Event> events = null;
        try {
            events = this.search(searchQuery, pastEvents, maxResults);
        } catch (ParseException pex) {
            logger.info("Error parsing query: " + searchQuery);
        } catch (Exception ex) {
            logger.error("Error searching events", ex);
        }
        if (events != null && events.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (Event event : events) {
                sb.append("<div>\n");
                sb.append("<div class=\"eventDate\">").append(dateFormat.format(event.getStartDate()))
                        .append("</div>");
                if (event.getOwner() != null) {
                    sb.append("<div class=\"eventSignature\"><a href=\"")
                            .append(event.getOwner().getJug().getWebSiteUrl()).append("\">")
                            .append(event.getOwner().getJug().getName()).append("</a></div>");
                }
                sb.append("<div class=\"eventContent\"><a href=\"").append(baseUrl).append("/event/")
                        .append(event.getId()).append("\">").append(event.getTitle()).append("</a></div>");
                sb.append("</div>\n");
            }
            util.setValue("content_textSearch_result", sb.toString(), false);
        } else {
            util.setValue("content_textSearch_result", "", false);
        }
    }
}

From source file:org.codehaus.groovy.grails.plugins.springsecurity.AjaxAwareAccessDeniedHandler.java

/**
 * {@inheritDoc}/*  ww  w . ja  v a  2s.  c  o  m*/
 * @see org.springframework.security.web.access.AccessDeniedHandler#handle(
 *    javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
 *    org.springframework.security.access.AccessDeniedException)
 */
public void handle(final HttpServletRequest request, final HttpServletResponse response,
        final AccessDeniedException e) throws IOException, ServletException {

    if (e != null && isLoggedIn() && authenticationTrustResolver.isRememberMe(getAuthentication())) {
        // user has a cookie but is getting bounced because of IS_AUTHENTICATED_FULLY,
        // so Acegi won't save the original request
        request.getSession().setAttribute(WebAttributes.SAVED_REQUEST,
                new DefaultSavedRequest(request, portResolver));
    }

    if (response.isCommitted()) {
        return;
    }

    boolean ajaxError = ajaxErrorPage != null && SpringSecurityUtils.isAjax(request);
    if (errorPage == null && !ajaxError) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
        return;
    }

    boolean includePort = true;
    String scheme = request.getScheme();
    String serverName = request.getServerName();
    int serverPort = portResolver.getServerPort(request);
    String contextPath = request.getContextPath();
    boolean inHttp = "http".equals(scheme.toLowerCase());
    boolean inHttps = "https".equals(scheme.toLowerCase());

    if (inHttp && (serverPort == 80)) {
        includePort = false;
    } else if (inHttps && (serverPort == 443)) {
        includePort = false;
    }

    String redirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath;
    if (ajaxError) {
        redirectUrl += ajaxErrorPage;
    } else if (errorPage != null) {
        redirectUrl += errorPage;
    }
    response.sendRedirect(response.encodeRedirectURL(redirectUrl));
}

From source file:com.rapid.actions.Webservice.java

@Override
public JSONObject doAction(RapidRequest rapidRequest, JSONObject jsonAction) throws Exception {

    _logger.trace("Webservice action : " + jsonAction);

    // get the application
    Application application = rapidRequest.getApplication();

    // get the page
    Page page = rapidRequest.getPage();//from w  ww.  j av  a 2 s  .c  o  m

    // get the webservice action call sequence
    int sequence = jsonAction.optInt("sequence", 1);

    // placeholder for the object we're about to return
    JSONObject jsonData = null;

    // only proceed if there is a request and application and page
    if (_request != null && application != null && page != null) {

        // get any json inputs 
        JSONArray jsonInputs = jsonAction.optJSONArray("inputs");

        // placeholder for the action cache
        ActionCache actionCache = rapidRequest.getRapidServlet().getActionCache();

        // if an action cache was found
        if (actionCache != null) {

            // log that we found action cache
            _logger.debug("Webservice action cache found");

            // attempt to fetch data from the cache
            jsonData = actionCache.get(application.getId(), getId(), jsonInputs.toString());

        }

        // if there is either no cache or we got no data
        if (jsonData == null) {

            // get the body into a string
            String body = _request.getBody().trim();
            // remove prolog if present
            if (body.indexOf("\"?>") > 0)
                body = body.substring(body.indexOf("\"?>") + 3).trim();
            // check number of parameters
            int pCount = Strings.occurrences(body, "?");
            // throw error if incorrect
            if (pCount != jsonInputs.length())
                throw new Exception("Request has " + pCount + " parameter" + (pCount == 1 ? "" : "s") + ", "
                        + jsonInputs.length() + " provided");
            // retain the current position
            int pos = body.indexOf("?");
            // keep track of the index of the ?
            int index = 0;
            // if there are any question marks
            if (pos > 0 && jsonInputs.length() > index) {
                // loop, but check condition at the end
                do {
                    // get the input
                    JSONObject input = jsonInputs.getJSONObject(index);
                    // url escape the value
                    String value = XML.escape(input.optString("value"));
                    // replace the ? with the input value
                    body = body.substring(0, pos) + value + body.substring(pos + 1);
                    // look for the next question mark
                    pos = body.indexOf("?", pos + 1);
                    // inc the index for the next round
                    index++;
                    // stop looping if no more ?
                } while (pos > 0);
            }

            // retrieve the action
            String action = _request.getAction();
            // create a placeholder for the request url
            URL url = null;
            // get the request url
            String requestURL = _request.getUrl();

            // if we got one
            if (requestURL != null) {

                // if the given request url starts with http use it as is, otherwise use the soa servlet
                if (_request.getUrl().startsWith("http")) {
                    // trim it
                    requestURL = requestURL.trim();
                    // insert any parameters
                    requestURL = application
                            .insertParameters(rapidRequest.getRapidServlet().getServletContext(), requestURL);
                    // use the url 
                    url = new URL(requestURL);
                } else {
                    // get our request
                    HttpServletRequest httpRequest = rapidRequest.getRequest();
                    // make a url for the soa servlet
                    url = new URL(httpRequest.getScheme(), httpRequest.getServerName(),
                            httpRequest.getServerPort(), httpRequest.getContextPath() + "/soa");
                    // check whether we have any id / version seperators
                    String[] actionParts = action.split("/");
                    // add this app and version if none
                    if (actionParts.length < 2)
                        action = application.getId() + "/" + application.getVersion() + "/" + action;
                }

                // establish the connection
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                // if we are requesting from ourself
                if (url.getPath().startsWith(rapidRequest.getRequest().getContextPath())) {
                    // get our session id
                    String sessionId = rapidRequest.getRequest().getSession().getId();
                    // add it to the call for internal authentication
                    connection.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
                }

                // set the content type and action header accordingly
                if ("SOAP".equals(_request.getType())) {
                    connection.setRequestProperty("Content-Type", "text/xml");
                    connection.setRequestProperty("SOAPAction", action);
                } else if ("JSON".equals(_request.getType())) {
                    connection.setRequestProperty("Content-Type", "application/json");
                    if (action.length() > 0)
                        connection.setRequestProperty("Action", action);
                } else if ("XML".equals(_request.getType())) {
                    connection.setRequestProperty("Content-Type", "text/xml");
                    if (action.length() > 0)
                        connection.setRequestProperty("Action", action);
                }

                // if a body has been specified
                if (body.length() > 0) {

                    // Triggers POST.
                    connection.setDoOutput(true);

                    // get the output stream from the connection into which we write the request
                    OutputStream output = connection.getOutputStream();

                    // write the processed body string into the request output stream
                    output.write(body.getBytes("UTF8"));
                }

                // check the response code
                int responseCode = connection.getResponseCode();

                // read input stream if all ok, otherwise something meaningful should be in error stream
                if (responseCode == 200) {

                    // get the input stream
                    InputStream response = connection.getInputStream();
                    // prepare an soaData object
                    SOAData soaData = null;

                    // read the response accordingly
                    if ("JSON".equals(_request.getType())) {
                        SOAJSONReader jsonReader = new SOAJSONReader();
                        String jsonResponse = Strings.getString(response);
                        soaData = jsonReader.read(jsonResponse);
                    } else {
                        SOAXMLReader xmlReader = new SOAXMLReader(_request.getRoot());
                        soaData = xmlReader.read(response);
                    }

                    SOADataWriter jsonWriter = new SOARapidWriter(soaData);

                    String jsonString = jsonWriter.write();

                    jsonData = new JSONObject(jsonString);

                    if (actionCache != null)
                        actionCache.put(application.getId(), getId(), jsonInputs.toString(), jsonData);

                    response.close();

                } else {

                    InputStream response = connection.getErrorStream();

                    String errorMessage = null;

                    if ("SOAP".equals(_request.getType())) {

                        String responseXML = Strings.getString(response);

                        errorMessage = XML.getElementValue(responseXML, "faultcode");

                    }

                    if (errorMessage == null) {

                        BufferedReader rd = new BufferedReader(new InputStreamReader(response));

                        errorMessage = rd.readLine();

                        rd.close();

                    }

                    // log the error
                    _logger.error(errorMessage);

                    // only if there is no application cache show the error, otherwise it sends an empty response
                    if (actionCache == null) {

                        throw new JSONException(
                                " response code " + responseCode + " from server : " + errorMessage);

                    } else {

                        _logger.debug("Error not shown to user due to cache : " + errorMessage);

                    }

                }

                connection.disconnect();

            } // request url != null

        } // jsonData == null

    } // got app and page

    // if the jsonData is still null make an empty one
    if (jsonData == null)
        jsonData = new JSONObject();

    // add the sequence
    jsonData.put("sequence", sequence);

    // return the object
    return jsonData;

}

From source file:org.slc.sli.dashboard.security.SLIAuthenticationEntryPoint.java

private void saveCookieWithToken(HttpServletRequest request, HttpServletResponse response, String token) {

    // DE476 Using custom header, since servlet api version 2.5 does not support
    // httpOnly//w w w.  j  av a  2 s.  com
    // TODO: Remove custom header and use cookie when servlet-api is upgraded to 3.0
    // response.setHeader("Set-Cookie", DASHBOARD_COOKIE + "=" + (String) token +
    // ";path=/;domain=" + domain of the request + ";Secure;HttpOnly");
    String encryptedToken = null;
    String headerString = "";

    // DE883 Encrypt the cookie and save it in the header.
    try {
        encryptedToken = propDecryptor.encrypt(token);
        headerString = DASHBOARD_COOKIE + "=" + URLEncoder.encode(encryptedToken, "UTF-8") + ";path=/;domain="
                + request.getServerName() + ";HttpOnly";

        if (isSecureRequest(request)) {
            headerString = headerString + (";Secure");
        }

    } catch (Exception e) {
        LOG.error(e.getMessage());
    }

    response.setHeader("Set-Cookie", headerString);
}

From source file:com.cyclopsgroup.waterview.servlet.ServletPageRuntime.java

/**
 * Default constructor of default web runtime
 * //  www  . j  av a  2 s  .  c om
 * @param request Http request object
 * @param response Http response object
 * @param fileUpload File upload component
 * @param services ServiceManager object
 * @throws Exception Throw it out
 */
ServletPageRuntime(HttpServletRequest request, HttpServletResponse response, FileUpload fileUpload,
        ServiceManager services) throws Exception {
    this.response = response;
    this.request = request;
    setSessionContext(new HttpSessionContext(request.getSession()));

    String requestPath = request.getPathInfo();
    if (StringUtils.isEmpty(requestPath) || requestPath.equals("/")) {
        requestPath = "Index.jelly";
    } else if (requestPath.charAt(0) == '/') {
        requestPath = requestPath.substring(1);
    }
    setRequestPath(requestPath);

    setOutput(new PrintWriter(response.getOutputStream()));
    if (FileUpload.isMultipartContent(request)) {
        setRequestParameters(new MultipartServletRequestValueParser(request, fileUpload));
    } else {
        setRequestParameters(new ServletRequestValueParser(request));
    }
    setServiceManager(services);

    StringBuffer sb = new StringBuffer(request.getScheme());
    sb.append("://").append(request.getServerName());
    if (request.getServerPort() != 80) {
        sb.append(':').append(request.getServerPort());
    }
    sb.append(request.getContextPath());
    setApplicationBaseUrl(sb.toString());

    sb.append(request.getServletPath());
    setPageBaseUrl(sb.toString());

    Context pageContext = new DefaultContext(new HashMap());
    pageContext.put("request", request);
    pageContext.put("response", response);
    setPageContext(pageContext);
}

From source file:org.edeoliveira.oauth2.dropwizard.oauth2.auth.OAuth2Resource.java

@POST
@Timed//from w  w w  .  j ava2 s .  co  m
@Path(value = "/login")
public Response login(@FormParam("username") String username, @FormParam("password") String password,
        @Context final HttpServletRequest request) {
    WebTarget target = client.target(tokenUrl);
    Invocation.Builder builder = target.request();

    Form form = new Form();
    form.param("grant_type", "password");
    form.param("username", username);
    form.param("password", password);
    form.param("scope", cfg.getScope());
    form.param("client_id", cfg.getClient_id());
    form.param("client_secret", cfg.getClient_secret());

    Response response = builder.accept(MediaType.APPLICATION_JSON)
            .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED));

    if (response.getStatus() != HttpStatus.SC_OK) {
        response.close();
        return Response.status(Response.Status.UNAUTHORIZED).entity("{ \"error\": \"auth failed\"}").build();
    }

    try {
        AccessToken token = response.readEntity(AccessToken.class);
        NewCookie nc = engine.buildCookie(username, token, request.getServerName());

        StringBuilder sb = new StringBuilder();
        sb.append("{\"name\": \"").append(username).append("\", ");
        sb.append("\"expiresIn\": \"").append(token.getExpiresIn()).append("\"}");

        return Response.ok(sb.toString()).cookie(nc).build();
    } catch (Exception ex) {
        log.error("Error while building login response", ex);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    } finally {
        response.close();
    }
}