aboutsummaryrefslogtreecommitdiff
path: root/src/test/java/org/traccar/helper/ServletHelperTest.java
blob: 7359bf3dd59da4e5bdd0cdbb7fe3ca89bfb4e7ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package org.traccar.helper;

import org.apache.struts.mock.MockHttpServletRequest;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.assertEquals;

public class ServletHelperTest {

    @Test
    public void testIpBehindReverseProxy() {
        MockRequest request = new MockRequest();
        request.setRemoteAddress("147.120.1.5");
        request.addHeader("X-FORWARDED-FOR", "231.23.45.65, 10.20.10.33, 10.20.20.34");

        assertEquals("231.23.45.65", ServletHelper.retrieveRemoteAddress(request));
    }

    @Test
    public void testNormalIp() {
        MockRequest request = new MockRequest();
        request.setRemoteAddress("231.23.45.65");

        assertEquals("231.23.45.65", ServletHelper.retrieveRemoteAddress(request));
    }

    private final static class MockRequest extends MockHttpServletRequest {

        private String remoteAddress;

        private Map<String, String> headers = new HashMap<>();

        public void setRemoteAddress(String remoteAddress) {
            this.remoteAddress = remoteAddress;
        }

        public void addHeader(String name, String value) {
            headers.put(name, value);
        }

        @Override
        public String getHeader(String name) {
            return headers.get(name);
        }

        @Override
        public String getRemoteAddr() {
            return remoteAddress;
        }

    }

}