Java Code Examples for java.sql.Driver#acceptsURL()

The following examples show how to use java.sql.Driver#acceptsURL() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TracingDriver.java    From java-jdbc with Apache License 2.0 6 votes vote down vote up
protected Driver findDriver(String realUrl) throws SQLException {
  if (realUrl == null || realUrl.trim().length() == 0) {
    throw new IllegalArgumentException("url is required");
  }

  for (Driver candidate : Collections.list(DriverManager.getDrivers())) {
    try {
      if (!(candidate instanceof TracingDriver) && candidate.acceptsURL(realUrl)) {
        return candidate;
      }
    } catch (SQLException ignored) {
      // intentionally ignore exception
    }
  }

  throw new SQLException("Unable to find a driver that accepts url: " + realUrl);
}
 
Example 2
Source File: SQLDriverManager.java    From jsqsh with Apache License 2.0 6 votes vote down vote up
/**
 * Similar to DriverManager.getDriver() except that it searches
 * through our shiny new classloader.
 * 
 * @param url
 * @return
 * @throws SQLException
 */
private Driver getDriverFromUrl(String url)
    throws SQLException {
    
    for (SQLDriver driver : drivers.values()) {
        
        try {
            
            Driver d = (Driver) Class.forName(driver.getDriverClass(), 
                true, classLoader).newInstance();
            
            if (d.acceptsURL(url)) {
                
                return d;
            }
        }
        catch (Exception e) {
            
            /* IGNORED */
        }
    }
    
    return DriverManager.getDriver(url);
}
 
Example 3
Source File: HiveDriver.java    From pentaho-hadoop-shims with Apache License 2.0 6 votes vote down vote up
private final boolean acceptsURL( String url, Driver driver, NamedCluster namedCluster ) throws SQLException {

    if ( !defaultConfiguration ) {
      return false;
    }

    if ( driver == null ) {
      return false;
    }
    try {
      return isRequiredShim( namedCluster, url ) && driver.acceptsURL( url );
    } catch ( Throwable e ) {
      // This should not have happened. If there was an error during processing, assume this driver can't
      // handle the URL and thus return false
      return false;
    }
  }
 
Example 4
Source File: ConnectionFactory.java    From query2report with GNU General Public License v3.0 5 votes vote down vote up
public static boolean testConnection(ConnectionParams params) throws Exception {
	boolean status = false;
	String url = params.getUrl();
	DriverParams driverParams = DriverManager.getDriverManager().getDriver(params.getDriver());
	String driverClass = driverParams.getClassName();
	String username = params.getUsername();
	String password = params.getPassword();
	String decPassword = EncryptionUtil.decrypt(password);
	logger.info("Trying to get connection to DB " + url + " for user " + username + " and driver class [" + driverClass + "]");
	try{
		Driver driver = (Driver) Class.forName(driverClass).newInstance();
		Properties props = new Properties();
		props.put("user", username);
		props.put("password", decPassword);
		if(driver.acceptsURL(url)){
			Connection connection = driver.connect(url, props);
			connection.setAutoCommit(false);
			logger.info("Got new connection to DB " + url + " for user " + username);
			status=true;
			params.setIsConnectionSuccess(Boolean.toString(status));
			connection.close();
		}else{
			logger.error("Driver "+params.getDriver()+" is not suitable for URL "+url);
			throw new RuntimeException("Driver "+params.getDriver()+" is not suitable for URL "+url);
		}
	}catch (Throwable e){
		logger.error("Error getting connection to "+url+" for user "+username,e);
		throw e;
	}
	return status;
}
 
Example 5
Source File: JdbcTest.java    From java-jdbc with Apache License 2.0 5 votes vote down vote up
private static Driver getUnderlyingDriver(final String url) throws SQLException {
  final Enumeration<Driver> enumeration = DriverManager.getDrivers();
  while (enumeration.hasMoreElements()) {
    final Driver driver = enumeration.nextElement();
    if (driver.acceptsURL(url) && !(driver instanceof TracingDriver)) {
      return driver;
    }
  }
  return null;
}
 
Example 6
Source File: DriverLocatorImpl.java    From pentaho-hadoop-shims with Apache License 2.0 5 votes vote down vote up
@Override public Driver getDriver( String url ) {
  Iterator<Map.Entry<ServiceReference<Driver>, Driver>> drivers = getDrivers();
  while ( drivers.hasNext() ) {
    Driver driver = drivers.next().getValue();
    try {
      if ( driver.acceptsURL( url ) ) {
        return driver;
      }
    } catch ( SQLException e ) {
      logger.error( String.format( "Unable to see if driver %s acceptsURL %s", driver, url ) );
    }
  }
  return null;
}
 
Example 7
Source File: JdbcDrivers.java    From dekaf with Apache License 2.0 5 votes vote down vote up
private static boolean isDriverAcceptingConnectionString(final @NotNull Driver driver,
                                                         final @NotNull String connectionString)
{
  try {
    return driver.acceptsURL(connectionString);
  }
  catch (SQLException e) {
    // TODO log in debug mode
    return false;
  }
}
 
Example 8
Source File: JdbcIntermediateRdbmsProvider.java    From dekaf with Apache License 2.0 5 votes vote down vote up
@NotNull
private Driver getSuitableDriver(@NotNull String connectionString,
                                 @NotNull List<Driver> drivers) throws SQLException {
  for (Driver driver : drivers) {
    if (driver.acceptsURL(connectionString)) return driver;
  }
  throw new SQLException("No suitable driver", "08001");
}
 
Example 9
Source File: DriverTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Check that drivers accept the correct urls and reject those for other supported drivers.
 *
 * @throws SQLException, Exception
 */
public void testAcceptsURL() throws SQLException, Exception {
    String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
    String orgurl = TestConfiguration.getCurrent().getJDBCUrl(dbName);

    loadDriver();
    String defaultdburl = orgurl + ";create=true";

    // Test that we loaded the right driver by making a connection
    Driver driver = DriverManager.getDriver(defaultdburl);

    int  frameworkOffset;
    int EMBEDDED_OFFSET = 0;
    int DERBYNETCLIENT_OFFSET = 1;
    if (usingDerbyNetClient())
        frameworkOffset = DERBYNETCLIENT_OFFSET;
    else // assume (usingEmbedded())
        frameworkOffset = EMBEDDED_OFFSET;

    // URLS to check.  New urls need to also be added to the acceptsUrl table
    //GemStone changes BEGIN
    //String EMBEDDED_URL = "jdbc:derby:";
    String EMBEDDED_URL = "jdbc:gemfirexd:";
    // GemStone changes END
    String INVALID_URL = "jdbc:db2j:";
    String hostName = TestConfiguration.getCurrent().getHostName();
    int port = TestConfiguration.getCurrent().getPort();
    String CLIENT_URL =
        "jdbc:derby://"+hostName+":"+port+"/"+dbName+";create=true";

    String[] urls = new String[]
    {
        EMBEDDED_URL,
        CLIENT_URL,
        INVALID_URL,
    };

    // Table that shows whether tested urls should return true for
    // acceptsURL under the given framework
    // The acceptsURLTable uses  the frameworkOffset column int he table
    // to check for valid results for each framework
    boolean[][] acceptsURLTable = new boolean[][]
    {
    // Framework/url      EMBEDDED     DERBYNETCLIENT
    /* EMBEDDED_URL*/  {   true      ,  false        },
    /* CLIENT_URL  */  {   false     ,  true         },
    /* INVALID_URL */  {   false     ,  false        }
    };

    for (int u = 0; u < urls.length;u++)
    {
        String url = urls[u];
        boolean expectedAcceptance = acceptsURLTable[u][frameworkOffset];
        boolean actualAcceptance = driver.acceptsURL(url);
        assertEquals(expectedAcceptance, actualAcceptance);
    }
}
 
Example 10
Source File: JdbcDataAdapterService.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Connection getConnection() throws SQLException{
		JdbcDataAdapter jdbcDataAdapter = getJdbcDataAdapter();
		if (jdbcDataAdapter != null) 
		{
			ClassLoader oldThreadClassLoader = Thread.currentThread().getContextClassLoader();

			try 
			{
				Thread.currentThread().setContextClassLoader(getClassLoader(oldThreadClassLoader));
				
				Class<?> clazz = JRClassLoader.loadClassForRealName(jdbcDataAdapter.getDriver());
				Driver driver = (Driver) clazz.getDeclaredConstructor().newInstance();
				
//				Driver driver = (Driver) (Class.forName(
//						jdbcDataAdapter.getDriver(), true, getClassLoader()))
//						.getDeclaredConstructor().newInstance();

				
				Properties	connectProps = new Properties();
				Map<String, String> map = jdbcDataAdapter.getProperties();
				if(map != null)
					for(String key: map.keySet())
						connectProps.setProperty(key, map.get(key));
				

				String password = jdbcDataAdapter.getPassword();
				SecretsUtil secretService = SecretsUtil.getInstance(getJasperReportsContext());
				if (secretService != null)
					password = secretService.getSecret(SECRETS_CATEGORY, password);

				connectProps.setProperty("user", jdbcDataAdapter.getUsername());
				connectProps.setProperty("password", password);
				
				connection = driver.connect(jdbcDataAdapter.getUrl(), connectProps);
				if(connection == null)
				{
					boolean urlValid = driver.acceptsURL(jdbcDataAdapter.getUrl());
					if (!urlValid)
					{
						throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_INVALID_URL, 
								new Object[] {jdbcDataAdapter.getUrl(), jdbcDataAdapter.getDriver()});
					}
					
					throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_CONNECTION_NOT_CREATED, 
							new Object[] {jdbcDataAdapter.getUrl()});
				}
				
				setupConnection(jdbcDataAdapter);
			}
			catch (ClassNotFoundException | InstantiationException | IllegalAccessException 
				| NoSuchMethodException | InvocationTargetException e) {
				throw new JRRuntimeException(e);
			} finally {
				Thread.currentThread().setContextClassLoader(oldThreadClassLoader);
			}
			return connection;
		}
		return null;
	}
 
Example 11
Source File: DriverTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Check that drivers accept the correct urls and reject those for other supported drivers.
 *
 * @throws SQLException, Exception
 */
public void testAcceptsURL() throws SQLException, Exception {
    String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
    String orgurl = TestConfiguration.getCurrent().getJDBCUrl(dbName);

    loadDriver();
    String defaultdburl = orgurl + ";create=true";

    // Test that we loaded the right driver by making a connection
    Driver driver = DriverManager.getDriver(defaultdburl);

    int  frameworkOffset;
    int EMBEDDED_OFFSET = 0;
    int DERBYNETCLIENT_OFFSET = 1;
    if (usingDerbyNetClient())
        frameworkOffset = DERBYNETCLIENT_OFFSET;
    else // assume (usingEmbedded())
        frameworkOffset = EMBEDDED_OFFSET;

    // URLS to check.  New urls need to also be added to the acceptsUrl table
    //GemStone changes BEGIN
    //String EMBEDDED_URL = "jdbc:derby:";
    String EMBEDDED_URL = "jdbc:gemfirexd:";
    // GemStone changes END
    String INVALID_URL = "jdbc:db2j:";
    String hostName = TestConfiguration.getCurrent().getHostName();
    int port = TestConfiguration.getCurrent().getPort();
    String CLIENT_URL =
        "jdbc:derby://"+hostName+":"+port+"/"+dbName+";create=true";

    String[] urls = new String[]
    {
        EMBEDDED_URL,
        CLIENT_URL,
        INVALID_URL,
    };

    // Table that shows whether tested urls should return true for
    // acceptsURL under the given framework
    // The acceptsURLTable uses  the frameworkOffset column int he table
    // to check for valid results for each framework
    boolean[][] acceptsURLTable = new boolean[][]
    {
    // Framework/url      EMBEDDED     DERBYNETCLIENT
    /* EMBEDDED_URL*/  {   true      ,  false        },
    /* CLIENT_URL  */  {   false     ,  true         },
    /* INVALID_URL */  {   false     ,  false        }
    };

    for (int u = 0; u < urls.length;u++)
    {
        String url = urls[u];
        boolean expectedAcceptance = acceptsURLTable[u][frameworkOffset];
        boolean actualAcceptance = driver.acceptsURL(url);
        assertEquals(expectedAcceptance, actualAcceptance);
    }
}
 
Example 12
Source File: DriverTest.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Check that drivers accept the correct urls and reject those for other supported drivers.
 *
 * @throws SQLException, Exception
 */
public void testAcceptsURL() throws SQLException, Exception {
    String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
    String orgurl = TestConfiguration.getCurrent().getJDBCUrl(dbName);

    loadDriver();
    String defaultdburl = orgurl + ";create=true";

    // Test that we loaded the right driver by making a connection
    Driver driver = DriverManager.getDriver(defaultdburl);

    int  frameworkOffset;
    int EMBEDDED_OFFSET = 0;
    int DERBYNETCLIENT_OFFSET = 1;
    if (usingDerbyNetClient())
        frameworkOffset = DERBYNETCLIENT_OFFSET;
    else // assume (usingEmbedded())
        frameworkOffset = EMBEDDED_OFFSET;

    // URLS to check.  New urls need to also be added to the acceptsUrl table
    String EMBEDDED_URL = "jdbc:splice:";
    String INVALID_URL = "jdbc:db2j:";
    String hostName = TestConfiguration.getCurrent().getHostName();
    int port = TestConfiguration.getCurrent().getPort();
    String CLIENT_URL =
            "jdbc:splice://"+hostName+":"+port+"/"+dbName+";create=true";

    String[] urls = new String[]
            {
                    EMBEDDED_URL,
                    CLIENT_URL,
                    INVALID_URL,
            };

    // Table that shows whether tested urls should return true for 
    // acceptsURL under the given framework
    // The acceptsURLTable uses  the frameworkOffset column int he table 
    // to check for valid results for each framework
    boolean[][] acceptsURLTable = new boolean[][]
            {
                    // Framework/url      EMBEDDED     DERBYNETCLIENT
    /* EMBEDDED_URL*/  {   true      ,  false        },
    /* CLIENT_URL  */  {   false     ,  true         },     
    /* INVALID_URL */  {   false     ,  false        }
            };

    for (int u = 0; u < urls.length;u++)
    {
        String url = urls[u];
        boolean expectedAcceptance = acceptsURLTable[u][frameworkOffset];
        boolean actualAcceptance = driver.acceptsURL(url);
        assertEquals(expectedAcceptance, actualAcceptance);
    }
}