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