baa63b8c6229882e592a3d4398a4991d1daa6ef6
[aai/search-data-service.git] / src / main / java / org / onap / aai / sa / rest / ApiUtils.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.sa.rest;
22
23 import org.onap.aai.cl.mdc.MdcContext;
24 import org.onap.aai.sa.searchdbabstraction.util.SearchDbConstants;
25 import org.slf4j.MDC;
26 import org.springframework.http.HttpHeaders;
27 import org.springframework.http.HttpStatus;
28
29 import javax.servlet.http.HttpServletRequest;
30 import java.util.UUID;
31
32 // Spring Imports
33
34 public class ApiUtils {
35
36   public static final String SEARCH_AUTH_POLICY_NAME = "search";
37   public static final String URL_PREFIX = "services/search-data-service/v1/search";
38
39   public enum Action {
40     POST, GET, PUT, DELETE
41   };
42
43   /**
44    * This method uses the contents of the supplied HTTP headers and request
45    * structures to populate the MDC Context used for logging purposes.
46    *
47    * @param httpReq - HTTP request structure.
48    * @param headers - HTTP headers
49    */
50 //  protected static void initMdcContext(HttpServletRequest httpReq, HttpHeaders headers) {
51 //
52 //    // Auto generate a transaction if we were not provided one.
53 //    String transId = null;
54 //    if (headers != null) {
55 //      // transId = headers.getRequestHeaders().getFirst("X-TransactionId");
56 //      transId = headers.getFirst("X-TransactionId");
57 //
58 //      if ((transId == null) || (transId.equals(""))) {
59 //        transId = UUID.randomUUID().toString();
60 //      }
61 //    }
62 //
63 //    String fromIp = (httpReq != null) ? httpReq.getRemoteAddr() : "";
64 //    String fromApp = (headers != null) ? headers.getFirst("X-FromAppId") : "";
65 //
66 //    MdcContext.initialize(transId, SearchDbConstants.SDB_SERVICE_NAME, "", fromApp, fromIp);
67 //  }
68
69   protected static void initMdcContext ( HttpServletRequest httpReq, HttpHeaders headers) {
70
71     // Auto generate a transaction if we were not provided one.
72     String transId = null;
73     if (headers != null) {
74       // transId = headers.getRequestHeaders().getFirst("X-TransactionId");
75       transId = headers.getFirst("X-TransactionId");
76
77       if ((transId == null) || (transId.equals(""))) {
78         transId = UUID.randomUUID().toString();
79       }
80     }
81
82
83     String fromIp = (httpReq != null) ? httpReq.getRemoteHost () : "";
84     String fromApp = (headers != null) ? headers.getFirst("X-FromAppId") : "";
85
86     MdcContext.initialize(transId, SearchDbConstants.SDB_SERVICE_NAME, "", fromApp, fromIp);
87   }
88
89   protected static void clearMdcContext() {
90     MDC.clear();
91   }
92
93   public static String buildIndexUri(String index) {
94
95     return (URL_PREFIX + "/indexes/") + index;
96   }
97
98   public static String buildDocumentUri(String index, String documentId) {
99
100     return buildIndexUri(index) + "/documents/" + documentId;
101   }
102
103   public static boolean validateIndexUri(String uri) {
104
105     // If the URI starts with a leading '/' character, remove it.
106     uri = uri.startsWith("/") ? uri.substring(1) : uri;
107
108     // Now, tokenize the URI string.
109     String[] tokens = uri.split("/");
110
111     return (tokens.length == 6) && (tokens[4].equals("indexes"));
112
113   }
114
115   public static boolean validateDocumentUri(String uri, boolean requireId) {
116
117     // If the URI starts with a leading '/' character, remove it.
118     uri = uri.startsWith("/") ? uri.substring(1) : uri;
119
120     // Now, tokenize the URI string.
121     String[] tokens = uri.split("/");
122
123     if (requireId) {
124       return (tokens.length == 8) && (tokens[4].equals("indexes")
125                                       && (tokens[6].equals("documents")));
126     } else {
127       return ((tokens.length == 8) || (tokens.length == 7))
128         && (tokens[4].equals("indexes") && (tokens[6].equals("documents")));
129     }
130   }
131
132   public static String extractIndexFromUri(String uri) {
133
134     // If the URI starts with a leading '/' character, remove it.
135     uri = uri.startsWith("/") ? uri.substring(1) : uri;
136
137     // Now, tokenize the URI string.
138     String[] tokens = uri.split("/");
139
140     int i = 0;
141     for (String token : tokens) {
142       if (token.equals("indexes")) {
143         if (i + 1 < tokens.length) {
144           return tokens[i + 1];
145         }
146       }
147       i++;
148     }
149
150     return null;
151   }
152
153   public static String extractIdFromUri(String uri) {
154
155     // If the URI starts with a leading '/' character, remove it.
156     uri = uri.startsWith("/") ? uri.substring(1) : uri;
157
158     // Now, tokenize the URI string.
159     String[] tokens = uri.split("/");
160
161     int i = 0;
162     for (String token : tokens) {
163       if (token.equals("documents")) {
164         if (i + 1 < tokens.length) {
165           return tokens[i + 1];
166         }
167       }
168       i++;
169     }
170
171     return null;
172   }
173
174   public static String getHttpStatusString(int httpStatusCode) {
175     // Some of the status codes we use are still in draft state in the standards, and are not
176     // recognized in the javax library.  We need to manually translate these to human-readable
177     // strings.
178     String statusString = "Unknown";
179     HttpStatus status = null;
180
181     try {
182       status = HttpStatus.valueOf ( httpStatusCode );
183     } catch (IllegalArgumentException e) {}
184
185
186     if (status == null) {
187       switch (httpStatusCode) {
188       case 207:
189         statusString = "Multi Status";
190         break;
191       default:
192       }
193     } else {
194       statusString = status.getReasonPhrase ();
195     }
196
197     return statusString;
198   }
199 }