1 /*******************************************************************************
2 * ============LICENSE_START==================================================
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
11 * * http://www.apache.org/licenses/LICENSE-2.0
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====================================================
20 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 ******************************************************************************/
25 package org.onap.dmaap.datarouter.node;
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;
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;
49 * Utility functions for the data router node
51 public class NodeUtils {
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");
61 * Base64 encode a byte array
63 * @param raw The bytes to be encoded
64 * @return The encoded string
66 public static String base64Encode(byte[] raw) {
67 return (Base64.encodeBase64String(raw));
71 * Given a user and password, generate the credentials
73 * @param user User name
74 * @param password User password
75 * @return Authorization header value
77 public static String getAuthHdr(String user, String password) {
78 if (user == null || password == null) {
81 return ("Basic " + base64Encode((user + ":" + password).getBytes()));
85 * Given a node name, generate the credentials
87 * @param node Node name
89 public static String getNodeAuthHdr(String node, String key) {
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) {
98 .error("Exception in generating Credentials for given node name:= " + exception.toString(), exception);
104 * Given a keystore file and its password, return the value of the CN of the first private key entry with a
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
112 public static String getCanonicalName(String kstype, String ksfile, String kspass) {
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(),
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);
129 return (getCanonicalName(ks));
133 * Given a keystore, return the value of the CN of the first private key entry with a certificate.
135 * @param ks The KeyStore
136 * @return CN of the certificate subject or null
138 public static String getCanonicalName(KeyStore ks) {
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);
146 String subject = c.getSubjectX500Principal().getName();
147 String[] parts = subject.split(",");
148 if (parts.length < 1) {
151 subject = parts[5].trim();
152 if (!subject.startsWith("CN=")) {
156 return (subject.substring(3));
160 } catch (Exception e) {
161 nodeUtilsLogger.error("NODE0402 Error extracting my name from my keystore file " + e.toString(), e);
167 * Given a string representation of an IP address, get the corresponding byte array
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
172 public static byte[] getInetAddress(String ip) {
174 return (InetAddress.getByName(ip).getAddress());
175 } catch (Exception exception) {
177 .error("Exception in generating byte array for given IP address := " + exception.toString(), exception);
183 * Given a uri with parameters, split out the feed ID and file ID
185 public static String[] getFeedAndFileID(String uriandparams) {
186 int end = uriandparams.length();
187 int i = uriandparams.indexOf('#');
188 if (i != -1 && i < end) {
191 i = uriandparams.indexOf('?');
192 if (i != -1 && i < end) {
195 end = uriandparams.lastIndexOf('/', end);
199 i = uriandparams.lastIndexOf('/', end - 1);
203 return (new String[]{uriandparams.substring(i + 1, end), uriandparams.substring(end + 1)});
207 * Escape fields that might contain vertical bar, backslash, or newline by replacing them with backslash p,
208 * backslash e and backslash n.
210 public static String loge(String s) {
214 return (s.replaceAll("\\\\", "\\\\e").replaceAll("\\|", "\\\\p").replaceAll("\n", "\\\\n"));
218 * Undo what loge does.
220 public static String unloge(String s) {
224 return (s.replaceAll("\\\\p", "\\|").replaceAll("\\\\n", "\n").replaceAll("\\\\e", "\\\\"));
228 * Format a logging timestamp as yyyy-mm-ddThh:mm:ss.mmmZ
230 public static String logts(long when) {
231 return (logts(new Date(when)));
235 * Format a logging timestamp as yyyy-mm-ddThh:mm:ss.mmmZ
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));
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.
247 public static void setIpAndFqdnForEelf(String method) {
249 MDC.put(MDC_SERVICE_NAME, method);
251 MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
252 MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
253 } catch (Exception exception) {
255 .error("Exception in generating byte array for given IP address := " + exception.toString(), exception);