OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 174 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
17 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
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
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.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.utils;
15
 
41 ilm 16
import java.io.ByteArrayOutputStream;
17
import java.io.IOException;
18
import java.io.InputStream;
19
import java.io.OutputStream;
177 ilm 20
import java.io.UnsupportedEncodingException;
17 ilm 21
import java.net.InetAddress;
22
import java.net.NetworkInterface;
67 ilm 23
import java.net.ServerSocket;
17 ilm 24
import java.net.SocketException;
41 ilm 25
import java.net.URL;
177 ilm 26
import java.net.URLEncoder;
27
import java.nio.charset.StandardCharsets;
174 ilm 28
import java.security.KeyManagementException;
29
import java.security.NoSuchAlgorithmException;
30
import java.security.cert.X509Certificate;
17 ilm 31
import java.util.Enumeration;
177 ilm 32
import java.util.LinkedHashMap;
33
import java.util.Map;
34
import java.util.Map.Entry;
17 ilm 35
 
41 ilm 36
import javax.net.ssl.HostnameVerifier;
37
import javax.net.ssl.HttpsURLConnection;
174 ilm 38
import javax.net.ssl.SSLContext;
41 ilm 39
import javax.net.ssl.SSLSession;
174 ilm 40
import javax.net.ssl.TrustManager;
41
import javax.net.ssl.X509TrustManager;
41 ilm 42
 
17 ilm 43
public class NetUtils {
44
 
67 ilm 45
    public static int findFreePort(final int preferred) {
46
        return findFreePort(null, preferred);
47
    }
48
 
17 ilm 49
    /**
67 ilm 50
     * Returns a free port number on localhost.
51
     *
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.
54
     * @return preferred if free otherwise any free port.
55
     */
56
    public static int findFreePort(final String addr, final int preferred) {
57
        if (isPortFree(addr, preferred))
58
            return preferred;
59
        else
60
            return findFreePort(addr);
61
    }
62
 
63
    /**
64
     * Returns a free port number on localhost.
65
     *
66
     * @return a free port number on localhost, or -1 if unable to find a free port
67
     */
68
    public static int findFreePort() {
69
        return findFreePort(null);
70
    }
71
 
72
    public static int findFreePort(final String addr) {
73
        return checkPort(addr, 0);
74
    }
75
 
76
    public static boolean isPortFree(final String addr, final int port) {
77
        if (port <= 0)
78
            throw new IllegalArgumentException(port + " is negative");
79
        return checkPort(addr, port) == port;
80
    }
81
 
82
    // with code from from org/eclipse/jdt/launching/SocketUtil.java
83
    private static int checkPort(final String addr, final int port) {
84
        ServerSocket socket = null;
85
        try {
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
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));
90
            return socket.getLocalPort();
91
        } catch (IOException e) {
92
        } finally {
93
            if (socket != null) {
94
                try {
95
                    socket.close();
96
                } catch (IOException e) {
97
                }
98
            }
99
        }
100
        return -1;
101
    }
102
 
103
    /**
17 ilm 104
     * Whether the passed address refers to this computer.
105
     *
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.
108
     */
109
    static public final boolean isSelfAddr(String addr) {
110
        if (addr == null)
111
            return false;
112
        if (addr.startsWith("127.") || addr.startsWith("localhost"))
113
            return true;
114
 
115
        try {
116
            final Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
117
            while (en.hasMoreElements()) {
118
                final NetworkInterface ni = en.nextElement();
119
                final Enumeration<InetAddress> addresses = ni.getInetAddresses();
120
                while (addresses.hasMoreElements()) {
121
                    final InetAddress inetAddress = addresses.nextElement();
122
                    if (addr.startsWith(inetAddress.getHostAddress()))
123
                        return true;
124
                }
125
            }
126
            return false;
127
        } catch (SocketException e) {
128
            e.printStackTrace();
129
            return false;
130
        }
131
    }
132
 
57 ilm 133
    public static final HostnameVerifier HostnameNonVerifier = new HostnameVerifier() {
134
        @Override
41 ilm 135
        public boolean verify(String hostname, SSLSession session) {
136
            return true;
137
        }
57 ilm 138
    };
41 ilm 139
 
174 ilm 140
    public static final String getHTTPContent(String address) {
141
        return getHTTPContent(address, false);
142
    }
143
 
57 ilm 144
    public static final String getHTTPContent(String address, final boolean dontVerify) {
41 ilm 145
        String content = "";
146
        OutputStream out = null;
147
        HttpsURLConnection conn = null;
148
        InputStream in = null;
149
        try {
150
            URL url = new URL(address);
151
            out = new ByteArrayOutputStream();
152
            conn = (HttpsURLConnection) url.openConnection();
153
            // Sur la connexion
57 ilm 154
            if (dontVerify) {
155
                conn.setHostnameVerifier(HostnameNonVerifier);
41 ilm 156
                // ou globalement
157
                // HttpsURLConnection.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
158
            }
159
 
160
            in = conn.getInputStream();
161
            final byte[] buffer = new byte[1024];
162
            int numRead;
163
 
164
            while ((numRead = in.read(buffer)) != -1) {
165
                out.write(buffer, 0, numRead);
166
 
167
            }
168
            content = out.toString();
169
 
170
        } catch (Exception exception) {
171
            exception.printStackTrace();
172
        } finally {
173
            try {
174
                if (in != null) {
175
                    in.close();
176
                }
177
                if (out != null) {
178
                    out.close();
179
                }
180
            } catch (IOException ioe) {
181
            }
182
        }
183
 
184
        return content;
185
    }
174 ilm 186
 
177 ilm 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
    }
221
 
174 ilm 222
    // Create a trust manager that does not validate certificate chains
223
    static private final TrustManager[] TRUSTALL_MANAGERS = new TrustManager[] { new X509TrustManager() {
224
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
225
            return null;
226
        }
227
 
228
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
229
        }
230
 
231
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
232
        }
233
    } };
234
 
235
    static public final SSLContext createTrustAllContext() throws KeyManagementException, NoSuchAlgorithmException {
236
        final SSLContext sc = SSLContext.getInstance("TLS");
237
        sc.init(null, TRUSTALL_MANAGERS, new java.security.SecureRandom());
238
        return sc;
239
    }
17 ilm 240
}