2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * Modifications Copyright (C) 2019 Nordix Foundation.
5 * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.policy.apex.core.infrastructure.messaging.util;
26 import java.io.ByteArrayOutputStream;
27 import java.io.IOException;
28 import java.io.ObjectOutputStream;
29 import java.net.InetAddress;
30 import java.net.NetworkInterface;
31 import java.net.Socket;
32 import java.net.UnknownHostException;
33 import java.util.Enumeration;
34 import lombok.AccessLevel;
35 import lombok.NoArgsConstructor;
36 import org.slf4j.ext.XLogger;
37 import org.slf4j.ext.XLoggerFactory;
40 * The Class MessagingUtils is a class with static methods used in IPC messaging for finding free ports, translating
41 * host names to addresses, serializing objects and flushing object streams.
43 * @author Sajeevan Achuthan (sajeevan.achuthan@ericsson.com)
45 @NoArgsConstructor(access = AccessLevel.PRIVATE)
46 public final class MessagingUtils {
47 // The port number of the lowest user port, ports 0-1023 are system ports
48 private static final int LOWEST_USER_PORT = 1024;
51 * Port number is an unsigned 16-bit integer, so maximum port is 65535.
53 private static final int MAX_PORT_RANGE = 65535;
55 // Logger for this class
56 private static final XLogger LOGGER = XLoggerFactory.getXLogger(MessagingUtils.class);
59 * This method searches the availability of the port, if the requested port not available, this method will throw an
62 * @param port the port to check
63 * @return the port verified as being free
64 * @throws RuntimeException on port allocation errors
66 public static int checkPort(final int port) {
67 LOGGER.entry("Checking availability of port {}", port);
69 if (isPortAvailable(port)) {
70 LOGGER.debug("Port {} is available ", port);
73 LOGGER.debug("Port {} is not available", port);
74 throw new IllegalArgumentException("could not allocate requested port: " + port);
78 * This method searches the availability of the port, if the requested port not available,this method will increment
79 * the port number and check the availability of that port, this process will continue until it reaches max port
80 * range which is MAX_PORT_RANGE.
82 * @param port the first port to check
83 * @return the port that was found
84 * @throws RuntimeException on port allocation errors
86 public static int findPort(final int port) {
87 LOGGER.entry("Checking availability of port {}", port);
89 int availablePort = port;
91 while (availablePort <= MAX_PORT_RANGE) {
92 if (isPortAvailable(availablePort)) {
93 LOGGER.debug("Port {} is available ", availablePort);
96 LOGGER.debug("Port {} is not available", availablePort);
99 throw new IllegalArgumentException("could not find free available");
103 * Check if port is available or not.
105 * @param port the port to test
106 * @return true if port is available
108 public static boolean isPortAvailable(final int port) {
109 try (final var socket = new Socket("localhost", port)) {
111 } catch (final IOException ignoredException) {
112 LOGGER.trace("Port {} is available", port, ignoredException);
118 * Returns the local host address.
120 * @return the local host address
121 * @throws IllegalStateException if the local host's address cannot be found
123 public static InetAddress getHost() {
125 return InetAddress.getLocalHost();
126 } catch (final UnknownHostException e) {
127 throw new IllegalStateException(e.getMessage(), e);
132 * This method searches the availability of the port, if the requested port not available,this method will increment
133 * the port number and check the availability, this process will continue until it find port available.
135 * @param port the first port to check
136 * @return the port that was found
137 * @throws RuntimeException on port allocation errors
139 public static int allocateAddress(final int port) {
140 if (port < LOWEST_USER_PORT) {
141 throw new IllegalArgumentException("The port " + port + " is already in use");
143 return MessagingUtils.findPort(port);
147 * Get an Internet Address for the local host.
149 * @return an Internet address
150 * @throws UnknownHostException if the address of the local host cannot be found
152 public static InetAddress getLocalHostLanAddress() throws UnknownHostException {
154 InetAddress candidateAddress = null;
155 // Iterate all NICs (network interface cards)...
156 for (final Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces
157 .hasMoreElements();) {
158 final NetworkInterface iface = ifaces.nextElement();
159 // Iterate all IP addresses assigned to each card...
160 for (final Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs
161 .hasMoreElements();) {
162 final InetAddress inetAddr = inetAddrs.nextElement();
163 if (!inetAddr.isLoopbackAddress()) {
165 if (inetAddr.isSiteLocalAddress()) {
166 // Found non-loopback site-local address. Return it
169 } else if (candidateAddress == null) {
170 // Found non-loopback address, but not
171 // necessarily site-local.
172 // Store it as a candidate to be returned if
173 // site-local address is not subsequently
175 candidateAddress = inetAddr;
176 // Note that we don't repeatedly assign
177 // non-loopback non-site-local addresses as
179 // only the first. For subsequent iterations,
180 // candidate will be non-null.
185 if (candidateAddress != null) {
186 // We did not find a site-local address, but we found some other
187 // non-loopback address.
188 // Server might have a non-site-local address assigned to its
189 // NIC (or it might be running
190 // IPv6 which deprecates the "site-local" concept).
191 // Return this non-loopback candidate address...
192 return candidateAddress;
194 // At this point, we did not find a non-loopback address.
195 // Fall back to returning whatever InetAddress.getLocalHost()
197 final var jdkSuppliedAddress = InetAddress.getLocalHost();
198 if (jdkSuppliedAddress == null) {
199 throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
201 return jdkSuppliedAddress;
202 } catch (final Exception e) {
203 final var unknownHostException =
204 new UnknownHostException("Failed to determine LAN address: " + e);
205 unknownHostException.initCause(e);
206 throw unknownHostException;
211 * This method serializes the message holder objects.
213 * @param object the object
216 public static byte[] serializeObject(final Object object) {
217 LOGGER.entry(object.getClass().getName());
218 final var bytesOut = new ByteArrayOutputStream();
219 try (var oos = new ObjectOutputStream(bytesOut)) {
220 oos.writeObject(object);
221 } catch (final IOException e) {
222 LOGGER.warn("error on object serialization", e);
224 return bytesOut.toByteArray();