a6c3c58547bb7925ab2075254fa9f466a1ba9ca6
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.core.infrastructure.messaging.util;
23
24 import java.io.ByteArrayOutputStream;
25 import java.io.IOException;
26 import java.io.ObjectOutputStream;
27 import java.net.InetAddress;
28 import java.net.NetworkInterface;
29 import java.net.Socket;
30 import java.net.UnknownHostException;
31 import java.util.Enumeration;
32 import org.slf4j.ext.XLogger;
33 import org.slf4j.ext.XLoggerFactory;
34
35 /**
36  * The Class MessagingUtils is a class with static methods used in IPC messaging for finding free
37  * ports, translating host names to addresses, serializing objects and flushing object streams.
38  *
39  * @author Sajeevan Achuthan (sajeevan.achuthan@ericsson.com)
40  */
41 public final class MessagingUtils {
42     // The port number of the lowest user port, ports 0-1023 are system ports
43     private static final int LOWEST_USER_PORT = 1024;
44
45     /**
46      * Port number is an unsigned 16-bit integer, so maximum port is 65535.
47      */
48     private static final int MAX_PORT_RANGE = 65535;
49
50     // Logger for this class
51     private static final XLogger LOGGER = XLoggerFactory.getXLogger(MessagingUtils.class);
52
53     /**
54      * Private constructor used to prevent sub class instantiation.
55      */
56     private MessagingUtils() {}
57
58     /**
59      * This method searches the availability of the port, if the requested port not available, this
60      * method will throw an exception.
61      *
62      * @param port the port to check
63      * @return the port verified as being free
64      * @throws RuntimeException on port allocation errors
65      */
66     public static int checkPort(final int port) {
67         LOGGER.entry("Checking availability of  port {}", port);
68
69         if (isPortAvailable(port)) {
70             LOGGER.debug("Port {} is available ", port);
71             return port;
72         }
73         LOGGER.debug("Port {} is not available", port);
74         throw new IllegalArgumentException("could not allocate requested port: " + port);
75     }
76
77     /**
78      * This method searches the availability of the port, if the requested port not available,this
79      * method will increment the port number and check the availability of that port, this process
80      * will continue until it reaches max port range which is MAX_PORT_RANGE.
81      *
82      * @param port the first port to check
83      * @return the port that was found
84      * @throws RuntimeException on port allocation errors
85      */
86     public static int findPort(final int port) {
87         LOGGER.entry("Checking availability of  port {}", port);
88
89         int availablePort = port;
90
91         while (availablePort <= MAX_PORT_RANGE) {
92             if (isPortAvailable(availablePort)) {
93                 LOGGER.debug("Port {} is available ", availablePort);
94                 return availablePort;
95             }
96             LOGGER.debug("Port {} is not available", availablePort);
97             availablePort++;
98         }
99         throw new IllegalArgumentException("could not find free available");
100     }
101
102     /**
103      * Check if port is available or not.
104      *
105      * @param port the port to test
106      * @return true if port is available
107      */
108     public static boolean isPortAvailable(final int port) {
109         try (final Socket socket = new Socket("localhost", port)) {
110             return false;
111         } catch (final IOException ignoredException) {
112             LOGGER.trace("Port {} is available", port, ignoredException);
113             return true;
114         }
115     }
116
117     /**
118      * Returns the local host address.
119      *
120      * @return the local host address
121      * @throws IllegalStateException if the local host's address cannot be found
122      */
123     public static InetAddress getHost() {
124         try {
125             return InetAddress.getLocalHost();
126         } catch (final UnknownHostException e) {
127             throw new IllegalStateException(e.getMessage(), e);
128         }
129     }
130
131     /**
132      * This method searches the availability of the port, if the requested port not available,this
133      * method will increment the port number and check the availability, this process will continue
134      * until it find port available.
135      *
136      * @param port the first port to check
137      * @return the port that was found
138      * @throws RuntimeException on port allocation errors
139      */
140     public static int allocateAddress(final int port) {
141         if (port < LOWEST_USER_PORT) {
142             throw new IllegalArgumentException("The port " + port + "  is already in use");
143         }
144         return MessagingUtils.findPort(port);
145     }
146
147     /**
148      * Get an Internet Address for the local host.
149      *
150      * @return an Internet address
151      * @throws UnknownHostException if the address of the local host cannot be found
152      */
153     public static InetAddress getLocalHostLanAddress() throws UnknownHostException {
154         try {
155             InetAddress candidateAddress = null;
156             // Iterate all NICs (network interface cards)...
157             for (final Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces
158                     .hasMoreElements();) {
159                 final NetworkInterface iface = ifaces.nextElement();
160                 // Iterate all IP addresses assigned to each card...
161                 for (final Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs
162                         .hasMoreElements();) {
163                     final InetAddress inetAddr = inetAddrs.nextElement();
164                     if (!inetAddr.isLoopbackAddress()) {
165
166                         if (inetAddr.isSiteLocalAddress()) {
167                             // Found non-loopback site-local address. Return it
168                             // immediately...
169                             return inetAddr;
170                         } else if (candidateAddress == null) {
171                             // Found non-loopback address, but not
172                             // necessarily site-local.
173                             // Store it as a candidate to be returned if
174                             // site-local address is not subsequently
175                             // found...
176                             candidateAddress = inetAddr;
177                             // Note that we don't repeatedly assign
178                             // non-loopback non-site-local addresses as
179                             // candidates,
180                             // only the first. For subsequent iterations,
181                             // candidate will be non-null.
182                         }
183                     }
184                 }
185             }
186             if (candidateAddress != null) {
187                 // We did not find a site-local address, but we found some other
188                 // non-loopback address.
189                 // Server might have a non-site-local address assigned to its
190                 // NIC (or it might be running
191                 // IPv6 which deprecates the "site-local" concept).
192                 // Return this non-loopback candidate address...
193                 return candidateAddress;
194             }
195             // At this point, we did not find a non-loopback address.
196             // Fall back to returning whatever InetAddress.getLocalHost()
197             // returns...
198             final InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
199             if (jdkSuppliedAddress == null) {
200                 throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
201             }
202             return jdkSuppliedAddress;
203         } catch (final Exception e) {
204             final UnknownHostException unknownHostException =
205                     new UnknownHostException("Failed to determine LAN address: " + e);
206             unknownHostException.initCause(e);
207             throw unknownHostException;
208         }
209     }
210
211     /**
212      * This method serializes the message holder objects.
213      *
214      * @param object the object
215      * @return byte[]
216      */
217     public static byte[] serializeObject(final Object object) {
218         LOGGER.entry(object.getClass().getName());
219         final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
220         ObjectOutputStream oos = null;
221         try {
222             oos = new ObjectOutputStream(bytesOut);
223             oos.writeObject(object);
224         } catch (final IOException e) {
225             LOGGER.warn("error on object serialization", e);
226         } finally {
227             flushAndClose(oos, bytesOut);
228         }
229         return bytesOut.toByteArray();
230     }
231
232     /**
233      * Flush and close an object stream and a byte array output stream.
234      *
235      * @param oos the object output stream
236      * @param bytesOut the byte array output stream
237      */
238     private static void flushAndClose(final ObjectOutputStream oos, final ByteArrayOutputStream bytesOut) {
239         try {
240             if (oos != null) {
241                 oos.flush();
242                 oos.close();
243             }
244             if (bytesOut != null) {
245                 bytesOut.close();
246             }
247
248         } catch (final IOException e) {
249             LOGGER.error("Failed to close the Srialization operation");
250             LOGGER.catching(e);
251         }
252     }
253 }