You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@metamodel.apache.org by ka...@apache.org on 2014/01/05 20:57:09 UTC

[2/4] git commit: Added initial draft of DataContextFactoryBean with support for JDBC, CSV and Excel

Added initial draft of DataContextFactoryBean with support for JDBC, CSV
and Excel

Project: http://git-wip-us.apache.org/repos/asf/incubator-metamodel/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-metamodel/commit/f387893c
Tree: http://git-wip-us.apache.org/repos/asf/incubator-metamodel/tree/f387893c
Diff: http://git-wip-us.apache.org/repos/asf/incubator-metamodel/diff/f387893c

Branch: refs/heads/spring-module
Commit: f387893c5e1e0333371f0760650b74a76117b589
Parents: f8a4e8f
Author: Kasper Sørensen <i....@gmail.com>
Authored: Sun Jan 5 19:35:32 2014 +0100
Committer: Kasper Sørensen <i....@gmail.com>
Committed: Sun Jan 5 19:35:32 2014 +0100

----------------------------------------------------------------------
 pom.xml                                         |  19 ++
 spring/.gitignore                               |   4 +
 spring/pom.xml                                  |   6 +
 .../spring/DataContextFactoryBean.java          | 207 +++++++++++++++++++
 .../apache/metamodel/spring/SpringResource.java | 115 +++++++++++
 5 files changed, 351 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-metamodel/blob/f387893c/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 40b871c..f7c846a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -319,6 +319,25 @@ under the License.
 										<ignore />
 									</action>
 								</pluginExecution>
+								<pluginExecution>
+									<pluginExecutionFilter>
+										<groupId>
+											org.apache.rat
+										</groupId>
+										<artifactId>
+											apache-rat-plugin
+										</artifactId>
+										<versionRange>
+											[0.8,)
+										</versionRange>
+										<goals>
+											<goal>check</goal>
+										</goals>
+									</pluginExecutionFilter>
+									<action>
+										<ignore></ignore>
+									</action>
+								</pluginExecution>
 							</pluginExecutions>
 						</lifecycleMappingMetadata>
 					</configuration>

http://git-wip-us.apache.org/repos/asf/incubator-metamodel/blob/f387893c/spring/.gitignore
----------------------------------------------------------------------
diff --git a/spring/.gitignore b/spring/.gitignore
new file mode 100644
index 0000000..954270f
--- /dev/null
+++ b/spring/.gitignore
@@ -0,0 +1,4 @@
+/.settings
+/target
+/.classpath
+/.project
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-metamodel/blob/f387893c/spring/pom.xml
----------------------------------------------------------------------
diff --git a/spring/pom.xml b/spring/pom.xml
index 6c8c355..bb1e6ec 100644
--- a/spring/pom.xml
+++ b/spring/pom.xml
@@ -39,6 +39,12 @@ under the License.
 			<version>${project.version}</version>
 			<optional>true</optional>
 		</dependency>
+		<dependency>
+		    <groupId>org.springframework</groupId>
+		    <artifactId>spring-context</artifactId>
+		    <version>3.0.7.RELEASE</version>
+		    <scope>provided</scope>
+		</dependency>
 
 		<!-- test -->
 		<dependency>

http://git-wip-us.apache.org/repos/asf/incubator-metamodel/blob/f387893c/spring/src/main/java/org/apache/metamodel/spring/DataContextFactoryBean.java
----------------------------------------------------------------------
diff --git a/spring/src/main/java/org/apache/metamodel/spring/DataContextFactoryBean.java b/spring/src/main/java/org/apache/metamodel/spring/DataContextFactoryBean.java
new file mode 100644
index 0000000..c231126
--- /dev/null
+++ b/spring/src/main/java/org/apache/metamodel/spring/DataContextFactoryBean.java
@@ -0,0 +1,207 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.metamodel.spring;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+
+import javax.sql.DataSource;
+
+import org.apache.metamodel.DataContext;
+import org.apache.metamodel.csv.CsvConfiguration;
+import org.apache.metamodel.csv.CsvDataContext;
+import org.apache.metamodel.excel.ExcelConfiguration;
+import org.apache.metamodel.excel.ExcelDataContext;
+import org.apache.metamodel.jdbc.JdbcDataContext;
+import org.apache.metamodel.schema.TableType;
+import org.apache.metamodel.util.BooleanComparator;
+import org.apache.metamodel.util.FileHelper;
+import org.apache.metamodel.util.FileResource;
+import org.apache.metamodel.util.Resource;
+import org.apache.metamodel.util.UrlResource;
+import org.slf4j.LoggerFactory;
+import org.slf4j.Logger;
+import org.springframework.beans.factory.FactoryBean;
+
+/**
+ * A spring {@link FactoryBean} that produces MetaModel {@link DataContext}
+ * objects based on property values that will typically be injected by the
+ * Spring configuration.
+ */
+public class DataContextFactoryBean implements FactoryBean<DataContext> {
+
+    private static final Logger logger = LoggerFactory.getLogger(DataContextFactoryBean.class);
+
+    private String _type;
+    private org.springframework.core.io.Resource _resource;
+    private String _filename;
+    private String _url;
+    private String _columnNameLineNumber;
+    private String _skipEmptyLines;
+    private String _skipEmptyColumns;
+    private String _encoding;
+    private String _separatorChar;
+    private String _quoteChar;
+    private String _escapeChar;
+    private String _failOnInconsistentRowLength;
+    private String _multilineValues;
+    private TableType[] _tableTypes;
+    private String _catalogName;
+    private DataSource _dataSource;
+    private String _username;
+    private String _password;
+    private String _driverClassName;
+
+    @Override
+    public DataContext getObject() throws Exception {
+        String type = _type == null ? "" : _type.toLowerCase();
+        if ("csv".equals(type)) {
+            return createCsvDataContext();
+        } else if ("excel".equals(type)) {
+            return createExcelDataContext();
+        } else if ("jdbc".equals(type)) {
+            return createJdbcDataContext();
+        }
+
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+    private DataContext createJdbcDataContext() {
+        TableType[] tableTypes = _tableTypes;
+        if (tableTypes == null) {
+            tableTypes = TableType.DEFAULT_TABLE_TYPES;
+        }
+
+        if (_dataSource == null) {
+            final String driverClassName = getString(_driverClassName, null);
+            if (driverClassName != null) {
+                try {
+                    Class.forName(driverClassName);
+                } catch (ClassNotFoundException e) {
+                    logger.error("Failed to initialize JDBC driver class '" + driverClassName + "'!", e);
+                }
+            }
+
+            final Connection connection;
+            try {
+                if (_username == null && _password == null) {
+                    connection = DriverManager.getConnection(_url);
+                } else {
+                    connection = DriverManager.getConnection(_url, _username, _password);
+                }
+            } catch (Exception e) {
+                logger.error("Failed to get JDBC connection using URL: " + _url, e);
+                throw new IllegalStateException("Failed to get JDBC connection", e);
+            }
+
+            return new JdbcDataContext(connection, tableTypes, _catalogName);
+        }
+
+        return new JdbcDataContext(_dataSource, tableTypes, _catalogName);
+    }
+
+    private DataContext createExcelDataContext() {
+        final int columnNameLineNumber = getInt(_columnNameLineNumber, ExcelConfiguration.DEFAULT_COLUMN_NAME_LINE);
+        final boolean skipEmptyLines = getBoolean(_skipEmptyLines, true);
+        final boolean skipEmptyColumns = getBoolean(_skipEmptyColumns, false);
+        final ExcelConfiguration configuration = new ExcelConfiguration(columnNameLineNumber, skipEmptyLines,
+                skipEmptyColumns);
+        return new ExcelDataContext(getResourceInternal(), configuration);
+    }
+
+    private DataContext createCsvDataContext() {
+        final int columnNameLineNumber = getInt(_columnNameLineNumber, CsvConfiguration.DEFAULT_COLUMN_NAME_LINE);
+        final String encoding = getString(_encoding, FileHelper.DEFAULT_ENCODING);
+        final char separatorChar = getChar(_separatorChar, CsvConfiguration.DEFAULT_SEPARATOR_CHAR);
+        final char quoteChar = getChar(_quoteChar, CsvConfiguration.DEFAULT_QUOTE_CHAR);
+        final char escapeChar = getChar(_escapeChar, CsvConfiguration.DEFAULT_ESCAPE_CHAR);
+        final boolean failOnInconsistentRowLength = getBoolean(_failOnInconsistentRowLength, false);
+        final boolean multilineValues = getBoolean(_multilineValues, true);
+        final CsvConfiguration configuration = new CsvConfiguration(columnNameLineNumber, encoding, separatorChar,
+                quoteChar, escapeChar, failOnInconsistentRowLength, multilineValues);
+        return new CsvDataContext(getResourceInternal(), configuration);
+    }
+
+    private Resource getResourceInternal() {
+        if (_resource != null) {
+            return new SpringResource(_resource);
+        } else if (_filename != null) {
+            return new FileResource(_filename);
+        } else if (_url != null) {
+            return new UrlResource(_url);
+        }
+        return null;
+    }
+
+    @Override
+    public Class<DataContext> getObjectType() {
+        return DataContext.class;
+    }
+
+    @Override
+    public boolean isSingleton() {
+        return false;
+    }
+
+    private int getInt(String value, int ifNull) {
+        if (value == null) {
+            return ifNull;
+        }
+        value = value.trim();
+        if (value.isEmpty()) {
+            return ifNull;
+        }
+        return Integer.parseInt(value);
+    }
+
+    private String getString(String value, String ifNull) {
+        if (value == null) {
+            return ifNull;
+        }
+        value = value.trim();
+        if (value.isEmpty()) {
+            return ifNull;
+        }
+        return value;
+    }
+
+    private char getChar(String value, char ifNull) {
+        if (value == null) {
+            return ifNull;
+        }
+        value = value.trim();
+        if (value.isEmpty()) {
+            return ifNull;
+        }
+        // TODO: Check special strings like &quot;
+        return value.charAt(0);
+    }
+
+    private boolean getBoolean(String value, boolean ifNull) {
+        if (value == null) {
+            return ifNull;
+        }
+        value = value.trim();
+        if (value.isEmpty()) {
+            return ifNull;
+        }
+        return BooleanComparator.parseBoolean(value);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-metamodel/blob/f387893c/spring/src/main/java/org/apache/metamodel/spring/SpringResource.java
----------------------------------------------------------------------
diff --git a/spring/src/main/java/org/apache/metamodel/spring/SpringResource.java b/spring/src/main/java/org/apache/metamodel/spring/SpringResource.java
new file mode 100644
index 0000000..2b0f532
--- /dev/null
+++ b/spring/src/main/java/org/apache/metamodel/spring/SpringResource.java
@@ -0,0 +1,115 @@
+package org.apache.metamodel.spring;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.apache.metamodel.util.Action;
+import org.apache.metamodel.util.FileHelper;
+import org.apache.metamodel.util.Func;
+import org.apache.metamodel.util.Resource;
+import org.apache.metamodel.util.ResourceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A {@link Resource} implementation based on spring's similar
+ * {@link org.springframework.core.io.Resource} concept.
+ */
+public class SpringResource implements Resource {
+
+    private static final Logger logger = LoggerFactory.getLogger(SpringResource.class);
+
+    private final org.springframework.core.io.Resource _resource;
+
+    public SpringResource(org.springframework.core.io.Resource resource) {
+        _resource = resource;
+    }
+
+    @Override
+    public void append(Action<OutputStream> arg0) throws ResourceException {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public long getLastModified() {
+        try {
+            return _resource.lastModified();
+        } catch (IOException e) {
+            logger.warn("Failed to get last modified date of resource: " + _resource, e);
+            return -1;
+        }
+    }
+
+    @Override
+    public String getName() {
+        return _resource.getFilename();
+    }
+
+    @Override
+    public String getQualifiedPath() {
+        try {
+            return _resource.getURI().toString();
+        } catch (IOException e) {
+            throw new IllegalStateException("Failed to get URI of resource: " + _resource, e);
+        }
+    }
+
+    @Override
+    public long getSize() {
+        try {
+            return _resource.contentLength();
+        } catch (IOException e) {
+            throw new IllegalStateException("Failed to get content length of resource: " + _resource, e);
+        }
+    }
+
+    @Override
+    public boolean isExists() {
+        return _resource.exists();
+    }
+
+    @Override
+    public boolean isReadOnly() {
+        return true;
+    }
+
+    @Override
+    public InputStream read() throws ResourceException {
+        try {
+            return _resource.getInputStream();
+        } catch (IOException e) {
+            throw new IllegalStateException("Failed to get input stream of resource: " + _resource, e);
+        }
+    }
+
+    @Override
+    public void read(Action<InputStream> action) throws ResourceException {
+        final InputStream in = read();
+        try {
+            action.run(in);
+        } catch (Exception e) {
+            throw new ResourceException(this, "Error occurred in read callback", e);
+        } finally {
+            FileHelper.safeClose(in);
+        }
+    }
+
+    @Override
+    public <E> E read(Func<InputStream, E> func) throws ResourceException {
+        final InputStream in = read();
+        try {
+            return func.eval(in);
+        } catch (Exception e) {
+            throw new ResourceException(this, "Error occurred in read callback", e);
+        } finally {
+            FileHelper.safeClose(in);
+        }
+    }
+
+    @Override
+    public void write(Action<OutputStream> arg0) throws ResourceException {
+        throw new UnsupportedOperationException();
+    }
+
+}