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:be.fedict.eid.dss.sp.bean.SPBean.java

private byte[] setRequest(HttpServletRequest httpServletRequest, String language, String target) {

    byte[] document = (byte[]) httpServletRequest.getSession()
            .getAttribute(UploadServlet.DOCUMENT_SESSION_ATTRIBUTE);

    this.language = language;
    this.contentType = (String) httpServletRequest.getSession().getAttribute("ContentType");
    this.relayState = UUID.randomUUID().toString();
    LOG.debug("RelayState: " + this.relayState);

    this.destination = "../eid-dss/protocol/simple";
    this.target = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + ":"
            + httpServletRequest.getServerPort() + httpServletRequest.getContextPath() + "/" + target
            + "?requestId=" + new Random().nextInt(1000);

    // store data on session for response handling
    httpServletRequest.getSession().setAttribute("target", this.target);
    httpServletRequest.getSession().setAttribute("RelayState", this.relayState);

    return document;
}

From source file:com.provenance.cloudprovenance.traceabilitystore.ws.controler.TraceabilityStoreController.java

@Override
@GET/*from  w  ww  .  j  a  v a2 s  .c  o m*/
@Path(value = "/{serviceId}/{traceabilityType}")
public Response getTraceabilityDocumentId(@PathParam("serviceId") String serviceId,
        @PathParam("traceabilityType") String traceabilityType, @Context HttpServletRequest request) {

    if (currentTraceabilityRecordId == null) {
        logger.warn("Current file record Id does not exist, need to create a new record !!!");
        ResponseBuilder rBuilder = Response.status(404);
        rBuilder.entity("<TraceabilityDocument></TraceabilityDocument>");
        return rBuilder.build();

    } else {
        String responseUri = request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort() + request.getRequestURI() + "/" + currentTraceabilityRecordId;

        logger.info("Response URI: " + responseUri);

        logger.info("Returning the current record Id");
        ResponseBuilder rBuilder = Response.status(200);
        String responseContent = trResponse.genTraceabilityRecordIdResponse(currentTraceabilityRecordId,
                serviceId, defaultFileExtensionOfrecord, responseUri);

        logger.info("Sending GET resource URI response: " + responseContent);

        rBuilder.entity(responseContent);
        return rBuilder.build();
    }
}

From source file:com.liferay.portal.util.PortalUtil.java

public static String getPortalURL(HttpServletRequest req, boolean secure) {
    StringBuffer sb = new StringBuffer();

    String serverProtocol = GetterUtil.getString(PropsUtil.get(PropsUtil.WEB_SERVER_PROTOCOL));

    if (secure || Http.HTTPS.equals(serverProtocol)) {
        sb.append(Http.HTTPS_WITH_SLASH);
    } else {/*from  w  w w  . j  a  v  a  2 s  . c om*/
        sb.append(Http.HTTP_WITH_SLASH);
    }

    String serverHost = PropsUtil.get(PropsUtil.WEB_SERVER_HOST);

    if (Validator.isNull(serverHost)) {
        sb.append(req.getServerName());
    } else {
        sb.append(serverHost);
    }

    int serverHttpPort = GetterUtil.get(PropsUtil.get(PropsUtil.WEB_SERVER_HTTP_PORT), -1);

    if (serverHttpPort == -1) {
        if (!secure && (req.getServerPort() != Http.HTTP_PORT)) {
            sb.append(StringPool.COLON).append(req.getServerPort());
        }
    } else {
        if (!secure && (req.getServerPort() != serverHttpPort)) {
            if (serverHttpPort != Http.HTTP_PORT) {
                sb.append(StringPool.COLON).append(serverHttpPort);
            }
        }
    }

    int serverHttpsPort = GetterUtil.get(PropsUtil.get(PropsUtil.WEB_SERVER_HTTPS_PORT), -1);

    if (serverHttpsPort == -1) {
        if (secure && (req.getServerPort() != Http.HTTPS_PORT)) {
            sb.append(StringPool.COLON).append(req.getServerPort());
        }
    } else {
        if (secure && (req.getServerPort() != serverHttpsPort)) {
            if (serverHttpsPort != Http.HTTPS_PORT) {
                sb.append(StringPool.COLON).append(serverHttpsPort);
            }
        }
    }

    return sb.toString();
}

From source file:org.eclipse.orion.server.authentication.formpersona.PersonaHelper.java

/**
 * If the request appears to be from a loopback interface, returns an audience constructed from the server name.
 * Otherwise returns null./*from w  w w.j av a 2  s. c  o  m*/
 */
private String getLoopbackAudience(HttpServletRequest req) throws PersonaException {
    try {
        String serverName = req.getServerName();
        try {
            // First ensure the request is coming from the IP of a loopback device
            if (isLoopback(InetAddress.getByName(req.getLocalAddr()))) {
                // Verify that the server name resolves to a loopback device, to prevent spoofing/proxying
                InetAddress addr = InetAddress.getByName(serverName);
                if (isLoopback(addr))
                    return new URI(req.getScheme(), req.getRemoteUser(), serverName, req.getServerPort(), null,
                            null, null).toString();
            }
        } catch (UnknownHostException e) {
            // Bogus serverName, ignore
        }
    } catch (URISyntaxException e) {
        throw new PersonaException(e);
    }
    return null;
}

From source file:org.sample.jsonp.TestServlet.java

/**
 * Processes requests for both HTTP//from w w  w. j a  va  2  s  .c  o m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet TestServlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");
        Client client = ClientBuilder.newClient();
        client.register(MoxyJsonFeature.class);

        WebTarget target = client.target("http://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath() + "/webresources/endpoint");

        JsonObject jsonObject = Json.createObjectBuilder().add("apple", "red").add("banana", "yellow").build();

        JsonObject jo = target.request().post(Entity.entity(jsonObject, MediaType.APPLICATION_JSON),
                JsonObject.class);
        out.println(jo);
        out.println("</body>");
        out.println("</html>");
    }
}

From source file:de.tuttas.servlets.ClientConfig.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   www.ja v  a 2 s .co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        Config c = Config.getInstance();
        Set set = c.clientConfig.keySet();

        Iterator<?> keys = set.iterator();

        while (keys.hasNext()) {

            String key = (String) keys.next();

            out.println("var " + key + "=\"" + c.clientConfig.get(key) + "\";");

        }
        out.println("var debug=" + c.debug + ";");
        out.println("var servername=\"" + request.getServerName() + "\";");
        out.println("var serverport=" + request.getServerPort() + ";");

    }
}

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

private void doHandle(final String target, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException { // check async requests
    // get map/* w  ww. j av  a2 s . c  o  m*/
    final UrlMap map = urlMap.get();
    if (map == null) {
        if (JettyDebug.handlers) {
            LOG.debug("null URL map, no handler matched!");
        }
        return;
    }

    // perform lookup
    final MappedEntry<Handler> entry = map.getMatch(request.getScheme(), request.getServerName(),
            request.getServerPort(), target);
    if (entry == null) {
        if (JettyDebug.handlers) {
            LOG.debug("no matching handler for {}", request.getRequestURL());
        }
        return;
    }

    final String oldContextPath = baseRequest.getContextPath();
    try {
        // adjust context path and execute
        final String mapped = entry.getMapped();
        baseRequest.setContextPath((mapped != null) && (mapped.length() > 0) ? mapped : URIUtil.SLASH);

        // get handler
        final Handler handler = entry.getValue();
        if (JettyDebug.handlers) {
            LOG.debug("found matching handler for {}: {}", request.getRequestURL(), handler);
            LOG.debug("adjusted context path for {} to {}", request.getRequestURL(),
                    baseRequest.getContextPath());
        }

        // lazy start handler
        if (!handler.isStarted()) {
            if (JettyDebug.handlers) {
                LOG.debug("lazy start of handler {}", handler);
            }
            try {
                handler.start();
            } catch (final Exception e) {
                if (Platform.inDebugMode()) {
                    LOG.debug("Exception starting handler {}. {}",
                            new Object[] { handler, ExceptionUtils.getRootCauseMessage(e), e });
                    throw new IllegalStateException(
                            String.format("Failed to start registered handler '%s' for mapping '%s'. %s",
                                    handler, mapped, ExceptionUtils.getRootCauseMessage(e)),
                            e);
                } else {
                    LOG.warn("Exception starting handler {}. {}",
                            new Object[] { handler, ExceptionUtils.getRootCauseMessage(e) });
                    throw new IllegalStateException("Application Not Available");
                }
            }
        }

        // handle
        handler.handle(target, baseRequest, request, response);
    } finally {
        baseRequest.setContextPath(oldContextPath);
    }
}

From source file:org.apache.ode.axis2.service.DeploymentBrowser.java

public boolean doFilter(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String requestURI = request.getRequestURI();
    final int deplUri = requestURI.indexOf("/deployment");
    if (deplUri > 0) {
        final String root = request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort() + requestURI.substring(0, deplUri);
        int offset = requestURI.length() > (deplUri + 11) ? 1 : 0;
        final String[] segments = requestURI.substring(deplUri + 11 + offset).split("/");
        if (segments.length == 0 || segments[0].length() == 0) {
            renderHtml(response, "ODE Deployment Browser", new DocBody() {
                public void render(Writer out) throws IOException {
                    out.write("<p><a href=\"bundles/\">Deployed Bundles</a></p>");
                    out.write("<p><a href=\"services/\">Process Services</a></p>");
                    out.write("<p><a href=\"processes/\">Process Definitions</a></p>");
                }// ww w. ja  va 2 s.c  om
            });
        } else if (segments.length > 0) {
            if ("services".equals(segments[0])) {
                if (segments.length == 1) {
                    renderHtml(response, "Services Implemented by Your Processes", new DocBody() {
                        public void render(Writer out) throws IOException {
                            for (Object serviceName : _config.getServices().keySet())
                                if (!"Version".equals(serviceName)) {
                                    AxisService service = _config.getService(serviceName.toString());

                                    // The service can be one of the dynamically registered ODE services, a process
                                    // service or an unknown service deployed in the same Axis2 instance.
                                    String url = null;
                                    if ("DeploymentService".equals(service.getName())
                                            || "InstanceManagement".equals(service.getName())
                                            || "ProcessManagement".equals(service.getName()))
                                        url = service.getName();
                                    else if (service.getFileName() != null) {
                                        String relative = bundleUrlFor(service.getFileName().getFile());
                                        if (relative != null)
                                            url = root + relative;
                                        else
                                            url = root + "/services/" + service.getName() + "?wsdl";
                                    }

                                    out.write("<p><a href=\"" + url + "\">" + serviceName + "</a></p>");
                                    String axis2wsdl = root + "/processes/" + serviceName + "?wsdl";
                                    out.write("<ul><li>Axis2 WSDL: <a href=\"" + axis2wsdl + "\">" + axis2wsdl
                                            + "</a></li>");
                                    out.write(
                                            "<li>Endpoint: " + (root + "/processes/" + serviceName) + "</li>");
                                    Iterator iter = service.getOperations();
                                    ArrayList<String> ops = new ArrayList<String>();
                                    while (iter.hasNext())
                                        ops.add(((AxisOperation) iter.next()).getName().getLocalPart());
                                    out.write("<li>Operations: " + StringUtils.join(ops, ", ") + "</li></ul>");
                                }
                        }
                    });
                } else {
                    final String serviceName = requestURI.substring(deplUri + 12 + 9);
                    final AxisService axisService = _config.getService(serviceName);
                    if (axisService != null) {
                        renderXml(response, new DocBody() {
                            public void render(Writer out) throws IOException {
                                if ("InstanceManagement".equals(serviceName)
                                        || "ProcessManagement".equals(serviceName))
                                    write(out, new File(_appRoot, "pmapi.wsdl").getPath());
                                else if (requestURI.indexOf("pmapi.xsd") > 0)
                                    write(out, new File(_appRoot, "pmapi.xsd").getPath());
                                else if ("DeploymentService".equals(serviceName))
                                    write(out, new File(_appRoot, "deploy.wsdl").getPath());
                                else
                                    write(out, axisService.getFileName().getFile());
                            }
                        });
                    } else {
                        renderHtml(response, "Service Not Found", new DocBody() {
                            public void render(Writer out) throws IOException {
                                out.write("<p>Couldn't find service " + serviceName + "</p>");
                            }
                        });
                    }
                }
            } else if ("processes".equals(segments[0])) {
                if (segments.length == 1) {
                    renderHtml(response, "Deployed Processes", new DocBody() {
                        public void render(Writer out) throws IOException {
                            for (QName process : _store.getProcesses()) {
                                String url = root + bundleUrlFor(
                                        _store.getProcessConfiguration(process).getBpelDocument());
                                String[] nameVer = process.getLocalPart().split("-");
                                out.write("<p><a href=\"" + url + "\">" + nameVer[0] + "</a> (v" + nameVer[1]
                                        + ")");
                                out.write(" - " + process.getNamespaceURI() + "</p>");
                            }
                        }
                    });
                }
            } else if ("bundles".equals(segments[0])) {
                if (segments.length == 1) {
                    renderHtml(response, "Deployment Bundles", new DocBody() {
                        public void render(Writer out) throws IOException {
                            for (String bundle : _store.getPackages())
                                out.write("<p><a href=\"" + bundle + "\">" + bundle + "</a></p>");
                        }
                    });
                } else if (segments.length == 2) {
                    renderHtml(response, "Files in Bundle " + segments[1], new DocBody() {
                        public void render(Writer out) throws IOException {
                            List<QName> processes = _store.listProcesses(segments[1]);
                            if (processes != null && processes.size() > 0) {
                                List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles();
                                for (File file : files) {
                                    String relativePath = file.getPath()
                                            .substring(file.getPath().indexOf("processes") + 10)
                                            .replaceAll("\\\\", "/");
                                    out.write(
                                            "<p><a href=\"" + relativePath + "\">" + relativePath + "</a></p>");
                                }
                            } else {
                                out.write("<p>Couldn't find bundle " + segments[1] + "</p>");
                            }
                        }
                    });
                } else if (segments.length > 2) {
                    List<QName> processes = _store.listProcesses(segments[1]);
                    if (processes != null && processes.size() > 0) {
                        List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles();
                        for (final File file : files) {
                            String relativePath = requestURI.substring(deplUri + 12 + 9 + segments[1].length());
                            // replace slashes with the correct file separator so the match below is not always false
                            relativePath = relativePath.replace('/', File.separatorChar);
                            if (file.getPath().endsWith(relativePath)) {
                                renderXml(response, new DocBody() {
                                    public void render(Writer out) throws IOException {
                                        write(out, file.getPath());
                                    }
                                });
                                return true;
                            }
                        }
                    } else {
                        renderHtml(response, "No Bundle Found", new DocBody() {
                            public void render(Writer out) throws IOException {
                                out.write("<p>Couldn't find bundle " + segments[2] + "</p>");
                            }
                        });
                    }
                }
            } else if ("getBundleDocs".equals(segments[0])) {
                if (segments.length == 1) {
                    renderXml(response, new DocBody() {
                        public void render(Writer out) throws IOException {
                            out.write("<getBundleDocsResponse>");
                            out.write("<error>Not enough args..</error>");
                            out.write("</getBundleDocsResponse>");
                        }
                    });
                } else if (segments.length == 2) {
                    final String bundleName = segments[1];
                    final List<QName> processes = _store.listProcesses(bundleName);
                    if (processes != null) {
                        renderXml(response, new DocBody() {
                            public void render(Writer out) throws IOException {
                                out.write("<getBundleDocsResponse><name>" + bundleName + "</name>");
                                //final List<File> files = _store.getProcessConfiguration(processes.get(0)).getFiles();
                                //final String pid = _store.getProcessConfiguration(processes.get(0)).getProcessId().toString();

                                for (final QName process : processes) {
                                    List<File> files = _store.getProcessConfiguration(process).getFiles();
                                    String pid = _store.getProcessConfiguration(process).getProcessId()
                                            .toString();
                                    out.write("<process><pid>" + pid + "</pid>");
                                    for (final File file : files) {
                                        if (file.getPath().endsWith(".wsdl")) {
                                            String relativePath = file.getPath().substring(
                                                    _store.getDeployDir().getCanonicalPath().length() + 1)
                                                    .replace(File.separatorChar, '/');
                                            out.write("<wsdl>" + relativePath + "</wsdl>");
                                        }
                                        if (file.getPath().endsWith(".bpel")) {
                                            String relativePath = file.getPath().substring(
                                                    _store.getDeployDir().getCanonicalPath().length() + 1)
                                                    .replace(File.separatorChar, '/');
                                            out.write("<bpel>" + relativePath + "</bpel>");
                                        }

                                    }
                                    out.write("</process>");
                                }
                                out.write("</getBundleDocsResponse>");
                            }
                        });

                    }
                }
            } else if ("getProcessDefinition".equals(segments[0])) {
                if (segments.length == 1) {
                    renderXml(response, new DocBody() {
                        public void render(Writer out) throws IOException {
                            out.write("<getProcessDefinitionResponse>");
                            out.write("<error>Not enough args..</error>");
                            out.write("</getProcessDefinitionResponse>");
                        }
                    });
                } else if (segments.length == 2) {
                    String processName = segments[1];
                    for (QName process : _store.getProcesses()) {
                        String[] nameVer = process.getLocalPart().split("-");
                        if (processName.equals(nameVer[0])) {
                            final String url = root
                                    + bundleUrlFor(_store.getProcessConfiguration(process).getBpelDocument());
                            renderXml(response, new DocBody() {
                                public void render(Writer out) throws IOException {
                                    out.write("<getProcessDefinition>");
                                    out.write("<url>" + url + "</url>");
                                    out.write("</getProcessDefinition>");
                                }
                            });
                        }
                    }

                }
            }
        }
        return true;
    }
    return false;
}

From source file:org.kew.rmf.reconciliation.ws.ReconciliationServiceController.java

/**
 * Retrieve reconciliation service metadata.
 *//*from  w  w w. j  a v a2  s .  co m*/
@RequestMapping(value = "/reconcile/{configName}", method = { RequestMethod.GET,
        RequestMethod.POST }, produces = "application/json; charset=UTF-8")
public ResponseEntity<String> getMetadata(HttpServletRequest request, @PathVariable String configName,
        @RequestParam(value = "callback", required = false) String callback, Model model)
        throws JsonGenerationException, JsonMappingException, IOException {
    logger.info("{}: Get Metadata request", configName);

    String myUrl = request.getScheme() + "://" + request.getServerName()
            + (request.getServerPort() == 80 ? "" : (":" + request.getServerPort()));
    String basePath = servletContext.getContextPath() + "/reconcile/" + configName;

    Metadata metadata;
    try {
        metadata = reconciliationService.getMetadata(configName);
    } catch (MatchExecutionException e) {
        return new ResponseEntity<String>(e.toString(), HttpStatus.NOT_FOUND);
    }

    if (metadata != null) {
        String metadataJson = jsonMapper.writeValueAsString(metadata).replace("LOCAL", myUrl).replace("BASE",
                basePath);
        return new ResponseEntity<String>(wrapResponse(callback, metadataJson), HttpStatus.OK);
    }
    return null;
}