Example usage for javax.servlet.http HttpServletRequest getServerPort

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

Introduction

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

Prototype

public int getServerPort();

Source Link

Document

Returns the port number to which the request was sent.

Usage

From source file:org.apache.shiro.samples.spring.web.JnlpController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    Subject subject = SecurityUtils.getSubject();
    Session session = null;//  w  w  w. jav a2s .  c  om

    if (subject != null) {
        session = subject.getSession();
    }
    if (session == null) {
        String msg = "Expected a non-null Shiro session.";
        throw new IllegalArgumentException(msg);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("http://");
    sb.append(request.getServerName());
    if (request.getServerPort() != 80) {
        sb.append(":");
        sb.append(request.getServerPort());
    }
    sb.append(request.getContextPath());

    // prevent JNLP caching by setting response headers
    response.setHeader("cache-control", "no-cache");
    response.setHeader("pragma", "no-cache");

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("codebaseUrl", sb.toString());
    model.put("sessionId", session.getId());
    return new ModelAndView(jnlpView, model);
}

From source file:com.music.web.AuthenticationController.java

@RequestMapping("/persona/auth")
@ResponseBody/* w  w  w.j a va2  s. c  o m*/
public String authenticateWithPersona(@RequestParam String assertion,
        @RequestParam boolean userRequestedAuthentication, HttpServletRequest request,
        HttpServletResponse httpResponse, Model model) throws IOException {
    if (context.getUser() != null) {
        return "";
    }
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("assertion", assertion);
    params.add("audience", request.getScheme() + "://" + request.getServerName() + ":"
            + (request.getServerPort() == 80 ? "" : request.getServerPort()));
    PersonaVerificationResponse response = restTemplate.postForObject(
            "https://verifier.login.persona.org/verify", params, PersonaVerificationResponse.class);
    if (response.getStatus().equals("okay")) {
        User user = userService.getUserByEmail(response.getEmail());
        if (user == null && userRequestedAuthentication) {
            return "/socialSignUp?email=" + response.getEmail();
        } else if (user != null) {
            if (userRequestedAuthentication || user.isLoginAutomatically()) {
                signInAdapter.signIn(user, httpResponse, true);
                return "/";
            } else {
                return "";
            }
        } else {
            return ""; //in case this is not a user-requested operation, do nothing
        }
    } else {
        logger.warn("Persona authentication failed due to reason: " + response.getReason());
        throw new IllegalStateException("Authentication failed");
    }
}

From source file:org.gluu.oxauth.client.session.SignOutHandler.java

protected final String constructRedirectUrl(final HttpServletRequest request) {
    log.trace("Starting constructRedirectUrl");
    String redirectUri = null;//from   w ww.  j a v a2  s. co  m
    String[] redirectUriParameters = (String[]) request.getParameterMap()
            .get(Configuration.OAUTH_POST_LOGOUT_REDIRECT_URI);
    if (redirectUriParameters != null && redirectUriParameters.length > 0) {
        redirectUri = redirectUriParameters[0];
    }

    log.trace("redirectUri from request = " + redirectUri);
    if (redirectUri == null || redirectUri.equals("")) {
        int serverPort = request.getServerPort();
        if ((serverPort == 80) || (serverPort == 443)) {
            redirectUri = String.format("%s://%s%s", request.getScheme(), request.getServerName(),
                    "/identity/authentication/finishlogout");
        } else {
            redirectUri = String.format("%s://%s:%s%s", request.getScheme(), request.getServerName(),
                    request.getServerPort(), "/identity");
        }

    }
    log.trace("Final redirectUri = " + redirectUri);
    return redirectUri;
}

From source file:com.wisemapping.mail.NotificationService.java

private void sendNotification(@NotNull Map<String, String> model, @Nullable User user,
        @NotNull HttpServletRequest request) {
    model.put("fullName", (user != null ? user.getFullName() : "'anonymous'"));
    final String userEmail = user != null ? user.getEmail() : "'anonymous'";

    model.put("email", userEmail);
    model.put("userAgent", request.getHeader(SupportedUserAgent.USER_AGENT_HEADER));
    model.put("server", request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort());
    model.put("requestURI", request.getRequestURI());
    model.put("method", request.getMethod());
    model.put("remoteAddress", request.getRemoteAddr());

    try {/*from w w  w.  ja  va2  s.co m*/
        final String errorReporterEmail = mailer.getErrorReporterEmail();
        if (errorReporterEmail != null && !errorReporterEmail.isEmpty()) {

            if (!notificationFilter.hasBeenSend(userEmail, model)) {
                mailer.sendEmail(mailer.getServerSenderEmail(), errorReporterEmail,
                        "[WiseMapping] Bug from '" + (user != null ? user.getEmail() + "'" : "'anonymous'"),
                        model, "errorNotification.vm");
            }
        }
    } catch (Exception e) {
        handleException(e);
    }
}

From source file:com.frameworkset.platform.cms.driver.url.impl.CMSURLParserImpl.java

/**
 * Parse a servlet request to a portal URL.
 * @param request  the servlet request to parse.
 * @return the portal URL.//from w w  w .  jav  a2s.  c  o m
 */
public CMSURL parse(HttpServletRequest request) {

    if (LOG.isDebugEnabled()) {
        LOG.debug("Parsing URL: " + request.getRequestURI());
    }

    String protocol = request.isSecure() ? "https://" : "http://";
    String server = request.getServerName();
    int port = request.getServerPort();
    String contextPath = request.getContextPath();
    String servletName = request.getServletPath();

    // Construct portal URL using info retrieved from servlet request.
    CMSURL portalURL = null;
    if ((request.isSecure() && port != 443) || (!request.isSecure() && port != 80)) {
        portalURL = new CMSURLImpl(protocol, server, port, contextPath, servletName);
    } else {
        portalURL = new CMSURLImpl(protocol, server, contextPath, servletName);
    }

    String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        return portalURL;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Parsing request pathInfo: " + pathInfo);
    }
    StringBuffer renderPath = new StringBuffer();
    StringTokenizer st = new StringTokenizer(pathInfo, "/", false);
    while (st.hasMoreTokens()) {

        String token = st.nextToken();

        // Part of the render path: append to renderPath.
        if (!token.startsWith(PREFIX)) {
            //              renderPath.append(token);
            //Fix for PLUTO-243
            renderPath.append('/').append(token);
        }
        // Action window definition: portalURL.setActionWindow().
        else if (token.startsWith(PREFIX + ACTION)) {
            portalURL.setActionWindow(decodeControlParameter(token)[0]);
        }
        // Window state definition: portalURL.setWindowState().
        else if (token.startsWith(PREFIX + WINDOW_STATE)) {
            String[] decoded = decodeControlParameter(token);
            //              portalURL.setWindowState(decoded[0], new WindowState(decoded[1]));
        }
        // Portlet mode definition: portalURL.setPortletMode().
        else if (token.startsWith(PREFIX + PORTLET_MODE)) {
            String[] decoded = decodeControlParameter(token);
            //              portalURL.setPortletMode(decoded[0], new PortletMode(decoded[1]));
        }
        // Portal URL parameter: portalURL.addParameter().
        else {
            String value = null;
            if (st.hasMoreTokens()) {
                value = st.nextToken();
            }
            portalURL.addParameter(decodeParameter(token, value));
        }
    }
    if (renderPath.length() > 0) {
        portalURL.setRenderPath(renderPath.toString());
    }

    // Return the portal URL.
    return portalURL;
}

From source file:com.rometools.propono.atom.server.impl.FileBasedAtomHandler.java

/**
 * Contruct handler for one request, using specified file storage directory.
 *
 * @param req Request to be handled.//from  w w  w.j av a 2  s. c  o  m
 * @param uploaddir File storage upload dir.
 */
public FileBasedAtomHandler(final HttpServletRequest req, final String uploaddir) {
    LOG.debug("ctor");

    userName = authenticateBASIC(req);

    atomProtocolURL = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
            + req.getContextPath() + req.getServletPath();

    contextURI = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
            + req.getContextPath();

    try {
        service = new FileBasedAtomService(userName, uploaddir, contextURI, req.getContextPath(),
                req.getServletPath());
    } catch (final Throwable t) {
        throw new RuntimeException("ERROR creating FileBasedAtomService", t);
    }
}

From source file:org.jahia.services.applications.pluto.JahiaPortalURLParserImpl.java

/**
 * Parse a servlet request to a portal URL.
 *
 * @return the portal URL.//  w  w w.j a  v  a 2  s . c  o  m
 */
public PortalURL parse(HttpServletRequest request) {
    final String urlBase = request.getScheme() + "://" + request.getServerName() + ":"
            + request.getServerPort();
    final String contextPath = request.getContextPath();
    final String servletName = request.getServletPath();
    final String pathInfo = request.getPathInfo();
    return parse(urlBase, contextPath, servletName, pathInfo, request.getParameter(PORTLET_INFO));
}

From source file:se.vgregion.pubsub.loadtesting.LoadtestingServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // ping publish
    // wait for notification
    // response/* w  ww  . ja  va  2s .co m*/
    // error if timeout

    if (req.getPathInfo().equals("/feed")) {
        // serve ATOM feed
        resp.getWriter().write(atom(getFragment(req)));
    } else {
        // publish

        UUID id = UUID.randomUUID();
        String publicationUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                + req.getContextPath() + "/feed#" + id;

        String hubUrl = System.getProperty("hub.url");
        if (hubUrl == null) {
            throw new RuntimeException("System properti hub.url missing");
        }

        try {
            CountDownLatch latch = new CountDownLatch(1);
            publications.put(id, latch);

            HttpPost publication = new HttpPost(hubUrl);
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("hub.mode", "publish"));
            parameters.add(new BasicNameValuePair("hub.url", publicationUrl));

            publication.setEntity(new UrlEncodedFormEntity(parameters));

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse publicationResponse = httpClient.execute(publication);

            if (publicationResponse.getStatusLine().getStatusCode() == 204) {
                try {
                    if (latch.await(20000, TimeUnit.MILLISECONDS)) {
                        // all happy, return
                        return;
                    } else {
                        // timeout
                        resp.sendError(591);
                    }
                } catch (InterruptedException e) {
                    // interrupted
                    resp.sendError(592);
                }
            } else {
                // publication failed
                resp.sendError(publicationResponse.getStatusLine().getStatusCode(),
                        publicationResponse.getStatusLine().getReasonPhrase());
            }
        } finally {
            // try to prevent memory leaks
            publications.remove(id);
        }
    }
}

From source file:org.magnum.dataup.VideoController.java

private String getUrlBaseForLocalServer() {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getRequest();/*from   w  w w  . j  ava  2  s .  c o m*/
    InetAddress IP = null;
    try {
        IP = getLocalHostLANAddress();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    System.out.println("IP of my system is := " + IP.getHostAddress());
    String base = "http://" + IP.getHostAddress()
            + ((request.getServerPort() != 80) ? ":" + request.getServerPort() : "");
    System.out.println("dataUrl is :" + base);
    return base;
}

From source file:com.athena.peacock.controller.web.lb.LoadBalancerController.java

@RequestMapping("/applyListener")
public @ResponseBody SimpleJsonResponse applyListener(HttpServletRequest request, SimpleJsonResponse jsonRes,
        LoadBalancerDto loadBalancer) throws Exception {
    Assert.notNull(loadBalancer.getLoadBalancerId(), "loadBalancerId can not be null.");
    Assert.notNull(loadBalancer.getMachineId(), "machineId can not be null.");

    try {//from w  ww. j  a  va  2  s . c o  m
        String urlPrefix = "http://" + request.getServerName() + ":" + request.getServerPort() + "/"
                + request.getContextPath() + "/repo";
        lbListenerService.applyListener(loadBalancer, urlPrefix);
        jsonRes.setMsg("Load Balancer Listener ? ??.");
    } catch (Exception e) {
        jsonRes.setSuccess(false);
        jsonRes.setMsg("Load Balancer Listener  ?  ? ?.");

        logger.error("Unhandled Expeption has occurred. ", e);
    }

    return jsonRes;
}