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