Fix formatting
[dmaap/datarouter.git] / datarouter-node / src / main / java / org / onap / dmaap / datarouter / node / NodeUtils.java
1 /*******************************************************************************
2  * ============LICENSE_START==================================================
3  * * org.onap.dmaap
4  * * ===========================================================================
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * * ===========================================================================
7  * * Licensed under the Apache License, Version 2.0 (the "License");
8  * * you may not use this file except in compliance with the License.
9  * * You may obtain a copy of the License at
10  * *
11  *  *      http://www.apache.org/licenses/LICENSE-2.0
12  * *
13  *  * Unless required by applicable law or agreed to in writing, software
14  * * distributed under the License is distributed on an "AS IS" BASIS,
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * * See the License for the specific language governing permissions and
17  * * limitations under the License.
18  * * ============LICENSE_END====================================================
19  * *
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  * *
22  ******************************************************************************/
23
24
25 package org.onap.dmaap.datarouter.node;
26
27 import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
28 import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
29 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
30
31 import com.att.eelf.configuration.EELFLogger;
32 import com.att.eelf.configuration.EELFManager;
33 import java.io.FileInputStream;
34 import java.io.IOException;
35 import java.net.InetAddress;
36 import java.security.KeyStore;
37 import java.security.MessageDigest;
38 import java.security.cert.X509Certificate;
39 import java.text.SimpleDateFormat;
40 import java.util.Date;
41 import java.util.Enumeration;
42 import java.util.TimeZone;
43 import javax.servlet.http.HttpServletResponse;
44 import org.apache.commons.codec.binary.Base64;
45 import org.apache.log4j.Logger;
46 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
47 import org.slf4j.MDC;
48
49 /**
50  * Utility functions for the data router node
51  */
52 public class NodeUtils {
53
54     private static EELFLogger eelfLogger = EELFManager.getInstance()
55             .getLogger("org.onap.dmaap.datarouter.node.NodeUtils");
56     private static Logger nodeUtilsLogger = Logger.getLogger("org.onap.dmaap.datarouter.node.NodeUtils");
57
58     private NodeUtils() {
59     }
60
61     /**
62      * Base64 encode a byte array
63      *
64      * @param raw The bytes to be encoded
65      * @return The encoded string
66      */
67     public static String base64Encode(byte[] raw) {
68         return (Base64.encodeBase64String(raw));
69     }
70
71     /**
72      * Given a user and password, generate the credentials
73      *
74      * @param user User name
75      * @param password User password
76      * @return Authorization header value
77      */
78     public static String getAuthHdr(String user, String password) {
79         if (user == null || password == null) {
80             return (null);
81         }
82         return ("Basic " + base64Encode((user + ":" + password).getBytes()));
83     }
84
85     /**
86      * Given a node name, generate the credentials
87      *
88      * @param node Node name
89      */
90     public static String getNodeAuthHdr(String node, String key) {
91         try {
92             MessageDigest md = MessageDigest.getInstance("SHA");
93             md.update(key.getBytes());
94             md.update(node.getBytes());
95             md.update(key.getBytes());
96             return (getAuthHdr(node, base64Encode(md.digest())));
97         } catch (Exception exception) {
98             nodeUtilsLogger
99                     .error("Exception in generating Credentials for given node name:= " + exception.toString(),
100                             exception);
101             return (null);
102         }
103     }
104
105     /**
106      * Given a keystore file and its password, return the value of the CN of the first private key entry with a
107      * certificate.
108      *
109      * @param kstype The type of keystore
110      * @param ksfile The file name of the keystore
111      * @param kspass The password of the keystore
112      * @return CN of the certificate subject or null
113      */
114     public static String getCanonicalName(String kstype, String ksfile, String kspass) {
115         KeyStore ks;
116         try {
117             ks = KeyStore.getInstance(kstype);
118             try (FileInputStream fileInputStream = new FileInputStream(ksfile)) {
119                 ks.load(fileInputStream, kspass.toCharArray());
120             } catch (IOException ioException) {
121                 nodeUtilsLogger.error("IOException occurred while opening FileInputStream: " + ioException.getMessage(),
122                         ioException);
123                 return (null);
124             }
125         } catch (Exception e) {
126             setIpAndFqdnForEelf("getCanonicalName");
127             eelfLogger.error(EelfMsgs.MESSAGE_KEYSTORE_LOAD_ERROR, ksfile, e.toString());
128             nodeUtilsLogger.error("NODE0401 Error loading my keystore file + " + ksfile + " " + e.toString(), e);
129             return (null);
130         }
131         return (getCanonicalName(ks));
132     }
133
134     /**
135      * Given a keystore, return the value of the CN of the first private key entry with a certificate.
136      *
137      * @param ks The KeyStore
138      * @return CN of the certificate subject or null
139      */
140     public static String getCanonicalName(KeyStore ks) {
141         try {
142             Enumeration<String> aliases = ks.aliases();
143             while (aliases.hasMoreElements()) {
144                 String s = aliases.nextElement();
145                 if (ks.entryInstanceOf(s, KeyStore.PrivateKeyEntry.class)) {
146                     X509Certificate c = (X509Certificate) ks.getCertificate(s);
147                     if (c != null) {
148                         String subject = c.getSubjectX500Principal().getName();
149                         String[] parts = subject.split(",");
150                         if (parts.length < 1) {
151                             return (null);
152                         }
153                         subject = parts[5].trim();
154                         if (!subject.startsWith("CN=")) {
155                             return (null);
156
157                         }
158                         return (subject.substring(3));
159                     }
160                 }
161             }
162         } catch (Exception e) {
163             nodeUtilsLogger.error("NODE0402 Error extracting my name from my keystore file " + e.toString(), e);
164         }
165         return (null);
166     }
167
168     /**
169      * Given a string representation of an IP address, get the corresponding byte array
170      *
171      * @param ip The IP address as a string
172      * @return The IP address as a byte array or null if the address is invalid
173      */
174     public static byte[] getInetAddress(String ip) {
175         try {
176             return (InetAddress.getByName(ip).getAddress());
177         } catch (Exception exception) {
178             nodeUtilsLogger
179                     .error("Exception in generating byte array for given IP address := " + exception.toString(),
180                             exception);
181         }
182         return (null);
183     }
184
185     /**
186      * Given a uri with parameters, split out the feed ID and file ID
187      */
188     public static String[] getFeedAndFileID(String uriandparams) {
189         int end = uriandparams.length();
190         int i = uriandparams.indexOf('#');
191         if (i != -1 && i < end) {
192             end = i;
193         }
194         i = uriandparams.indexOf('?');
195         if (i != -1 && i < end) {
196             end = i;
197         }
198         end = uriandparams.lastIndexOf('/', end);
199         if (end < 2) {
200             return (null);
201         }
202         i = uriandparams.lastIndexOf('/', end - 1);
203         if (i == -1) {
204             return (null);
205         }
206         return (new String[]{uriandparams.substring(i + 1, end), uriandparams.substring(end + 1)});
207     }
208
209     /**
210      * Escape fields that might contain vertical bar, backslash, or newline by replacing them with backslash p,
211      * backslash e and backslash n.
212      */
213     public static String loge(String s) {
214         if (s == null) {
215             return (s);
216         }
217         return (s.replaceAll("\\\\", "\\\\e").replaceAll("\\|", "\\\\p").replaceAll("\n", "\\\\n"));
218     }
219
220     /**
221      * Undo what loge does.
222      */
223     public static String unloge(String s) {
224         if (s == null) {
225             return (s);
226         }
227         return (s.replaceAll("\\\\p", "\\|").replaceAll("\\\\n", "\n").replaceAll("\\\\e", "\\\\"));
228     }
229
230     /**
231      * Format a logging timestamp as yyyy-mm-ddThh:mm:ss.mmmZ
232      */
233     public static String logts(long when) {
234         return (logts(new Date(when)));
235     }
236
237     /**
238      * Format a logging timestamp as yyyy-mm-ddThh:mm:ss.mmmZ
239      */
240     public static synchronized String logts(Date when) {
241         SimpleDateFormat logDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
242         logDate.setTimeZone(TimeZone.getTimeZone("GMT"));
243         return (logDate.format(when));
244     }
245
246     /* Method prints method name, server FQDN and IP Address of the machine in EELF logs
247      * @Method - setIpAndFqdnForEelf - Rally:US664892
248      * @Params - method, prints method name in EELF log.
249      */
250     public static void setIpAndFqdnForEelf(String method) {
251         MDC.clear();
252         MDC.put(MDC_SERVICE_NAME, method);
253         try {
254             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
255             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
256         } catch (Exception exception) {
257             nodeUtilsLogger
258                     .error("Exception in generating byte array for given IP address := " + exception.toString(),
259                             exception);
260         }
261
262     }
263
264     public static void sendResponseError(HttpServletResponse response, int errorCode, Logger intlogger) {
265         try {
266             response.sendError(errorCode);
267         } catch (IOException ioe) {
268             intlogger.error("IOException" + ioe.getMessage());
269         }
270     }
271
272
273 }