update link to upper-constraints.txt
[msb/apigateway.git] / apiroute / apiroute-service / src / main / java / org / onap / msb / apiroute / wrapper / util / MicroServiceUtil.java
1 /*******************************************************************************
2  * Copyright 2016-2017 ZTE, Inc. and others.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  * 
7  * http://www.apache.org/licenses/LICENSE-2.0
8  * 
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  ******************************************************************************/
14 package org.onap.msb.apiroute.wrapper.util;
15
16 import java.util.regex.Pattern;
17
18 import javax.servlet.http.HttpServletRequest;
19
20 import org.apache.commons.lang3.StringUtils;
21
22
23 public class MicroServiceUtil {
24     public static final String PREFIX_PATH = "discover:microservices";
25
26     private static final Pattern SERVICE_KEY_REGEX_PATTERN =
27                     Pattern.compile("discover:microservices:(?<servicename>[^:]+)(:(?<version>[^:]*))");
28
29
30     public static String getPrefixedKey(String... paths) {
31         StringBuffer sb = new StringBuffer();
32
33         sb.append(PREFIX_PATH);
34
35         for (int i = 0; i < paths.length; i++) {
36             sb.append(":");
37             sb.append(paths[i]);
38         }
39         return sb.toString();
40     }
41
42
43     public static String getServiceKey(String serviceName, String version) {
44         return getPrefixedKey(serviceName, version);
45     }
46
47     public static Pattern getServiceKeyRegexPattern() {
48         return SERVICE_KEY_REGEX_PATTERN;
49     }
50
51
52
53     public static String getRealIp(HttpServletRequest request) {
54         String ip = request.getHeader("X-Forwarded-For");
55         if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
56             // After the reverse proxy can have multiple IP value for many times, the first IP is
57             // the real IP
58             int index = ip.indexOf(",");
59             if (index != -1) {
60                 return ip.substring(0, index);
61             } else {
62                 return ip;
63             }
64         }
65         ip = request.getHeader("X-Real-IP");
66
67         if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
68             return ip;
69         }
70
71
72         return request.getRemoteAddr();
73
74     }
75
76
77 }