/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.commons.util;

import javax.servlet.http.HttpServletRequest;

/**
 * The utils class to handle http request.
 */
public class HttpRequestService {

    private static final String HTTP_HEADER_X_FORWARDED_FOR = "X-Forwarded-For";

    /**
     * Returns the IP address of the server.
     *
     * @param request
     *            - the http servlet request.
     * @return the IP address of the server.
     */
    public String getIpServer(final HttpServletRequest request) {
        // server address
        return request.getLocalAddr();
    }

    /**
     * Returns the IP address of the client.
     *
     * @param request
     *            - the http servlet request.
     * @return the IP address of the client.
     */
    public String getIpClientAddress(final HttpServletRequest request) {
        String address = request.getRemoteAddr();
        String xForwardedFor = request.getHeader(HTTP_HEADER_X_FORWARDED_FOR);
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            int index = xForwardedFor.indexOf(',');
            if (index > 0) {
                address = xForwardedFor.substring(0, index);
            } else {
                address = xForwardedFor;
            }
        }
        return address;
    }
}
