View Javadoc
1   /*
2    * junixsocket
3    *
4    * Copyright 2009-2026 Christian Kohlschütter
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * 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, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.newsclub.net.mysql;
19  
20  import java.io.File;
21  import java.io.IOException;
22  import java.net.Socket;
23  import java.net.SocketException;
24  import java.util.Properties;
25  
26  import org.newsclub.net.unix.AFUNIXSocket;
27  import org.newsclub.net.unix.AFUNIXSocketAddress;
28  
29  import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;
30  import com.mysql.jdbc.SocketFactory;
31  
32  /**
33   * Connect to mysql databases (and compatibles) using UNIX domain sockets.
34   *
35   * NOTE: This SocketFactory currently implements the "old" Connector/J SocketFactory. This may
36   * change in the future.
37   *
38   * For the time being, see AFUNIXDatabaseSocketFactoryCJ to forcibly use the new "CJ"-style
39   * SocketFactory.
40   *
41   * @see AFUNIXDatabaseSocketFactoryCJ
42   */
43  @SuppressWarnings("deprecation")
44  public class AFUNIXDatabaseSocketFactory implements SocketFactory {
45    private Socket socket = null;
46  
47    /**
48     * Creates a new instance.
49     */
50    public AFUNIXDatabaseSocketFactory() {
51    }
52  
53    @Override
54    @SuppressFBWarnings("EI_EXPOSE_REP")
55    public Socket afterHandshake() throws SocketException, IOException {
56      return socket;
57    }
58  
59    @Override
60    @SuppressFBWarnings("EI_EXPOSE_REP")
61    public Socket beforeHandshake() throws SocketException, IOException {
62      return socket;
63    }
64  
65    @Override
66    @SuppressFBWarnings({"EI_EXPOSE_REP", "PATH_TRAVERSAL_IN"})
67    public Socket connect(String host, int portNumber, Properties props) throws SocketException,
68        IOException {
69      // Adjust the path to your MySQL socket by setting the
70      // "junixsocket.file" property
71      // If no socket path is given, use the default: /tmp/mysql.sock
72      final File socketFile = new File(props.getProperty("junixsocket.file", "/tmp/mysql.sock"));
73  
74      socket = AFUNIXSocket.connectTo(AFUNIXSocketAddress.of(socketFile));
75      return socket;
76    }
77  }