]> git.basschouten.com Git - openhab-addons.git/blob
cab26f1c2548ceed0e1fe403c8090cbb5f199ccc
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.homematic.internal.handler;
14
15 import java.util.ArrayList;
16 import java.util.List;
17
18 /**
19  * A very simple pool implementation that handles free port numbers used by the RPC server if multiple bridges are
20  * configured.
21  *
22  * @author Gerhard Riegler - Initial contribution
23  */
24 public class SimplePortPool {
25     private static int START_PORT = 9125;
26
27     private List<PortInfo> availablePorts = new ArrayList<>();
28
29     /**
30      * Adds the specified port to the pool and mark it as in use.
31      */
32     public void setInUse(int port) {
33         PortInfo portInfo = new PortInfo();
34         portInfo.port = port;
35         portInfo.free = false;
36         availablePorts.add(portInfo);
37     }
38
39     /**
40      * Returns the next free port number.
41      */
42     public synchronized int getNextPort() {
43         for (PortInfo portInfo : availablePorts) {
44             if (portInfo.free) {
45                 portInfo.free = false;
46                 return portInfo.port;
47             }
48         }
49
50         PortInfo portInfo = new PortInfo();
51         while (isPortInUse(START_PORT++)) {
52         }
53         portInfo.port = START_PORT - 1;
54         portInfo.free = false;
55         availablePorts.add(portInfo);
56
57         return portInfo.port;
58     }
59
60     /**
61      * Returns true, if the specified port is not in use.
62      */
63     private boolean isPortInUse(int port) {
64         for (PortInfo portInfo : availablePorts) {
65             if (portInfo.port == port) {
66                 return !portInfo.free;
67             }
68         }
69         return false;
70     }
71
72     /**
73      * Releases a unused port number.
74      */
75     public synchronized void release(int port) {
76         for (PortInfo portInfo : availablePorts) {
77             if (portInfo.port == port) {
78                 portInfo.free = true;
79             }
80         }
81     }
82
83     private class PortInfo {
84         int port;
85         boolean free;
86     }
87 }