Search in sources :

Example 1 with CommandPreProcessor

use of org.apache.jena.jdbc.preprocessing.CommandPreProcessor in project jena by apache.

the class AbstractJenaDriverTests method driver_config_precedence_04.

/**
     * Tests the precedence rules for connection URL parameters
     * 
     * @throws SQLException
     * @throws IOException
     */
@Test
public void driver_config_precedence_04() throws SQLException, IOException {
    File f = null;
    try {
        f = File.createTempFile("config", ".properties");
        FileWriter writer = new FileWriter(f);
        writer.write("test=external");
        writer.close();
        String url = this.getConnectionUrl();
        Assume.assumeNotNull(url);
        Assume.assumeFalse(url.contains(JenaDriver.PARAM_CONFIG + "="));
        url = url + "&" + JenaDriver.PARAM_PRE_PROCESSOR + "=" + Echo.class.getCanonicalName() + "&test=url&" + JenaDriver.PARAM_CONFIG + "=" + f.getAbsolutePath();
        JenaDriver driver = this.getDriver();
        Properties ps = new Properties();
        JenaConnection conn = (JenaConnection) driver.connect(url, ps);
        Iterator<CommandPreProcessor> preProcessors = conn.getPreProcessors();
        Assert.assertTrue(preProcessors.hasNext());
        Echo echo = (Echo) preProcessors.next();
        Properties actual = echo.getProperties();
        Assert.assertEquals("url", actual.getProperty("test"));
        conn.close();
    } finally {
        if (f != null && f.exists()) {
            f.delete();
        }
    }
}
Also used : ResultsEcho(org.apache.jena.jdbc.postprocessing.ResultsEcho) Echo(org.apache.jena.jdbc.preprocessing.Echo) CommandPreProcessor(org.apache.jena.jdbc.preprocessing.CommandPreProcessor) FileWriter(java.io.FileWriter) Properties(java.util.Properties) JenaConnection(org.apache.jena.jdbc.connections.JenaConnection) File(java.io.File) Test(org.junit.Test)

Example 2 with CommandPreProcessor

use of org.apache.jena.jdbc.preprocessing.CommandPreProcessor in project jena by apache.

the class AbstractJenaDriverTests method driver_config_precedence_02.

/**
     * Tests the precedence rules for connection URL parameters
     * 
     * @throws SQLException
     */
@Test
public void driver_config_precedence_02() throws SQLException {
    String url = this.getConnectionUrl();
    Assume.assumeNotNull(url);
    url = url + "&" + JenaDriver.PARAM_PRE_PROCESSOR + "=" + Echo.class.getCanonicalName() + "&test=url";
    JenaDriver driver = this.getDriver();
    Properties ps = new Properties();
    JenaConnection conn = (JenaConnection) driver.connect(url, ps);
    Iterator<CommandPreProcessor> preProcessors = conn.getPreProcessors();
    Assert.assertTrue(preProcessors.hasNext());
    Echo echo = (Echo) preProcessors.next();
    Properties actual = echo.getProperties();
    Assert.assertEquals("url", actual.getProperty("test"));
    conn.close();
}
Also used : ResultsEcho(org.apache.jena.jdbc.postprocessing.ResultsEcho) Echo(org.apache.jena.jdbc.preprocessing.Echo) CommandPreProcessor(org.apache.jena.jdbc.preprocessing.CommandPreProcessor) Properties(java.util.Properties) JenaConnection(org.apache.jena.jdbc.connections.JenaConnection) Test(org.junit.Test)

Example 3 with CommandPreProcessor

use of org.apache.jena.jdbc.preprocessing.CommandPreProcessor in project jena by apache.

the class AbstractJenaDriverTests method driver_connect_07.

/**
     * Tests using a driver to create a connection with its own URLs plus the
     * standard pre-processor parameter
     * 
     * @throws SQLException
     */
@Test
public void driver_connect_07() throws SQLException {
    String url = this.getConnectionUrl();
    Assume.assumeNotNull(url);
    // We can register it twice if we want
    url = url + "&" + JenaDriver.PARAM_PRE_PROCESSOR + "=" + Echo.class.getCanonicalName();
    url = url + "&" + JenaDriver.PARAM_PRE_PROCESSOR + "=" + Echo.class.getCanonicalName();
    JenaDriver driver = this.getDriver();
    JenaConnection conn = (JenaConnection) driver.connect(url, null);
    Assert.assertFalse(conn.isClosed());
    Iterator<CommandPreProcessor> iter = conn.getPreProcessors();
    Assert.assertTrue(iter.hasNext());
    iter.next();
    Assert.assertTrue(iter.hasNext());
    iter.next();
    Assert.assertFalse(iter.hasNext());
    conn.close();
    Assert.assertTrue(conn.isClosed());
}
Also used : CommandPreProcessor(org.apache.jena.jdbc.preprocessing.CommandPreProcessor) JenaConnection(org.apache.jena.jdbc.connections.JenaConnection) Test(org.junit.Test)

Example 4 with CommandPreProcessor

use of org.apache.jena.jdbc.preprocessing.CommandPreProcessor in project jena by apache.

the class AbstractJenaDriverTests method driver_config_precedence_01.

/**
     * Tests the precedence rules for connection URL parameters
     * 
     * @throws SQLException
     */
@Test
public void driver_config_precedence_01() throws SQLException {
    String url = this.getConnectionUrl();
    Assume.assumeNotNull(url);
    url = url + "&" + JenaDriver.PARAM_PRE_PROCESSOR + "=" + Echo.class.getCanonicalName() + "&test=url";
    JenaDriver driver = this.getDriver();
    Properties ps = new Properties();
    ps.put("test", "props");
    JenaConnection conn = (JenaConnection) driver.connect(url, ps);
    Iterator<CommandPreProcessor> preProcessors = conn.getPreProcessors();
    Assert.assertTrue(preProcessors.hasNext());
    Echo echo = (Echo) preProcessors.next();
    Properties actual = echo.getProperties();
    Assert.assertEquals("props", actual.getProperty("test"));
    conn.close();
}
Also used : ResultsEcho(org.apache.jena.jdbc.postprocessing.ResultsEcho) Echo(org.apache.jena.jdbc.preprocessing.Echo) CommandPreProcessor(org.apache.jena.jdbc.preprocessing.CommandPreProcessor) Properties(java.util.Properties) JenaConnection(org.apache.jena.jdbc.connections.JenaConnection) Test(org.junit.Test)

Example 5 with CommandPreProcessor

use of org.apache.jena.jdbc.preprocessing.CommandPreProcessor in project jena by apache.

the class JenaDriver method connect.

@SuppressWarnings("unchecked")
@Override
public final Connection connect(String url, Properties props) throws SQLException {
    // Make sure to return null if the URL is not supported
    if (!this.acceptsURL(url))
        return null;
    // Compute the effective properties
    Properties ps = this.getEffectiveProperties(url, props);
    this.modifyProperties(ps);
    // Configure logging appropriately
    String logConfig = ps.getProperty(PARAM_LOGGING);
    if (logConfig == null || logConfig.trim().length() == 0) {
        logConfig = NO_AUTO_LOGGING_CONFIGURATION;
    }
    // configure)
    if (!logConfig.equals(NO_AUTO_LOGGING_CONFIGURATION)) {
        // Search file system first
        File logConfigFile = new File(logConfig);
        if (logConfigFile.exists() && logConfigFile.isFile()) {
            PropertyConfigurator.configure(logConfig);
            LOGGER.info("Successfully configured logging using log file " + logConfigFile.getAbsolutePath());
        } else {
            // Otherwise try class path
            URL logURL = this.getClass().getResource(logConfig);
            if (logURL != null) {
                PropertyConfigurator.configure(logURL);
                LOGGER.info("Successfully configured logging using class path resource " + logConfig);
            } else {
                throw new SQLException("Unable to locate the specified log4j configuration file on either the file system or the class path");
            }
        }
    }
    // Figure out desired JDBC compatibility level
    int compatibilityLevel = JdbcCompatibility.parseLevel(ps.get(PARAM_JDBC_COMPATIBILITY));
    // Try to create the connection
    JenaConnection conn = null;
    boolean abort = false;
    try {
        // Attempt connection
        conn = this.connect(ps, compatibilityLevel);
        // Prepare reduced properties for initializing any pre and
        // post-processors with
        Properties initProps = new Properties(ps);
        initProps.remove(PARAM_PASSWORD);
        // Attempt registration of command pre-processors
        Object ppObj = ps.get(PARAM_PRE_PROCESSOR);
        List<String> preProcessors;
        if (ppObj != null) {
            if (ppObj instanceof String) {
                // Single instance to try and register
                preProcessors = new ArrayList<String>();
                preProcessors.add(ppObj.toString());
            } else if (ppObj instanceof List<?>) {
                // Multiple instances to try and register
                preProcessors = (List<String>) ppObj;
            } else {
                // Parameter set to some unexpected type
                LOGGER.error("Driver Parameter " + PARAM_PRE_PROCESSOR + " has unexpected invalid value");
                throw new SQLException("Parameter " + PARAM_PRE_PROCESSOR + " was set to a value of unexpected type " + ppObj.getClass().getCanonicalName() + ", expected either a String or List<String> as the parameter value");
            }
            // Try and create each pre-processor
            for (String ppClassName : preProcessors) {
                // Ignore null values
                if (ppClassName == null)
                    continue;
                try {
                    LOGGER.info("Attempting to initialize pre-processor " + ppClassName);
                    Class<?> c = Class.forName(ppClassName);
                    Object i = c.newInstance();
                    if (i instanceof CommandPreProcessor) {
                        // If it implements the right interface initialize
                        // and
                        // register it
                        CommandPreProcessor pp = (CommandPreProcessor) i;
                        pp.initialize(initProps);
                        conn.addPreProcessor(pp);
                        LOGGER.info("Initialized pre-processor " + ppClassName + " successfully");
                    } else {
                        // Otherwise throw an error
                        LOGGER.error("Invalid value for " + PARAM_PRE_PROCESSOR + " parameter, references a class that exists but does not implement the required interface");
                        throw new SQLException("Parameter " + PARAM_PRE_PROCESSOR + " includes the value " + ppClassName + " which references a class that does not implement the expected CommandPreProcessor interface, please ensure that the class name is corect and that the class implements the required interface");
                    }
                } catch (ClassNotFoundException e) {
                    // Unable to find the referenced class
                    LOGGER.error("Invalid value for " + PARAM_PRE_PROCESSOR + " parameter, references a class that did not exist", e);
                    throw new SQLException("Parameter " + PARAM_PRE_PROCESSOR + " includes the value " + ppClassName + " which references a class that could not be found, please ensure that the class name is correct and the JAR containing this class is on your class path", e);
                } catch (InstantiationException e) {
                    // Unable to instantiate the referenced class
                    LOGGER.error("Invalid value for " + PARAM_PRE_PROCESSOR + " parameter, references a class that exists but does not have an appropriate constructor", e);
                    throw new SQLException("Parameter " + PARAM_PRE_PROCESSOR + " includes the value " + ppClassName + " which references a class that could not be sucessfully instantiated, this class must have an unparameterized constructor to be usable with this parameter.  If this is not possible try calling addPreProcessor() on the returned JenaConnection instead", e);
                } catch (IllegalAccessException e) {
                    // Referenced class is not accessible
                    LOGGER.error("Invalid value for " + PARAM_PRE_PROCESSOR + " parameter, references a class that exists but is inaccessible", e);
                    throw new SQLException("Parameter " + PARAM_PRE_PROCESSOR + " includes the value " + ppClassName + " which references a class that could not be sucessfully instantiated, this class must have a publicly accessible unparameterized constructor to be usable with this parameter.  If this is not possible try calling addPreProcessor() on the returned JenaConnection instead", e);
                } catch (SQLException e) {
                    // Throw as-is
                    throw e;
                } catch (Exception e) {
                    // Unexpected error
                    LOGGER.error("Invalid value for " + PARAM_PRE_PROCESSOR + " parameter, references a class that attempting to initialize produced an unexpected exception", e);
                    throw new SQLException("Parameter " + PARAM_PRE_PROCESSOR + " includes the value " + ppClassName + " which caused an unexpected exception when trying to instantiate it, see the inner exception for details", e);
                }
            }
        }
        // Attempt registration of results post-processors
        ppObj = ps.get(PARAM_POST_PROCESSOR);
        List<String> postProcessors;
        if (ppObj != null) {
            if (ppObj instanceof String) {
                // Single instance to try and register
                postProcessors = new ArrayList<String>();
                postProcessors.add(ppObj.toString());
            } else if (ppObj instanceof List<?>) {
                // Multiple instances to try and register
                postProcessors = (List<String>) ppObj;
            } else {
                // Parameter set to some unexpected type
                LOGGER.error("Driver Parameter " + PARAM_POST_PROCESSOR + " has unexpected invalid value");
                throw new SQLException("Parameter " + PARAM_POST_PROCESSOR + " was set to a value of unexpected type " + ppObj.getClass().getCanonicalName() + ", expected either a String or List<String> as the parameter value");
            }
            // Try and create each pre-processor
            for (String ppClassName : postProcessors) {
                // Ignore null values
                if (ppClassName == null)
                    continue;
                try {
                    LOGGER.info("Attempting to initialize post-processor " + ppClassName);
                    Class<?> c = Class.forName(ppClassName);
                    Object i = c.newInstance();
                    if (i instanceof ResultsPostProcessor) {
                        // If it implements the right interface initialize
                        // and
                        // register it
                        ResultsPostProcessor pp = (ResultsPostProcessor) i;
                        pp.initialize(initProps);
                        conn.addPostProcessor(pp);
                        LOGGER.info("Initialized post-processor " + ppClassName + " successfully");
                    } else {
                        // Otherwise throw an error
                        LOGGER.error("Invalid value for " + PARAM_POST_PROCESSOR + " parameter, references a class that exists but does not implement the required interface");
                        throw new SQLException("Parameter " + PARAM_POST_PROCESSOR + " includes the value " + ppClassName + " which references a class that does not implement the expected ResultsPostProcessor interface, please ensure that the class name is corect and that the class implements the required interface");
                    }
                } catch (ClassNotFoundException e) {
                    // Unable to find the referenced class
                    LOGGER.error("Invalid value for " + PARAM_POST_PROCESSOR + " parameter, references a class that did not exist", e);
                    throw new SQLException("Parameter " + PARAM_POST_PROCESSOR + " includes the value " + ppClassName + " which references a class that could not be found, please ensure that the class name is correct and the JAR containing this class is on your class path", e);
                } catch (InstantiationException e) {
                    // Unable to instantiate the referenced class
                    LOGGER.error("Invalid value for " + PARAM_POST_PROCESSOR + " parameter, references a class that exists but does not have an appropriate constructor", e);
                    throw new SQLException("Parameter " + PARAM_POST_PROCESSOR + " includes the value " + ppClassName + " which references a class that could not be sucessfully instantiated, this class must have an unparameterized constructor to be usable with this parameter.  If this is not possible try calling addPostProcessor() on the returned JenaConnection instead", e);
                } catch (IllegalAccessException e) {
                    // Referenced class is not accessible
                    LOGGER.error("Invalid value for " + PARAM_POST_PROCESSOR + " parameter, references a class that exists but is inaccessible", e);
                    throw new SQLException("Parameter " + PARAM_POST_PROCESSOR + " includes the value " + ppClassName + " which references a class that could not be sucessfully instantiated, this class must have a publicly accessible unparameterized constructor to be usable with this parameter.  If this is not possible try calling addPostProcessor() on the returned JenaConnection instead", e);
                } catch (SQLException e) {
                    // Throw as-is
                    throw e;
                } catch (Exception e) {
                    // Unexpected error
                    LOGGER.error("Invalid value for " + PARAM_POST_PROCESSOR + " parameter, references a class that attempting to initialize produced an unexpected exception", e);
                    throw new SQLException("Parameter " + PARAM_POST_PROCESSOR + " includes the value " + ppClassName + " which caused an unexpected exception when trying to instantiate it, see the inner exception for details", e);
                }
            }
        }
        // connection
        return conn;
    } catch (SQLException e) {
        abort = true;
        throw e;
    } catch (Exception e) {
        abort = true;
        LOGGER.error("Unexpected exception while establishing a connection", e);
        throw new SQLException("Unexpected exception while establishing a connection, see inner exception for details", e);
    } finally {
        // If something has gone badly wrong close the connection
        if (abort && conn != null) {
            conn.close();
        }
    }
}
Also used : ResultsPostProcessor(org.apache.jena.jdbc.postprocessing.ResultsPostProcessor) SQLException(java.sql.SQLException) Properties(java.util.Properties) JenaConnection(org.apache.jena.jdbc.connections.JenaConnection) URL(java.net.URL) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) SQLException(java.sql.SQLException) CommandPreProcessor(org.apache.jena.jdbc.preprocessing.CommandPreProcessor) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File)

Aggregations

JenaConnection (org.apache.jena.jdbc.connections.JenaConnection)11 CommandPreProcessor (org.apache.jena.jdbc.preprocessing.CommandPreProcessor)11 Test (org.junit.Test)10 Properties (java.util.Properties)7 ResultsEcho (org.apache.jena.jdbc.postprocessing.ResultsEcho)7 Echo (org.apache.jena.jdbc.preprocessing.Echo)7 File (java.io.File)6 FileWriter (java.io.FileWriter)5 ResultsPostProcessor (org.apache.jena.jdbc.postprocessing.ResultsPostProcessor)2 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 URL (java.net.URL)1 SQLException (java.sql.SQLException)1 SQLFeatureNotSupportedException (java.sql.SQLFeatureNotSupportedException)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1