Java Code Examples for javax.servlet.http.HttpServletRequest#getRemotePort()

The following examples show how to use javax.servlet.http.HttpServletRequest#getRemotePort() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LogToFile.java    From OASystem with MIT License 6 votes vote down vote up
public void log(HttpServletRequest req, HttpServletResponse resp,String content){
	String str = "["+sdf.format(new Date())+"]"+"\t";//����ʱ��
	str += req.getMethod()+"\t\t";//����ʽ
	str += req.getRemoteAddr()+":"+req.getRemotePort()+"\t";//����IP
	//�����û�
	HttpSession session = req.getSession();
	String userId = (String)session.getAttribute("userJobId");
	if(userId==null){
		str += "�ο�\t\t";
	}else{
		str += userId+"\t\t";
	}
	str += content+"\t";//����
	str += req.getServletPath()+"\t";//����·��
	str += req.getQueryString()+"\t";//����
	str += System.lineSeparator();
	wirteToFile(str);
	System.out.println("��"+PROJECT_NAME+"��"+str);
}
 
Example 2
Source File: HttpRequestInfo.java    From odo with Apache License 2.0 6 votes vote down vote up
public HttpRequestInfo(HttpServletRequest request) {
    this.authType = request.getAuthType();
    this.contextPath = request.getContextPath();
    populateHeaders(request);
    this.method = request.getMethod();
    this.pathInfo = request.getPathInfo();
    this.queryString = request.getQueryString();
    this.requestURI = request.getRequestURI();
    this.servletPath = request.getServletPath();
    this.contentType = request.getContentType();
    this.characterEncoding = request.getCharacterEncoding();
    this.contentLength = request.getContentLength();
    this.localName = request.getLocalName();
    this.localPort = request.getLocalPort();
    populateParameters(request);
    this.protocol = request.getProtocol();
    this.remoteAddr = request.getRemoteAddr();
    this.remoteHost = request.getRemoteHost();
    this.remotePort = request.getRemotePort();
    this.serverName = request.getServerName();
    this.secure = request.isSecure();
    populateAttributes(request);
}
 
Example 3
Source File: Zippy.java    From XRTB with Apache License 2.0 6 votes vote down vote up
/**
 * Return the IP address of this
 * 
 * @param request
 *            HttpServletRequest. The web browser's request object.
 * @return String the ip:remote-port of this browswer's connection.
 */

public String getIpAddress(HttpServletRequest request) {
	String ip = request.getHeader("x-forwarded-for");
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		ip = request.getHeader("Proxy-Client-IP");
	}
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		ip = request.getHeader("WL-Proxy-Client-IP");
	}
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		ip = request.getRemoteAddr();
	}
	ip += ":" + request.getRemotePort();
	return ip;
}
 
Example 4
Source File: PeerSpanDecorator.java    From opentracing-toolbox with MIT License 6 votes vote down vote up
@Override
public void onRequest(final HttpServletRequest request, final Span span) {
    final String ip = request.getRemoteAddr();
    final String hostname = request.getRemoteHost();
    final int port = request.getRemotePort();

    span.setTag(PEER_ADDRESS, hostname + ":" + port);
    span.setTag(PEER_PORT, port);

    if (!ip.equals(hostname)) {
        span.setTag(PEER_HOSTNAME, hostname);
    }

    if (isProbablyIPv6(ip)) {
        span.setTag(PEER_HOST_IPV6, ip);
    } else {
        span.setTag(PEER_HOST_IPV4, ip);
    }
}
 
Example 5
Source File: HttpReceiverServlet.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
boolean validatePostRequest(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
  boolean valid = false;
  if (!getReceiver().isApplicationIdEnabled() || validateAppId(req, res)) {
    String compression = req.getHeader(HttpConstants.X_SDC_COMPRESSION_HEADER);
    if (compression == null) {
      valid = true;
    } else {
      switch (compression) {
        case HttpConstants.SNAPPY_COMPRESSION:
          valid = true;
          break;
        default:
          String requestor = req.getRemoteAddr() + ":" + req.getRemotePort();
          LOG.warn("Invalid compression '{}' in request from '{}', returning error", compression, requestor);
          res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported compression: " + compression);
          break;
      }
    }
  }
  return valid && getReceiver().validate(req, res);
}
 
Example 6
Source File: ServletConnectionPrincipal.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
public ServletConnectionPrincipal(HttpServletRequest request)
{
    _address = new InetSocketAddress(request.getRemoteHost(), request.getRemotePort());
    _metadata = new ServletRequestMetaData(request);
    HttpSession session =  request.getSession(false);
    if (session != null)
    {
        MessageDigest md;
        try
        {
            md = MessageDigest.getInstance("SHA-256");
            md.update(session.getId().getBytes(UTF8));
        }
        catch (NoSuchAlgorithmException | UnsupportedEncodingException e)
        {
            throw new RuntimeException("Cannot create SHA-256 hash", e);
        }
        byte[] digest = md.digest();
        _sessionId = Base64.getEncoder().encodeToString(digest).substring(0, HASH_TRUNCATION_LENGTH);
    }
    else
    {
        _sessionId = null;
    }
}
 
Example 7
Source File: AuthenticationDataHttp.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public AuthenticationDataHttp(HttpServletRequest request) {
    if (request == null) {
        throw new IllegalArgumentException();
    }
    this.request = request;
    this.remoteAddress = new InetSocketAddress(request.getRemoteAddr(), request.getRemotePort());
}
 
Example 8
Source File: HttpServletRequestSnapshot.java    From cxf with Apache License 2.0 5 votes vote down vote up
public HttpServletRequestSnapshot(HttpServletRequest request) {
    super(request);
    authType = request.getAuthType();
    characterEncoding = request.getCharacterEncoding();
    contentLength = request.getContentLength();
    contentType = request.getContentType();
    contextPath = request.getContextPath();
    cookies = request.getCookies();
    requestHeaderNames = request.getHeaderNames();
    Enumeration<String> tmp = request.getHeaderNames();
    while (tmp.hasMoreElements()) {
        String key = tmp.nextElement();
        headersMap.put(key, request.getHeaders(key));
    }
    localAddr = request.getLocalAddr();
    local = request.getLocale();
    localName = request.getLocalName();
    localPort = request.getLocalPort();
    method = request.getMethod();
    pathInfo = request.getPathInfo();
    pathTranslated = request.getPathTranslated();
    protocol = request.getProtocol();
    queryString = request.getQueryString();
    remoteAddr = request.getRemoteAddr();
    remoteHost = request.getRemoteHost();
    remotePort = request.getRemotePort();
    remoteUser = request.getRemoteUser();
    requestURI = request.getRequestURI();
    requestURL = request.getRequestURL();
    requestedSessionId = request.getRequestedSessionId();
    schema = request.getScheme();
    serverName = request.getServerName();
    serverPort = request.getServerPort();
    servletPath = request.getServletPath();
    if (request.isRequestedSessionIdValid()) {
        session = request.getSession();
    }
    principal = request.getUserPrincipal();
}
 
Example 9
Source File: RTBServer.java    From XRTB with Apache License 2.0 5 votes vote down vote up
/**
 * Return the IP address of this
 * 
 * @param request
 *            HttpServletRequest. The web browser's request object.
 * @return String the ip:remote-port of this browswer's connection.
 */
public String getIpAddress(HttpServletRequest request) {
	String ip = request.getHeader("x-forwarded-for");
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		ip = request.getHeader("Proxy-Client-IP");
	}
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		ip = request.getHeader("WL-Proxy-Client-IP");
	}
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		ip = request.getRemoteAddr();
	}
	ip += ":" + request.getRemotePort();
	return ip;
}
 
Example 10
Source File: HttpReceiverServlet.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected boolean validateAppId(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
  boolean valid = false;
  List<? extends CredentialValue> ourAppIds = null;
  try {
    ourAppIds = getReceiver().getAppIds();
  } catch (StageException e) {
    throw new IOException("Cant resolve credential value", e);
  }
  String requestor = req.getRemoteAddr() + ":" + req.getRemotePort();
  String reqAppId = req.getHeader(HttpConstants.X_SDC_APPLICATION_ID_HEADER);

  if (reqAppId == null && receiver.isAppIdViaQueryParamAllowed()) {
    String[] ids = getQueryParameters(req).get(HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM);
    if(ids!=null && ids.length>0)
      reqAppId = ids[0];
  }

  if (reqAppId == null) {
    LOG.warn("Request from '{}' missing appId, rejected", requestor);
    res.sendError(HttpServletResponse.SC_FORBIDDEN, "Missing 'appId'");
  } else {
    int counter = 0;
    while(counter < ourAppIds.size() && !valid){
      valid = valid || ourAppIds.get(counter).get().equals(reqAppId);
      counter++;
    }
    if(!valid) {
      LOG.warn("Request from {} rejected due to invalid appid {}", requestor, reqAppId);
      res.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid 'appId'");
    }
  }
  return valid;
}
 
Example 11
Source File: WebMQ.java    From bidder with Apache License 2.0 5 votes vote down vote up
/**
 * Return the IP address of this
 * 
 * @param request
 *            HttpServletRequest. The web browser's request object.
 * @return String the ip:remote-port of this browswer's connection.
 */
public String getIpAddress(HttpServletRequest request) {
	String ip = request.getHeader("x-forwarded-for");
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		ip = request.getHeader("Proxy-Client-IP");
	}
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		ip = request.getHeader("WL-Proxy-Client-IP");
	}
	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		ip = request.getRemoteAddr();
	}
	ip += ":" + request.getRemotePort();
	return ip;
}
 
Example 12
Source File: RTBServer.java    From bidder with Apache License 2.0 5 votes vote down vote up
/**
 * Return the IP address of this
 *
 * @param request HttpServletRequest. The web browser's request object.
 * @return String the ip:remote-port of this browswer's connection.
 */
public String getIpAddress(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
    }
    ip += ":" + request.getRemotePort();
    return ip;
}
 
Example 13
Source File: SiteToSiteResource.java    From nifi with Apache License 2.0 4 votes vote down vote up
private PeerDescription getSourcePeerDescription(@Context HttpServletRequest req) {
    return new PeerDescription(req.getRemoteHost(), req.getRemotePort(), req.isSecure());
}
 
Example 14
Source File: KeycloakSessionServletFilter.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    servletRequest.setCharacterEncoding("UTF-8");

    final HttpServletRequest request = (HttpServletRequest)servletRequest;

    KeycloakSessionFactory sessionFactory = (KeycloakSessionFactory) servletRequest.getServletContext().getAttribute(KeycloakSessionFactory.class.getName());
    KeycloakSession session = sessionFactory.create();
    Resteasy.pushContext(KeycloakSession.class, session);
    ClientConnection connection = new ClientConnection() {
        @Override
        public String getRemoteAddr() {
            return request.getRemoteAddr();
        }

        @Override
        public String getRemoteHost() {
            return request.getRemoteHost();
        }

        @Override
        public int getRemotePort() {
            return request.getRemotePort();
        }

        @Override
        public String getLocalAddr() {
            return request.getLocalAddr();
        }

        @Override
        public int getLocalPort() {
            return request.getLocalPort();
        }
    };
    session.getContext().setConnection(connection);
    Resteasy.pushContext(ClientConnection.class, connection);

    KeycloakTransaction tx = session.getTransactionManager();
    Resteasy.pushContext(KeycloakTransaction.class, tx);
    tx.begin();

    try {
        filterChain.doFilter(servletRequest, servletResponse);
    } finally {
        if (servletRequest.isAsyncStarted()) {
            servletRequest.getAsyncContext().addListener(createAsyncLifeCycleListener(session));
        } else {
            closeSession(session);
        }
    }
}
 
Example 15
Source File: NetworkUtils.java    From spring-boot with Apache License 2.0 4 votes vote down vote up
public static int getPort(HttpServletRequest request) {
    return request.getRemotePort();
}
 
Example 16
Source File: NetworkUtils.java    From spring-boot with Apache License 2.0 4 votes vote down vote up
public static int getPort(HttpServletRequest request) {
    return request.getRemotePort();
}
 
Example 17
Source File: KeycloakSessionServletFilter.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    servletRequest.setCharacterEncoding("UTF-8");

    final HttpServletRequest request = (HttpServletRequest)servletRequest;

    KeycloakSessionFactory sessionFactory = (KeycloakSessionFactory) servletRequest.getServletContext().getAttribute(KeycloakSessionFactory.class.getName());
    KeycloakSession session = sessionFactory.create();
    Resteasy.pushContext(KeycloakSession.class, session);
    ClientConnection connection = new ClientConnection() {
        @Override
        public String getRemoteAddr() {
            return request.getRemoteAddr();
        }

        @Override
        public String getRemoteHost() {
            return request.getRemoteHost();
        }

        @Override
        public int getRemotePort() {
            return request.getRemotePort();
        }

        @Override
        public String getLocalAddr() {
            return request.getLocalAddr();
        }

        @Override
        public int getLocalPort() {
            return request.getLocalPort();
        }
    };
    session.getContext().setConnection(connection);
    Resteasy.pushContext(ClientConnection.class, connection);

    KeycloakTransaction tx = session.getTransactionManager();
    Resteasy.pushContext(KeycloakTransaction.class, tx);
    tx.begin();

    try {
        filterChain.doFilter(servletRequest, servletResponse);
    } finally {
        if (servletRequest.isAsyncStarted()) {
            servletRequest.getAsyncContext().addListener(createAsyncLifeCycleListener(session));
        } else {
            closeSession(session);
        }
    }
}
 
Example 18
Source File: NetworkUtils.java    From spring-boot with Apache License 2.0 4 votes vote down vote up
public static int getPort(HttpServletRequest request) {
    return request.getRemotePort();
}
 
Example 19
Source File: ServletRequestCopy.java    From onedev with MIT License 4 votes vote down vote up
public ServletRequestCopy(HttpServletRequest request) {
	this.servletPath = request.getServletPath();
	this.contextPath = request.getContextPath();
	this.pathInfo = request.getPathInfo();
	this.requestUri = request.getRequestURI();
	this.requestURL = request.getRequestURL();
	this.method = request.getMethod();
	this.serverName = request.getServerName();
	this.serverPort = request.getServerPort();
	this.protocol = request.getProtocol();
	this.scheme = request.getScheme();
	
	
	/*
	 * have to comment out below two lines as otherwise web socket will
	 * report UnSupportedOperationException upon connection
	 */
	//this.characterEncoding = request.getCharacterEncoding();
	//this.contentType = request.getContentType();
	//this.requestedSessionId = request.getRequestedSessionId();
	this.characterEncoding = null;
	this.contentType = null;
	this.requestedSessionId = null;
	
	this.locale = request.getLocale();
	this.locales = request.getLocales();
	this.isSecure = request.isSecure();
	this.remoteUser = request.getRemoteUser();
	this.remoteAddr = request.getRemoteAddr();
	this.remoteHost = request.getRemoteHost();
	this.remotePort = request.getRemotePort();
	this.localAddr = request.getLocalAddr();
	this.localName = request.getLocalName();
	this.localPort = request.getLocalPort();
	this.pathTranslated = request.getPathTranslated();
	this.principal = request.getUserPrincipal();

	HttpSession session = request.getSession(true);
	httpSession = new HttpSessionCopy(session);

	String s;
	Enumeration<String> e = request.getHeaderNames();
	while (e != null && e.hasMoreElements()) {
		s = e.nextElement();
		Enumeration<String> headerValues = request.getHeaders(s);
		this.headers.put(s, headerValues);
	}

	e = request.getAttributeNames();
	while (e != null && e.hasMoreElements()) {
		s = e.nextElement();
		attributes.put(s, request.getAttribute(s));
	}

	e = request.getParameterNames();
	while (e != null && e.hasMoreElements()) {
		s = e.nextElement();
		parameters.put(s, request.getParameterValues(s));
	}
}
 
Example 20
Source File: DataTransferResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
private Peer constructPeer(final HttpServletRequest req, final InputStream inputStream,
                           final OutputStream outputStream, final String portId, final String transactionId) {
    String clientHostName = req.getRemoteHost();
    try {
        // req.getRemoteHost returns IP address, try to resolve hostname to be consistent with RAW protocol.
        final InetAddress clientAddress = InetAddress.getByName(clientHostName);
        clientHostName = clientAddress.getHostName();
    } catch (UnknownHostException e) {
        logger.info("Failed to resolve client hostname {}, due to {}", clientHostName, e.getMessage());
    }
    final int clientPort = req.getRemotePort();

    final PeerDescription peerDescription = new PeerDescription(clientHostName, clientPort, req.isSecure());

    final NiFiUser user = NiFiUserUtils.getNiFiUser();
    final String userDn = user == null ? null : user.getIdentity();
    final HttpServerCommunicationsSession commSession = new HttpServerCommunicationsSession(inputStream, outputStream, transactionId, userDn);

    boolean useCompression = false;
    final String useCompressionStr = req.getHeader(HANDSHAKE_PROPERTY_USE_COMPRESSION);
    if (!isEmpty(useCompressionStr) && Boolean.valueOf(useCompressionStr)) {
        useCompression = true;
    }

    final String requestExpiration = req.getHeader(HANDSHAKE_PROPERTY_REQUEST_EXPIRATION);
    final String batchCount = req.getHeader(HANDSHAKE_PROPERTY_BATCH_COUNT);
    final String batchSize = req.getHeader(HANDSHAKE_PROPERTY_BATCH_SIZE);
    final String batchDuration = req.getHeader(HANDSHAKE_PROPERTY_BATCH_DURATION);

    commSession.putHandshakeParam(HandshakeProperty.PORT_IDENTIFIER, portId);
    commSession.putHandshakeParam(HandshakeProperty.GZIP, String.valueOf(useCompression));

    if (!isEmpty(requestExpiration)) {
        commSession.putHandshakeParam(REQUEST_EXPIRATION_MILLIS, requestExpiration);
    }
    if (!isEmpty(batchCount)) {
        commSession.putHandshakeParam(BATCH_COUNT, batchCount);
    }
    if (!isEmpty(batchSize)) {
        commSession.putHandshakeParam(BATCH_SIZE, batchSize);
    }
    if (!isEmpty(batchDuration)) {
        commSession.putHandshakeParam(BATCH_DURATION, batchDuration);
    }

    if (peerDescription.isSecure()) {
        final NiFiUser nifiUser = NiFiUserUtils.getNiFiUser();
        logger.debug("initiating peer, nifiUser={}", nifiUser);
        commSession.setUserDn(nifiUser.getIdentity());
    }

    // TODO: Followed how SocketRemoteSiteListener define peerUrl and clusterUrl, but it can be more meaningful values, especially for clusterUrl.
    final String peerUrl = "nifi://" + clientHostName + ":" + clientPort;
    final String clusterUrl = "nifi://localhost:" + req.getLocalPort();

    return new Peer(peerDescription, commSession, peerUrl, clusterUrl);
}