OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 174 | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 174 Rev 177
1
/*
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 * 
3
 * 
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 * 
5
 * 
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
9
 * language governing permissions and limitations under the License.
10
 * 
10
 * 
11
 * When distributing the software, include this License Header Notice in each file.
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
12
 */
13
 
13
 
14
 package org.openconcerto.utils;
14
 package org.openconcerto.utils;
15
 
15
 
16
import java.io.ByteArrayOutputStream;
16
import java.io.ByteArrayOutputStream;
17
import java.io.IOException;
17
import java.io.IOException;
18
import java.io.InputStream;
18
import java.io.InputStream;
19
import java.io.OutputStream;
19
import java.io.OutputStream;
-
 
20
import java.io.UnsupportedEncodingException;
20
import java.net.InetAddress;
21
import java.net.InetAddress;
21
import java.net.NetworkInterface;
22
import java.net.NetworkInterface;
22
import java.net.ServerSocket;
23
import java.net.ServerSocket;
23
import java.net.SocketException;
24
import java.net.SocketException;
24
import java.net.URL;
25
import java.net.URL;
-
 
26
import java.net.URLEncoder;
-
 
27
import java.nio.charset.StandardCharsets;
25
import java.security.KeyManagementException;
28
import java.security.KeyManagementException;
26
import java.security.NoSuchAlgorithmException;
29
import java.security.NoSuchAlgorithmException;
27
import java.security.cert.X509Certificate;
30
import java.security.cert.X509Certificate;
28
import java.util.Enumeration;
31
import java.util.Enumeration;
-
 
32
import java.util.LinkedHashMap;
-
 
33
import java.util.Map;
-
 
34
import java.util.Map.Entry;
29
 
35
 
30
import javax.net.ssl.HostnameVerifier;
36
import javax.net.ssl.HostnameVerifier;
31
import javax.net.ssl.HttpsURLConnection;
37
import javax.net.ssl.HttpsURLConnection;
32
import javax.net.ssl.SSLContext;
38
import javax.net.ssl.SSLContext;
33
import javax.net.ssl.SSLSession;
39
import javax.net.ssl.SSLSession;
34
import javax.net.ssl.TrustManager;
40
import javax.net.ssl.TrustManager;
35
import javax.net.ssl.X509TrustManager;
41
import javax.net.ssl.X509TrustManager;
36
 
42
 
37
public class NetUtils {
43
public class NetUtils {
38
 
44
 
39
    public static int findFreePort(final int preferred) {
45
    public static int findFreePort(final int preferred) {
40
        return findFreePort(null, preferred);
46
        return findFreePort(null, preferred);
41
    }
47
    }
42
 
48
 
43
    /**
49
    /**
44
     * Returns a free port number on localhost.
50
     * Returns a free port number on localhost.
45
     * 
51
     * 
46
     * @param addr the bind address, <code>null</code> meaning an address of the loopback interface.
52
     * @param addr the bind address, <code>null</code> meaning an address of the loopback interface.
47
     * @param preferred if this port is free, then it's returned.
53
     * @param preferred if this port is free, then it's returned.
48
     * @return preferred if free otherwise any free port.
54
     * @return preferred if free otherwise any free port.
49
     */
55
     */
50
    public static int findFreePort(final String addr, final int preferred) {
56
    public static int findFreePort(final String addr, final int preferred) {
51
        if (isPortFree(addr, preferred))
57
        if (isPortFree(addr, preferred))
52
            return preferred;
58
            return preferred;
53
        else
59
        else
54
            return findFreePort(addr);
60
            return findFreePort(addr);
55
    }
61
    }
56
 
62
 
57
    /**
63
    /**
58
     * Returns a free port number on localhost.
64
     * Returns a free port number on localhost.
59
     * 
65
     * 
60
     * @return a free port number on localhost, or -1 if unable to find a free port
66
     * @return a free port number on localhost, or -1 if unable to find a free port
61
     */
67
     */
62
    public static int findFreePort() {
68
    public static int findFreePort() {
63
        return findFreePort(null);
69
        return findFreePort(null);
64
    }
70
    }
65
 
71
 
66
    public static int findFreePort(final String addr) {
72
    public static int findFreePort(final String addr) {
67
        return checkPort(addr, 0);
73
        return checkPort(addr, 0);
68
    }
74
    }
69
 
75
 
70
    public static boolean isPortFree(final String addr, final int port) {
76
    public static boolean isPortFree(final String addr, final int port) {
71
        if (port <= 0)
77
        if (port <= 0)
72
            throw new IllegalArgumentException(port + " is negative");
78
            throw new IllegalArgumentException(port + " is negative");
73
        return checkPort(addr, port) == port;
79
        return checkPort(addr, port) == port;
74
    }
80
    }
75
 
81
 
76
    // with code from from org/eclipse/jdt/launching/SocketUtil.java
82
    // with code from from org/eclipse/jdt/launching/SocketUtil.java
77
    private static int checkPort(final String addr, final int port) {
83
    private static int checkPort(final String addr, final int port) {
78
        ServerSocket socket = null;
84
        ServerSocket socket = null;
79
        try {
85
        try {
80
            // ATTN InetAddress.getByName(null) means an address of the loopback interface, while
86
            // ATTN InetAddress.getByName(null) means an address of the loopback interface, while
81
            // passing null means any/all local addresses. The problem is that the constructor will
87
            // passing null means any/all local addresses. The problem is that the constructor will
82
            // succeed for a given port even if it is already bound with the other address.
88
            // succeed for a given port even if it is already bound with the other address.
83
            socket = new ServerSocket(port, 0, InetAddress.getByName(addr));
89
            socket = new ServerSocket(port, 0, InetAddress.getByName(addr));
84
            return socket.getLocalPort();
90
            return socket.getLocalPort();
85
        } catch (IOException e) {
91
        } catch (IOException e) {
86
        } finally {
92
        } finally {
87
            if (socket != null) {
93
            if (socket != null) {
88
                try {
94
                try {
89
                    socket.close();
95
                    socket.close();
90
                } catch (IOException e) {
96
                } catch (IOException e) {
91
                }
97
                }
92
            }
98
            }
93
        }
99
        }
94
        return -1;
100
        return -1;
95
    }
101
    }
96
 
102
 
97
    /**
103
    /**
98
     * Whether the passed address refers to this computer.
104
     * Whether the passed address refers to this computer.
99
     * 
105
     * 
100
     * @param addr an ip or dns address, eg "192.168.28.52".
106
     * @param addr an ip or dns address, eg "192.168.28.52".
101
     * @return <code>true</code> if <code>addr</code> is bound to an interface of this computer.
107
     * @return <code>true</code> if <code>addr</code> is bound to an interface of this computer.
102
     */
108
     */
103
    static public final boolean isSelfAddr(String addr) {
109
    static public final boolean isSelfAddr(String addr) {
104
        if (addr == null)
110
        if (addr == null)
105
            return false;
111
            return false;
106
        if (addr.startsWith("127.") || addr.startsWith("localhost"))
112
        if (addr.startsWith("127.") || addr.startsWith("localhost"))
107
            return true;
113
            return true;
108
 
114
 
109
        try {
115
        try {
110
            final Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
116
            final Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
111
            while (en.hasMoreElements()) {
117
            while (en.hasMoreElements()) {
112
                final NetworkInterface ni = en.nextElement();
118
                final NetworkInterface ni = en.nextElement();
113
                final Enumeration<InetAddress> addresses = ni.getInetAddresses();
119
                final Enumeration<InetAddress> addresses = ni.getInetAddresses();
114
                while (addresses.hasMoreElements()) {
120
                while (addresses.hasMoreElements()) {
115
                    final InetAddress inetAddress = addresses.nextElement();
121
                    final InetAddress inetAddress = addresses.nextElement();
116
                    if (addr.startsWith(inetAddress.getHostAddress()))
122
                    if (addr.startsWith(inetAddress.getHostAddress()))
117
                        return true;
123
                        return true;
118
                }
124
                }
119
            }
125
            }
120
            return false;
126
            return false;
121
        } catch (SocketException e) {
127
        } catch (SocketException e) {
122
            e.printStackTrace();
128
            e.printStackTrace();
123
            return false;
129
            return false;
124
        }
130
        }
125
    }
131
    }
126
 
132
 
127
    public static final HostnameVerifier HostnameNonVerifier = new HostnameVerifier() {
133
    public static final HostnameVerifier HostnameNonVerifier = new HostnameVerifier() {
128
        @Override
134
        @Override
129
        public boolean verify(String hostname, SSLSession session) {
135
        public boolean verify(String hostname, SSLSession session) {
130
            return true;
136
            return true;
131
        }
137
        }
132
    };
138
    };
133
 
139
 
134
    public static final String getHTTPContent(String address) {
140
    public static final String getHTTPContent(String address) {
135
        return getHTTPContent(address, false);
141
        return getHTTPContent(address, false);
136
    }
142
    }
137
 
143
 
138
    public static final String getHTTPContent(String address, final boolean dontVerify) {
144
    public static final String getHTTPContent(String address, final boolean dontVerify) {
139
        String content = "";
145
        String content = "";
140
        OutputStream out = null;
146
        OutputStream out = null;
141
        HttpsURLConnection conn = null;
147
        HttpsURLConnection conn = null;
142
        InputStream in = null;
148
        InputStream in = null;
143
        try {
149
        try {
144
            URL url = new URL(address);
150
            URL url = new URL(address);
145
            out = new ByteArrayOutputStream();
151
            out = new ByteArrayOutputStream();
146
            conn = (HttpsURLConnection) url.openConnection();
152
            conn = (HttpsURLConnection) url.openConnection();
147
            // Sur la connexion
153
            // Sur la connexion
148
            if (dontVerify) {
154
            if (dontVerify) {
149
                conn.setHostnameVerifier(HostnameNonVerifier);
155
                conn.setHostnameVerifier(HostnameNonVerifier);
150
                // ou globalement
156
                // ou globalement
151
                // HttpsURLConnection.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
157
                // HttpsURLConnection.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
152
            }
158
            }
153
 
159
 
154
            in = conn.getInputStream();
160
            in = conn.getInputStream();
155
            final byte[] buffer = new byte[1024];
161
            final byte[] buffer = new byte[1024];
156
            int numRead;
162
            int numRead;
157
 
163
 
158
            while ((numRead = in.read(buffer)) != -1) {
164
            while ((numRead = in.read(buffer)) != -1) {
159
                out.write(buffer, 0, numRead);
165
                out.write(buffer, 0, numRead);
160
 
166
 
161
            }
167
            }
162
            content = out.toString();
168
            content = out.toString();
163
 
169
 
164
        } catch (Exception exception) {
170
        } catch (Exception exception) {
165
            exception.printStackTrace();
171
            exception.printStackTrace();
166
        } finally {
172
        } finally {
167
            try {
173
            try {
168
                if (in != null) {
174
                if (in != null) {
169
                    in.close();
175
                    in.close();
170
                }
176
                }
171
                if (out != null) {
177
                if (out != null) {
172
                    out.close();
178
                    out.close();
173
                }
179
                }
174
            } catch (IOException ioe) {
180
            } catch (IOException ioe) {
175
            }
181
            }
176
        }
182
        }
177
 
183
 
178
        return content;
184
        return content;
179
    }
185
    }
-
 
186
 
-
 
187
    static public final String urlEncode(final String... kv) {
-
 
188
        final int size = kv.length;
-
 
189
        if (size % 2 != 0)
-
 
190
            throw new IllegalArgumentException("Odd number of items : " + size);
-
 
191
        final LinkedHashMap<String, Object> map = new LinkedHashMap<>(size / 2, 1);
-
 
192
        for (int i = 0; i < size; i += 2) {
-
 
193
            map.put(kv[i], kv[i + 1]);
-
 
194
        }
-
 
195
        return urlEncode(map);
-
 
196
    }
-
 
197
 
-
 
198
    static public final String urlEncode(final Map<String, ?> map) {
-
 
199
        if (map.isEmpty())
-
 
200
            return "";
-
 
201
        final String charset = StandardCharsets.UTF_8.name();
-
 
202
        final StringBuilder sb = new StringBuilder(256);
-
 
203
        for (final Entry<String, ?> e : map.entrySet()) {
-
 
204
            final Object value = e.getValue();
-
 
205
            // Avoid null and "null" confusion.
-
 
206
            if (value != null) {
-
 
207
                try {
-
 
208
                    sb.append(URLEncoder.encode(e.getKey(), charset));
-
 
209
                    sb.append('=');
-
 
210
                    sb.append(URLEncoder.encode(String.valueOf(value), charset));
-
 
211
                    sb.append('&');
-
 
212
                } catch (UnsupportedEncodingException exn) {
-
 
213
                    throw new IllegalStateException("UTF-8 should be standard", exn);
-
 
214
                }
-
 
215
            }
-
 
216
        }
-
 
217
        // remove last '&'
-
 
218
        sb.setLength(sb.length() - 1);
-
 
219
        return sb.toString();
-
 
220
    }
180
 
221
 
181
    // Create a trust manager that does not validate certificate chains
222
    // Create a trust manager that does not validate certificate chains
182
    static private final TrustManager[] TRUSTALL_MANAGERS = new TrustManager[] { new X509TrustManager() {
223
    static private final TrustManager[] TRUSTALL_MANAGERS = new TrustManager[] { new X509TrustManager() {
183
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
224
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
184
            return null;
225
            return null;
185
        }
226
        }
186
 
227
 
187
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
228
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
188
        }
229
        }
189
 
230
 
190
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
231
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
191
        }
232
        }
192
    } };
233
    } };
193
 
234
 
194
    static public final SSLContext createTrustAllContext() throws KeyManagementException, NoSuchAlgorithmException {
235
    static public final SSLContext createTrustAllContext() throws KeyManagementException, NoSuchAlgorithmException {
195
        final SSLContext sc = SSLContext.getInstance("TLS");
236
        final SSLContext sc = SSLContext.getInstance("TLS");
196
        sc.init(null, TRUSTALL_MANAGERS, new java.security.SecureRandom());
237
        sc.init(null, TRUSTALL_MANAGERS, new java.security.SecureRandom());
197
        return sc;
238
        return sc;
198
    }
239
    }
199
}
240
}