OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 177 | Rev 182 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 177 Rev 180
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.io.UnsupportedEncodingException;
21
import java.net.InetAddress;
21
import java.net.InetAddress;
22
import java.net.NetworkInterface;
22
import java.net.NetworkInterface;
23
import java.net.ServerSocket;
23
import java.net.ServerSocket;
24
import java.net.SocketException;
24
import java.net.SocketException;
25
import java.net.URL;
25
import java.net.URL;
26
import java.net.URLEncoder;
26
import java.net.URLEncoder;
27
import java.nio.charset.StandardCharsets;
27
import java.nio.charset.StandardCharsets;
28
import java.security.KeyManagementException;
28
import java.security.KeyManagementException;
29
import java.security.NoSuchAlgorithmException;
29
import java.security.NoSuchAlgorithmException;
30
import java.security.cert.X509Certificate;
30
import java.security.cert.X509Certificate;
31
import java.util.Enumeration;
31
import java.util.Enumeration;
32
import java.util.LinkedHashMap;
32
import java.util.LinkedHashMap;
33
import java.util.Map;
33
import java.util.Map;
34
import java.util.Map.Entry;
34
import java.util.Map.Entry;
35
 
35
 
36
import javax.net.ssl.HostnameVerifier;
36
import javax.net.ssl.HostnameVerifier;
37
import javax.net.ssl.HttpsURLConnection;
37
import javax.net.ssl.HttpsURLConnection;
38
import javax.net.ssl.SSLContext;
38
import javax.net.ssl.SSLContext;
39
import javax.net.ssl.SSLSession;
39
import javax.net.ssl.SSLSession;
40
import javax.net.ssl.TrustManager;
40
import javax.net.ssl.TrustManager;
41
import javax.net.ssl.X509TrustManager;
41
import javax.net.ssl.X509TrustManager;
42
 
42
 
43
public class NetUtils {
43
public class NetUtils {
44
 
44
 
45
    public static int findFreePort(final int preferred) {
45
    public static int findFreePort(final int preferred) {
46
        return findFreePort(null, preferred);
46
        return findFreePort(null, preferred);
47
    }
47
    }
48
 
48
 
49
    /**
49
    /**
50
     * Returns a free port number on localhost.
50
     * Returns a free port number on localhost.
51
     * 
51
     * 
52
     * @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.
53
     * @param preferred if this port is free, then it's returned.
53
     * @param preferred if this port is free, then it's returned.
54
     * @return preferred if free otherwise any free port.
54
     * @return preferred if free otherwise any free port.
55
     */
55
     */
56
    public static int findFreePort(final String addr, final int preferred) {
56
    public static int findFreePort(final String addr, final int preferred) {
57
        if (isPortFree(addr, preferred))
57
        if (isPortFree(addr, preferred))
58
            return preferred;
58
            return preferred;
59
        else
59
        else
60
            return findFreePort(addr);
60
            return findFreePort(addr);
61
    }
61
    }
62
 
62
 
63
    /**
63
    /**
64
     * Returns a free port number on localhost.
64
     * Returns a free port number on localhost.
65
     * 
65
     * 
66
     * @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
67
     */
67
     */
68
    public static int findFreePort() {
68
    public static int findFreePort() {
69
        return findFreePort(null);
69
        return findFreePort(null);
70
    }
70
    }
71
 
71
 
72
    public static int findFreePort(final String addr) {
72
    public static int findFreePort(final String addr) {
73
        return checkPort(addr, 0);
73
        return checkPort(addr, 0);
74
    }
74
    }
75
 
75
 
76
    public static boolean isPortFree(final String addr, final int port) {
76
    public static boolean isPortFree(final String addr, final int port) {
77
        if (port <= 0)
77
        if (port <= 0)
78
            throw new IllegalArgumentException(port + " is negative");
78
            throw new IllegalArgumentException(port + " is negative");
79
        return checkPort(addr, port) == port;
79
        return checkPort(addr, port) == port;
80
    }
80
    }
81
 
81
 
82
    // with code from from org/eclipse/jdt/launching/SocketUtil.java
82
    // with code from from org/eclipse/jdt/launching/SocketUtil.java
83
    private static int checkPort(final String addr, final int port) {
83
    private static int checkPort(final String addr, final int port) {
84
        ServerSocket socket = null;
84
        ServerSocket socket = null;
85
        try {
85
        try {
86
            // 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
87
            // 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
88
            // 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.
89
            socket = new ServerSocket(port, 0, InetAddress.getByName(addr));
89
            socket = new ServerSocket(port, 0, InetAddress.getByName(addr));
90
            return socket.getLocalPort();
90
            return socket.getLocalPort();
91
        } catch (IOException e) {
91
        } catch (IOException e) {
92
        } finally {
92
        } finally {
93
            if (socket != null) {
93
            if (socket != null) {
94
                try {
94
                try {
95
                    socket.close();
95
                    socket.close();
96
                } catch (IOException e) {
96
                } catch (IOException e) {
97
                }
97
                }
98
            }
98
            }
99
        }
99
        }
100
        return -1;
100
        return -1;
101
    }
101
    }
102
 
102
 
103
    /**
103
    /**
104
     * Whether the passed address refers to this computer.
104
     * Whether the passed address refers to this computer.
105
     * 
105
     * 
106
     * @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".
107
     * @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.
108
     */
108
     */
109
    static public final boolean isSelfAddr(String addr) {
109
    static public final boolean isSelfAddr(String addr) {
110
        if (addr == null)
110
        if (addr == null)
111
            return false;
111
            return false;
112
        if (addr.startsWith("127.") || addr.startsWith("localhost"))
112
        if (addr.startsWith("127.") || addr.startsWith("localhost"))
113
            return true;
113
            return true;
114
 
114
 
115
        try {
115
        try {
116
            final Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
116
            final Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
117
            while (en.hasMoreElements()) {
117
            while (en.hasMoreElements()) {
118
                final NetworkInterface ni = en.nextElement();
118
                final NetworkInterface ni = en.nextElement();
119
                final Enumeration<InetAddress> addresses = ni.getInetAddresses();
119
                final Enumeration<InetAddress> addresses = ni.getInetAddresses();
120
                while (addresses.hasMoreElements()) {
120
                while (addresses.hasMoreElements()) {
121
                    final InetAddress inetAddress = addresses.nextElement();
121
                    final InetAddress inetAddress = addresses.nextElement();
122
                    if (addr.startsWith(inetAddress.getHostAddress()))
122
                    if (addr.startsWith(inetAddress.getHostAddress()))
123
                        return true;
123
                        return true;
124
                }
124
                }
125
            }
125
            }
126
            return false;
126
            return false;
127
        } catch (SocketException e) {
127
        } catch (SocketException e) {
128
            e.printStackTrace();
128
            e.printStackTrace();
129
            return false;
129
            return false;
130
        }
130
        }
131
    }
131
    }
132
 
132
 
133
    public static final HostnameVerifier HostnameNonVerifier = new HostnameVerifier() {
133
    public static final HostnameVerifier HostnameNonVerifier = new HostnameVerifier() {
134
        @Override
134
        @Override
135
        public boolean verify(String hostname, SSLSession session) {
135
        public boolean verify(String hostname, SSLSession session) {
136
            return true;
136
            return true;
137
        }
137
        }
138
    };
138
    };
139
 
139
 
140
    public static final String getHTTPContent(String address) {
140
    public static final String getHTTPContent(String address) {
141
        return getHTTPContent(address, false);
141
        return getHTTPContent(address, false);
142
    }
142
    }
143
 
143
 
144
    public static final String getHTTPContent(String address, final boolean dontVerify) {
144
    public static final String getHTTPContent(String address, final boolean dontVerify) {
145
        String content = "";
145
        String content = "";
146
        OutputStream out = null;
146
        OutputStream out = null;
147
        HttpsURLConnection conn = null;
147
        HttpsURLConnection conn = null;
148
        InputStream in = null;
148
        InputStream in = null;
149
        try {
149
        try {
150
            URL url = new URL(address);
150
            URL url = new URL(address);
151
            out = new ByteArrayOutputStream();
151
            out = new ByteArrayOutputStream();
152
            conn = (HttpsURLConnection) url.openConnection();
152
            conn = (HttpsURLConnection) url.openConnection();
153
            // Sur la connexion
153
            // Sur la connexion
154
            if (dontVerify) {
154
            if (dontVerify) {
155
                conn.setHostnameVerifier(HostnameNonVerifier);
155
                conn.setHostnameVerifier(HostnameNonVerifier);
156
                // ou globalement
156
                // ou globalement
157
                // HttpsURLConnection.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
157
                // HttpsURLConnection.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
158
            }
158
            }
159
 
159
 
160
            in = conn.getInputStream();
160
            in = conn.getInputStream();
161
            final byte[] buffer = new byte[1024];
161
            final byte[] buffer = new byte[1024];
162
            int numRead;
162
            int numRead;
163
 
163
 
164
            while ((numRead = in.read(buffer)) != -1) {
164
            while ((numRead = in.read(buffer)) != -1) {
165
                out.write(buffer, 0, numRead);
165
                out.write(buffer, 0, numRead);
166
 
166
 
167
            }
167
            }
168
            content = out.toString();
168
            content = out.toString();
169
 
169
 
170
        } catch (Exception exception) {
170
        } catch (Exception exception) {
171
            exception.printStackTrace();
171
            exception.printStackTrace();
172
        } finally {
172
        } finally {
173
            try {
173
            try {
174
                if (in != null) {
174
                if (in != null) {
175
                    in.close();
175
                    in.close();
176
                }
176
                }
177
                if (out != null) {
177
                if (out != null) {
178
                    out.close();
178
                    out.close();
179
                }
179
                }
180
            } catch (IOException ioe) {
180
            } catch (IOException ioe) {
181
            }
181
            }
182
        }
182
        }
183
 
183
 
184
        return content;
184
        return content;
185
    }
185
    }
186
 
186
 
-
 
187
    /**
-
 
188
     * Encode for POST message application/x-www-form-urlencoded
-
 
189
     */
187
    static public final String urlEncode(final String... kv) {
190
    static public final String urlEncode(final String... kv) {
188
        final int size = kv.length;
191
        final int size = kv.length;
189
        if (size % 2 != 0)
192
        if (size % 2 != 0)
190
            throw new IllegalArgumentException("Odd number of items : " + size);
193
            throw new IllegalArgumentException("Odd number of items : " + size);
191
        final LinkedHashMap<String, Object> map = new LinkedHashMap<>(size / 2, 1);
194
        final LinkedHashMap<String, Object> map = new LinkedHashMap<>(size / 2, 1);
192
        for (int i = 0; i < size; i += 2) {
195
        for (int i = 0; i < size; i += 2) {
193
            map.put(kv[i], kv[i + 1]);
196
            map.put(kv[i], kv[i + 1]);
194
        }
197
        }
195
        return urlEncode(map);
198
        return urlEncode(map);
196
    }
199
    }
197
 
200
 
-
 
201
    /**
-
 
202
     * Encode for POST message application/x-www-form-urlencoded
-
 
203
     */
198
    static public final String urlEncode(final Map<String, ?> map) {
204
    static public final String urlEncode(final Map<String, ?> map) {
199
        if (map.isEmpty())
205
        if (map.isEmpty())
200
            return "";
206
            return "";
201
        final String charset = StandardCharsets.UTF_8.name();
207
        final String charset = StandardCharsets.UTF_8.name();
202
        final StringBuilder sb = new StringBuilder(256);
208
        final StringBuilder sb = new StringBuilder(256);
203
        for (final Entry<String, ?> e : map.entrySet()) {
209
        for (final Entry<String, ?> e : map.entrySet()) {
204
            final Object value = e.getValue();
210
            final Object value = e.getValue();
205
            // Avoid null and "null" confusion.
211
            // Avoid null and "null" confusion.
206
            if (value != null) {
212
            if (value != null) {
207
                try {
213
                try {
208
                    sb.append(URLEncoder.encode(e.getKey(), charset));
214
                    sb.append(URLEncoder.encode(e.getKey(), charset).replace("+", "%20"));
209
                    sb.append('=');
215
                    sb.append('=');
210
                    sb.append(URLEncoder.encode(String.valueOf(value), charset));
216
                    sb.append(URLEncoder.encode(String.valueOf(value), charset).replace("+", "%20"));
211
                    sb.append('&');
217
                    sb.append('&');
212
                } catch (UnsupportedEncodingException exn) {
218
                } catch (UnsupportedEncodingException exn) {
213
                    throw new IllegalStateException("UTF-8 should be standard", exn);
219
                    throw new IllegalStateException("UTF-8 should be standard", exn);
214
                }
220
                }
215
            }
221
            }
216
        }
222
        }
217
        // remove last '&'
223
        // remove last '&'
218
        sb.setLength(sb.length() - 1);
224
        sb.setLength(sb.length() - 1);
219
        return sb.toString();
225
        return sb.toString();
220
    }
226
    }
221
 
227
 
222
    // Create a trust manager that does not validate certificate chains
228
    // Create a trust manager that does not validate certificate chains
223
    static private final TrustManager[] TRUSTALL_MANAGERS = new TrustManager[] { new X509TrustManager() {
229
    static private final TrustManager[] TRUSTALL_MANAGERS = new TrustManager[] { new X509TrustManager() {
224
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
230
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
225
            return null;
231
            return null;
226
        }
232
        }
227
 
233
 
228
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
234
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
229
        }
235
        }
230
 
236
 
231
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
237
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
232
        }
238
        }
233
    } };
239
    } };
234
 
240
 
235
    static public final SSLContext createTrustAllContext() throws KeyManagementException, NoSuchAlgorithmException {
241
    static public final SSLContext createTrustAllContext() throws KeyManagementException, NoSuchAlgorithmException {
236
        final SSLContext sc = SSLContext.getInstance("TLS");
242
        final SSLContext sc = SSLContext.getInstance("TLS");
237
        sc.init(null, TRUSTALL_MANAGERS, new java.security.SecureRandom());
243
        sc.init(null, TRUSTALL_MANAGERS, new java.security.SecureRandom());
238
        return sc;
244
        return sc;
239
    }
245
    }
240
}
246
}