Organise imports to ONAP Java standards
[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 java.util.UUID;
24 import javax.servlet.http.HttpServletRequest;
25 import org.onap.aai.cl.mdc.MdcContext;
26 import org.onap.aai.sa.searchdbabstraction.util.SearchDbConstants;
27 import org.slf4j.MDC;
28 import org.springframework.http.HttpHeaders;
29 import org.springframework.http.HttpStatus;
30
31 // Spring Imports
32
33 public class ApiUtils {
34
35   public static final String SEARCH_AUTH_POLICY_NAME = "search";
36   public static final String URL_PREFIX = "services/search-data-service/v1/search";
37
38   public enum Action {
39     POST, GET, PUT, DELETE
40   };
41
42   /**
43    * This method uses the contents of the supplied HTTP headers and request
44    * structures to populate the MDC Context used for logging purposes.
45    *
46    * @param httpReq - HTTP request structure.
47    * @param headers - HTTP headers
48    */
49 //  protected static void initMdcContext(HttpServletRequest httpReq, HttpHeaders headers) {
50 //
51 //    // Auto generate a transaction if we were not provided one.
52 //    String transId = null;
53 //    if (headers != null) {
54 //      // transId = headers.getRequestHeaders().getFirst("X-TransactionId");
55 //      transId = headers.getFirst("X-TransactionId");
56 //
57 //      if ((transId == null) || (transId.equals(""))) {
58 //        transId = UUID.randomUUID().toString();
59 //      }
60 //    }
61 //
62 //    String fromIp = (httpReq != null) ? httpReq.getRemoteAddr() : "";
63 //    String fromApp = (headers != null) ? headers.getFirst("X-FromAppId") : "";
64 //
65 //    MdcContext.initialize(transId, SearchDbConstants.SDB_SERVICE_NAME, "", fromApp, fromIp);
66 //  }
67
68   protected static void initMdcContext ( HttpServletRequest httpReq, HttpHeaders headers) {
69
70     // Auto generate a transaction if we were not provided one.
71     String transId = null;
72     if (headers != null) {
73       // transId = headers.getRequestHeaders().getFirst("X-TransactionId");
74       transId = headers.getFirst("X-TransactionId");
75
76       if ((transId == null) || (transId.equals(""))) {
77         transId = UUID.randomUUID().toString();
78       }
79     }
80
81
82     String fromIp = (httpReq != null) ? httpReq.getRemoteHost () : "";
83     String fromApp = (headers != null) ? headers.getFirst("X-FromAppId") : "";
84
85     MdcContext.initialize(transId, SearchDbConstants.SDB_SERVICE_NAME, "", fromApp, fromIp);
86   }
87
88   protected static void clearMdcContext() {
89     MDC.clear();
90   }
91
92   public static String buildIndexUri(String index) {
93
94     return (URL_PREFIX + "/indexes/") + index;
95   }
96
97   public static String buildDocumentUri(String index, String documentId) {
98
99     return buildIndexUri(index) + "/documents/" + documentId;
100   }
101
102   public static boolean validateIndexUri(String uri) {
103
104     // If the URI starts with a leading '/' character, remove it.
105     uri = uri.startsWith("/") ? uri.substring(1) : uri;
106
107     // Now, tokenize the URI string.
108     String[] tokens = uri.split("/");
109
110     return (tokens.length == 6) && (tokens[4].equals("indexes"));
111
112   }
113
114   public static boolean validateDocumentUri(String uri, boolean requireId) {
115
116     // If the URI starts with a leading '/' character, remove it.
117     uri = uri.startsWith("/") ? uri.substring(1) : uri;
118
119     // Now, tokenize the URI string.
120     String[] tokens = uri.split("/");
121
122     if (requireId) {
123       return (tokens.length == 8) && (tokens[4].equals("indexes")
124                                       && (tokens[6].equals("documents")));
125     } else {
126       return ((tokens.length == 8) || (tokens.length == 7))
127         && (tokens[4].equals("indexes") && (tokens[6].equals("documents")));
128     }
129   }
130
131   public static String extractIndexFromUri(String uri) {
132
133     // If the URI starts with a leading '/' character, remove it.
134     uri = uri.startsWith("/") ? uri.substring(1) : uri;
135
136     // Now, tokenize the URI string.
137     String[] tokens = uri.split("/");
138
139     int i = 0;
140     for (String token : tokens) {
141       if (token.equals("indexes")) {
142         if (i + 1 < tokens.length) {
143           return tokens[i + 1];
144         }
145       }
146       i++;
147     }
148
149     return null;
150   }
151
152   public static String extractIdFromUri(String uri) {
153
154     // If the URI starts with a leading '/' character, remove it.
155     uri = uri.startsWith("/") ? uri.substring(1) : uri;
156
157     // Now, tokenize the URI string.
158     String[] tokens = uri.split("/");
159
160     int i = 0;
161     for (String token : tokens) {
162       if (token.equals("documents")) {
163         if (i + 1 < tokens.length) {
164           return tokens[i + 1];
165         }
166       }
167       i++;
168     }
169
170     return null;
171   }
172
173   public static String getHttpStatusString(int httpStatusCode) {
174     // Some of the status codes we use are still in draft state in the standards, and are not
175     // recognized in the javax library.  We need to manually translate these to human-readable
176     // strings.
177     String statusString = "Unknown";
178     HttpStatus status = null;
179
180     try {
181       status = HttpStatus.valueOf ( httpStatusCode );
182     } catch (IllegalArgumentException e) {}
183
184
185     if (status == null) {
186       switch (httpStatusCode) {
187       case 207:
188         statusString = "Multi Status";
189         break;
190       default:
191       }
192     } else {
193       statusString = status.getReasonPhrase ();
194     }
195
196     return statusString;
197   }
198 }