001/*
002 * ============================================================================
003 * Copyright © 2002-2026 by Thomas Thrien.
004 * All Rights Reserved.
005 * ============================================================================
006 * Licensed to the public under the agreements of the GNU Lesser General Public
007 * License, version 3.0 (the "License"). You may obtain a copy of the License at
008 *
009 *      http://www.gnu.org/licenses/lgpl.html
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
013 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
014 * License for the specific language governing permissions and limitations
015 * under the License.
016 */
017
018package org.tquadrat.foundation.util;
019
020import static java.lang.Math.max;
021import static java.lang.String.format;
022import static java.lang.System.arraycopy;
023import static java.lang.System.currentTimeMillis;
024import static java.lang.System.getProperties;
025import static java.lang.System.getProperty;
026import static java.lang.System.nanoTime;
027import static java.lang.Thread.currentThread;
028import static java.net.InetAddress.getByName;
029import static java.util.Arrays.stream;
030import static java.util.Collections.list;
031import static java.util.Locale.ROOT;
032import static org.apiguardian.api.API.Status.DEPRECATED;
033import static org.apiguardian.api.API.Status.EXPERIMENTAL;
034import static org.apiguardian.api.API.Status.INTERNAL;
035import static org.apiguardian.api.API.Status.STABLE;
036import static org.tquadrat.foundation.lang.CommonConstants.PROPERTY_CPUARCHITECTURE;
037import static org.tquadrat.foundation.lang.CommonConstants.PROPERTY_OSNAME;
038import static org.tquadrat.foundation.lang.CommonConstants.PROPERTY_OSVERSION;
039import static org.tquadrat.foundation.lang.CommonConstants.PROPERTY_USER_NAME;
040import static org.tquadrat.foundation.lang.CommonConstants.TIME_DELTA_BEGINGREGORIAN2BEGINEPOCH;
041import static org.tquadrat.foundation.lang.Objects.isNull;
042import static org.tquadrat.foundation.lang.Objects.nonNull;
043import static org.tquadrat.foundation.lang.Objects.requireNonNullArgument;
044import static org.tquadrat.foundation.lang.Objects.requireNotEmptyArgument;
045import static org.tquadrat.foundation.util.StringUtils.splitString;
046
047import java.io.File;
048import java.math.BigInteger;
049import java.net.Inet4Address;
050import java.net.InetAddress;
051import java.net.NetworkInterface;
052import java.net.SocketException;
053import java.net.UnknownHostException;
054import java.time.Duration;
055import java.time.Instant;
056import java.time.ZoneId;
057import java.util.Collection;
058import java.util.HashMap;
059import java.util.HexFormat;
060import java.util.IllformedLocaleException;
061import java.util.List;
062import java.util.Locale;
063import java.util.Map;
064import java.util.Optional;
065import java.util.Random;
066import java.util.regex.Pattern;
067import java.util.regex.PatternSyntaxException;
068
069import org.apiguardian.api.API;
070import org.tquadrat.foundation.annotation.ClassVersion;
071import org.tquadrat.foundation.annotation.UtilityClass;
072import org.tquadrat.foundation.exception.PrivateConstructorForStaticClassCalledError;
073import org.tquadrat.foundation.lang.CommonConstants;
074import org.tquadrat.foundation.lang.Lazy;
075
076/**
077 *  <p>{@summary This class provides some system related helper and convenience
078 *  methods.}</p>
079 *
080 *  @author Thomas Thrien - thomas.thrien@tquadrat.org
081 *  @version $Id: SystemUtils.java 1260 2026-08-17 15:26:45Z tquadrat $
082 *  @since 0.0.5
083 *
084 *  @UMLGraph.link
085 */
086@SuppressWarnings( {"ClassWithTooManyMethods", "OverlyComplexClass"} )
087@ClassVersion( sourceVersion = "$Id: SystemUtils.java 1260 2026-08-17 15:26:45Z tquadrat $" )
088@API( status = STABLE, since = "0.0.5" )
089@UtilityClass
090public final class SystemUtils
091{
092        /*---------------*\
093    ====** Inner Classes **====================================================
094        \*---------------*/
095    /**
096     *  <p>{@summary The operating system families that are supported (or not) by Java.}</p>
097     *  <p>Currently, we can distinguish only between Microsoft Windows,
098     *  UNIX/Linux and macOS/OS-X.</p>
099     *
100     *  @author Thomas Thrien - thomas.thrien@tquadrat.org
101     *  @version $Id: SystemUtils.java 1260 2026-08-17 15:26:45Z tquadrat $
102     *  @since 0.0.6
103     *
104     *  @UMLGraph.link
105     *
106     *  @see SystemUtils#determineOperatingSystem()
107     */
108    @ClassVersion( sourceVersion = "$Id: SystemUtils.java 1260 2026-08-17 15:26:45Z tquadrat $" )
109    @API( status = STABLE, since = "0.0.6" )
110    public static enum OperatingSystem
111    {
112            /*------------------*\
113        ====** Enum Declaration **=============================================
114            \*------------------*/
115        /**
116         *  The operating system is OS-X
117         */
118        OSX,
119
120        /**
121         *  The operating system is UNIX/Linux.
122         */
123        UNIX,
124
125        /**
126         *  The operating system is Microsoft Windows.
127         */
128        WINDOWS,
129
130        /**
131         *  The current operating system is unknown to this library.
132         */
133        UNKNOWN;
134
135            /*---------*\
136        ====** Methods **======================================================
137            \*---------*/
138        /**
139         *  Returns the operating system architecture.
140         *
141         *  @return The architecture.
142         */
143        @SuppressWarnings( "static-method" )
144        public final String getArchitecture() {return getProperty( PROPERTY_CPUARCHITECTURE ); }
145
146        /**
147         *  Returns the name of the operating system.
148         *
149         *  @return The operating system name.
150         */
151        @SuppressWarnings( "static-method" )
152        public final String getName() { return getProperty( PROPERTY_OSNAME ); }
153
154        /**
155         *  Returns the name of the operating system.
156         *
157         *  @return The operating system name.
158         */
159        public final String getNameVersion() { return format( "%s %s (%s)", getName(), getVersion(), getArchitecture() ); }
160
161        /**
162         *  Returns the version of the operating system.
163         *
164         *  @return The version of the operating system.
165         */
166        @SuppressWarnings( "static-method" )
167        public final String getVersion() { return getProperty( PROPERTY_OSVERSION ); }
168    }
169    //  enum OperatingSystem
170
171        /*-----------*\
172    ====** Constants **========================================================
173        \*-----------*/
174    /**
175     *  The valid bits for a node id: {@value}.
176     *
177     *  @see #m_Node
178     */
179    @API( status = INTERNAL, since = "0.1.0" )
180    private static final long m_NodeIdBits = 0x0000FFFFFFFFFFFFL;
181
182    /**
183     *  The sign bit for a node id: {@value}.
184     *
185     *  @see #m_Node
186     */
187    @API( status = INTERNAL, since = "0.1.0" )
188    private static final long m_NodeIdSign = 0x0000010000000000L;
189
190    /**
191     *  The length of a String containing a MAC address: {@value}.
192     */
193    @API( status = STABLE, since = "0.0.5" )
194    public static final int MAC_ADDRESS_Size = 17;
195
196    /**
197     *  Factor for the conversion of milliseconds to nanoseconds.
198     */
199    private static final BigInteger ONE_MILLION = BigInteger.valueOf( 1_000_000 );
200
201    /**
202     *  Factor for the conversion of seconds to milliseconds.
203     */
204    private static final BigInteger ONE_THOUSAND = BigInteger.valueOf( 1_000 );
205
206    /**
207     *  The regular expression for a valid IPv4 address: {@value}.
208     */
209    @API( status = STABLE, since = "0.0.5" )
210    public static final String PATTERN_IPv4_ADDRESS = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
211
212    /**
213     *  <p>{@summary The name of the system property for the node id:
214     *  {@value}.}</p>
215     *  <p>The value has to be a positive number. It will be parsed by
216     *  {@link Long#decode(String)};
217     *  this means, it could be a decimal, a hex or an octal number – so be
218     *  careful with leading zeroes!</p>
219     *  <p>This system property is not necessarily configured; if missing, the
220     *  node id will be determined by the hardware address of the NIC.</p>
221     *
222     *  @see #getNodeId()
223     */
224    @API( status = STABLE, since = "0.1.0" )
225    public static final String PROPERTY_NODE_ID = "org.tquadrat.foundation.util.SystemUtils.NodeId";
226
227        /*------------*\
228    ====** Attributes **=======================================================
229        \*------------*/
230    /**
231     *  The location or node id.
232     */
233    private static Long m_Node = null;
234
235        /*------------------------*\
236    ====** Static Initialisations **===========================================
237        \*------------------------*/
238    /**
239     *  <p>{@summary The adjustment value that is used to align the time
240     *  returned from
241     *  {@link System#nanoTime()}
242     *  with the system time.}</p>
243     *
244     *  @see #currentTimeNanos()
245     */
246    private static final BigInteger m_NanoAdjust;
247
248    /**
249     *  The operating system.
250     */
251    private static final Lazy<OperatingSystem> m_OperatingSystem;
252
253    /**
254     *  The pattern to check a string for an IPv4 address.
255     */
256    private static final Lazy<Pattern> m_PatternIPv4Address;
257    /**
258     *  The random number generator.
259     */
260    private static final Lazy<Random> m_Random;
261
262    static
263    {
264        //---* The node id *---------------------------------------------------
265        final var nodeId = Long.getLong( PROPERTY_NODE_ID );
266        if( nonNull( nodeId ) )
267        {
268            m_Node = Long.valueOf( (nodeId.longValue() & m_NodeIdBits) | m_NodeIdSign );
269        }
270
271        //---* The operating system *------------------------------------------
272        m_OperatingSystem = Lazy.use( SystemUtils::determineOperatingSystem );
273
274        //---* The pattern for the IP addresses *------------------------------
275        m_PatternIPv4Address = Lazy.use( () ->
276        {
277            try
278            {
279                return Pattern.compile( PATTERN_IPv4_ADDRESS );
280            }
281            catch( final PatternSyntaxException e )
282            {
283                throw new ExceptionInInitializerError( e );
284            }
285        } );
286
287        //---* The random number generator *-----------------------------------
288        m_Random = Lazy.use( Random::new );
289
290        //---* The time adjustment *-------------------------------------------
291        final var timeDelta = BigInteger.valueOf( TIME_DELTA_BEGINGREGORIAN2BEGINEPOCH ).multiply( ONE_THOUSAND ).multiply( ONE_MILLION );
292        final var nanoNow = BigInteger.valueOf( nanoTime() );
293        final var milliNow = BigInteger.valueOf( currentTimeMillis() ).multiply( ONE_MILLION );
294        m_NanoAdjust = milliNow.subtract( nanoNow ).add( timeDelta );
295    }
296
297        /*--------------*\
298    ====** Constructors **=====================================================
299        \*--------------*/
300    /**
301     *  No instance allowed for this class.
302     */
303    private SystemUtils() { throw new PrivateConstructorForStaticClassCalledError( SystemUtils.class ); }
304
305        /*---------*\
306    ====** Methods **==========================================================
307        \*---------*/
308    /**
309     *  <p>{@summary Converts an IP address that is given as a string into an
310     *  {@link InetAddress}
311     *  object.}</p>
312     *
313     *  TODO Currently this method do not process IPv6 addresses properly.
314     *
315     *  @param  ipAddress   The string with the IP address.
316     *  @return The {@code InetAddress} object.
317     *  @throws IllegalArgumentException    The given parameter is not a valid
318     *      IP address.
319     */
320    @API( status = EXPERIMENTAL, since = "0.0.5" )
321    public static final InetAddress convertIPAddress( final CharSequence ipAddress )
322    {
323        final var message = "IP address is invalid: %1$s";
324        InetAddress retValue = null;
325
326        final var arg = requireNotEmptyArgument( ipAddress, "ipAddress" ).toString();
327        if( m_PatternIPv4Address.get().matcher( arg ).matches() || arg.contains( ":" ) )
328        {
329            try
330            {
331                retValue = getByName( arg );
332            }
333            catch( final UnknownHostException e )
334            {
335                throw new IllegalArgumentException( format( message, arg ), e );
336            }
337        }
338        else
339        {
340            throw new IllegalArgumentException( format( message, arg ) );
341        }
342
343        //---* Done *----------------------------------------------------------
344        return retValue;
345    }   //  convertIPAddress()
346
347    /**
348     *  <p>{@summary Returns a pseudo node id; this is useful in cases a
349     *  machine does not have a network card (NIC) so that a MAC address could
350     *  not be obtained, or if the real node id should not be used.}</p>
351     *  <p>Each call to this method will return a new value.</p>
352     *
353     *  @return The node id.
354     */
355    @API( status = STABLE, since = "0.0.5" )
356    public static final long createPseudoNodeId()
357    {
358        final var retValue = (getRandom().nextLong() & m_NodeIdBits) | m_NodeIdSign;
359
360        //---* Done *----------------------------------------------------------
361        return retValue;
362    }   //  createPseudoNodeId()
363
364    /**
365     *  Creates the alias map for the old (deprecated) zone ids that are used
366     *  for the call to
367     *  {@link ZoneId#of(String, java.util.Map)}
368     *  to retrieve a
369     *  {@link ZoneId}
370     *  instance for the given zone id.
371     *
372     *  @return The alias map.
373     *
374     *  @since 0.0.6
375     *
376     *  @deprecated Use
377     *      {@link DateTimeUtils#createZoneIdAliasMap()}
378     *      instead.
379     */
380    @API( status = DEPRECATED, since = "0.0.6" )
381    @Deprecated( since = "0.4.0", forRemoval = true )
382    public static final Map<String,String> createZoneIdAliasMap()
383    {
384        return DateTimeUtils.createZoneIdAliasMap();
385    }   //  createZoneIdAliasMap()
386
387    /**
388     *  Returns the current time as nanoseconds since the beginning of the
389     *  Gregorian calendar (1582-10-15T00:00).
390     *
391     *  @return The current time in nanoseconds.
392     */
393    @API( status = STABLE, since = "0.0.5" )
394    public static final BigInteger currentTimeNanos()
395    {
396        final var retValue = m_NanoAdjust.add( BigInteger.valueOf( nanoTime() ) );
397
398        //---* Done *----------------------------------------------------------
399        return retValue;
400    }   //  currentTimeNanos()
401
402    /**
403     *  Determines an IP address of the machine this program is running on.
404     *  Usually this will be one of the addresses that is visible to the
405     *  outside. In addition, the method has a clear precedence for IPv4
406     *  addresses over IPv6 ones.
407     *
408     *  @return An instance of
409     *      {@link Optional}
410     *      that holds the IP address; it will be empty if really no network
411     *      adapter is active on this machine.
412     *  @throws SocketException Problems to retrieve the internet address.
413     */
414    @SuppressWarnings( "OverlyNestedMethod" )
415    @API( status = STABLE, since = "0.0.5" )
416    public static final Optional<InetAddress> determineIPAddress() throws SocketException
417    {
418        Optional<InetAddress> retValue = Optional.empty();
419
420        List<InetAddress> addresses;
421        ScanLoop: for( final var networkInterface : getNetworkInterfaces() )
422        {
423            /*
424             * Due to the nature of the scan logic, the returned address will
425             * always be that of the last NIC in sequence that is not the
426             * {@code loopback} interface.
427             */
428            if( networkInterface.isUp() )
429            {
430                addresses = list( networkInterface.getInetAddresses() );
431                AddressLoop: for( final var address : addresses )
432                {
433                    /*
434                     * The AddressLoop terminates early, when the first IPv4
435                     * address for the NIC was found.
436                     */
437                    if( networkInterface.isLoopback() )
438                    {
439                        /*
440                         * We take loopback if we do not get something
441                         * better ...
442                         */
443                        if( retValue.isEmpty() )
444                        {
445                            retValue = Optional.of( address );
446                            if( address instanceof Inet4Address ) break AddressLoop;
447                        }
448                        else if( !(retValue.get() instanceof Inet4Address) )
449                        {
450                            retValue = Optional.of( address );
451                            break AddressLoop;
452                        }
453                    }
454                    else
455                    {
456                        retValue = Optional.of( address );
457                        if( address instanceof Inet4Address ) break AddressLoop;
458                    }
459                }
460            }
461        }   //  ScanLoop:
462
463        //---* Done *----------------------------------------------------------
464        return retValue;
465    }   //  determineIPAddress()
466
467    /**
468     *  Determines all the IP addresses of the machine this program is running
469     *  on.
470     *
471     *  @return The IP addresses.
472     */
473    @API( status = STABLE, since = "0.0.5" )
474    public static final InetAddress [] determineIPAddresses()
475    {
476        final var retValue = getNetworkInterfaces().stream()
477            .flatMap( networkInterface -> list( networkInterface.getInetAddresses() ).stream() )
478            .toArray( InetAddress []::new );
479
480        //---* Done *----------------------------------------------------------
481        return retValue;
482    }   //  determineIPAddresses()
483
484    /**
485     *  Determines the operating system.
486     *
487     *  @return The operating system.
488     */
489    private static final OperatingSystem determineOperatingSystem()
490    {
491        /*
492         * TODO Add more criteria for each family. And perhaps it should be
493         * distinguished between Linux, BSD and Unix (and there between HP-UX
494         * and AIX) ...
495         */
496        var retValue = OperatingSystem.UNKNOWN;
497
498        /*
499         * All currently known MS-DOS and Windows versions and their file
500         * systems use the backslash as the separator for folders.
501         * They also use the semicolon as the PATH separator.
502         */
503        final var fileSeparator = File.separatorChar;
504        final var pathSeparator = File.pathSeparatorChar;
505        if( (fileSeparator == '\\') && (pathSeparator == ';') )
506        {
507            retValue = OperatingSystem.WINDOWS;
508        }
509        else if( (fileSeparator == '/') && (pathSeparator == ':') )
510        {
511            if( getProperty( PROPERTY_OSNAME ).toLowerCase( ROOT ).contains( "osx" ) )
512            {
513                retValue = OperatingSystem.OSX;
514            }
515            else
516            {
517                retValue = OperatingSystem.UNIX;
518            }
519        }
520
521        //---* Done *----------------------------------------------------------
522        return retValue;
523    }   //  determineOperatingSystem()
524
525    /**
526     *  Determines those IP addresses of the machine this program is running
527     *  on that are used to communicate with the outside world. This means that
528     *  only those <i>active</i> network interfaces are considered that are
529     *  <i>not</i> a {@code loopback} interface.
530     *
531     *  @return The IP addresses.
532     */
533    @API( status = STABLE, since = "0.0.5" )
534    public static final InetAddress [] determineOutboundIPAddresses()
535    {
536        final var retValue = getNetworkInterfaces().stream()
537            .filter( networkInterface ->
538            {
539                try
540                {
541                    return networkInterface.isUp() && !networkInterface.isLoopback();
542                }
543                catch( final SocketException ignored )
544                {
545                    return false;
546                }
547            } )
548            .flatMap( networkInterface -> list( networkInterface.getInetAddresses() ).stream() )
549            .toArray( InetAddress []::new );
550
551        //---* Done *----------------------------------------------------------
552        return retValue;
553    }   //  determineOutboundIPAddresses()
554
555    /**
556     *  Formats the given node id as a MAC address string.
557     *
558     *  @param  nodeId  The node id.
559     *  @return The MAC address string.
560     */
561    @API( status = STABLE, since = "0.0.5" )
562    public static final String formatNodeIdAsMAC( final long nodeId )
563    {
564        if( nodeId != (nodeId & m_NodeIdBits) )
565        {
566            throw new IllegalArgumentException( "Node id is invalid: %1$d".formatted( nodeId ) );
567        }
568
569        final var hexFormat = HexFormat.of();
570        final var bytes = hexFormat.parseHex( hexFormat.toHexDigits( nodeId, 12 ) );
571        final var retValue = HexFormat.ofDelimiter( "-" ).withUpperCase().formatHex( bytes );
572
573        //---* Done *----------------------------------------------------------
574        return retValue;
575    }   //  formatNodeIdAsMAC()
576
577    /**
578     *  Returns the MAC address for the current computer. In case the machine
579     *  will have more than one network card (NIC), the returned MAC is
580     *  selected in the same as for
581     *  {@link #getNodeId()}.
582     *
583     *  @return The MAC address.
584     */
585    @API( status = STABLE, since = "0.0.5" )
586    public static final String getMACAddress() { return formatNodeIdAsMAC( getNodeId() ); }
587
588    /**
589     *  Returns a
590     *  {@link Collection}
591     *  of all the network interfaces on this machine. Instead of throwing an
592     *  exception, the method will return an empty collection in case the
593     *  machine do not have network configured. Otherwise, the collection
594     *  contains at least one element, possibly representing a {@code loopback}
595     *  interface that only supports communication between entities on this
596     *  machine.
597     *
598     *  @return The
599     *      {@link NetworkInterface}s found on this machine.
600     *
601     *  @see java.net.NetworkInterface#getNetworkInterfaces()
602     */
603    @API( status = STABLE, since = "0.0.5" )
604    public static final Collection<NetworkInterface> getNetworkInterfaces()
605    {
606        Collection<NetworkInterface> retValue = List.of();
607        try
608        {
609            retValue = List.copyOf( list( java.net.NetworkInterface.getNetworkInterfaces() ) );
610        }
611        catch( final SocketException ignored )
612        {
613            /*
614             * There are no NICs on this machine, so we return the empty list.
615             */
616        }
617
618        //---* Done *----------------------------------------------------------
619        return retValue;
620    }   //  getNetworkInterfaces()
621
622    /**
623     *  Returns the unique id of this node.
624     *
625     *  @return The node id.
626     *
627     *  @see #PROPERTY_NODE_ID
628     */
629    @SuppressWarnings( "OverlyComplexMethod" )
630    @API( status = STABLE, since = "0.0.5" )
631    public static final long getNodeId()
632    {
633        if( isNull( m_Node ) )
634        {
635            final var interfaces = getNetworkInterfaces();
636            var randomGenerationRequired = interfaces.isEmpty();
637            if( !randomGenerationRequired )
638            {
639                var count = interfaces.size();
640                ScanLoop: for( final var nic : interfaces )
641                {
642                    try
643                    {
644                        if( (--count > 0) && (nic.isLoopback() || nic.isVirtual()) )
645                        {
646                            /*
647                             * We prefer a real hardware NIC if we can get one.
648                             */
649                            continue ScanLoop;
650                        }
651
652                        final var hardwareAddress = nic.getHardwareAddress();
653                        if( nonNull( hardwareAddress ) && (hardwareAddress.length > 0) )
654                        {
655                            m_Node = Long.valueOf( new BigInteger( hardwareAddress ).longValue() & m_NodeIdBits );
656                            break ScanLoop;
657                        }
658                    }
659                    catch( final SocketException ignored )
660                    {
661                        /*
662                         *  If a SocketException is caught here, this indicates
663                         *  that we have problems to determine the NICs. In
664                         *  this case, we have to create a random node id.
665                         */
666                        break ScanLoop;
667                    }
668                }   //  ScanLoop:
669
670                /*
671                 * If we still do not have a valid node id, it seems that none
672                 * of the NICs have a hardware address; may be that they are
673                 * NICs for a virtual machine or virtual NICs of some kind.
674                 * But is it possible to have a NIC without a MAC?
675                 */
676                randomGenerationRequired = isNull( m_Node );
677            }
678
679            if( randomGenerationRequired )
680            {
681                //---* We have to create a random location *-------------------
682                m_Node = Long.valueOf( createPseudoNodeId() );
683            }
684        }
685
686        final var retValue = m_Node.longValue();
687
688        //---* Done *----------------------------------------------------------
689        return retValue;
690    }   //  getNodeId()
691
692    /**
693     *  Returns the current operating system.
694     *
695     *  @return The operating system.
696     */
697    @API( status = STABLE, since = "0.0.6" )
698    public static final OperatingSystem getOperatingSystem() { return m_OperatingSystem.get(); }
699
700    /**
701     *  Returns the PID, the process id, for the VM this (the current) program
702     *  runs in.
703     *
704     *  @return The PID.
705     *  @throws UnsupportedOperationException   The implementation of
706     *      {@link ProcessHandle}
707     *      that is currently in use does not support the operation
708     *      {@link ProcessHandle#pid()}.
709     *
710     *  @see ProcessHandle#pid()
711     */
712    @API( status = STABLE, since = "0.0.5" )
713    public static final long getPID() throws UnsupportedOperationException
714    {
715        final var retValue = ProcessHandle.current().pid();
716
717        //---* Done *----------------------------------------------------------
718        return retValue;
719    }   //  getPID()
720
721    /**
722     *  Returns the system random number generator.
723     *
724     *  @return The random number generator.
725     */
726    @API( status = STABLE, since = "0.0.5" )
727    public static final Random getRandom() { return m_Random.get(); }
728
729    /**
730     *  Returns the current username from the system property
731     *  {@value CommonConstants#PROPERTY_USER_NAME}.
732     *
733     *  @return The username.
734     *
735     *  @since 0.4.8
736     */
737    @API( status = STABLE, since = "0.4.8" )
738    public static final String getUserName() { return getProperty( PROPERTY_USER_NAME ); }
739
740    /**
741     *  Returns the alias map; if not yet created, the alias map will be
742     *  created by a call to
743     *  {@link #createZoneIdAliasMap()}
744     *  and the result to that call will be cached for future calls.
745     *
746     *  @return The alias map.
747     *
748     *  @see #createZoneIdAliasMap()
749     *
750     *  @since 0.0.6
751     *
752     *  @deprecated Use
753     *      {@link DateTimeUtils#getZoneIdAliasMap()}
754     *      instead.
755     */
756    @API( status = DEPRECATED, since = "0.0.5" )
757    @Deprecated( since = "0.4.0", forRemoval = true )
758    public static final Map<String,String> getZoneIdAliasMap() { return DateTimeUtils.getZoneIdAliasMap(); }
759
760    /**
761     *  Checks whether the current system has a network interface installed.
762     *
763     *  @return {@true} if the current system has a network interface
764     *      installed, {@false} otherwise.
765     */
766    @API( status = STABLE, since = "0.0.5" )
767    public static final boolean hasNetworkInterface()
768    {
769        final var retValue = !getNetworkInterfaces().isEmpty();
770
771        //---* Done *----------------------------------------------------------
772        return retValue;
773    }   //  hasNetworkInterface()
774
775    /**
776     *  An implementation of
777     *  {@link Thread#sleep(long)}
778     *  that does not throw an exception in case it will be interrupted.
779     *
780     *  @note   While sleeping, the thread does not lose ownership of any
781     *      monitors.
782     *
783     *  @param  millis  The time to sleep in milliseconds.
784     *  @return  {@true} if the sleep was interrupted, {@false} if it
785     *      terminated as planned.
786     */
787    @SuppressWarnings( {"BooleanMethodNameMustStartWithQuestion", "BusyWait"} )
788    @API( status = STABLE, since = "0.0.7" )
789    public static final boolean repose( final long millis )
790    {
791        var retValue = true;
792        final var endTimeMillis  = currentTimeMillis() + millis;
793        SleepLoop: while( currentTimeMillis() < endTimeMillis )
794        {
795            try
796            {
797                Thread.sleep( max( 0, endTimeMillis - currentTimeMillis() ) );
798                retValue = false;
799            }
800            catch( final InterruptedException ignored )
801            {
802               if( currentThread().isInterrupted() ) break SleepLoop;
803            }
804        }   //  SleepLoop:
805
806        //---* Done *----------------------------------------------------------
807        return retValue;
808    }   //  repose()
809
810    /**
811     *  An implementation of
812     *  {@link Thread#sleep(Duration)}
813     *  that does not throw an exception in case it will be interrupted.
814     *
815     *  @note   While sleeping, the thread does not lose ownership of any
816     *      monitors.
817     *
818     *  @param  duration    The time to sleep.
819     *  @return  {@true} if the sleep was interrupted, {@false} if it
820     *      terminated as planned.
821     */
822    @SuppressWarnings( "BooleanMethodNameMustStartWithQuestion" )
823    @API( status = STABLE, since = "0.0.7" )
824    public static final boolean repose( final Duration duration )
825    {
826        var retValue = true;
827        var remainingDuration = requireNonNullArgument( duration, "duration" );
828        var now = Instant.now();
829        final var endTime = now.plus( duration );
830        SleepLoop: while( retValue && now.isBefore( endTime ) )
831        {
832            try
833            {
834                Thread.sleep( remainingDuration );
835                retValue = false;
836            }
837            catch( final InterruptedException _ )
838            {
839                if( currentThread().isInterrupted() ) break SleepLoop;
840                now = Instant.now();
841                remainingDuration = Duration.between( now, endTime );
842            }
843        }   //  SleepLoop:
844
845        //---* Done *----------------------------------------------------------
846        return retValue;
847    }   //  repose()
848
849    /**
850     *  An implementation of
851     *  {@link #sleepUntil(Instant)}
852     *  that does not throw an exception when interrupted.
853     *
854     *  @note   While sleeping, the thread does not lose ownership of any
855     *      monitors.
856     *
857     *  @param  until   The end time for the sleep period.
858     *  @return  {@true} if the sleep was interrupted, {@false} if it
859     *      terminated as planned.
860     */
861    @SuppressWarnings( "BooleanMethodNameMustStartWithQuestion" )
862    @API( status = STABLE, since = "0.0.7" )
863    public static final boolean reposeUntil( final Instant until )
864    {
865        var retValue = true;
866        SleepLoop: while( Instant.now().isBefore( requireNonNullArgument( until, "until" ) ) )
867        {
868            /*
869             * It is intended that Instant::now will be called twice, returning
870             * different results. This will increase accuracy (OK, just
871             * marginally), without causing much harm – we want to waste time
872             * anyway.
873             */
874            try
875            {
876                Thread.sleep( Duration.between( Instant.now(), until ) );
877                retValue = false;
878            }
879            catch( final InterruptedException ignored )
880            {
881                if( currentThread().isInterrupted() ) break SleepLoop;
882            }
883        }
884
885        //---* Done *----------------------------------------------------------
886        return retValue;
887    }   //  reposeUntil()
888    /**
889     *  Retrieves an instance of
890     *  {@link Locale}
891     *  for the given locale name. This method will look up the requested
892     *  locale first in the locales returned by
893     *  {@link Locale#getAvailableLocales()}
894     *  before it will create a new instance of {@code Locale} using
895     *  {@link java.util.Locale.Builder Locale.Builder}.<br>
896     *  <br>The method will return
897     *  {@link Optional#empty()}
898     *  when the format of the given {@code localeName} is invalid.<br>
899     *  <br>If none of the already existing instances of {@code Locale} matches
900     *  the given name, the language part, the country part, the variant part
901     *  and the script part (if provided) are used to create a new instance. If
902     *  extensions are given, they will be ignored.<br>
903     *  <br>If the given locale name is empty or contains only whitespace, the
904     *  method will return
905     *  {@link Locale#ROOT}.
906     *
907     *  @param  localeName  The name of the locale.
908     *  @return An instance of
909     *      {@link Optional}
910     *      that holds the instance of {@code Locale} for the given name.
911     */
912    @SuppressWarnings( {"AssignmentToNull", "OverlyNestedMethod", "OverlyComplexMethod"} )
913    @API( status = STABLE, since = "0.0.6" )
914    public static final Optional<Locale> retrieveLocale( final CharSequence localeName )
915    {
916        final var name = requireNonNullArgument( localeName, "localeName" ).toString();
917        @SuppressWarnings( "OverlyLongLambda" )
918        final var locale = name.isBlank()
919            ? ROOT
920            : stream( Locale.getAvailableLocales() )
921                  .filter( currentLocale -> currentLocale.toString().equals( name ) )
922                  .findFirst()
923                  .orElseGet( () ->
924                  {
925                      Locale result = null;
926                      final var parts = splitString( name, '_' );
927                      try
928                      {
929                          final var builder = new Locale.Builder();
930                          ComposeSwitch: result = switch( parts.length )
931                          {
932                              case 1 -> builder.setLanguage( parts[0] ).build();
933                              case 2 -> builder.setLanguage( parts[0] ).setRegion( parts[1] ).build();
934                              case 3 -> {
935                                  builder.setLanguage( parts[0] ).setRegion( parts[1] );
936                                  if( parts[2].startsWith( "#" ) )
937                                  {
938                                      if( parts[2].length() == 4 )
939                                          builder.setScript( parts[2].substring( 1 ) );
940                                  }
941                                  else
942                                  {
943                                      builder.setVariant( parts[2] );
944                                  }
945                                  yield builder.build();
946                              }
947                              case 4 -> {
948                                  builder.setLanguage( parts[0] ).setRegion( parts[1] );
949                                  if( parts[2].startsWith( "#" ) )
950                                  {
951                                      builder.setScript( parts[2].substring( 1 ) );
952                                  }
953                                  else
954                                  {
955                                      builder.setVariant( parts[2] );
956                                      if( parts[3].startsWith( "#" ) )
957                                      {
958                                          if( parts[3].length() == 4 )
959                                              builder.setScript( parts[3].substring( 1 ) );
960                                      }
961                                  }
962                                  yield builder.build();
963                              }
964                              case 5 -> builder.setLanguage( parts[0] ).setRegion( parts[1] ).setVariant( parts[2] ).setScript( parts[3].substring( 1 ) ).build();
965                              default -> null; // Invalid input ...
966                          };    //  ComposeSwitch:
967                      }
968                      catch( final IllformedLocaleException ignored )
969                      {
970                          result = null;
971                      }
972                      return result;
973                  } );
974
975        final var retValue = Optional.ofNullable( locale );
976
977        //---* Done *----------------------------------------------------------
978        return retValue;
979    }   //  retrieveLocale()
980
981    /**
982     *  An implementation of
983     *  {@link Thread#sleep}
984     *  that takes an instance of
985     *  {@link Duration}
986     *  to determine the time to sleep.
987     *
988     *  @note   While sleeping, the thread does not lose ownership of any
989     *      monitors.
990     *
991     *  @param  duration    The time to sleep.
992     *  @throws InterruptedException    Another thread has interrupted the
993     *      current thread (that one executing {@code sleep()}). The
994     *      <i>interrupted status</i> of the current thread is cleared when
995     *      this exception is thrown.
996     *
997     *  @deprecated Use
998     *      {@link Thread#sleep(Duration)}
999     *      instead.
1000     */
1001    @API( status = DEPRECATED, since = "0.0.7" )
1002    @Deprecated( since = "0.4.8", forRemoval = true )
1003    public static final void sleep( final Duration duration ) throws InterruptedException
1004    {
1005        final var milliseconds = requireNonNullArgument( duration, "duration" ).toMillis();
1006        Thread.sleep( milliseconds );
1007    }   //  sleep()
1008
1009    /**
1010     *  Causes the currently executing thread to sleep (temporarily cease
1011     *  execution) until the specified time, subject to the precision and
1012     *  accuracy of system timers and schedulers. The thread does not lose
1013     *  ownership of any monitors.
1014     *
1015     *  @note   While sleeping, the thread does not lose ownership of any
1016     *      monitors.
1017     *
1018     *  @param  until   The end time for the sleep.
1019     *  @throws InterruptedException    Another thread has interrupted the
1020     *      current thread (that one executing {@code sleep()}). The
1021     *      <i>interrupted status</i> of the current thread is cleared when
1022     *      this exception is thrown.
1023     *
1024     *  @see Thread#sleep(long)
1025     *
1026     *  @since 0.0.7
1027     */
1028    @API( status = STABLE, since = "0.0.7" )
1029    public static final void sleepUntil( final Instant until ) throws InterruptedException
1030    {
1031        final var milliseconds = max( 0, requireNonNullArgument( until, "until" ).toEpochMilli() - currentTimeMillis() );
1032        Thread.sleep( milliseconds );
1033    }   //  sleepUntil()
1034
1035    /**
1036     *  <p>{@summary Returns the
1037     *  {@linkplain System#getProperties() system properties}}
1038     *  as a
1039     *  {@link Map Map&lt;String,String&gt;}.</p>
1040     *  <p>{@link System#getProperties()}
1041     *  returns an instance of
1042     *  {@link java.util.Properties}, and that is implementing
1043     *  {@code Map<String,Object>}. Although it is unlikely that a value is
1044     *  <i>not</i> a String (if not impossible …), this method allows
1045     *  to enforce it.</p>
1046     *
1047     *  @note   A mere cast to {@code Map<String,String>} does not work
1048     *      &hellip;
1049     *
1050     *  @return An unmodifiable map with the system properties as Strings.
1051     */
1052    public static final Map<String,String> systemPropertiesAsStringMap()
1053    {
1054        final Map<String,String> map = new HashMap<>();
1055        final var properties = getProperties();
1056        for( final var key : properties.stringPropertyNames() )
1057        {
1058            map.put( key, properties.getProperty( key ) );
1059        }
1060        final var retValue = Map.copyOf( map );
1061
1062        //---* Done *----------------------------------------------------------
1063        return retValue;
1064    }   //  systemPropertiesAsStringMap()
1065
1066    /**
1067     *  <p>{@summary Translates a given MAC address into a numerical node
1068     *  id.}</p>
1069     *  <p>A MAC address is a string consisting of 12 hex digits, grouped by
1070     *  two, each group separated by a hyphen:
1071     *  <code><i>xx</i>-<i>xx</i>-<i>xx</i>-<i>xx</i>-<i>xx</i>-<i>xx</i></code></p>
1072     *
1073     *  @param  macAddress  The MAC address to translate.
1074     *  @return The node id.
1075     */
1076    @API( status = STABLE, since = "0.0.5" )
1077    public static final long translateMACToNodeId( final String macAddress )
1078    {
1079        final var bytes = HexFormat.ofDelimiter( "-" ).withUpperCase().parseHex( requireNotEmptyArgument( macAddress, "macAddress" ) );
1080        if( bytes.length != 6 )
1081        {
1082            throw new IllegalArgumentException( "MAC address is invalid: %1$s".formatted( macAddress ) );
1083        }
1084        final var bytes2 = new byte [7];
1085        arraycopy( bytes, 0, bytes2, 1, 6 );
1086        final var retValue = new BigInteger( bytes2 ).longValue();
1087
1088        //---* Done *----------------------------------------------------------
1089        return retValue;
1090    }   //  translateMACToNodeId()
1091}
1092//  class SystemUtils
1093
1094/*
1095 *  End of File
1096 */