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.utils;
27 import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
28 import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
29 import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
30 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
32 import com.att.eelf.configuration.EELFLogger;
33 import com.att.eelf.configuration.EELFManager;
35 import java.io.FileInputStream;
36 import java.io.IOException;
37 import java.net.InetAddress;
38 import java.security.KeyStore;
39 import java.security.KeyStoreException;
40 import java.security.MessageDigest;
41 import java.security.NoSuchAlgorithmException;
42 import java.security.cert.CertificateException;
43 import java.security.cert.X509Certificate;
44 import java.text.SimpleDateFormat;
45 import java.util.Date;
46 import java.util.Enumeration;
47 import java.util.TimeZone;
48 import java.util.UUID;
49 import java.util.zip.GZIPInputStream;
50 import javax.naming.InvalidNameException;
51 import javax.naming.ldap.LdapName;
52 import javax.naming.ldap.Rdn;
53 import jakarta.servlet.http.HttpServletRequest;
54 import jakarta.servlet.http.HttpServletResponse;
55 import org.apache.commons.codec.binary.Base64;
56 import org.apache.commons.lang3.StringUtils;
57 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
61 * Utility functions for the data router node.
63 public class NodeUtils {
65 private static final EELFLogger eelfLogger = EELFManager.getInstance().getLogger(NodeUtils.class);
71 * Base64 encode a byte array.
73 * @param raw The bytes to be encoded
74 * @return The encoded string
76 public static String base64Encode(byte[] raw) {
77 return (Base64.encodeBase64String(raw));
81 * Given a user and password, generate the credentials.
83 * @param user User name
84 * @param password User password
85 * @return Authorization header value
87 public static String getAuthHdr(String user, String password) {
88 if (user == null || password == null) {
91 return ("Basic " + base64Encode((user + ":" + password).getBytes()));
95 * Given a node name, generate the credentials.
97 * @param node Node name
99 public static String getNodeAuthHdr(String node, String key) {
101 MessageDigest md = MessageDigest.getInstance("SHA-512");
102 md.update(key.getBytes());
103 md.update(node.getBytes());
104 md.update(key.getBytes());
105 return (getAuthHdr(node, base64Encode(md.digest())));
106 } catch (Exception exception) {
108 .error("Exception in generating Credentials for given node name:= " + exception.getMessage(),
115 * Given a string representation of an IP address, get the corresponding byte array.
117 * @param ip The IP address as a string
118 * @return The IP address as a byte array or null if the address is invalid
120 public static byte[] getInetAddress(String ip) {
122 return (InetAddress.getByName(ip).getAddress());
123 } catch (Exception exception) {
125 .error("Exception in generating byte array for given IP address := " + exception.toString(),
132 * Given a uri with parameters, split out the feed ID and file ID.
134 public static String[] getFeedAndFileID(String uriandparams) {
135 int end = uriandparams.length();
136 int index = uriandparams.indexOf('#');
137 if (index != -1 && index < end) {
140 index = uriandparams.indexOf('?');
141 if (index != -1 && index < end) {
144 end = uriandparams.lastIndexOf('/', end);
148 index = uriandparams.lastIndexOf('/', end - 1);
152 return (new String[]{uriandparams.substring(index + 1, end), uriandparams.substring(end + 1)});
156 * Escape fields that might contain vertical bar, backslash, or newline by replacing them with backslash p,
157 * backslash e and backslash n.
159 public static String loge(String string) {
160 if (string == null) {
163 return (string.replaceAll("\\\\", "\\\\e").replaceAll("\\|", "\\\\p").replaceAll("\n", "\\\\n"));
167 * Undo what loge does.
169 public static String unloge(String string) {
170 if (string == null) {
173 return (string.replaceAll("\\\\p", "\\|").replaceAll("\\\\n", "\n").replaceAll("\\\\e", "\\\\"));
177 * Format a logging timestamp as yyyy-mm-ddThh:mm:ss.mmmZ
179 public static String logts(long when) {
180 return (logts(new Date(when)));
184 * Format a logging timestamp as yyyy-mm-ddThh:mm:ss.mmmZ
186 public static synchronized String logts(Date when) {
187 SimpleDateFormat logDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
188 logDate.setTimeZone(TimeZone.getTimeZone("GMT"));
189 return (logDate.format(when));
192 /** Method prints method name, server FQDN and IP Address of the machine in EELF logs.
194 * @param method Prints method name in EELF log.
196 public static void setIpAndFqdnForEelf(String method) {
198 MDC.put(MDC_SERVICE_NAME, method);
200 MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
201 MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
202 } catch (Exception exception) {
204 .error("Exception in generating byte array for given IP address := " + exception.toString(),
210 /** Method sets RequestIs and InvocationId for se in EELF logs.
212 * @param req Request used to get RequestId and InvocationId.
214 public static void setRequestIdAndInvocationId(HttpServletRequest req) {
215 String reqId = req.getHeader("X-ONAP-RequestID");
216 if (StringUtils.isBlank(reqId)) {
217 reqId = UUID.randomUUID().toString();
219 MDC.put(MDC_KEY_REQUEST_ID, reqId);
220 String invId = req.getHeader("X-InvocationID");
221 if (StringUtils.isBlank(invId)) {
222 invId = UUID.randomUUID().toString();
224 MDC.put("InvocationId", invId);
228 * Sends error as response with error code input.
230 public static void sendResponseError(HttpServletResponse response, int errorCode, EELFLogger intlogger) {
232 response.sendError(errorCode);
233 } catch (IOException ioe) {
234 intlogger.error("IOException", ioe);
239 * If file is of type gzip.
241 * @param file The name of the file to be checked
242 * @return True if the file is of type gzip
244 public static boolean isFiletypeGzip(File file) {
245 try (FileInputStream fileInputStream = new FileInputStream(file);
246 GZIPInputStream ignored = new GZIPInputStream(fileInputStream)) {
248 } catch (IOException e) {
249 eelfLogger.error("NODE0403 " + file + " Not in gzip(gz) format: " + e + e);