|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | + * or more contributor license agreements. See the NOTICE file |
| 4 | + * distributed with this work for additional information |
| 5 | + * regarding copyright ownership. The ASF licenses this file |
| 6 | + * to you under the Apache License, Version 2.0 (the |
| 7 | + * "License"); you may not use this file except in compliance |
| 8 | + * with the License. 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, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | + |
| 20 | +package org.opengrok.web.api.v1.controller; |
| 21 | + |
| 22 | +import java.io.IOException; |
| 23 | +import java.net.DatagramSocket; |
| 24 | +import java.net.ServerSocket; |
| 25 | + |
| 26 | +/** |
| 27 | + * Represents a helper for checking a network port, borrowed from Apache |
| 28 | + * Usergrid's AvailablePortFinder.java. |
| 29 | + */ |
| 30 | +public class PortChecker { |
| 31 | + /** The minimum number of server port number. */ |
| 32 | + public static final int MIN_PORT_NUMBER = 1; |
| 33 | + |
| 34 | + /** The maximum number of server port number. */ |
| 35 | + public static final int MAX_PORT_NUMBER = 65535; |
| 36 | + |
| 37 | + /** |
| 38 | + * Checks to see if a specific port is available. |
| 39 | + * |
| 40 | + * @param port the port to check for availability |
| 41 | + */ |
| 42 | + public static boolean available(int port) { |
| 43 | + if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) { |
| 44 | + throw new IllegalArgumentException("Port out of valid range: " + port); |
| 45 | + } |
| 46 | + |
| 47 | + ServerSocket ss = null; |
| 48 | + DatagramSocket ds = null; |
| 49 | + try { |
| 50 | + ss = new ServerSocket(port); |
| 51 | + ss.setReuseAddress(true); |
| 52 | + ds = new DatagramSocket(port); |
| 53 | + ds.setReuseAddress(true); |
| 54 | + return true; |
| 55 | + } catch (IOException e) { |
| 56 | + return false; |
| 57 | + } finally { |
| 58 | + if (ds != null) { |
| 59 | + ds.close(); |
| 60 | + } |
| 61 | + |
| 62 | + if (ss != null) { |
| 63 | + try { |
| 64 | + ss.close(); |
| 65 | + } catch (IOException e) { |
| 66 | + /* should not be thrown */ |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + /* private to enforce static */ |
| 73 | + private PortChecker() { |
| 74 | + } |
| 75 | +} |
0 commit comments