Merge "Fix Sonar bugs"
[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 org.apache.commons.codec.binary.Base64;
44 import org.apache.log4j.Logger;
45 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
46 import org.slf4j.MDC;
47
48 /**
49  * Utility functions for the data router node
50  */
51 public class NodeUtils {
52
53     private static EELFLogger eelfLogger = EELFManager.getInstance()
54         .getLogger("org.onap.dmaap.datarouter.node.NodeUtils");
55     private static Logger nodeUtilsLogger = Logger.getLogger("org.onap.dmaap.datarouter.node.NodeUtils");
56
57     private NodeUtils() {
58     }
59
60     /**
61      * Base64 encode a byte array
62      *
63      * @param raw The bytes to be encoded
64      * @return The encoded string
65      */
66     public static String base64Encode(byte[] raw) {
67         return (Base64.encodeBase64String(raw));
68     }
69
70     /**
71      * Given a user and password, generate the credentials
72      *
73      * @param user User name
74      * @param password User password
75      * @return Authorization header value
76      */
77     public static String getAuthHdr(String user, String password) {
78         if (user == null || password == null) {
79             return (null);
80         }
81         return ("Basic " + base64Encode((user + ":" + password).getBytes()));
82     }
83
84     /**
85      * Given a node name, generate the credentials
86      *
87      * @param node Node name
88      */
89     public static String getNodeAuthHdr(String node, String key) {
90         try {
91             MessageDigest md = MessageDigest.getInstance("SHA");
92             md.update(key.getBytes());
93             md.update(node.getBytes());
94             md.update(key.getBytes());
95             return (getAuthHdr(node, base64Encode(md.digest())));
96         } catch (Exception exception) {
97             nodeUtilsLogger
98                 .error("Exception in generating Credentials for given node name:= " + exception.toString(), exception);
99             return (null);
100         }
101     }
102
103     /**
104      * Given a keystore file and its password, return the value of the CN of the first private key entry with a
105      * certificate.
106      *
107      * @param kstype The type of keystore
108      * @param ksfile The file name of the keystore
109      * @param kspass The password of the keystore
110      * @return CN of the certificate subject or null
111      */
112     public static String getCanonicalName(String kstype, String ksfile, String kspass) {
113         KeyStore ks;
114         try {
115             ks = KeyStore.getInstance(kstype);
116             try (FileInputStream fileInputStream = new FileInputStream(ksfile)) {
117                 ks.load(fileInputStream, kspass.toCharArray());
118             } catch (IOException ioException) {
119                 nodeUtilsLogger.error("IOException occurred while opening FileInputStream: " + ioException.getMessage(),
120                     ioException);
121                 return (null);
122             }
123         } catch (Exception e) {
124             setIpAndFqdnForEelf("getCanonicalName");
125             eelfLogger.error(EelfMsgs.MESSAGE_KEYSTORE_LOAD_ERROR, ksfile, e.toString());
126             nodeUtilsLogger.error("NODE0401 Error loading my keystore file + " + ksfile + " " + e.toString(), e);
127             return (null);
128         }
129         return (getCanonicalName(ks));
130     }
131
132     /**
133      * Given a keystore, return the value of the CN of the first private key entry with a certificate.
134      *
135      * @param ks The KeyStore
136      * @return CN of the certificate subject or null
137      */
138     public static String getCanonicalName(KeyStore ks) {
139         try {
140             Enumeration<String> aliases = ks.aliases();
141             while (aliases.hasMoreElements()) {
142                 String s = aliases.nextElement();
143                 if (ks.entryInstanceOf(s, KeyStore.PrivateKeyEntry.class)) {
144                     X509Certificate c = (X509Certificate) ks.getCertificate(s);
145                     if (c != null) {
146                         String subject = c.getSubjectX500Principal().getName();
147                         String[] parts = subject.split(",");
148                         if (parts.length < 1) {
149                             return (null);
150                         }
151                         subject = parts[5].trim();
152                         if (!subject.startsWith("CN=")) {
153                             return (null);
154
155                         }
156                         return (subject.substring(3));
157                     }
158                 }
159             }
160         } catch (Exception e) {
161             nodeUtilsLogger.error("NODE0402 Error extracting my name from my keystore file " + e.toString(), e);
162         }
163         return (null);
164     }
165
166     /**
167      * Given a string representation of an IP address, get the corresponding byte array
168      *
169      * @param ip The IP address as a string
170      * @return The IP address as a byte array or null if the address is invalid
171      */
172     public static byte[] getInetAddress(String ip) {
173         try {
174             return (InetAddress.getByName(ip).getAddress());
175         } catch (Exception exception) {
176             nodeUtilsLogger
177                 .error("Exception in generating byte array for given IP address := " + exception.toString(), exception);
178         }
179         return (null);
180     }
181
182     /**
183      * Given a uri with parameters, split out the feed ID and file ID
184      */
185     public static String[] getFeedAndFileID(String uriandparams) {
186         int end = uriandparams.length();
187         int i = uriandparams.indexOf('#');
188         if (i != -1 && i < end) {
189             end = i;
190         }
191         i = uriandparams.indexOf('?');
192         if (i != -1 && i < end) {
193             end = i;
194         }
195         end = uriandparams.lastIndexOf('/', end);
196         if (end < 2) {
197             return (null);
198         }
199         i = uriandparams.lastIndexOf('/', end - 1);
200         if (i == -1) {
201             return (null);
202         }
203         return (new String[]{uriandparams.substring(i + 1, end), uriandparams.substring(end + 1)});
204     }
205
206     /**
207      * Escape fields that might contain vertical bar, backslash, or newline by replacing them with backslash p,
208      * backslash e and backslash n.
209      */
210     public static String loge(String s) {
211         if (s == null) {
212             return (s);
213         }
214         return (s.replaceAll("\\\\", "\\\\e").replaceAll("\\|", "\\\\p").replaceAll("\n", "\\\\n"));
215     }
216
217     /**
218      * Undo what loge does.
219      */
220     public static String unloge(String s) {
221         if (s == null) {
222             return (s);
223         }
224         return (s.replaceAll("\\\\p", "\\|").replaceAll("\\\\n", "\n").replaceAll("\\\\e", "\\\\"));
225     }
226
227     /**
228      * Format a logging timestamp as yyyy-mm-ddThh:mm:ss.mmmZ
229      */
230     public static String logts(long when) {
231         return (logts(new Date(when)));
232     }
233
234     /**
235      * Format a logging timestamp as yyyy-mm-ddThh:mm:ss.mmmZ
236      */
237     public static synchronized String logts(Date when) {
238         SimpleDateFormat logDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
239         logDate.setTimeZone(TimeZone.getTimeZone("GMT"));
240         return (logDate.format(when));
241     }
242
243     /* Method prints method name, server FQDN and IP Address of the machine in EELF logs
244      * @Method - setIpAndFqdnForEelf - Rally:US664892
245      * @Params - method, prints method name in EELF log.
246      */
247     public static void setIpAndFqdnForEelf(String method) {
248         MDC.clear();
249         MDC.put(MDC_SERVICE_NAME, method);
250         try {
251             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
252             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
253         } catch (Exception exception) {
254             nodeUtilsLogger
255                 .error("Exception in generating byte array for given IP address := " + exception.toString(), exception);
256         }
257
258     }
259
260
261 }