Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.IOException;
- import java.io.UncheckedIOException;
- import java.net.InetAddress;
- import java.net.Socket;
- import java.net.SocketAddress;
- import java.net.UnknownHostException;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.Properties;
- import javax.net.SocketFactory;
- import org.newsclub.net.unix.AFUNIXSocket;
- import org.newsclub.net.unix.AFUNIXSocketAddress;
- import org.postgresql.PGProperty;
- import org.postgresql.core.SocketAddressFactory;
- import org.postgresql.util.HostSpec;
- public class SocketTest {
- public static void main(String[] args) throws SQLException {
- Properties props = new Properties();
- props.setProperty(PGProperty.SOCKET_FACTORY.getName(), LocalPostgresSocketFactory.class.getName());
- props.setProperty(PGProperty.SOCKET_ADDRESS_FACTORY.getName(),
- LocalPostgresSocketAddressFactory.class.getName());
- props.setProperty(PGProperty.PG_DBNAME.getName(), "testdb");
- props.setProperty(PGProperty.USER.getName(), "isopov");
- props.setProperty(PGProperty.PASSWORD.getName(), "isopov");
- try (Connection con = DriverManager.getConnection("jdbc:postgresql:testdb", props);
- Statement statement = con.createStatement();
- ResultSet res = statement.executeQuery("select 1")) {
- while (res.next()) {
- System.out.println(res.getString(1));
- }
- }
- }
- public static class LocalPostgresSocketAddressFactory implements SocketAddressFactory {
- @Override
- public SocketAddress create(HostSpec hostSpec) {
- try {
- return new AFUNIXSocketAddress(new File("/var/run/postgresql/.s.PGSQL.5432"));
- } catch (IOException e) {
- throw new UncheckedIOException(e);
- }
- }
- }
- public static class LocalPostgresSocketFactory extends SocketFactory {
- @Override
- public Socket createSocket() throws IOException {
- return AFUNIXSocket.newInstance();
- }
- @Override
- public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
- throw new RuntimeException();
- }
- @Override
- public Socket createSocket(InetAddress host, int port) throws IOException {
- throw new RuntimeException();
- }
- @Override
- public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
- throws IOException, UnknownHostException {
- throw new RuntimeException();
- }
- @Override
- public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
- throws IOException {
- throw new RuntimeException();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement