Example usage for javax.servlet.http HttpServletRequest getLocalPort

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

Introduction

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

Prototype

public int getLocalPort();

Source Link

Document

Returns the Internet Protocol (IP) port number of the interface on which the request was received.

Usage

From source file:org.archive.wayback.webapp.ServerRelativeArchivalRedirect.java

@Override
public boolean handleRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws ServletException, IOException {
    if (matchHost != null) {
        if (!matchHost.equals(httpRequest.getServerName())) {
            LOGGER.fine("Wrong host for ServerRelativeRed(" + httpRequest.getServerName() + ")");
            return false;
        }/*from   w w w.j av a2s .  c  om*/
    }
    if (matchPort != -1) {
        if (matchPort != httpRequest.getLocalPort()) {
            LOGGER.fine("Wrong port for ServerRealtiveRed(" + httpRequest.getServerName() + ")("
                    + httpRequest.getLocalPort() + ") :" + httpRequest.getRequestURI());
            return false;
        }
    }
    String replayUrl = (useCollection ? handleRequestWithCollection(httpRequest, httpResponse)
            : handleRequestWithoutCollection(httpRequest, httpResponse));
    if (replayUrl == null && replayPrefix != null) {
        String thisPath = httpRequest.getRequestURI();
        String queryString = httpRequest.getQueryString();
        if (queryString != null) {
            thisPath += "?" + queryString;
        }
        // TODO: rethink this fallback, for now adding https support as
        // well
        if (thisPath.startsWith("/http://") || thisPath.startsWith("/https://")) {
            // assume a replay request:
            StringBuilder sb = new StringBuilder(thisPath.length() + replayPrefix.length() + 16);
            sb.append(replayPrefix);
            sb.append(Timestamp.currentTimestamp().getDateStr());
            sb.append(thisPath);
            replayUrl = sb.toString();
        }
    }
    if (replayUrl != null) {
        // Gotta make sure this is properly cached, or
        // weird things happen:
        httpResponse.addHeader("Vary", "Referer");
        httpResponse.sendRedirect(replayUrl);
        return true;
    }
    return false;
}

From source file:org.mule.transport.servlet.MockHttpServletRequestBuilder.java

public HttpServletRequest buildRequest() throws Exception {
    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    when(mockRequest.getMethod()).thenReturn(method);

    Enumeration<String> emptyEnumeration = new Hashtable<String, String>().elements();
    when(mockRequest.getParameterNames()).thenReturn(emptyEnumeration);

    when(mockRequest.getRequestURI()).thenReturn(requestUri);
    when(mockRequest.getQueryString()).thenReturn(queryString);
    when(mockRequest.getInputStream()).thenReturn(inputStream);
    when(mockRequest.getSession(anyBoolean())).thenReturn(session);
    when(mockRequest.getCharacterEncoding()).thenReturn(characterEncoding);
    when(mockRequest.getLocalPort()).thenReturn(localPort);
    when(mockRequest.getContentType()).thenReturn(contentType);
    when(mockRequest.getRemoteAddr()).thenReturn(host);
    when(mockRequest.getHeader(eq(HttpConstants.HEADER_HOST))).thenReturn(host);
    when(mockRequest.getPathInfo()).thenReturn(pathInfo);

    addParameterExpectations(mockRequest);
    addAttributeExpectations(mockRequest);
    addHeaderExpectations(mockRequest);//from  w w w.  ja  v a  2s .c  om

    return mockRequest;
}

From source file:com.hphoto.server.ApiServlet.java

public void addCategory(Document doc, Element channel, HttpServletRequest request) {
    assert (request.getParameter("user") != null);

    String requestUrl = request.getRequestURL().toString();
    String base = "http://" + request.getServerName()
            + (request.getLocalPort() == 80 ? "" : ":" + Integer.toString(request.getLocalPort()));
    Category[] categories = null;/*from   w  w w.  j a v a 2 s.c  o  m*/
    UserProfile[] users = null;
    String owner = request.getParameter("user");
    String feed = request.getParameter("feed");
    String language = request.getParameter("hl");
    String kind = request.getParameter("kind");
    String albumid = request.getParameter("albumid");
    //Local local = language == null ? request.getLocale() : new Locale(language);
    boolean all = request.getParameter("acess") != null && request.getParameter("acess").equals("all");
    boolean api = feed != null && feed.equals("api");

    try {
        users = server.getUser(owner, 1);
        categories = server.getCategories(owner);
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    if (users == null || users.length == 0) {
        return;
    }

    addNode(doc, channel, "atom", "id", base + "/feed/" + feed + "/user/" + owner);
    addNode(doc, channel, "lastBuildDate", (new Date()).toString());
    addNode(doc, channel, "title", owner + " " + I18nUtil.getText(key, "title", request.getLocale()));
    addNode(doc, channel, "description", "");
    //add base,not complete
    addNode(doc, channel, "link", base + "/" + owner);
    addNode(doc, channel, "managingEditor", owner);
    addNode(doc, channel, "generator", "hphoto.com");
    addNode(doc, channel, "opensearch", "totalResults", "" + (categories != null ? categories.length : 0));
    //addNode(doc, channel, "opensearch", "startIndex", ""+1);
    //addNode(doc, channel, "opensearch", "itemsPerPage", ""+1000);
    Element image = addNode(doc, channel, "image");
    addNode(doc, image, "url", base + "/image/" + owner + "/" + "AHHYILU" + "/s48-c/" + owner);
    addNode(doc, image, "title", owner + " " + I18nUtil.getText(key, "title", request.getLocale()));
    addNode(doc, image, "link", base + "/" + owner);

    //channel
    if (categories != null) {
        for (Category category : categories) {
            if (!all) {
                if (!category.isOpened() || category.getCount() < 1) {
                    continue;
                }
            }
            Element item = addNode(doc, channel, "item");
            addNode(doc, item, "pubDate", category.getCreatdate().toString());
            addNode(doc, item, "atom", "updated", category.getLastupload().toString());
            addNode(doc, item, "title", category.getName());
            addNode(doc, item, "description",
                    getDescription(api, base, owner, category, I18nUtil.getLoacl(request)));
            addNode(doc, item, "link", "");
            addNode(doc, item, "author", owner);
            if (api) {
                //api data here
            }
            Element media = addNode(doc, item, "media:group");
            Element title = addNode(doc, media, "media", "title", category.getName());
            addAttribute(doc, title, "type", "plain");

            Element descript = addNode(doc, media, "media", "descript", "");
            addAttribute(doc, descript, "type", "plain");

            addNode(doc, media, "media", "keywords", "");

            String lablename = category.getLablename();
            String imgurl = category.getImgurl();
            String id = imgurl.substring(imgurl.lastIndexOf('/') + 1, imgurl.lastIndexOf('.'));
            String img = "/image/" + owner + "/" + lablename + "/" + id + ".jpg";
            String thumbnailImg = "/image/" + owner + "/" + lablename + "/s" + 160 + "-c/" + id + ".jpg";
            Element content = addNode(doc, media, "media", "content", "");
            addAttribute(doc, content, "url", base + img);
            addAttribute(doc, content, "type", "image/jpeg");
            addAttribute(doc, content, "medium", "image");

            Element thum = addNode(doc, media, "media", "thumbnail", "");
            addAttribute(doc, thum, "url", base + thumbnailImg);
            addAttribute(doc, thum, "height", "160");
            addAttribute(doc, thum, "width", "160");

            addNode(doc, media, "media", "credit", owner);

        }

    }

}

From source file:org.archive.wayback.core.WaybackRequest.java

/**
 * extract REFERER, remote IP and authorization information from the
 * HttpServletRequest//  ww  w .  j a  va2 s  . co  m
 * 
 * @param httpRequest
 */
private void extractHttpRequestInfo(HttpServletRequest httpRequest) {
    // attempt to get the HTTP referer if present..
    put(WaybackConstants.REQUEST_REFERER_URL, emptyIfNull(httpRequest.getHeader("REFERER")));
    put(WaybackConstants.REQUEST_REMOTE_ADDRESS, emptyIfNull(httpRequest.getRemoteAddr()));
    put(WaybackConstants.REQUEST_WAYBACK_HOSTNAME, emptyIfNull(httpRequest.getLocalName()));
    put(WaybackConstants.REQUEST_WAYBACK_PORT, String.valueOf(httpRequest.getLocalPort()));
    put(WaybackConstants.REQUEST_WAYBACK_CONTEXT, emptyIfNull(httpRequest.getContextPath()));
    put(WaybackConstants.REQUEST_AUTH_TYPE, emptyIfNull(httpRequest.getAuthType()));
    put(WaybackConstants.REQUEST_REMOTE_USER, emptyIfNull(httpRequest.getRemoteUser()));
    put(WaybackConstants.REQUEST_LOCALE_LANG, getUserLocale(httpRequest));

    Cookie[] cookies = httpRequest.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            put(cookie.getName(), cookie.getValue());
        }
    }
}

From source file:com.zimbra.cs.servlet.ZimbraServlet.java

/**
 * Filter the request based on incoming port.  If the allowed.ports
 * parameter is specified for the servlet, the incoming port must
 * match one of the listed ports.//  ww w  . jav  a2 s  .  c  om
 */
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean allowed = isRequestOnAllowedPort(request);
    if (!allowed) {
        SoapProtocol soapProto = SoapProtocol.Soap12;
        ServiceException e = ServiceException.FAILURE("Request not allowed on port " + request.getLocalPort(),
                null);
        ZimbraLog.soap.warn(null, e);
        Element fault = SoapProtocol.Soap12.soapFault(e);
        Element envelope = SoapProtocol.Soap12.soapEnvelope(fault);
        byte[] soapBytes = envelope.toUTF8();
        response.setContentType(soapProto.getContentType());
        response.setBufferSize(soapBytes.length + 2048);
        response.setContentLength(soapBytes.length);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getOutputStream().write(soapBytes);
        return;
    }
    super.service(request, response);
}

From source file:org.archive.wayback.webapp.RequestMapper.java

private String getContextID(HttpServletRequest request) {
    String requestPath = request.getRequestURI();
    String contextPath = request.getContextPath();
    if (requestPath.startsWith(contextPath)) {
        requestPath = requestPath.substring(contextPath.length());
    }//from  w ww  . j av a  2 s  .com
    String collection = "";
    if (requestPath.startsWith("/")) {
        int secondSlash = requestPath.indexOf("/", 1);
        if (secondSlash != -1) {
            collection = PORT_SEPARATOR + requestPath.substring(1, requestPath.indexOf("/", 1));
        } else {
            collection = PORT_SEPARATOR + requestPath.substring(1);
        }
    }
    return String.valueOf(request.getLocalPort()) + collection;
}

From source file:net.xy.jcms.shared.adapter.HttpRequestDataAccessContext.java

/**
 * default constructor/*w ww .j a v a2  s  .  c  o  m*/
 * 
 * @param request
 * @throws MalformedURLException
 * @throws URISyntaxException
 */
public HttpRequestDataAccessContext(final HttpServletRequest request)
        throws MalformedURLException, URISyntaxException {
    // gets cappsubrand default locale and various other jj related
    // informations mendatory to retrieve jj configuration
    try {
        request.setCharacterEncoding("UTF-8");
    } catch (final UnsupportedEncodingException e) {
    }
    contextPath = request.getContextPath() + "/";
    requestPath = request.getPathInfo().length() > 0 && request.getPathInfo().charAt(0) == '/'
            ? request.getPathInfo().substring(1)
            : request.getPathInfo();
    rootUrl = new URI(request.getProtocol().split("/", 2)[0], null, request.getLocalName(),
            request.getLocalPort(), "/", null, null);

    // properties
    if (request.getParameter("flushConfig") != null) {
        properties.put("flushConfig", true);
    }
}

From source file:com.hphoto.server.ApiServlet.java

public void addPhoto(Document doc, Element channel, HttpServletRequest request) {

    assert (request.getParameter("user") != null);
    assert (request.getParameter("album") != null);

    String requestUrl = request.getRequestURL().toString();
    String base = "http://" + request.getServerName()
            + (request.getLocalPort() == 80 ? "" : ":" + Integer.toString(request.getLocalPort()));

    Image[] images = null;/*from w ww .j a va 2  s  .  c o m*/
    UserProfile[] users = null;
    Category category = null;
    String owner = request.getParameter("user");
    String album = request.getParameter("album");
    String authKey = request.getParameter("authKey");

    boolean api = request.getParameter("feed") != null && request.getParameter("feed").equals("api");

    try {
        users = server.getUser(owner, 1);
        images = server.getImages(owner, album);
        category = server.getCategory(owner, album);
    } catch (IOException e) {
        return;
    }

    if (users == null || users.length == 0) {
        return;
    }
    if (category == null) {
        return;
    }
    if (!category.isOpened()) {
        if (!category.getAuthkey().equals(authKey)) {
            return;
        }
    }

    addNode(doc, channel, "atom", "id",
            base + "/feed/" + request.getParameter("feed") + "/user/" + owner + "/album/" + album);
    addNode(doc, channel, "lastBuildDate", (new Date()).toString());
    addNode(doc, channel, "title", owner + " " + I18nUtil.getText(key, "title", I18nUtil.getLoacl(request)));
    addNode(doc, channel, "description", "");
    //add base,not complete
    addNode(doc, channel, "link", base + "/" + owner + "/" + album
            + (category.getAuthkey() != null ? "?authKey=" + category.getAuthkey() : ""));
    addNode(doc, channel, "managingEditor", owner);
    addNode(doc, channel, "generator", "hphoto.com");
    addNode(doc, channel, "opensearch", "totalResults", "" + (images != null ? images.length : 0));
    addNode(doc, channel, "opensearch", "startIndex", "" + 1);
    addNode(doc, channel, "opensearch", "itemsPerPage", "" + 1000);

    String lablename = category.getLablename();
    String imgurl = category.getImgurl();
    String id = imgurl.substring(imgurl.lastIndexOf('/') + 1, imgurl.lastIndexOf('.'));
    String img = "/image/" + owner + "/" + lablename + "/s" + 160 + "-c/" + id + ".jpg";

    Element timage = addNode(doc, channel, "image");
    addNode(doc, timage, "url", base + img);
    addNode(doc, timage, "title", category.getName());
    addNode(doc, timage, "link", base + "/" + owner + "/" + lablename
            + (category.getAuthkey() != null ? "?authKey=" + category.getAuthkey() : ""));

    if (api) {
        //api data here
    }

    if (images != null) {
        //channel
        for (Image image : images) {

            Element item = addNode(doc, channel, "item");
            addNode(doc, item, "pubDate", image.getTimestamp().toString());
            addNode(doc, item, "atom", "updated", image.getTimestamp().toString());
            addNode(doc, item, "title", image.getFileName());
            addNode(doc, item, "description",
                    getDescription(api, base, owner, category, image, I18nUtil.getLoacl(request)));
            addNode(doc, item, "link", "");
            addNode(doc, item, "author", owner);
            if (api) {
                //api data here
            }
            Element media = addNode(doc, item, "media:group");
            Element title = addNode(doc, media, "media", "title", image.getFileName());
            addAttribute(doc, title, "type", "plain");

            Element descript = addNode(doc, media, "media", "descript", "");
            addAttribute(doc, descript, "type", "plain");

            addNode(doc, media, "media", "keywords", "");
            String img1 = base + "/image/" + owner + "/" + lablename + "/" + id + ".jpg";
            String thumbnailImg = base + "/image/" + owner + "/" + lablename + "/s" + 288 + "/" + image.getId()
                    + ".jpg";
            Element content = addNode(doc, media, "media", "content", "");
            addAttribute(doc, content, "url", img1);
            addAttribute(doc, content, "type", "image/jpeg");
            addAttribute(doc, content, "medium", "image");
            int[] value = getWidthAndHeight(image.getWidth(), image.getHeight(), 288);
            Element thum = addNode(doc, media, "media", "thumbnail", "");
            addAttribute(doc, thum, "url", thumbnailImg);
            addAttribute(doc, thum, "height", Integer.toString(value[1]));
            addAttribute(doc, thum, "width", Integer.toString(value[0]));

            addNode(doc, media, "media", "credit", owner);
        }
    }
}

From source file:org.archive.wayback.webapp.AccessPoint.java

/**
 * Construct an absolute URL that points to the root of the context that
 * recieved the request, including a trailing "/".
 * // ww  w.  j a  v  a2 s  .  co  m
 * @return String absolute URL pointing to the Context root where the
 *         request was revieved.
 */
private String getAbsoluteContextPrefix(HttpServletRequest httpRequest, boolean useRequestServer) {

    StringBuilder prefix = new StringBuilder();
    prefix.append(WaybackConstants.HTTP_URL_PREFIX);
    String waybackPort = null;
    if (useRequestServer) {
        prefix.append(httpRequest.getLocalName());
        waybackPort = String.valueOf(httpRequest.getLocalPort());
    } else {
        prefix.append(httpRequest.getServerName());
        waybackPort = String.valueOf(httpRequest.getServerPort());
    }
    if (!waybackPort.equals(WaybackConstants.HTTP_DEFAULT_PORT)) {
        prefix.append(":").append(waybackPort);
    }
    String contextPath = getContextPath(httpRequest);
    prefix.append(contextPath);
    return prefix.toString();
}

From source file:eu.planets_project.tb.impl.data.util.DataHandlerImpl.java

@Deprecated
public URI getHttpFileRef(File localFileRef, boolean input) throws URISyntaxException, FileNotFoundException {
    if (!localFileRef.canRead()) {
        throw new FileNotFoundException(localFileRef + " not found");
    }/*from www. j av a2s.co  m*/
    HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();
    String authority = req.getLocalName() + ":" + Integer.toString(req.getLocalPort());
    //distinguish between inputdata and outputdata
    if (input) {
        //URI input file ref to be created
        //URI(scheme,authority,path,query,fragement)
        return new URI("http", authority, "/planets-testbed/inputdata/" + localFileRef.getName(), null, null);
    } else {
        //URI output file ref to be created
        return new URI("http", authority, "/planets-testbed/outputdata/" + localFileRef.getName(), null, null);
    }
}