001package ca.uhn.fhir.util;
002
003/*
004 * #%L
005 * HAPI FHIR - Core Library
006 * %%
007 * Copyright (C) 2014 - 2018 University Health Network
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 * 
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 * 
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023import java.net.ServerSocket;
024import java.util.LinkedHashSet;
025
026/**
027 * Provides server ports
028 */
029@CoverageIgnore
030public class PortUtil {
031        private static LinkedHashSet<Integer> ourPorts = new LinkedHashSet<>();
032
033        /*
034         * Non instantiable
035         */
036        private PortUtil() {
037                // nothing
038        } 
039        
040        /**
041         * This is really only used for unit tests but is included in the library so it can be reused across modules. Use with caution.
042         */
043        public static int findFreePort() {
044                ServerSocket server;
045                try {
046                        int port;
047                        do {
048                                server = new ServerSocket(0);
049                                server.setReuseAddress(true);
050                                port = server.getLocalPort();
051                                server.close();
052                        } while (!ourPorts.add(port));
053
054                        Thread.sleep(500);
055                        return port;
056                } catch (Exception e) {
057                        //FIXME resource leak
058                        throw new Error(e);
059                }
060        }
061
062}
063