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.exoplatform.platform.portlet.juzu.notificationsAdmin.NotificationsAdministration.java

private void redirectToHomePage() {
    PortalRequestContext portalRequestContext = Util.getPortalRequestContext();
    HttpServletRequest currentServletRequest = portalRequestContext.getRequest();
    StringBuilder sb = new StringBuilder();
    sb.append(currentServletRequest.getScheme()).append("://").append(currentServletRequest.getServerName())
            .append(":").append(currentServletRequest.getServerPort()).append("/")
            .append(PortalContainer.getCurrentPortalContainerName()).append("/")
            .append(Util.getPortalRequestContext().getPortalOwner());

    WebuiRequestContext ctx = WebuiRequestContext.getCurrentInstance();
    JavascriptManager jsManager = ctx.getJavascriptManager();
    jsManager.addJavascript("try { window.location.href='" + sb.toString() + "' } catch(e) {"
            + "window.location.href('" + sb.toString() + "') }");
}

From source file:com.aimluck.eip.services.social.gadgets.ALGadgetContext.java

public String getServerBase() {
    HttpServletRequest request = ((JetspeedRunData) runData).getRequest();

    StringBuilder builder = new StringBuilder();
    String scheme = request.getScheme();
    String serverName = request.getServerName();
    int serverPort = request.getServerPort();

    builder.append(scheme).append("://");
    if (isLockedDomainRequired()) {
        byte[] sha1 = DigestUtils.sha(appUrl);
        String hash = new String(Base32.encodeBase32(sha1));
        builder.append(hash).append(getLockedDomainSuffix());
    } else {/*from  w  ww .j  ava2  s .  co m*/
        builder.append(serverName);
        if (serverPort != 80 || serverPort != 443) {
            builder.append(":").append(serverPort);
        }
    }
    String containerPath = JetspeedResources.getString("aipo.container.path");

    return builder.append(containerPath == null ? "" : containerPath).append("/gadgets/").toString();
}

From source file:org.esigate.servlet.impl.RequestFactory.java

public IncomingRequest create(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws IOException {
    HttpServletRequestContext context = new HttpServletRequestContext(request, response, servletContext,
            filterChain);//w  w w  .  ja  v  a2s. c  om
    // create request line
    String uri = UriUtils.createURI(request.getScheme(), request.getServerName(), request.getServerPort(),
            request.getRequestURI(), request.getQueryString(), null);
    ProtocolVersion protocolVersion = BasicLineParser.parseProtocolVersion(request.getProtocol(), null);
    IncomingRequest.Builder builder = IncomingRequest
            .builder(new BasicRequestLine(request.getMethod(), uri, protocolVersion));
    builder.setContext(context);
    // copy headers
    @SuppressWarnings("rawtypes")
    Enumeration names = request.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        @SuppressWarnings("rawtypes")
        Enumeration values = request.getHeaders(name);
        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            builder.addHeader(name, value);
        }
    }
    // create entity
    HttpServletRequestEntity entity = new HttpServletRequestEntity(request);
    builder.setEntity(entity);

    builder.setRemoteAddr(request.getRemoteAddr());
    builder.setRemoteUser(request.getRemoteUser());
    HttpSession session = request.getSession(false);
    if (session != null) {
        builder.setSessionId(session.getId());
    }
    builder.setUserPrincipal(request.getUserPrincipal());

    // Copy cookies
    // As cookie header contains only name=value so we don't need to copy
    // all attributes!
    javax.servlet.http.Cookie[] src = request.getCookies();
    if (src != null) {
        for (int i = 0; i < src.length; i++) {
            javax.servlet.http.Cookie c = src[i];
            BasicClientCookie dest = new BasicClientCookie(c.getName(), c.getValue());
            builder.addCookie(dest);
        }
    }
    builder.setSession(new HttpServletSession(request));
    builder.setContextPath(request.getContextPath());
    return builder.build();
}

From source file:org.pegadi.webapp.webstart.WebstartController.java

protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws Exception {

    Map<String, Object> model = new HashMap<String, Object>();
    List<String> libs = new ArrayList<String>();

    configBean.setVersion(resourceBundle.getString("version"));
    String contextPath = httpServletRequest.getContextPath();
    int serverport = httpServletRequest.getServerPort();
    String server = httpServletRequest.getServerName();
    configBean.setWebBase("http://" + server + ":" + serverport + contextPath);
    configBean.getProperties().put("server.host", server);
    File clientFolder = resourceLoader.getResource(configBean.getCodeBase()).getFile();

    if (clientFolder.isDirectory()) {
        File[] files = clientFolder.listFiles();
        for (File tempFile : files) {
            if (!tempFile.getName().contains(".jar")) {
                continue;
            }/*from  w w  w . j  ava  2s. co m*/
            if (tempFile.getName().contains(configBean.getMainLibBaseName())) {
                model.put("main", configBean.getCodeBase() + tempFile.getName());
            } else {
                libs.add(configBean.getCodeBase() + tempFile.getName());
            }
        }
    } else {
        log.error("ERROR: clientFolder " + clientFolder.getAbsolutePath() + " is not a directory");
        throw new ServletException("WebStartController: Could not read directory containing client jars.");
    }

    model.put("jars", libs);

    model.put("config", configBean);

    return new ModelAndView("webstart", model);
}

From source file:org.elissa.server.AMLSupport.java

/**
 * The POST request.EPCUpload.java/*from   w  ww . jav  a2s . c o  m*/
 */
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException {

    PrintWriter out = null;

    FileItem fileItem = null;

    try {
        String oryxBaseUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort()
                + req.getContextPath() + "/";

        // Get the PrintWriter
        res.setContentType("text/plain");
        res.setCharacterEncoding("utf-8");

        out = res.getWriter();

        // No isMultipartContent => Error
        final boolean isMultipartContent = ServletFileUpload.isMultipartContent(req);
        if (!isMultipartContent) {
            printError(out, "No Multipart Content transmitted.");
            return;
        }

        // Get the uploaded file
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
        servletFileUpload.setSizeMax(-1);
        final List<?> items;

        items = servletFileUpload.parseRequest(req);
        if (items.size() != 1) {
            printError(out, "Not exactly one File.");
            return;
        }

        fileItem = (FileItem) items.get(0);

        // replace dtd reference by existing reference /oryx/lib/ARIS-Export.dtd
        String amlStr = fileItem.getString("UTF-8");

        amlStr = amlStr.replaceFirst("\"ARIS-Export.dtd\"", "\"" + oryxBaseUrl + "lib/ARIS-Export.dtd\"");

        FileOutputStream fileout = null;
        OutputStreamWriter outwriter = null;

        try {
            fileout = new FileOutputStream(((DiskFileItem) fileItem).getStoreLocation());
            outwriter = new OutputStreamWriter(fileout, "UTF-8");
            outwriter.write(amlStr);
            outwriter.flush();

        } finally {
            if (outwriter != null)
                outwriter.close();
            if (fileout != null)
                fileout.close();
        }

        //parse AML file
        AMLParser parser = new AMLParser(((DiskFileItem) fileItem).getStoreLocation().getAbsolutePath());
        parser.parse();
        Collection<EPC> epcs = new HashSet<EPC>();
        Iterator<String> ids = parser.getModelIds().iterator();
        while (ids.hasNext()) {
            String modelId = ids.next();
            epcs.add(parser.getEPC(modelId));
        }

        // serialize epcs to eRDF oryx format
        OryxSerializer oryxSerializer = new OryxSerializer(epcs, oryxBaseUrl);
        oryxSerializer.parse();

        Document outputDocument = oryxSerializer.getDocument();

        // get document as string
        String docAsString = "";

        Source source = new DOMSource(outputDocument);
        StringWriter stringWriter = new StringWriter();
        Result result = new StreamResult(stringWriter);
        TransformerFactory tfactory = TransformerFactory.newInstance();
        Transformer transformer = tfactory.newTransformer();
        transformer.transform(source, result);
        docAsString = stringWriter.getBuffer().toString();

        // write response
        out.print("" + docAsString + "");

    } catch (Exception e) {
        handleException(out, e);
    } finally {
        if (fileItem != null) {
            fileItem.delete();
        }
    }
}

From source file:com.seajas.search.utilities.tags.URLTag.java

/**
 * Rewrite a URL.//from   w w  w .  j  a  v  a2  s.com
 * 
 * @param context
 * @param request
 * @param url
 * @param fullUrl
 * @return String
 */
public static String rewriteURL(final ServletContext context, final HttpServletRequest request,
        final String url, final Boolean fullUrl) {
    String rewrittenURL = url;

    String contextName = context.getContextPath();

    if (contextName == null)
        contextName = System.getProperty(SYSTEM_DEFAULT_CONTEXT);

    if (contextName.startsWith("/"))
        contextName = contextName.substring(1);

    if (Boolean.getBoolean(SYSTEM_REWRITTEN_URLS)) {
        if (rewrittenURL.startsWith(contextName))
            rewrittenURL = rewrittenURL.substring(contextName.length());
        if (rewrittenURL.startsWith("/" + contextName))
            rewrittenURL = rewrittenURL.substring(contextName.length() + 1);

        // Make sure the index link redirects to '/'

        if (rewrittenURL.equals("/index.html"))
            rewrittenURL = "/";
    } else if (!rewrittenURL.startsWith("/" + contextName))
        rewrittenURL = "/" + contextName + rewrittenURL;

    if (fullUrl) {
        String forwardedFor = request.getHeader("X-Forwarded-Host");

        rewrittenURL = request.getScheme() + "://"
                + (StringUtils.isEmpty(forwardedFor)
                        ? request.getServerName()
                                + (request.getServerPort() != 80 ? ":" + request.getServerPort() : "")
                        : forwardedFor)
                + (rewrittenURL.startsWith("/") ? rewrittenURL : "/" + rewrittenURL);
    }

    return rewrittenURL;
}

From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java

/**
 * Sets redirect url to next door GPT application
 * //  www .j  a v  a2  s .  c o  m
 * @param request
 *          the servlet request
 */
private void setURL(HttpServletRequest request) {

    StringBuffer sb = new StringBuffer();
    sb.append("http://").append(request.getServerName()).append(":").append(request.getServerPort())
            .append(_redirectURL);

    _redirectURL = sb.toString();

    LOGGER.finer(_redirectURL);
}

From source file:br.gov.jfrj.siga.base.SigaHTTP.java

/**
 * @param URL//from  w w  w .  j  a  v  a 2  s.  c o  m
 * @param request (se for modulo play, setar pra null)
 * @param cookieValue (necessario apenas nos modulos play)
 */
public String get(String URL, HttpServletRequest request, String cookieValue) {
    String html = "";

    if (URL.startsWith("/"))
        URL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + URL;

    try {
        // Efetua o request para o Service Provider (mdulo)
        Request req = Request.Get(URL);
        //    req.addHeader(COOKIE, JSESSIONID_PREFIX+getCookie(request, cookieValue));
        // Atribui o html retornado e pega o header do Response
        // Se a aplicao j efetuou a autenticao entre o mdulo da URL o contedo ser trago nesse primeiro GET
        // Caso contrrio passar pelo processo de autenticao (if abaixo)
        html = req.execute().handleResponse(new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse httpResponse)
                    throws ClientProtocolException, IOException {
                // O atributo que importa nesse header  o set-cookie que ser utilizado posteriormente
                headers = httpResponse.getAllHeaders();
                return IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");
            }
        });

        // Verifica se retornou o form de autenticao do picketlink 
        if (html.contains(HTTP_POST_BINDING_REQUEST)) {
            // Atribui o cookie recuperado no response anterior
            String setCookie = null;
            try {
                setCookie = extractCookieFromHeader(getHeader(SET_COOKIE));
            } catch (ElementNotFoundException elnf) {
                log.warning("Nao encontrou o set-cookie");
                setCookie = getCookie(request, cookieValue);
            }

            // Atribui o valor do SAMLRequest contido no html retornado no GET efetuado.
            String SAMLRequestValue = getAttributeValueFromHtml(html, SAMLRequest);
            // Atribui a URL do IDP (sigaidp)
            String idpURL = getAttributeActionFromHtml(html);

            // Faz um novo POST para o IDP com o SAMLRequest como parametro e utilizando o sessionID do IDP
            html = Request.Post(idpURL).addHeader(COOKIE, JSESSIONID_PREFIX + getIdp(request))
                    .bodyForm(Form.form().add(SAMLRequest, SAMLRequestValue).build()).execute().returnContent()
                    .toString();

            // Extrai o valor do SAMLResponse
            // Caso o SAMLResponse no esteja disponvel aqui,  porque o JSESSIONID utilizado no foi o do IDP.
            String SAMLResponseValue = getAttributeValueFromHtml(html, SAMLResponse);

            // Faz um POST para o SP com o atributo SAMLResponse utilizando o sessionid do primeiro GET
            // O retorno  discartado pois o resultado  um 302.
            Request.Post(URL).addHeader(COOKIE, JSESSIONID_PREFIX + setCookie)
                    .bodyForm(Form.form().add(SAMLResponse, SAMLResponseValue).build()).execute()
                    .discardContent();

            // Agora que estamos autenticado efetua o GET para pgina desejada.
            html = Request.Get(URL).addHeader(COOKIE, JSESSIONID_PREFIX + setCookie).execute().returnContent()
                    .toString();
            if (html.contains(HTTP_POST_BINDING_REQUEST)) {
                log.info("Alguma coisa falhou na autenticao!: " + idpURL);
            }
        }
    } catch (Exception io) {
        io.printStackTrace();
    }

    return html;
}

From source file:org.apache.shindig.gadgets.servlet.ServletUtilTest.java

@Test
public void testFromHttpServletRequest() throws Exception {
    HttpServletRequest original = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(original.getScheme()).andReturn("https");
    EasyMock.expect(original.getServerName()).andReturn("www.example.org");
    EasyMock.expect(original.getServerPort()).andReturn(444);
    EasyMock.expect(original.getRequestURI()).andReturn("/path/foo");
    EasyMock.expect(original.getQueryString()).andReturn("one=two&three=four");
    Vector<String> headerNames = new Vector<String>();
    headerNames.add("Header1");
    headerNames.add("Header2");
    EasyMock.expect(original.getHeaderNames()).andReturn(headerNames.elements());
    EasyMock.expect(original.getHeaders("Header1")).andReturn(makeEnumeration("HVal1", "HVal3"));
    EasyMock.expect(original.getHeaders("Header2")).andReturn(makeEnumeration("HVal2", "HVal4"));
    EasyMock.expect(original.getMethod()).andReturn("post");
    final ByteArrayInputStream bais = new ByteArrayInputStream("post body".getBytes());
    ServletInputStream sis = new ServletInputStream() {
        @Override/*w w w .ja va2s.co m*/
        public int read() throws IOException {
            return bais.read();
        }
    };
    EasyMock.expect(original.getInputStream()).andReturn(sis);
    EasyMock.expect(original.getRemoteAddr()).andReturn("1.2.3.4");

    EasyMock.replay(original);
    HttpRequest request = ServletUtil.fromHttpServletRequest(original);
    EasyMock.verify(original);

    assertEquals(Uri.parse("https://www.example.org:444/path/foo?one=two&three=four"), request.getUri());
    assertEquals(3, request.getHeaders().size());
    assertEquals("HVal1", request.getHeaders("Header1").get(0));
    assertEquals("HVal3", request.getHeaders("Header1").get(1));
    assertEquals("HVal2", request.getHeaders("Header2").get(0));
    assertEquals("HVal4", request.getHeaders("Header2").get(1));
    assertEquals("post", request.getMethod());
    assertEquals("post body", request.getPostBodyAsString());
    assertEquals("1.2.3.4", request.getParam(ServletUtil.REMOTE_ADDR_KEY));
}

From source file:org.glite.slcs.servlet.AbstractServlet.java

/**
 * Return the servlet URL for the servlet path. The servlet path must starts
 * with '/' and is relative the the context root.
 * //from ww w  . ja va 2 s . c o  m
 * @param req
 *            The HttpServletRequest object.
 * @param servletPath
 *            The servlet path relative to the context root.
 * @return The URL of the servlet.
 */
protected String getContextUrl(HttpServletRequest req, String servletPath) {
    StringBuffer sb = new StringBuffer();
    sb.append(req.getScheme()).append("://");
    sb.append(req.getServerName()).append(':').append(req.getServerPort());
    sb.append(req.getContextPath());
    sb.append(servletPath);
    return sb.toString();
}