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

The following examples show how to use javax.servlet.http.HttpServletRequest#getRemoteHost() . These examples are extracted from open source projects. 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
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 2
protected DriverGeneric IsConnected(HttpServletRequest Req)
{    
StartFramework();
String Tok=ExtractTok(Req);
if (Tok==null)
    return(null);
CurrentSession CS=PoolSessions.GetSession(Tok);
if (CS!=null)
    {
    PoolSessions.GetSession(Tok).setLastUse(new Date());
    return(PoolSessions.GetSession(Tok).getDrv());
    }
try {
DriverGeneric D=ProdocFW.getSession("PD", Tok, Tok);
CS=new CurrentSession(D.getUser().getName(), new Date(), Req.getRemoteHost(), D);
PoolSessions.AddSession(Tok, CS);
return(D);
} catch (Exception Ex)
    {
    PDLog.Error(Ex.getLocalizedMessage());
    return(null);
    }
}
 
Example 3
Source Project: molicode   File: LogInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest httpServletRequest,
                         HttpServletResponse httpServletResponse, Object o) throws Exception {
    //System.out.println("当前线程:" + Thread.currentThread().getName());
    String sid = httpServletRequest.getParameter(CommonConstant.SID);
    if (StringUtils.isNotEmpty(sid)) {
        MDC.put(CommonConstant.SID, sid);
    }

    //判断是否为本地ip访问,否则抛异常,避免出现严重问题
    String remoteHost = httpServletRequest.getRemoteHost();
    if (!Objects.equals(remoteHost, CommonConstant.LOCAL_HOST_IP) && !Profiles.getInstance().isHeadLess()) {
        return false;
    }
    return true;
}
 
Example 4
Source Project: guacamole-client   File: APIRequest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Wraps the given HttpServletRequest, using the given MultivaluedMap to
 * provide all request parameters. All HttpServletRequest functions which
 * do not deal with parameter names and values are delegated to the wrapped
 * request.
 *
 * @param request
 *     The HttpServletRequest to wrap.
 *
 * @param parameters
 *     All request parameters.
 */
public APIRequest(HttpServletRequest request,
        MultivaluedMap<String, String> parameters) {

    super(request);

    // Grab the remote host info
    this.remoteHost = request.getRemoteHost();

    // Grab the remote ip info
    this.remoteAddr = request.getRemoteAddr();

    // Copy parameters from given MultivaluedMap 
    this.parameters = new HashMap<String, String[]>(parameters.size());
    for (Map.Entry<String, List<String>> entry : parameters.entrySet()) {

        // Get parameter name and all corresponding values
        String name = entry.getKey();
        List<String> values = entry.getValue();

        // Add parameters to map
        this.parameters.put(name, values.toArray(new String[values.size()]));
        
    }
    
}
 
Example 5
@Override
public void onBeginRequest(RequestCycle cycle) {
	String username = "";
	if (NextServerSession.get().isSignedIn()) {
		username = NextServerSession.get().getUsername();
	}

	Session session = NextServerSession.get();
	String sessionId = NextServerSession.get().getId();
	if (sessionId == null) {
		session.bind();
		sessionId = session.getId();
	}

	HttpServletRequest request = ((ServletWebRequest) RequestCycle.get().getRequest()).getContainerRequest();
	String ip = request.getHeader("X-Forwarded-For");
	if (ip == null) {
		ip = request.getRemoteHost();
	}

	MDC.put("username", username);
	MDC.put("session", sessionId);
	MDC.put("ip", ip);
}
 
Example 6
Source Project: Tomcat7.0.67   File: TestRemoteIpFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokeAllProxiesAreInternal() throws Exception {

    // PREPARE
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11");
    filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3");
    filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for");
    filterDef.addInitParameter("proxiesHeader", "x-forwarded-by");

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("192.168.0.10");
    request.setRemoteHost("remote-host-original-value");
    request.addHeader("x-forwarded-for", "140.211.11.130, 192.168.0.10, 192.168.0.11");

    // TEST
    HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest();

    // VERIFY
    String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for");
    assertNull("all proxies are internal, x-forwarded-for must be null", actualXForwardedFor);

    String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by");
    assertNull("all proxies are internal, x-forwarded-by must be null", actualXForwardedBy);

    String actualRemoteAddr = actualRequest.getRemoteAddr();
    assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr);

    String actualRemoteHost = actualRequest.getRemoteHost();
    assertEquals("remoteHost", "140.211.11.130", actualRemoteHost);
}
 
Example 7
Source Project: development   File: ExampleServlet.java    License: Apache License 2.0 5 votes vote down vote up
public static String getRealRootPath(HttpServletRequest request)
        throws IOException {
    String remoteHostName = request.getRemoteHost();
    if ("127.0.0.1".equals(remoteHostName)) {
        remoteHostName = "localhost";
    } else {
        remoteHostName = InetLookup.resolveHost(remoteHostName);
        int idx = remoteHostName.indexOf('.');
        if (idx > 0) {
            remoteHostName = remoteHostName.substring(0, idx);
        }
    }
    return new File(Constants.ROOT_PATH, remoteHostName).getCanonicalPath();
}
 
Example 8
Source Project: Tomcat8-Source-Read   File: TestRemoteIpFilter.java    License: MIT License 5 votes vote down vote up
@Test
public void testInvokeAllProxiesAreInternal() throws Exception {

    // PREPARE
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11");
    filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3");
    filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for");
    filterDef.addInitParameter("proxiesHeader", "x-forwarded-by");

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("192.168.0.10");
    request.setRemoteHost("remote-host-original-value");
    request.addHeader("x-forwarded-for", "140.211.11.130, 192.168.0.10, 192.168.0.11");

    // TEST
    HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest();

    // VERIFY
    String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for");
    Assert.assertNull("all proxies are internal, x-forwarded-for must be null", actualXForwardedFor);

    String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by");
    Assert.assertNull("all proxies are internal, x-forwarded-by must be null", actualXForwardedBy);

    String actualRemoteAddr = actualRequest.getRemoteAddr();
    Assert.assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr);

    String actualRemoteHost = actualRequest.getRemoteHost();
    Assert.assertEquals("remoteHost", "140.211.11.130", actualRemoteHost);
}
 
Example 9
Source Project: sample.ferret   File: RequestData.java    License: Apache License 2.0 5 votes vote down vote up
public RequestData(final HttpServletRequest request) {
    method = request.getMethod();
    uri = request.getRequestURI();
    protocol = request.getProtocol();
    servletPath = request.getServletPath();
    pathInfo = request.getPathInfo();
    pathTranslated = request.getPathTranslated();
    characterEncoding = request.getCharacterEncoding();
    queryString = request.getQueryString();
    contentLength = request.getContentLength();
    contentType = request.getContentType();
    serverName = request.getServerName();
    serverPort = request.getServerPort();
    remoteUser = request.getRemoteUser();
    remoteAddress = request.getRemoteAddr();
    remoteHost = request.getRemoteHost();
    remotePort = request.getRemotePort();
    localAddress = request.getLocalAddr();
    localHost = request.getLocalName();
    localPort = request.getLocalPort();
    authorizationScheme = request.getAuthType();
    preferredClientLocale = request.getLocale();
    allClientLocales = Collections.list(request.getLocales());
    contextPath = request.getContextPath();
    userPrincipal = request.getUserPrincipal();
    requestHeaders = getRequestHeaders(request);
    cookies = getCookies(request.getCookies());
    requestAttributes = getRequestAttributes(request);
}
 
Example 10
Source Project: Tomcat8-Source-Read   File: TestRemoteIpFilter.java    License: MIT License 5 votes vote down vote up
@Test
public void testInvokeNotAllowedRemoteAddr() throws Exception {
    // PREPARE
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11");
    filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3");
    filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for");
    filterDef.addInitParameter("proxiesHeader", "x-forwarded-by");

    MockHttpServletRequest request = new MockHttpServletRequest();

    request.setRemoteAddr("not-allowed-internal-proxy");
    request.setRemoteHost("not-allowed-internal-proxy-host");
    request.setHeader("x-forwarded-for", "140.211.11.130, proxy1, proxy2");

    // TEST
    HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest();

    // VERIFY
    String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for");
    Assert.assertEquals("x-forwarded-for must be unchanged", "140.211.11.130, proxy1, proxy2", actualXForwardedFor);

    String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by");
    Assert.assertNull("x-forwarded-by must be null", actualXForwardedBy);

    String actualRemoteAddr = actualRequest.getRemoteAddr();
    Assert.assertEquals("remoteAddr", "not-allowed-internal-proxy", actualRemoteAddr);

    String actualRemoteHost = actualRequest.getRemoteHost();
    Assert.assertEquals("remoteHost", "not-allowed-internal-proxy-host", actualRemoteHost);
}
 
Example 11
Source Project: Tomcat7.0.67   File: TestRemoteIpFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIncomingRequestIsSecuredButProtocolHeaderSaysItIsNotWithDefaultValues() throws Exception {
    // PREPARE
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("protocolHeader", "x-forwarded-proto");

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("192.168.0.10");
    request.setSecure(true);
    request.setScheme("https");
    request.setHeader("x-forwarded-for", "140.211.11.130");
    request.setHeader("x-forwarded-proto", "http");

    // TEST
    HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest();

    // VERIFY
    boolean actualSecure = actualRequest.isSecure();
    assertFalse("request must be unsecured as header x-forwarded-proto said it is http", actualSecure);

    String actualScheme = actualRequest.getScheme();
    assertEquals("scheme must be http as header x-forwarded-proto said it is http", "http", actualScheme);

    String actualRemoteAddr = actualRequest.getRemoteAddr();
    assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr);

    String actualRemoteHost = actualRequest.getRemoteHost();
    assertEquals("remoteHost", "140.211.11.130", actualRemoteHost);

}
 
Example 12
Source Project: SpringAll   File: PreSendForwardFilter.java    License: MIT License 5 votes vote down vote up
@Override
public Object run() {
    RequestContext requestContext = RequestContext.getCurrentContext();
    HttpServletRequest request = requestContext.getRequest();
    String host = request.getRemoteHost();
    String method = request.getMethod();
    String uri = request.getRequestURI();
    log.info("请求URI:{},HTTP Method:{},请求IP:{}", uri, method, host);
    return null;
}
 
Example 13
Source Project: Tomcat7.0.67   File: TestRemoteIpFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokeUntrustedProxyInTheChain() throws Exception {
    // PREPARE
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11");
    filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3");
    filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for");
    filterDef.addInitParameter("proxiesHeader", "x-forwarded-by");

    MockHttpServletRequest request = new MockHttpServletRequest();

    request.setRemoteAddr("192.168.0.10");
    request.setRemoteHost("remote-host-original-value");
    request.setHeader("x-forwarded-for", "140.211.11.130, proxy1, untrusted-proxy, proxy2");

    // TEST
    HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest();

    // VERIFY
    String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for");
    assertEquals("ip/host before untrusted-proxy must appear in x-forwarded-for", "140.211.11.130, proxy1", actualXForwardedFor);

    String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by");
    assertEquals("ip/host after untrusted-proxy must appear in  x-forwarded-by", "proxy2", actualXForwardedBy);

    String actualRemoteAddr = actualRequest.getRemoteAddr();
    assertEquals("remoteAddr", "untrusted-proxy", actualRemoteAddr);

    String actualRemoteHost = actualRequest.getRemoteHost();
    assertEquals("remoteHost", "untrusted-proxy", actualRemoteHost);
}
 
Example 14
Source Project: tomcatsrc   File: TestRemoteIpFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokeUntrustedProxyInTheChain() throws Exception {
    // PREPARE
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11");
    filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3");
    filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for");
    filterDef.addInitParameter("proxiesHeader", "x-forwarded-by");

    MockHttpServletRequest request = new MockHttpServletRequest();

    request.setRemoteAddr("192.168.0.10");
    request.setRemoteHost("remote-host-original-value");
    request.setHeader("x-forwarded-for", "140.211.11.130, proxy1, untrusted-proxy, proxy2");

    // TEST
    HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest();

    // VERIFY
    String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for");
    assertEquals("ip/host before untrusted-proxy must appear in x-forwarded-for", "140.211.11.130, proxy1", actualXForwardedFor);

    String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by");
    assertEquals("ip/host after untrusted-proxy must appear in  x-forwarded-by", "proxy2", actualXForwardedBy);

    String actualRemoteAddr = actualRequest.getRemoteAddr();
    assertEquals("remoteAddr", "untrusted-proxy", actualRemoteAddr);

    String actualRemoteHost = actualRequest.getRemoteHost();
    assertEquals("remoteHost", "untrusted-proxy", actualRemoteHost);
}
 
Example 15
Source Project: ranger   File: AssetMgr.java    License: Apache License 2.0 4 votes vote down vote up
public void createPluginInfo(String serviceName, String pluginId, HttpServletRequest request, int entityType, Long downloadedVersion, long lastKnownVersion, long lastActivationTime, int httpCode, String clusterName, String pluginCapabilities) {
	RangerRESTUtils restUtils = new RangerRESTUtils();

	final String ipAddress = getRemoteAddress(request);
	final String appType = restUtils.getAppIdFromPluginId(pluginId);

	String tmpHostName = null;
	if (StringUtils.isNotBlank(pluginId)) {
		tmpHostName = restUtils.getHostnameFromPluginId(pluginId, serviceName);
	}
	if (StringUtils.isBlank(tmpHostName) && request != null) {
		tmpHostName = request.getRemoteHost();
	}

	final String hostName = (StringUtils.isBlank(tmpHostName)) ? ipAddress : tmpHostName;

	RangerPluginInfo pluginSvcVersionInfo = new RangerPluginInfo();

	pluginSvcVersionInfo.setServiceName(serviceName);
	pluginSvcVersionInfo.setAppType(appType);
	pluginSvcVersionInfo.setHostName(hostName);
	pluginSvcVersionInfo.setIpAddress(ipAddress);
	pluginSvcVersionInfo.setPluginCapabilities(StringUtils.isEmpty(pluginCapabilities) ? RangerPluginCapability.getBaseRangerCapabilities() : pluginCapabilities);

	switch (entityType) {
		case RangerPluginInfo.ENTITY_TYPE_POLICIES:
			pluginSvcVersionInfo.setPolicyActiveVersion(lastKnownVersion);
			pluginSvcVersionInfo.setPolicyActivationTime(lastActivationTime);
			pluginSvcVersionInfo.setPolicyDownloadedVersion(downloadedVersion);
			pluginSvcVersionInfo.setPolicyDownloadTime(new Date().getTime());
			break;
		case RangerPluginInfo.ENTITY_TYPE_TAGS:
			pluginSvcVersionInfo.setTagActiveVersion(lastKnownVersion);
			pluginSvcVersionInfo.setTagActivationTime(lastActivationTime);
			pluginSvcVersionInfo.setTagDownloadedVersion(downloadedVersion);
			pluginSvcVersionInfo.setTagDownloadTime(new Date().getTime());
			break;
		case RangerPluginInfo.ENTITY_TYPE_ROLES:
			pluginSvcVersionInfo.setRoleActiveVersion(lastKnownVersion);
			pluginSvcVersionInfo.setRoleActivationTime(lastActivationTime);
			pluginSvcVersionInfo.setRoleDownloadedVersion(downloadedVersion);
			pluginSvcVersionInfo.setRoleDownloadTime(new Date().getTime());
			break;
		case RangerPluginInfo.ENTITY_TYPE_USERSTORE:
			pluginSvcVersionInfo.setUserStoreActiveVersion(lastKnownVersion);
			pluginSvcVersionInfo.setUserStoreActivationTime(lastActivationTime);
			pluginSvcVersionInfo.setUserStoreDownloadedVersion(downloadedVersion);
			pluginSvcVersionInfo.setUserStoreDownloadTime(new Date().getTime());
			break;
	}

	createOrUpdatePluginInfo(pluginSvcVersionInfo, entityType , httpCode, clusterName);
}
 
Example 16
Source Project: nifi   File: SiteToSiteResource.java    License: 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 17
Source Project: init-spring   File: LoginBean.java    License: Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(Model model, HttpServletRequest request)
{
	Subject subject=SecurityUtils.getSubject();
	if(subject.isAuthenticated()||subject.isRemembered()){
		return "redirect:/home";
	}
	
	String username = request.getParameter("username");
	String password = request.getParameter("password");
	String loginKaptchaCode = request.getParameter("code");

	Session shiroSession = subject.getSession();
	Object kaptchaCode = shiroSession.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);

	if (kaptchaCode!=null && !StringUtils.equalsIgnoreCase(loginKaptchaCode, kaptchaCode.toString()))
	{
		model.addAttribute("message", "验证码错误!");
		return "/login";
	}

	UsernamePasswordToken token = new UsernamePasswordToken(username, password, false, request.getRemoteHost());
	try
	{
		subject.login(token);
		User user = jpaRealmRepository.findUserByName(username);
		user.setLastLogin(new Date());
		user = jpaRealmRepository.mergeUser(user);

		return "redirect:/home";
	} catch (UnknownAccountException uae)
	{
		model.addAttribute("message", "Unknown User!");
		log.info("Unknown User!");
	} catch (IncorrectCredentialsException ice)
	{
		model.addAttribute("message", "Incorrect Password!");
		log.info("Incorrect Password!");
	} catch (LockedAccountException lae)
	{
		model.addAttribute("message", "User Locked!");
		log.info("User Locked!");
	} catch (AuthenticationException ae)
	{
		model.addAttribute("message", "Authentication Failed!");
		log.info("Authentication Failed!");
	} 
	return "/login";
}
 
Example 18
Source Project: onedev   File: ServletRequestCopy.java    License: 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 19
@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 20
Source Project: development   File: ExampleServlet.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Upload a file into the given directory.
 * 
 * @param request
 *            - the HttpServletRequest object
 * @param response
 *            - the HttpServletResponse object
 * @param dir
 *            - the directory in which the files/directories are deleted
 * @param fileItemList
 *            - the list with the uploaded files
 */
private void upload(HttpServletRequest request, File dir,
        List<FileItem> fileItemList) {

    if (fileItemList == null) {
        return;
    }

    // Process the uploaded items
    Iterator<FileItem> it = fileItemList.iterator();
    while (it.hasNext()) {
        FileItem item = it.next();

        // Process a file upload
        if (!item.isFormField()) {
            String name = item.getName();
            int i = name.lastIndexOf("/");
            if (i < 0) {
                i = name.lastIndexOf("\\");
            }
            if (i >= 0) {
                name = name.substring(i + 1);
            }
            File file = new File(dir, name);
            if (isAccessible(request, file)) {
                try {
                    item.write(file);
                    BssClient bssClient = new BssClient(
                            request.getRemoteHost());
                    bssClient
                            .recordEvent(
                                    getSaasId(request),
                                    ProvisioningServiceSkeleton.EVENT_ID_FILE_UPLOAD,
                                    getUserId(request), MULTIPLIER);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}