View Javadoc
1   package ca.uhn.fhir.util;
2   
3   /*
4    * #%L
5    * HAPI FHIR - Core Library
6    * %%
7    * Copyright (C) 2014 - 2018 University Health Network
8    * %%
9    * Licensed under the Apache License, Version 2.0 (the "License");
10   * you may not use this file except in compliance with the License.
11   * You may obtain a copy of the License at
12   * 
13   *      http://www.apache.org/licenses/LICENSE-2.0
14   * 
15   * Unless required by applicable law or agreed to in writing, software
16   * distributed under the License is distributed on an "AS IS" BASIS,
17   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18   * See the License for the specific language governing permissions and
19   * limitations under the License.
20   * #L%
21   */
22  
23  import java.net.ServerSocket;
24  import java.util.LinkedHashSet;
25  
26  /**
27   * Provides server ports
28   */
29  @CoverageIgnore
30  public class PortUtil {
31  	private static LinkedHashSet<Integer> ourPorts = new LinkedHashSet<>();
32  
33  	/*
34  	 * Non instantiable
35  	 */
36  	private PortUtil() {
37  		// nothing
38  	} 
39  	
40  	/**
41  	 * This is really only used for unit tests but is included in the library so it can be reused across modules. Use with caution.
42  	 */
43  	public static int findFreePort() {
44  		ServerSocket server;
45  		try {
46  			int port;
47  			do {
48  				server = new ServerSocket(0);
49  				server.setReuseAddress(true);
50  				port = server.getLocalPort();
51  				server.close();
52  			} while (!ourPorts.add(port));
53  
54  			Thread.sleep(500);
55  			return port;
56  		} catch (Exception e) {
57  			//FIXME resource leak
58  			throw new Error(e);
59  		}
60  	}
61  
62  }
63