summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMegha Nidhi Dahal2012-03-06 16:14:04 (EST)
committer xgu2012-05-03 04:48:37 (EDT)
commit1f4c826aee600be6b8d70c8718779ee6477a0b30 (patch)
treec1ba9c1a6db21abd5c96569d9ecbf4d1e416e5f6
parent1f1b7312350f57509e93749b05b3d8d5e63ee3ad (diff)
downloadorg.eclipse.birt-1f4c826aee600be6b8d70c8718779ee6477a0b30.zip
org.eclipse.birt-1f4c826aee600be6b8d70c8718779ee6477a0b30.tar.gz
org.eclipse.birt-1f4c826aee600be6b8d70c8718779ee6477a0b30.tar.bz2
Excel ODA Source code contribution as found in BZ attachment 211884, plus bundled library jars
Bug: 361443 CQ: 6295, 6025, 6374, 6373, 6027, 6026
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/.classpath7
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/.project28
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/.settings/org.eclipse.jdt.core.prefs8
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/META-INF/MANIFEST.MF14
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/Readme.txt46
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/build.properties7
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/icons/datasetpage.icobin0 -> 318 bytes
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/icons/new_oda_dswiz.icobin0 -> 318 bytes
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/icons/profile.gifbin0 -> 152 bytes
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/plugin.properties19
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/plugin.xml70
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/Activator.java71
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/i18n/Messages.java44
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/i18n/messages.properties76
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/impl/CustomDataSetWizardPage.java394
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/util/IHelpConstants.java24
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/util/Utility.java36
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/wizards/ExcelDataSourcePageHelper.java353
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/wizards/ExcelDataSourcePropertyPage.java85
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/wizards/ExcelDataSourceWizardPage.java74
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/wizards/ExcelFileSelectionWizardPage.java1751
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/.classpath39
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/.project28
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/.settings/org.eclipse.jdt.core.prefs8
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/META-INF/MANIFEST.MF30
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/Readme.txt46
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/build.properties22
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/plugin.properties31
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/plugin.xml137
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/Activator.java41
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/ExcelODAConstants.java43
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/ResultSetMetaDataHelper.java147
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/Connection.java150
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/DataSetMetaData.java158
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/Driver.java92
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ExcelFileQuery.java989
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ParameterMetaData.java106
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ResultSet.java559
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ResultSetMetaData.java168
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/i18n/Messages.java44
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/i18n/messages.properties45
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/DataTypes.java107
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/ExcelFileReader.java261
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/ExcelFileSource.java533
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/RowCallBack.java17
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/XlsxFileReader.java214
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/XlsxRowCallBack.java47
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/querytextutil/ColumnsInfoUtil.java183
-rw-r--r--data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/querytextutil/QueryTextUtil.java434
49 files changed, 7786 insertions, 0 deletions
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/.classpath b/data/org.eclipse.birt.report.data.oda.excel.ui/.classpath
new file mode 100644
index 0000000..ad32c83
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/.classpath
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/.project b/data/org.eclipse.birt.report.data.oda.excel.ui/.project
new file mode 100644
index 0000000..ca8329d
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.birt.report.data.oda.excel.ui</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/.settings/org.eclipse.jdt.core.prefs b/data/org.eclipse.birt.report.data.oda.excel.ui/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000..3988f57
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,8 @@
+#Mon Aug 29 19:43:32 IST 2011
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/META-INF/MANIFEST.MF b/data/org.eclipse.birt.report.data.oda.excel.ui/META-INF/MANIFEST.MF
new file mode 100644
index 0000000..735ea8f
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/META-INF/MANIFEST.MF
@@ -0,0 +1,14 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: %plugin.name
+Bundle-SymbolicName: org.eclipse.birt.report.data.oda.excel.ui; singleton:=true
+Bundle-Version: 1.0.0.qualifier
+Bundle-Activator: org.eclipse.birt.report.data.oda.excel.ui.Activator
+Bundle-Vendor: Megha Nidhi Dahal
+Bundle-Localization: plugin
+Require-Bundle: org.eclipse.ui,
+ org.eclipse.core.runtime,
+ org.eclipse.datatools.connectivity.oda.design.ui;bundle-version="[3.2.0,4.0.0)",
+ org.eclipse.birt.report.data.oda.excel
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-ActivationPolicy: lazy
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/Readme.txt b/data/org.eclipse.birt.report.data.oda.excel.ui/Readme.txt
new file mode 100644
index 0000000..44d876e
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/Readme.txt
@@ -0,0 +1,46 @@
+***********************************************org.eclipse.birt.report.data.oda.excel.ui(v 1.0)******************************************************
+Plugin Name: org.eclipse.birt.report.data.oda.excel.ui
+Contributor: Megha Nidhi Dahal (http://www.birt-exchange.org/org/forum/index.php/user/28183-arpan/)
+Tags: Native Excel ODA, xls, xlsx, open data access, ODA Framework, Excel ODA, BIRT, Eclipse BIRT
+
+Platform Dependencies: Eclipse v3.6.2 or higher
+Plugin Dependencies: POI(http://poi.apache.org/), org.eclipse.ui, org.eclipse.core.runtime, org.eclipse.datatools.connectivity.oda.design.ui, org.eclipse.birt.report.data.oda.excel
+
+*******************************************************PLUGIN DESCRIPTION*******************************************************************
+org.eclipse.birt.report.data.oda.excel.ui ODA ui extension supports configuration of a data set over native excel data source. It provides the ui part of Excel ODA.
+Supports selective columns(fields/cell) selection and computed columns.
+
+Configuration can be done using only one sheet. However, multiple ';' delimited worksheet names can be passed to the Worksheet(s) parameter of the data set.
+
+*******************************************************DEPLOYMENT***************************************************************************
+The plugin is expected to be deployed along with 'org.eclipse.birt.report.data.oda.excel' plugin.
+Import both of these plugin projects in excel and export using the plugin manifest file. The exported jars are to be placed in the dropins folder of eclipse installation.
+
+Visit: http://wiki.eclipse.org/Birt_3.7_Migration_Guide#Custom_Extension_Point_Implementations
+
+********************************************************************LIMITATIONS**************************************************************
+Supports only one workbook per data set.
+Sheets can be identified only using names.
+Multiple sheet has to be delimited with ';', hence every ';' delimited text parameter linked to worksheets parameter of the data set will be treated as individual sheets.
+Valid sheet names cannot contain ';'
+
+************************************************************************ENHANCEMENTS*********************************************************
+Support for multiple workbooks.
+An option to indicate the ODA to consider sheet indexes instead of names.
+Consider a fragment of data from every sheet, i.e. row start index and end index to be configurable.
+
+***********************************************************************FAQS******************************************************************
+Q1: Does this ODA support excel formats other than Microsoft's native format?
+A: No.
+
+Q2: Does this ODA support Microsoft Excel 2010 (xlsx) format?
+A: Yes.
+
+Q3: Can the listed enhancements be implemented by anyone interested?
+A: Yes. There might be many more enhancements that can be implemented not just the ones listed.
+
+Q4: Will this ODA work without the org.eclipse.birt.report.data.oda.excel extension?
+A: No.
+
+Q5: Where can be the author of this extension contacted?
+A: The author of this plugin can be contacted at: http://www.birt-exchange.org/org/forum/index.php/user/28183-arpan/ \ No newline at end of file
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/build.properties b/data/org.eclipse.birt.report.data.oda.excel.ui/build.properties
new file mode 100644
index 0000000..895d775
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/build.properties
@@ -0,0 +1,7 @@
+source.. = src/
+output.. = bin/
+bin.includes = plugin.xml,\
+ META-INF/,\
+ .,\
+ plugin.properties,\
+ icons/
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/icons/datasetpage.ico b/data/org.eclipse.birt.report.data.oda.excel.ui/icons/datasetpage.ico
new file mode 100644
index 0000000..69f4ae1
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/icons/datasetpage.ico
Binary files differ
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/icons/new_oda_dswiz.ico b/data/org.eclipse.birt.report.data.oda.excel.ui/icons/new_oda_dswiz.ico
new file mode 100644
index 0000000..ff770b1
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/icons/new_oda_dswiz.ico
Binary files differ
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/icons/profile.gif b/data/org.eclipse.birt.report.data.oda.excel.ui/icons/profile.gif
new file mode 100644
index 0000000..6b86d07
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/icons/profile.gif
Binary files differ
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/plugin.properties b/data/org.eclipse.birt.report.data.oda.excel.ui/plugin.properties
new file mode 100644
index 0000000..5c49002
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/plugin.properties
@@ -0,0 +1,19 @@
+###############################################################################
+# Copyright (c) 2010 <<Your Company Name here>>
+#
+###############################################################################
+# Plug-in Configuration
+#
+oda.data.source.id=org.eclipse.birt.report.data.oda.excel
+#
+###############################################################################
+# NLS strings
+#
+plugin.name=Excel Data Source ODA Designer
+newwizard.name=Excel Data Source
+newwizard.description=Create a Excel Data Source connection profile
+wizard.window.title=New Excel Data Source Profile
+wizard.data.source.page.title=Excel Data Source
+profile.propertypage.name=Excel Data Source Connection Properties
+wizard.data.set.window.title=New Excel Data Set
+wizard.data.set.page.title=Select Columns
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/plugin.xml b/data/org.eclipse.birt.report.data.oda.excel.ui/plugin.xml
new file mode 100644
index 0000000..f6d66ab
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/plugin.xml
@@ -0,0 +1,70 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?>
+<plugin>
+
+ <extension
+ point="org.eclipse.datatools.connectivity.connectionProfile">
+ <newWizard
+ name="%newwizard.name"
+ icon="icons/new_oda_dswiz.ico"
+ profile="%oda.data.source.id"
+ description="%newwizard.description"
+ class="org.eclipse.datatools.connectivity.oda.design.ui.wizards.NewDataSourceWizard"
+ id="%oda.data.source.id">
+ </newWizard>
+ </extension>
+ <extension
+ point="org.eclipse.datatools.connectivity.ui.connectionProfileImage">
+ <profileImage
+ icon="icons/profile.gif"
+ profileID="%oda.data.source.id">
+ </profileImage>
+ </extension>
+ <extension
+ point="org.eclipse.ui.propertyPages">
+ <page
+ name="%profile.propertypage.name"
+ class="org.eclipse.birt.report.data.oda.excel.ui.wizards.ExcelDataSourcePropertyPage"
+ id="%oda.data.source.id">
+ <enabledWhen>
+ <instanceof
+ value="org.eclipse.datatools.connectivity.IConnectionProfile">
+ </instanceof>
+ </enabledWhen>
+ <filter
+ name="org.eclipse.datatools.profile.property.id"
+ value="%oda.data.source.id">
+ </filter>
+ </page>
+ </extension>
+ <extension
+ point="org.eclipse.datatools.connectivity.oda.design.ui.dataSource">
+ <dataSourceUI
+ id="%oda.data.source.id">
+ <newDataSourceWizard
+ pageClass="org.eclipse.birt.report.data.oda.excel.ui.wizards.ExcelDataSourceWizardPage"
+ includesProgressMonitor="false"
+ pageTitle="%wizard.data.source.page.title"
+ windowTitle="%wizard.window.title">
+ </newDataSourceWizard>
+ </dataSourceUI>
+ <dataSetUI
+ supportsOutParameters="true"
+ supportsInParameters="true"
+ initialPageId="org.eclipse.birt.report.data.oda.excel.dataSet.page1"
+ id="org.eclipse.birt.report.data.oda.excel.dataSet">
+ <dataSetWizard
+ class="org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSetWizard"
+ windowTitle="%wizard.data.set.window.title">
+ </dataSetWizard>
+ <dataSetPage
+ displayName="%wizard.data.set.page.title"
+ icon="icons/datasetpage.ico"
+ wizardPageClass="org.eclipse.birt.report.data.oda.excel.ui.wizards.ExcelFileSelectionWizardPage"
+ path="/"
+ id="org.eclipse.birt.report.data.oda.excel.dataSet.page1">
+ </dataSetPage>
+ </dataSetUI>
+ </extension>
+
+</plugin>
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/Activator.java b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/Activator.java
new file mode 100644
index 0000000..e0ea5a7
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/Activator.java
@@ -0,0 +1,71 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+package org.eclipse.birt.report.data.oda.excel.ui;
+
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The activator class controls the plug-in life cycle
+ */
+public class Activator extends AbstractUIPlugin {
+
+ // The plug-in ID
+ public static final String PLUGIN_ID = "org.eclipse.birt.report.data.oda.excel.ui"; //$NON-NLS-1$
+
+ // The shared instance
+ private static Activator plugin;
+
+ /**
+ * The constructor
+ */
+ public Activator() {
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ public void start(BundleContext context) throws Exception {
+ super.start(context);
+ plugin = this;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ public void stop(BundleContext context) throws Exception {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static Activator getDefault() {
+ return plugin;
+ }
+
+ /**
+ * Returns an image descriptor for the image file at the given
+ * plug-in relative path
+ *
+ * @param path the path
+ * @return the image descriptor
+ */
+ public static ImageDescriptor getImageDescriptor(String path) {
+ return imageDescriptorFromPlugin(PLUGIN_ID, path);
+ }
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/i18n/Messages.java b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/i18n/Messages.java
new file mode 100644
index 0000000..b02b0bc
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/i18n/Messages.java
@@ -0,0 +1,44 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+package org.eclipse.birt.report.data.oda.excel.ui.i18n;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+public class Messages
+{
+ private static final String BUNDLE_NAME = "org.eclipse.birt.report.data.oda.excel.ui.i18n.messages"; //$NON-NLS-1$
+
+ private static final ResourceBundle RESOURCE_BUNDLE =
+ ResourceBundle.getBundle(BUNDLE_NAME);
+
+ private Messages()
+ {
+ }
+
+ public static String getString( String key )
+ {
+ try
+ {
+ return RESOURCE_BUNDLE.getString( key );
+ }
+ catch( MissingResourceException e )
+ {
+ return '!' + key + '!';
+ }
+ }
+
+ public static String getFormattedString( String key, Object[] arguments )
+ {
+ return MessageFormat.format( getString( key ), arguments );
+ }
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/i18n/messages.properties b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/i18n/messages.properties
new file mode 100644
index 0000000..f34c2b6
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/i18n/messages.properties
@@ -0,0 +1,76 @@
+#
+#************************************************************************
+# Copyright (c) 2006, 2007 Actuate Corporation.
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Eclipse Public License v1.0
+# which accompanies this distribution, and is available at
+# http://www.eclipse.org/legal/epl-v10.html
+#
+# Contributors:
+# Actuate Corporation - initial API and implementation
+#
+#************************************************************************
+#
+wizard.title.selectColumns=Select Columns
+wizard.defaultMessage.selectFolder=Select the folder that contains the excel files.
+wizard.defaultMessage.selectFile=Select the file and the columns for the data set.
+
+label.selectFolder=S&elect folder:
+label.selectFile=Select f&ile:
+label.selectworksheet=Worksheet:
+label.includeTypeLine=Use second line as &data type indicator.
+label.includeColumnNameLine = Use first line &as column name indicator.
+label.dateFormat=Date Format:
+
+button.selectFolder.browse=B&rowse...
+button.moveUp=&Up
+button.moveDown=Do&wn
+button.delete=D&elete
+
+editor.title.name=Name
+editor.title.originalName=Original Name
+editor.title.type=Type
+
+
+datatypes.dateTime=Date Time
+datatypes.decimal=Decimal
+datatypes.float=Float
+datatypes.integer=Integer
+datatypes.string=String
+datatypes.date=Date
+datatypes.time=Time
+datatypes.boolean=Boolean
+
+tooltip.excelfilestyle=Move the mouse to each excel file style for more infomation.
+tooltip.csv=Comma-{ , } Seperated Values
+tooltip.ssv=Semicolon-{ ; } Seperated Values
+tooltip.psv=Pipe-{ | } Seperated Values
+tooltip.tsv=Tab-{ Tab } Seperated Values
+tooltip.columnnameline=Please make sure the existence of column names\n in the first row of the selected file.
+tooltip.typeline=Please make sure the existence of data type line\n in the second row of the selected file.
+tooltip.button.add=Add all the selected columns from the left table to the excel file data set.
+tooltip.button.up=Move up the selected item.
+tooltip.button.down=Move down the selected item.
+tooltip.button.delete=Delete the selected item.
+tooltip.trailNull=Trail null columns when reading lines of data.
+error.selectFolder=Please select a valid folder.
+error.selectColumns=Please select at least one column for this data set.
+error.emptyPath=Please enter a path.
+error.unexpectedError=An unexpected error happened.
+error.invalidConnectionFilePath=The specified connection profile source path, "{0}", does not exist.
+error.invalidFlatFilePath=Invalid excel file data source path. Please correct the connection profile.
+error.errorExist=Error exists in the current page. Would you like to save it anyway?
+error.noFiles=The folder, "{0}", does not have any specified files in it.
+error.invalidFilePath=The file path is invalid. Would you like to continue?
+error.emptyFilePath=The file path is empty. Would you like to continue?
+error.duplicatedNameValueOrEmpty=Duplicated Name Value or Empty
+error.invalidSavedColumnsInfo = Invalid saved Columns Info
+error.invalidColumnName=Invalid Column Name
+error.invalidQureyText=Invalid Query-Text
+
+title.warning=Warning
+warning.fileExtensionInvalid=The selected file might not be a valid excel file.
+confirm.reselectWorksheetTitle=Confirm to select a different sheet.
+confirm.reselectWorksheetMessage=Selecting a different sheet will leave previous operations unsaved.\n\nAre you sure?
+confirm.reselectFileTitle=Confirm to select a different file.
+confirm.reselectFileMessage=Selecting a different file will leave previous operations unsaved.\n\nAre you sure? \ No newline at end of file
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/impl/CustomDataSetWizardPage.java b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/impl/CustomDataSetWizardPage.java
new file mode 100644
index 0000000..6f9f58f
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/impl/CustomDataSetWizardPage.java
@@ -0,0 +1,394 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+
+package org.eclipse.birt.report.data.oda.excel.ui.impl;
+
+import org.eclipse.datatools.connectivity.oda.IConnection;
+import org.eclipse.datatools.connectivity.oda.IDriver;
+import org.eclipse.datatools.connectivity.oda.IParameterMetaData;
+import org.eclipse.datatools.connectivity.oda.IQuery;
+import org.eclipse.datatools.connectivity.oda.IResultSetMetaData;
+import org.eclipse.datatools.connectivity.oda.OdaException;
+import org.eclipse.datatools.connectivity.oda.design.DataSetDesign;
+import org.eclipse.datatools.connectivity.oda.design.DataSetParameters;
+import org.eclipse.datatools.connectivity.oda.design.DesignFactory;
+import org.eclipse.datatools.connectivity.oda.design.ParameterDefinition;
+import org.eclipse.datatools.connectivity.oda.design.ResultSetColumns;
+import org.eclipse.datatools.connectivity.oda.design.ResultSetDefinition;
+import org.eclipse.datatools.connectivity.oda.design.ui.designsession.DesignSessionUtil;
+import org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSetWizardPage;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+
+/**
+ * Auto-generated implementation of an ODA data set designer page
+ * for an user to create or edit an ODA data set design instance.
+ * This custom page provides a simple Query Text control for user input.
+ * It further extends the DTP design-time framework to update
+ * an ODA data set design instance based on the query's derived meta-data.
+ * <br>
+ * A custom ODA designer is expected to change this exemplary implementation
+ * as appropriate.
+ */
+public class CustomDataSetWizardPage extends DataSetWizardPage
+{
+
+ private static String DEFAULT_MESSAGE = "Define the query text for the data set";
+
+ private transient Text m_queryTextField;
+
+ /**
+ * Constructor
+ * @param pageName
+ */
+ public CustomDataSetWizardPage( String pageName )
+ {
+ super( pageName );
+ setTitle( pageName );
+ setMessage( DEFAULT_MESSAGE );
+ }
+
+ /**
+ * Constructor
+ * @param pageName
+ * @param title
+ * @param titleImage
+ */
+ public CustomDataSetWizardPage( String pageName, String title,
+ ImageDescriptor titleImage )
+ {
+ super( pageName, title, titleImage );
+ setMessage( DEFAULT_MESSAGE );
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSetWizardPage#createPageCustomControl(org.eclipse.swt.widgets.Composite)
+ */
+ public void createPageCustomControl( Composite parent )
+ {
+ setControl( createPageControl( parent ) );
+ initializeControl();
+ }
+
+ /**
+ * Creates custom control for user-defined query text.
+ */
+ private Control createPageControl( Composite parent )
+ {
+ Composite composite = new Composite( parent, SWT.NONE );
+ composite.setLayout( new GridLayout( 1, false ) );
+ GridData gridData = new GridData( GridData.HORIZONTAL_ALIGN_FILL
+ | GridData.VERTICAL_ALIGN_FILL );
+
+ composite.setLayoutData( gridData );
+
+ Label fieldLabel = new Label( composite, SWT.NONE );
+ fieldLabel.setText( "&Query Text:" );
+
+ m_queryTextField = new Text( composite, SWT.BORDER
+ | SWT.V_SCROLL | SWT.H_SCROLL );
+ GridData data = new GridData( GridData.FILL_HORIZONTAL );
+ data.heightHint = 100;
+ m_queryTextField.setLayoutData( data );
+ m_queryTextField.addModifyListener( new ModifyListener( )
+ {
+ public void modifyText( ModifyEvent e )
+ {
+ validateData();
+ }
+ } );
+
+ setPageComplete( false );
+ return composite;
+ }
+
+ /**
+ * Initializes the page control with the last edited data set design.
+ */
+ private void initializeControl( )
+ {
+ /*
+ * To optionally restore the designer state of the previous design session, use
+ * getInitializationDesignerState();
+ */
+
+ // Restores the last saved data set design
+ DataSetDesign dataSetDesign = getInitializationDesign();
+ if( dataSetDesign == null )
+ return; // nothing to initialize
+
+ String queryText = dataSetDesign.getQueryText();
+ if( queryText == null )
+ return; // nothing to initialize
+
+ // initialize control
+ m_queryTextField.setText( queryText );
+ validateData();
+ setMessage( DEFAULT_MESSAGE );
+
+ /*
+ * To optionally honor the request for an editable or
+ * read-only design session, use
+ * isSessionEditable();
+ */
+ }
+
+ /**
+ * Obtains the user-defined query text of this data set from page control.
+ * @return query text
+ */
+ private String getQueryText( )
+ {
+ return m_queryTextField.getText();
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSetWizardPage#collectDataSetDesign(org.eclipse.datatools.connectivity.oda.design.DataSetDesign)
+ */
+ protected DataSetDesign collectDataSetDesign( DataSetDesign design )
+ {
+ if( getControl() == null ) // page control was never created
+ return design; // no editing was done
+ if( ! hasValidData() )
+ return null; // to trigger a design session error status
+ savePage( design );
+ return design;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSetWizardPage#collectResponseState()
+ */
+ protected void collectResponseState( )
+ {
+ super.collectResponseState( );
+ /*
+ * To optionally assign a custom response state, for inclusion in the ODA
+ * design session response, use
+ * setResponseSessionStatus( SessionStatus status );
+ * setResponseDesignerState( DesignerState customState );
+ */
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSetWizardPage#canLeave()
+ */
+ protected boolean canLeave( )
+ {
+ return isPageComplete();
+ }
+
+ /**
+ * Validates the user-defined value in the page control exists
+ * and not a blank text.
+ * Set page message accordingly.
+ */
+ private void validateData( )
+ {
+ boolean isValid = ( m_queryTextField != null &&
+ getQueryText() != null && getQueryText().trim().length() > 0 );
+
+ if( isValid )
+ setMessage( DEFAULT_MESSAGE );
+ else
+ setMessage( "Requires input value.", ERROR );
+
+ setPageComplete( isValid );
+ }
+
+ /**
+ * Indicates whether the custom page has valid data to proceed
+ * with defining a data set.
+ */
+ private boolean hasValidData( )
+ {
+ validateData( );
+
+ return canLeave();
+ }
+
+ /**
+ * Saves the user-defined value in this page, and updates the specified
+ * dataSetDesign with the latest design definition.
+ */
+ private void savePage( DataSetDesign dataSetDesign )
+ {
+ // save user-defined query text
+ String queryText = getQueryText();
+ dataSetDesign.setQueryText( queryText );
+
+ // obtain query's current runtime metadata, and maps it to the dataSetDesign
+ IConnection customConn = null;
+ try
+ {
+ // instantiate your custom ODA runtime driver class
+ /* Note: You may need to manually update your ODA runtime extension's
+ * plug-in manifest to export its package for visibility here.
+ */
+ IDriver customDriver = new org.eclipse.birt.report.data.oda.excel.impl.Driver();
+
+ // obtain and open a live connection
+ customConn = customDriver.getConnection( null );
+ java.util.Properties connProps =
+ DesignSessionUtil.getEffectiveDataSourceProperties(
+ getInitializationDesign().getDataSourceDesign() );
+ customConn.open( connProps );
+
+ // update the data set design with the
+ // query's current runtime metadata
+ updateDesign( dataSetDesign, customConn, queryText );
+ }
+ catch( OdaException e )
+ {
+ // not able to get current metadata, reset previous derived metadata
+ dataSetDesign.setResultSets( null );
+ dataSetDesign.setParameters( null );
+
+ e.printStackTrace();
+ }
+ finally
+ {
+ closeConnection( customConn );
+ }
+ }
+
+ /**
+ * Updates the given dataSetDesign with the queryText and its derived metadata
+ * obtained from the ODA runtime connection.
+ */
+ private void updateDesign( DataSetDesign dataSetDesign,
+ IConnection conn, String queryText )
+ throws OdaException
+ {
+ IQuery query = conn.newQuery( null );
+ query.prepare( queryText );
+
+ // TODO a runtime driver might require a query to first execute before
+ // its metadata is available
+// query.setMaxRows( 1 );
+// query.executeQuery();
+
+ try
+ {
+ IResultSetMetaData md = query.getMetaData();
+ updateResultSetDesign( md, dataSetDesign );
+ }
+ catch( OdaException e )
+ {
+ // no result set definition available, reset previous derived metadata
+ dataSetDesign.setResultSets( null );
+ e.printStackTrace();
+ }
+
+ // proceed to get parameter design definition
+ try
+ {
+ IParameterMetaData paramMd = query.getParameterMetaData();
+ updateParameterDesign( paramMd, dataSetDesign );
+ }
+ catch( OdaException ex )
+ {
+ // no parameter definition available, reset previous derived metadata
+ dataSetDesign.setParameters( null );
+ ex.printStackTrace();
+ }
+
+ /*
+ * See DesignSessionUtil for more convenience methods
+ * to define a data set design instance.
+ */
+ }
+
+ /**
+ * Updates the specified data set design's result set definition based on the
+ * specified runtime metadata.
+ * @param md runtime result set metadata instance
+ * @param dataSetDesign data set design instance to update
+ * @throws OdaException
+ */
+ private void updateResultSetDesign( IResultSetMetaData md,
+ DataSetDesign dataSetDesign )
+ throws OdaException
+ {
+ ResultSetColumns columns = DesignSessionUtil.toResultSetColumnsDesign( md );
+
+ ResultSetDefinition resultSetDefn = DesignFactory.eINSTANCE
+ .createResultSetDefinition();
+ // resultSetDefn.setName( value ); // result set name
+ resultSetDefn.setResultSetColumns( columns );
+
+ // no exception in conversion; go ahead and assign to specified dataSetDesign
+ dataSetDesign.setPrimaryResultSet( resultSetDefn );
+ dataSetDesign.getResultSets().setDerivedMetaData( true );
+ }
+
+ /**
+ * Updates the specified data set design's parameter definition based on the
+ * specified runtime metadata.
+ * @param paramMd runtime parameter metadata instance
+ * @param dataSetDesign data set design instance to update
+ * @throws OdaException
+ */
+ private void updateParameterDesign( IParameterMetaData paramMd,
+ DataSetDesign dataSetDesign )
+ throws OdaException
+ {
+ DataSetParameters paramDesign =
+ DesignSessionUtil.toDataSetParametersDesign( paramMd,
+ DesignSessionUtil.toParameterModeDesign( IParameterMetaData.parameterModeIn ) );
+
+ // no exception in conversion; go ahead and assign to specified dataSetDesign
+ dataSetDesign.setParameters( paramDesign );
+ if( paramDesign == null )
+ return; // no parameter definitions; done with update
+
+ paramDesign.setDerivedMetaData( true );
+
+ // TODO replace below with data source specific implementation;
+ // hard-coded parameter's default value for demo purpose
+ if( paramDesign.getParameterDefinitions().size() > 0 )
+ {
+ ParameterDefinition paramDef =
+ (ParameterDefinition) paramDesign.getParameterDefinitions().get( 0 );
+ if( paramDef != null )
+ paramDef.setDefaultScalarValue( "dummy default value" );
+ }
+ }
+
+ /**
+ * Attempts to close given ODA connection.
+ */
+ private void closeConnection( IConnection conn )
+ {
+ try
+ {
+ if( conn != null && conn.isOpen() )
+ conn.close();
+ }
+ catch ( OdaException e )
+ {
+ // ignore
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/util/IHelpConstants.java b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/util/IHelpConstants.java
new file mode 100644
index 0000000..2c1d859
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/util/IHelpConstants.java
@@ -0,0 +1,24 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+package org.eclipse.birt.report.data.oda.excel.ui.util;
+
+public interface IHelpConstants
+{
+
+ public static final String PREFIX = "org.eclipse.datatools.oda.cshelp" + "."; //$NON-NLS-1$ //$NON-NLS-2$
+
+ public static final String CONEXT_ID_DATASOURCE_EXCEL = PREFIX
+ + "Wizard_ExcelDatasource_ID";//$NON-NLS-1$
+
+ public static final String CONEXT_ID_DATASET_EXCEL = PREFIX
+ + "Dialog_SelectTableColumn_ID";//$NON-NLS-1$
+
+} \ No newline at end of file
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/util/Utility.java b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/util/Utility.java
new file mode 100644
index 0000000..c0f5f65
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/util/Utility.java
@@ -0,0 +1,36 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+package org.eclipse.birt.report.data.oda.excel.ui.util;
+
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.ui.PlatformUI;
+
+/**
+ *
+ */
+
+public class Utility
+{
+
+ /**
+ * Set context-sensitive help
+ *
+ * @param control
+ * @param contextId
+ */
+ public static void setSystemHelp( Control control, String contextId )
+ {
+ PlatformUI.getWorkbench( )
+ .getHelpSystem( )
+ .setHelp( control, contextId );
+ }
+
+} \ No newline at end of file
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/wizards/ExcelDataSourcePageHelper.java b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/wizards/ExcelDataSourcePageHelper.java
new file mode 100644
index 0000000..f9fce66
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/wizards/ExcelDataSourcePageHelper.java
@@ -0,0 +1,353 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+package org.eclipse.birt.report.data.oda.excel.ui.wizards;
+
+import java.io.File;
+import java.util.Properties;
+
+import org.eclipse.birt.report.data.oda.excel.ExcelODAConstants;
+import org.eclipse.birt.report.data.oda.excel.ui.i18n.Messages;
+import org.eclipse.birt.report.data.oda.excel.ui.util.IHelpConstants;
+import org.eclipse.birt.report.data.oda.excel.ui.util.Utility;
+import org.eclipse.datatools.connectivity.oda.design.ui.nls.TextProcessorWrapper;
+import org.eclipse.jface.dialogs.IMessageProvider;
+import org.eclipse.jface.preference.PreferencePage;
+import org.eclipse.jface.wizard.WizardPage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.DirectoryDialog;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.Text;
+
+public class ExcelDataSourcePageHelper {
+
+ static final String DEFAULT_MESSAGE = Messages
+ .getString("wizard.defaultMessage.selectFolder"); //$NON-NLS-1$
+
+ private WizardPage wizardPage;
+ private PreferencePage propertyPage;
+
+ private transient Text folderLocation = null;
+ private transient Button typeLineCheckBox = null;
+ private transient Button browseFolderButton = null;
+ private transient Button columnNameLineCheckBox = null;
+
+ private static final int CORRECT_FOLDER = 0;
+ private static final int ERROR_FOLDER = 1;
+ private static final int ERROR_EMPTY_PATH = 2;
+ private static final String EMPTY_STRING = ""; //$NON-NLS-1$
+
+ public ExcelDataSourcePageHelper(ExcelDataSourceWizardPage page) {
+ wizardPage = page;
+ }
+
+ public ExcelDataSourcePageHelper(
+ ExcelDataSourcePropertyPage excelDataSourcePropertyPage) {
+ propertyPage = excelDataSourcePropertyPage;
+ }
+
+ /**
+ *
+ * @param parent
+ */
+ void createCustomControl(Composite parent) {
+ Composite content = new Composite(parent, SWT.NULL);
+ GridLayout layout = new GridLayout(3, false);
+ content.setLayout(layout);
+
+ // GridData data;
+ setupFolderLocation(content);
+
+ setupColumnNameLineCheckBox(content);
+
+ setupTypeLineCheckBox(content);
+
+ Utility.setSystemHelp(getControl(),
+ IHelpConstants.CONEXT_ID_DATASOURCE_EXCEL);
+ }
+
+ private void setupFolderLocation(Composite composite) {
+ Label label = new Label(composite, SWT.NONE);
+ label.setText(Messages.getString("label.selectFolder")); //$NON-NLS-1$
+
+ GridData data = new GridData(GridData.FILL_HORIZONTAL);
+
+ folderLocation = new Text(composite, SWT.BORDER);
+ folderLocation.setLayoutData(data);
+ setPageComplete(false);
+ folderLocation.addModifyListener(new ModifyListener() {
+
+ public void modifyText(ModifyEvent e) {
+ verifyFileLocation();
+ }
+
+ });
+
+ browseFolderButton = new Button(composite, SWT.NONE);
+ browseFolderButton.setText(Messages
+ .getString("button.selectFolder.browse")); //$NON-NLS-1$
+ browseFolderButton.addSelectionListener(new SelectionAdapter() {
+
+ /*
+ * @see
+ * org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse
+ * .swt.events.SelectionEvent)
+ */
+ public void widgetSelected(SelectionEvent e) {
+ DirectoryDialog dialog = new DirectoryDialog(folderLocation
+ .getShell());
+ String folderLocationValue = getFolderLocationString();
+ if (folderLocationValue != null
+ && folderLocationValue.trim().length() > 0) {
+ dialog.setFilterPath(folderLocationValue);
+ }
+
+ dialog.setMessage(DEFAULT_MESSAGE);
+ String selectedLocation = dialog.open();
+ if (selectedLocation != null) {
+ setFolderLocationString(selectedLocation);
+ }
+ }
+ });
+ }
+
+ /**
+ *
+ * @param composite
+ */
+ private void setupColumnNameLineCheckBox(Composite composite) {
+ Label labelFill = new Label(composite, SWT.NONE);
+ labelFill.setText(""); //$NON-NLS-1$
+
+ columnNameLineCheckBox = new Button(composite, SWT.CHECK);
+ columnNameLineCheckBox.setToolTipText(Messages
+ .getString("tooltip.columnnameline")); //$NON-NLS-1$
+ GridData gd = new GridData();
+ gd.horizontalSpan = 3;
+ columnNameLineCheckBox.setLayoutData(gd);
+ columnNameLineCheckBox.setText(Messages
+ .getString("label.includeColumnNameLine")); //$NON-NLS-1$
+ columnNameLineCheckBox.setSelection(true);
+ columnNameLineCheckBox.addSelectionListener(new SelectionAdapter() {
+
+ public void widgetSelected(SelectionEvent e) {
+ if (columnNameLineCheckBox.getSelection())
+ typeLineCheckBox.setEnabled(true);
+ else {
+ typeLineCheckBox.setSelection(false);
+ typeLineCheckBox.setEnabled(false);
+ }
+ }
+ });
+
+ }
+
+ /**
+ * @param composite
+ */
+ private void setupTypeLineCheckBox(Composite composite) {
+ typeLineCheckBox = new Button(composite, SWT.CHECK);
+ typeLineCheckBox.setToolTipText(Messages.getString("tooltip.typeline")); //$NON-NLS-1$
+ GridData data = new GridData();
+ data.horizontalSpan = 3;
+ typeLineCheckBox.setLayoutData(data);
+ typeLineCheckBox.setText(Messages.getString("label.includeTypeLine")); //$NON-NLS-1$
+ if (columnNameLineCheckBox.getSelection())
+ typeLineCheckBox.setEnabled(true);
+ else {
+ typeLineCheckBox.setSelection(false);
+ typeLineCheckBox.setEnabled(false);
+ }
+ }
+
+ /**
+ *
+ * @param props
+ * @return
+ */
+ Properties collectCustomProperties(Properties props) {
+ if (props == null)
+ props = new Properties();
+
+ // set custom driver specific properties
+ props.setProperty(ExcelODAConstants.CONN_HOME_DIR_PROP,
+ getFolderLocation().trim());
+ props.setProperty(ExcelODAConstants.CONN_INCLCOLUMNNAME_PROP,
+ getWhetherUseFirstLineAsColumnNameLine());
+ props.setProperty(ExcelODAConstants.CONN_INCLTYPELINE_PROP,
+ getWhetherUseSecondLineAsTypeLine());
+
+ return props;
+ }
+
+ /**
+ *
+ * @return
+ */
+ String getFolderLocation() {
+ if (folderLocation == null)
+ return EMPTY_STRING;
+ return getFolderLocationString();
+ }
+
+ /**
+ *
+ * @return
+ */
+ String getWhetherUseFirstLineAsColumnNameLine() {
+ if (columnNameLineCheckBox == null
+ || !columnNameLineCheckBox.getEnabled())
+ return EMPTY_STRING;
+ return columnNameLineCheckBox.getSelection() ? ExcelODAConstants.INC_COLUMN_NAME_YES
+ : ExcelODAConstants.INC_COLUMN_NAME_NO;
+ }
+
+ /**
+ *
+ * @return
+ */
+ String getWhetherUseSecondLineAsTypeLine() {
+ if (typeLineCheckBox == null)
+ return EMPTY_STRING;
+ return typeLineCheckBox.getSelection() ? ExcelODAConstants.INC_TYPE_LINE_YES
+ : ExcelODAConstants.INC_TYPE_LINE_NO;
+ }
+
+ /**
+ *
+ * @param profileProps
+ */
+ void initCustomControl(Properties profileProps) {
+ if (profileProps == null || profileProps.isEmpty()
+ || folderLocation == null)
+ return; // nothing to initialize
+
+ String folderPath = profileProps
+ .getProperty(ExcelODAConstants.CONN_HOME_DIR_PROP);
+ if (folderPath == null)
+ folderPath = EMPTY_STRING;
+ setFolderLocationString(folderPath);
+
+ String hasColumnNameLine = profileProps
+ .getProperty(ExcelODAConstants.CONN_INCLCOLUMNNAME_PROP);
+ if (hasColumnNameLine == null)
+ hasColumnNameLine = ExcelODAConstants.INC_COLUMN_NAME_YES;
+ if (hasColumnNameLine
+ .equalsIgnoreCase(ExcelODAConstants.INC_COLUMN_NAME_YES)) {
+ columnNameLineCheckBox.setSelection(true);
+
+ String useSecondLine = profileProps
+ .getProperty(ExcelODAConstants.CONN_INCLTYPELINE_PROP);
+ if (useSecondLine == null)
+ useSecondLine = EMPTY_STRING;
+ typeLineCheckBox.setEnabled(true);
+ typeLineCheckBox.setSelection(useSecondLine
+ .equalsIgnoreCase(ExcelODAConstants.INC_TYPE_LINE_YES));
+ } else {
+ columnNameLineCheckBox.setSelection(false);
+ typeLineCheckBox.setSelection(false);
+ typeLineCheckBox.setEnabled(false);
+ }
+
+ verifyFileLocation();
+ }
+
+ /**
+ *
+ * @param complete
+ */
+ private void setPageComplete(boolean complete) {
+ if (wizardPage != null)
+ wizardPage.setPageComplete(complete);
+ else if (propertyPage != null)
+ propertyPage.setValid(complete);
+ }
+
+ /**
+ *
+ * @return
+ */
+ private int verifyFileLocation() {
+ int result = CORRECT_FOLDER;
+ String folderLocationValue = getFolderLocationString();
+ if (folderLocationValue.trim().length() > 0) {
+ File f = new File(folderLocationValue.trim());
+ if (f.exists()) {
+ setMessage(DEFAULT_MESSAGE, IMessageProvider.NONE);
+ setPageComplete(true);
+ } else {
+ setMessage(
+ Messages.getString("error.selectFolder"), IMessageProvider.ERROR); //$NON-NLS-1$
+ setPageComplete(false);
+ result = ERROR_FOLDER;
+ }
+ } else {
+ setMessage(
+ Messages.getString("error.emptyPath"), IMessageProvider.ERROR); //$NON-NLS-1$
+ setPageComplete(false);
+ result = ERROR_EMPTY_PATH;
+ }
+ if (result == CORRECT_FOLDER)
+ return result;
+
+ if (wizardPage == null) {
+ setPageComplete(true);
+ setMessage(
+ Messages.getString("error.invalidFlatFilePath"), IMessageProvider.ERROR); //$NON-NLS-1$
+ }
+ return result;
+ }
+
+ /**
+ *
+ * @return
+ */
+ private String getFolderLocationString() {
+ return TextProcessorWrapper.deprocess(folderLocation.getText());
+ }
+
+ /**
+ *
+ * @param folderPath
+ */
+ private void setFolderLocationString(String folderPath) {
+ folderLocation.setText(TextProcessorWrapper.process(folderPath));
+ }
+
+ /**
+ *
+ * @param newMessage
+ * @param newType
+ */
+ private void setMessage(String newMessage, int newType) {
+ if (wizardPage != null)
+ wizardPage.setMessage(newMessage, newType);
+ else if (propertyPage != null)
+ propertyPage.setMessage(newMessage, newType);
+ }
+
+ private Control getControl() {
+ if (wizardPage != null)
+ return wizardPage.getControl();
+ if (propertyPage != null)
+ return propertyPage.getControl();
+
+ return null;
+ }
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/wizards/ExcelDataSourcePropertyPage.java b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/wizards/ExcelDataSourcePropertyPage.java
new file mode 100644
index 0000000..cc396bf
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/wizards/ExcelDataSourcePropertyPage.java
@@ -0,0 +1,85 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+
+package org.eclipse.birt.report.data.oda.excel.ui.wizards;
+
+import java.util.Properties;
+
+import org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSourceEditorPage;
+import org.eclipse.swt.widgets.Composite;
+
+public class ExcelDataSourcePropertyPage extends DataSourceEditorPage
+{
+
+ private ExcelDataSourcePageHelper pageHelper;
+
+ public ExcelDataSourcePropertyPage( )
+ {
+ super( );
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSourceEditorPage#collectCustomProperties(java.util.Properties)
+ */
+ public Properties collectCustomProperties( Properties profileProps )
+ {
+ /*
+ * Optionally assigns a custom designer state, for inclusion
+ * in the ODA design session response, using
+ * setResponseDesignerState( DesignerState customState );
+ */
+
+ if ( pageHelper == null )
+ return profileProps;
+
+ return pageHelper.collectCustomProperties( profileProps );
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSourceEditorPage#createAndInitCustomControl(org.eclipse.swt.widgets.Composite, java.util.Properties)
+ */
+ protected void createAndInitCustomControl( Composite parent,
+ Properties profileProps )
+ {
+ if ( pageHelper == null )
+ pageHelper = new ExcelDataSourcePageHelper( this );
+
+ pageHelper.createCustomControl( parent );
+
+ /*
+ * Optionally hides the Test Connection button, using
+ * setPingButtonVisible( false );
+ */
+
+ /*
+ * Optionally restores the state of a previous design session.
+ * Obtains designer state, using
+ * getInitializationDesignerState();
+ */
+
+ pageHelper.initCustomControl( profileProps );
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSourceEditorPage#refresh(java.util.Properties)
+ */
+ protected void refresh( Properties customConnectionProps )
+ {
+ if( pageHelper != null )
+ pageHelper.initCustomControl( customConnectionProps );
+
+ // enable/disable all controls on page in respect of the editable session state
+ enableAllControls( getControl(), isSessionEditable() );
+ }
+
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/wizards/ExcelDataSourceWizardPage.java b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/wizards/ExcelDataSourceWizardPage.java
new file mode 100644
index 0000000..68bb4f4
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/wizards/ExcelDataSourceWizardPage.java
@@ -0,0 +1,74 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+package org.eclipse.birt.report.data.oda.excel.ui.wizards;
+
+import java.util.Properties;
+
+import org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSourceWizardPage;
+import org.eclipse.swt.widgets.Composite;
+
+public class ExcelDataSourceWizardPage extends DataSourceWizardPage{
+
+ private ExcelDataSourcePageHelper pageHelper;
+ private Properties folderProperties;
+
+ public ExcelDataSourceWizardPage(String pageName) {
+ super(pageName);
+ setMessage( ExcelDataSourcePageHelper.DEFAULT_MESSAGE );
+ // page title is specified in extension manifest
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSourceWizardPage#createPageCustomControl(org.eclipse.swt.widgets.Composite)
+ */
+ public void createPageCustomControl( Composite parent )
+ {
+ if ( pageHelper == null )
+ pageHelper = new ExcelDataSourcePageHelper( this );
+ pageHelper.createCustomControl( parent );
+ pageHelper.initCustomControl( folderProperties ); // in case init was called before create
+
+ /*
+ * Optionally hides the Test Connection button, using
+ * setPingButtonVisible( false );
+ */
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSourceWizardPage#collectCustomProperties()
+ */
+ public Properties collectCustomProperties( )
+ {
+ /*
+ * Optionally assign a custom designer state, for inclusion
+ * in the ODA design session response, using
+ * setResponseDesignerState( DesignerState customState );
+ */
+
+ if ( pageHelper != null )
+ return pageHelper.collectCustomProperties( folderProperties );
+
+ return ( folderProperties != null ) ? folderProperties
+ : new Properties( );
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSourceWizardPage#initPageCustomControl(java.util.Properties)
+ */
+ public void setInitialProperties( Properties dataSourceProps )
+ {
+ folderProperties = dataSourceProps;
+ if ( pageHelper == null )
+ return; // ignore, wait till createPageCustomControl to initialize
+ pageHelper.initCustomControl( folderProperties );
+ }
+
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/wizards/ExcelFileSelectionWizardPage.java b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/wizards/ExcelFileSelectionWizardPage.java
new file mode 100644
index 0000000..b2aa69b
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel.ui/src/org/eclipse/birt/report/data/oda/excel/ui/wizards/ExcelFileSelectionWizardPage.java
@@ -0,0 +1,1751 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+package org.eclipse.birt.report.data.oda.excel.ui.wizards;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.birt.report.data.oda.excel.ExcelODAConstants;
+import org.eclipse.birt.report.data.oda.excel.impl.Driver;
+import org.eclipse.birt.report.data.oda.excel.impl.util.ExcelFileReader;
+import org.eclipse.birt.report.data.oda.excel.impl.util.querytextutil.ColumnsInfoUtil;
+import org.eclipse.birt.report.data.oda.excel.impl.util.querytextutil.QueryTextUtil;
+import org.eclipse.birt.report.data.oda.excel.ui.i18n.Messages;
+import org.eclipse.birt.report.data.oda.excel.ui.util.IHelpConstants;
+import org.eclipse.birt.report.data.oda.excel.ui.util.Utility;
+import org.eclipse.datatools.connectivity.oda.IConnection;
+import org.eclipse.datatools.connectivity.oda.IDriver;
+import org.eclipse.datatools.connectivity.oda.IQuery;
+import org.eclipse.datatools.connectivity.oda.IResultSetMetaData;
+import org.eclipse.datatools.connectivity.oda.OdaException;
+import org.eclipse.datatools.connectivity.oda.design.DataSetDesign;
+import org.eclipse.datatools.connectivity.oda.design.DesignFactory;
+import org.eclipse.datatools.connectivity.oda.design.Properties;
+import org.eclipse.datatools.connectivity.oda.design.ResultSetColumns;
+import org.eclipse.datatools.connectivity.oda.design.ResultSetDefinition;
+import org.eclipse.datatools.connectivity.oda.design.ui.designsession.DesignSessionUtil;
+import org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSetWizardPage;
+import org.eclipse.datatools.connectivity.oda.util.manifest.ConnectionProfileProperty;
+import org.eclipse.jface.dialogs.MessageDialog;
+import org.eclipse.jface.resource.ImageDescriptor;
+import org.eclipse.jface.viewers.ArrayContentProvider;
+import org.eclipse.jface.viewers.CellEditor;
+import org.eclipse.jface.viewers.ComboBoxCellEditor;
+import org.eclipse.jface.viewers.ComboViewer;
+import org.eclipse.jface.viewers.ICellModifier;
+import org.eclipse.jface.viewers.ILabelProviderListener;
+import org.eclipse.jface.viewers.ISelectionChangedListener;
+import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.jface.viewers.ITableLabelProvider;
+import org.eclipse.jface.viewers.LabelProvider;
+import org.eclipse.jface.viewers.SelectionChangedEvent;
+import org.eclipse.jface.viewers.StructuredSelection;
+import org.eclipse.jface.viewers.TableViewer;
+import org.eclipse.jface.viewers.TextCellEditor;
+import org.eclipse.jface.viewers.Viewer;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.MouseAdapter;
+import org.eclipse.swt.events.MouseEvent;
+import org.eclipse.swt.events.SelectionAdapter;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.graphics.Image;
+import org.eclipse.swt.layout.FormAttachment;
+import org.eclipse.swt.layout.FormData;
+import org.eclipse.swt.layout.FormLayout;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.swt.widgets.List;
+import org.eclipse.swt.widgets.TableColumn;
+import org.eclipse.swt.widgets.TableItem;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.ui.ISharedImages;
+import org.eclipse.ui.PlatformUI;
+
+/**
+ * Extends the ODA design ui framework to provide a driver-specific custom
+ * editor page to create or edit an ODA data set design instance.
+ */
+public class ExcelFileSelectionWizardPage extends DataSetWizardPage implements
+ ISelectionChangedListener {
+
+ private static String DEFAULT_MESSAGE = Messages
+ .getString("wizard.defaultMessage.selectFile"); //$NON-NLS-1$
+
+ private static final String queryTextDelimiter = ":"; //$NON-NLS-1$
+ private static final String columnsInfoStartSymbol = "{"; //$NON-NLS-1$
+ private static final String columnsInfoEndSymbol = "}"; //$NON-NLS-1$
+
+ private static String name = Messages.getString("editor.title.name"); //$NON-NLS-1$
+ private static String originalName = Messages
+ .getString("editor.title.originalName"); //$NON-NLS-1$
+ private static String dataType = Messages.getString("editor.title.type"); //$NON-NLS-1$
+ private String dateFormat = ExcelODAConstants.DEFAULT_DATE_FORMAT;
+
+ private static String[] dataTypeDisplayNames = new String[] {
+ Messages.getString("datatypes.decimal"), //$NON-NLS-1$
+ Messages.getString("datatypes.float"), //$NON-NLS-1$
+ Messages.getString("datatypes.integer"), //$NON-NLS-1$
+ Messages.getString("datatypes.date"), //$NON-NLS-1$
+ Messages.getString("datatypes.string"), //$NON-NLS-1$
+ Messages.getString("datatypes.boolean") //$NON-NLS-1$
+ };
+
+ private Map<Object, Object> dataTypeDisplayNameMap = new HashMap<Object, Object>();
+
+ private Map<Object, Object> dataTypeValueMape = new HashMap<Object, Object>();
+
+ private final int DEFAULT_WIDTH = 200;
+ private final int DEFAULT_HEIGHT = 200;
+
+ private transient ComboViewer fileViewer = null;
+ private transient ComboViewer worksheetsCombo = null;
+ private transient Text dateFormatText = null;
+ private transient List availableList = null;
+ private transient TableViewer selectedColumnsViewer = null;
+ private transient Button btnAdd = null;
+ private transient Button btnRemove = null;
+ private transient Button btnMoveUp = null;
+ private transient Button btnMoveDown = null;
+
+ private String odaHome;
+ private String inclColumnNameLine;
+ private String inclTypeLine;
+ private String savedSelectedColumnsInfoString;
+
+ /** store latest selected file */
+ private File selectedFile;
+
+ /** store latest selected sheet name */
+ private String currentSheetName;
+
+ private boolean isNewFile;
+
+ private String nameOfFileWithErrorInLastAccess = null;
+
+ private java.util.List<String[]> originalFileColumnsInfoList = new ArrayList<String[]>();
+ private java.util.List<String[]> savedSelectedColumnsInfoList = new ArrayList<String[]>();
+
+ /**
+ * @param pageName
+ */
+ public ExcelFileSelectionWizardPage(String pageName) {
+ super(pageName);
+ setTitle(pageName);
+ createColumnTypeMap();
+ setMessage(DEFAULT_MESSAGE);
+
+ setPageComplete(false);
+ }
+
+ /**
+ * @param pageName
+ * @param title
+ * @param titleImage
+ */
+ public ExcelFileSelectionWizardPage(String pageName, String title,
+ ImageDescriptor titleImage) {
+ super(pageName, title, titleImage);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSetWizardPage
+ * #createPageCustomControl(org.eclipse.swt.widgets.Composite)
+ */
+ public void createPageCustomControl(Composite parent) {
+ setControl(createPageControl(parent));
+ initializeControl();
+
+ Utility.setSystemHelp(getControl(),
+ IHelpConstants.CONEXT_ID_DATASET_EXCEL);
+ }
+
+ /**
+ *
+ *
+ */
+ private void createColumnTypeMap() {
+ dataTypeDisplayNameMap.put(new Integer(4),
+ Messages.getString("datatypes.integer")); //$NON-NLS-1$
+ dataTypeDisplayNameMap.put(new Integer(8),
+ Messages.getString("datatypes.float")); //$NON-NLS-1$
+ dataTypeDisplayNameMap.put(new Integer(12),
+ Messages.getString("datatypes.string")); //$NON-NLS-1$
+ dataTypeDisplayNameMap.put(new Integer(91),
+ Messages.getString("datatypes.date")); //$NON-NLS-1$
+ dataTypeDisplayNameMap.put(new Integer(2),
+ Messages.getString("datatypes.decimal")); //$NON-NLS-1$
+ dataTypeDisplayNameMap.put(new Integer(16),
+ Messages.getString("datatypes.boolean")); //$NON-NLS-1$
+
+ dataTypeValueMape.put(Messages.getString("datatypes.integer"), "INT"); //$NON-NLS-1$ //$NON-NLS-2$
+ dataTypeValueMape.put(Messages.getString("datatypes.float"), //$NON-NLS-1$
+ "DOUBLE"); //$NON-NLS-1$
+ dataTypeValueMape.put(Messages.getString("datatypes.string"), //$NON-NLS-1$
+ "STRING"); //$NON-NLS-1$
+ dataTypeValueMape.put(Messages.getString("datatypes.date"), "DATE"); //$NON-NLS-1$ //$NON-NLS-2$
+ dataTypeValueMape.put(Messages.getString("datatypes.decimal"), //$NON-NLS-1$
+ "BIGDECIMAL"); //$NON-NLS-1$
+ dataTypeValueMape.put(Messages.getString("datatypes.boolean"), //$NON-NLS-1$
+ "BOOLEAN"); //$NON-NLS-1$
+ }
+
+ /**
+ *
+ *
+ */
+ private void initializeControl() {
+ /*
+ * Optionally restores the state of a previous design session. Obtains
+ * designer state, using getInitializationDesignerState();
+ */
+
+ DataSetDesign dataSetDesign = getInitializationDesign();
+ if (dataSetDesign == null)
+ return; // nothing to initialize
+
+ String queryText = dataSetDesign.getQueryText();
+ if (queryText == null)
+ return; // nothing to initialize
+
+ updateValuesFromQuery(queryText);
+
+ if (dataSetDesign.getPublicProperties() != null) {
+ currentSheetName = dataSetDesign.getPublicProperties().getProperty(
+ ExcelODAConstants.CONN_WORKSHEETS_PROP);
+ }
+ if (dataSetDesign.getPublicProperties() != null) {
+ dateFormat = dataSetDesign.getPublicProperties().getProperty(
+ ExcelODAConstants.CONN_DATE_FORMAT_PROP);
+ dateFormat = dateFormat == null ? ExcelODAConstants.DEFAULT_DATE_FORMAT : dateFormat.trim();
+ dateFormatText.setText(dateFormat);
+ }
+ /*
+ * Optionally honor the request for an editable or read-only design
+ * session isSessionEditable();
+ */
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.datatools.connectivity.oda.design.ui.wizards.DataSetWizardPage
+ * #collectDataSetDesign(org.eclipse.datatools.connectivity.oda.design.
+ * DataSetDesign)
+ */
+ protected DataSetDesign collectDataSetDesign(DataSetDesign design) {
+ // if this page in DataSetEditor hasn't been activated
+ if (fileViewer == null)
+ return design;
+
+ savePage(design);
+ return design;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.datatools.connectivity.oda.design.internal.ui.DataSetWizardPage
+ * #collectResponseState()
+ */
+ protected void collectResponseState() {
+ super.collectResponseState();
+ /*
+ * Optionally assigns custom response state, for inclusion in the ODA
+ * design session response, using setResponseSessionStatus(
+ * SessionStatus status ) setResponseDesignerState( DesignerState
+ * customState );
+ */
+ }
+
+ /**
+ *
+ * @param parent
+ * @return
+ */
+ private Control createPageControl(Composite parent) {
+ Composite composite = new Composite(parent, SWT.NULL);
+
+ FormLayout layout = new FormLayout();
+ composite.setLayout(layout);
+
+ FormData data = new FormData();
+ data.left = new FormAttachment(0, 5);
+ data.top = new FormAttachment(0, 5);
+
+ Label label = new Label(composite, SWT.NONE);
+ label.setText(Messages.getString("label.selectFile")); //$NON-NLS-1$
+ label.setLayoutData(data);
+
+ createTopComposite(composite, label);
+
+ createLeftComposite(composite);
+
+ Composite btnComposite = createAddBtnComposite(composite);
+
+ createRightComposite(composite, btnComposite);
+
+ setupEditors();
+
+ loadProperties();
+
+ updateFileList();
+ return composite;
+ }
+
+ /**
+ * Create the top composite of the page
+ *
+ * @param composite
+ * @param label
+ */
+ private void createTopComposite(Composite composite, Label label) {
+ FormData data = new FormData();
+ data.left = new FormAttachment(label, 5);
+ data.right = new FormAttachment(40, -5);
+ fileViewer = new ComboViewer(composite, SWT.BORDER | SWT.READ_ONLY);
+ fileViewer.getControl().setLayoutData(data);
+ fileViewer.setContentProvider(new ArrayContentProvider());
+ fileViewer.addSelectionChangedListener(new ISelectionChangedListener() {
+ @Override
+ public void selectionChanged(SelectionChangedEvent event) {
+ File file = (File) ((IStructuredSelection) event.getSelection())
+ .getFirstElement();
+
+ if (file.equals(selectedFile))
+ {
+ isNewFile = false;
+ return;
+ }
+
+ selectedFile = file;
+ isNewFile = true;
+ populateWorkSheetCombo();
+ }
+ });
+ fileViewer.setLabelProvider(new LabelProvider() {
+ public String getText(Object element) {
+ return ((File) element).getName();
+ }
+ });
+
+ data = new FormData();
+ data.left = new FormAttachment(fileViewer.getControl(), 5);
+ data.top = new FormAttachment(0, 5);
+
+ label = new Label(composite, SWT.NONE);
+ label.setText(Messages.getString("label.selectworksheet")); //$NON-NLS-1$
+ label.setLayoutData(data);
+
+ data = new FormData();
+ data.left = new FormAttachment(label, 5);
+ data.right = new FormAttachment(80, -5);
+ worksheetsCombo = new ComboViewer(composite, SWT.BORDER | SWT.READ_ONLY);
+ worksheetsCombo.getControl().setLayoutData(data);
+ worksheetsCombo.setContentProvider(new ArrayContentProvider());
+ worksheetsCombo.addSelectionChangedListener(this);
+
+ data = new FormData();
+ data.left = new FormAttachment(worksheetsCombo.getControl(), 5);
+ data.top = new FormAttachment(0, 5);
+
+ label = new Label(composite, SWT.NONE);
+ label.setText(Messages.getString("label.dateFormat")); //$NON-NLS-1$
+ label.setLayoutData(data);
+
+ data = new FormData();
+ data.left = new FormAttachment(label, 5);
+ data.right = new FormAttachment(100, -5);
+ dateFormatText = new Text(composite, SWT.BORDER);
+ dateFormatText.setLayoutData(data);
+ dateFormatText.setText(dateFormat);
+ }
+
+ /**
+ * Create the left composite of the page
+ *
+ * @param composite
+ */
+ private void createLeftComposite(Composite composite) {
+ FormData data = new FormData();
+ data.top = new FormAttachment(fileViewer.getControl(), 10, SWT.BOTTOM);
+ data.left = new FormAttachment(0, 5);
+ data.right = new FormAttachment(40, -5);
+ data.bottom = new FormAttachment(100, -5);
+ data.width = DEFAULT_WIDTH;
+ data.height = DEFAULT_HEIGHT;
+ availableList = new List(composite, SWT.MULTI | SWT.BORDER
+ | SWT.H_SCROLL | SWT.V_SCROLL);
+
+ availableList.setLayoutData(data);
+ availableList.addSelectionListener(new SelectionAdapter() {
+
+ public void widgetSelected(SelectionEvent e) {
+ selectedColumnsViewer.getTable().deselectAll();
+ btnAdd.setEnabled(true);
+ btnRemove.setEnabled(false);
+ btnMoveDown.setEnabled(false);
+ btnMoveUp.setEnabled(false);
+ }
+ });
+
+ availableList.addMouseListener(new MouseAdapter() {
+
+ public void mouseDoubleClick(MouseEvent e) {
+ addColumns();
+ }
+ });
+ }
+
+ /**
+ * Create the middle button composite that displays ADD button
+ *
+ * @param composite
+ * @return
+ */
+ private Composite createAddBtnComposite(Composite composite) {
+ FormData data = new FormData();
+ data.top = new FormAttachment(50, 5);
+ data.left = new FormAttachment(availableList, 3);
+
+ Composite btnComposite = new Composite(composite, SWT.NONE);
+ btnComposite.setLayoutData(data);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 1;
+ btnComposite.setLayout(layout);
+
+ btnAdd = new Button(btnComposite, SWT.NONE);
+ GridData gridData = new GridData(GridData.VERTICAL_ALIGN_CENTER
+ | GridData.FILL_HORIZONTAL);
+ gridData.heightHint = 25;
+ btnAdd.setLayoutData(gridData);
+ btnAdd.setToolTipText(Messages.getString("tooltip.button.add"));
+
+ if (btnAdd.getStyle() == (btnAdd.getStyle() | SWT.LEFT_TO_RIGHT)) {
+ btnAdd.setImage(PlatformUI.getWorkbench().getSharedImages()
+ .getImage(ISharedImages.IMG_TOOL_FORWARD));
+ } else {
+ btnAdd.setImage(PlatformUI.getWorkbench().getSharedImages()
+ .getImage(ISharedImages.IMG_TOOL_BACK));
+ }
+
+ btnAdd.addSelectionListener(new SelectionAdapter() {
+
+ public void widgetSelected(SelectionEvent e) {
+ addColumns();
+ }
+ });
+
+ return btnComposite;
+ }
+
+ /**
+ * Create the right composite of the page
+ *
+ * @param composite
+ * @param btnComposite
+ */
+ private void createRightComposite(Composite composite,
+ Composite btnComposite) {
+ FormData data = new FormData();
+ data.top = new FormAttachment(fileViewer.getControl(), 10, SWT.BOTTOM);
+ data.left = new FormAttachment(btnComposite, 3);
+ data.right = new FormAttachment(100, -2);
+ data.bottom = new FormAttachment(100, -5);
+
+ Composite rightComposite = new Composite(composite, SWT.BORDER);
+ rightComposite.setLayoutData(data);
+ GridLayout layout = new GridLayout();
+ layout.numColumns = 2;
+ rightComposite.setLayout(layout);
+
+ selectedColumnsViewer = new TableViewer(rightComposite, SWT.MULTI
+ | SWT.FULL_SELECTION | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
+ selectedColumnsViewer.getTable().setHeaderVisible(true);
+ selectedColumnsViewer.getTable().setLinesVisible(true);
+ selectedColumnsViewer.getTable().setLayoutData(
+ new GridData(GridData.FILL_BOTH));
+
+ TableColumn column = new TableColumn(selectedColumnsViewer.getTable(),
+ SWT.NONE);
+ column.setText(Messages.getString("editor.title.name")); //$NON-NLS-1$
+ column.setWidth(100);
+ column = new TableColumn(selectedColumnsViewer.getTable(), SWT.NONE);
+ column.setText(Messages.getString("editor.title.originalName")); //$NON-NLS-1$
+ column.setWidth(100);
+ column = new TableColumn(selectedColumnsViewer.getTable(), SWT.NONE);
+ column.setText(Messages.getString("editor.title.type")); //$NON-NLS-1$
+ column.setWidth(100);
+
+ selectedColumnsViewer.getTable().addSelectionListener(
+ new SelectionAdapter() {
+
+ public void widgetSelected(SelectionEvent e) {
+ btnAdd.setEnabled(false);
+ availableList.deselectAll();
+
+ int count = selectedColumnsViewer.getTable()
+ .getSelectionCount();
+ int index = selectedColumnsViewer.getTable()
+ .getSelectionIndex();
+ if (count == 1) {
+ btnRemove.setEnabled(true);
+ if (selectedColumnsViewer.getTable().getItemCount() == 1) {
+ btnMoveUp.setEnabled(false);
+ btnMoveDown.setEnabled(false);
+ } else if (index == 0) {
+ btnMoveUp.setEnabled(false);
+ btnMoveDown.setEnabled(true);
+ } else if (index == (selectedColumnsViewer
+ .getTable().getItemCount() - 1)) {
+ btnMoveUp.setEnabled(true);
+ btnMoveDown.setEnabled(false);
+ } else {
+ btnMoveUp.setEnabled(true);
+ btnMoveDown.setEnabled(true);
+ }
+ } else if (count > 1) {
+ btnRemove.setEnabled(true);
+ btnMoveUp.setEnabled(false);
+ btnMoveDown.setEnabled(false);
+ } else {
+ btnRemove.setEnabled(false);
+ btnMoveUp.setEnabled(false);
+ btnMoveDown.setEnabled(false);
+ }
+ }
+ });
+
+ setColumnsViewerContent();
+
+ setColumnsViewerLabels();
+
+ selectedColumnsViewer.getTable().addMouseListener(new MouseAdapter() {
+
+ public void mouseDoubleClick(MouseEvent e) {
+ removeColumns();
+ }
+ });
+
+ createEditBtnGroup(rightComposite);
+ }
+
+ /**
+ * Create the right button group that displays the UP,DOWN and REMOVE
+ * buttons
+ *
+ * @param rightComposite
+ */
+ private void createEditBtnGroup(Composite rightComposite) {
+ Composite btnComposite = new Composite(rightComposite, SWT.NONE);
+ GridLayout layout = new GridLayout();
+ layout.verticalSpacing = 5;
+ btnComposite.setLayout(layout);
+
+ btnMoveUp = new Button(btnComposite, SWT.NONE);
+ btnMoveUp.setText(Messages.getString("button.moveUp"));
+ btnMoveUp.setToolTipText(Messages.getString("tooltip.button.up"));
+ btnMoveUp.addSelectionListener(new SelectionAdapter() {
+
+ public void widgetSelected(SelectionEvent e) {
+ moveUpItem();
+ }
+ });
+
+ btnRemove = new Button(btnComposite, SWT.NONE);
+ btnRemove.setText(Messages.getString("button.delete"));
+ btnRemove.setToolTipText(Messages.getString("tooltip.button.delete"));
+ btnRemove.addSelectionListener(new SelectionAdapter() {
+
+ public void widgetSelected(SelectionEvent e) {
+ removeColumns();
+ }
+ });
+
+ btnMoveDown = new Button(btnComposite, SWT.NONE);
+ btnMoveDown.setText(Messages.getString("button.moveDown"));
+ btnMoveDown.setToolTipText(Messages.getString("tooltip.button.down"));
+ btnMoveDown.addSelectionListener(new SelectionAdapter() {
+
+ public void widgetSelected(SelectionEvent e) {
+ moveDownItem();
+ }
+ });
+
+ resetButtonWidth();
+ }
+
+ private void resetButtonWidth() {
+ int widthHint = Math.max(
+ btnMoveUp.computeSize(SWT.DEFAULT, SWT.DEFAULT).x,
+ btnRemove.computeSize(SWT.DEFAULT, SWT.DEFAULT).x);
+ widthHint = Math.max(widthHint,
+ btnMoveDown.computeSize(SWT.DEFAULT, SWT.DEFAULT).x);
+ widthHint = Math.max(widthHint, 52);
+ GridData btnGd = new GridData();
+ btnGd.widthHint = widthHint;
+ btnMoveUp.setLayoutData(btnGd);
+ btnRemove.setLayoutData(btnGd);
+ btnMoveDown.setLayoutData(btnGd);
+ }
+
+ /**
+ * Set the labels of the ColumnsViewer
+ *
+ */
+ private void setColumnsViewerLabels() {
+ selectedColumnsViewer.setLabelProvider(new ITableLabelProvider() {
+
+ public Image getColumnImage(Object element, int columnIndex) {
+ return null;
+ }
+
+ public String getColumnText(Object element, int columnIndex) {
+ return ((String[]) element)[columnIndex];
+ }
+
+ public void addListener(ILabelProviderListener listener) {
+
+ }
+
+ public void dispose() {
+
+ }
+
+ public boolean isLabelProperty(Object element, String property) {
+ return false;
+ }
+
+ public void removeListener(ILabelProviderListener listener) {
+
+ }
+
+ });
+ }
+
+ /**
+ * Set the content of the ColumnsViewer
+ *
+ */
+ private void setColumnsViewerContent() {
+ selectedColumnsViewer
+ .setContentProvider(new IStructuredContentProvider() {
+
+ public Object[] getElements(Object inputElement) {
+ if (inputElement instanceof java.util.List) {
+ return ((java.util.List<?>) inputElement).toArray();
+ }
+
+ return new Object[0];
+ }
+
+ public void dispose() {
+ }
+
+ public void inputChanged(Viewer viewer, Object oldInput,
+ Object newInput) {
+ }
+ });
+ }
+
+ /**
+ * setup the editors in the table viewer
+ *
+ */
+ private void setupEditors() {
+ CellEditor[] editors = new CellEditor[3];
+ editors[0] = new TextCellEditor(selectedColumnsViewer.getTable(),
+ SWT.NONE);
+ editors[2] = new ComboBoxCellEditor(selectedColumnsViewer.getTable(),
+ dataTypeDisplayNames, SWT.READ_ONLY);
+
+ selectedColumnsViewer.setColumnProperties(new String[] { name,
+ originalName, dataType });
+ selectedColumnsViewer.setCellEditors(editors);
+ selectedColumnsViewer.setCellModifier(new ICellModifier() {
+
+ public boolean canModify(Object element, String property) {
+ return true;
+ }
+
+ public Object getValue(Object element, String property) {
+ Object value = null;
+ if (name.equals(property)) {
+ value = ((String[]) element)[0];
+ } else if (originalName.equals(property)) {
+ value = ((String[]) element)[1];
+ } else if (dataType.equals(property)) {
+ String temp = ((String[]) element)[2];
+ if (temp == null) {
+ value = new Integer(0);
+ } else {
+ for (int i = 0; i < dataTypeDisplayNames.length; i++) {
+ if (temp.equals(dataTypeDisplayNames[i])) {
+ value = new Integer(i);
+ break;
+ }
+ }
+ }
+ }
+ return value;
+ }
+
+ public void modify(Object element, String property, Object value) {
+ String[] actualElement = (String[]) ((TableItem) element)
+ .getData();
+ if (value != null) {
+ if (name.equals(property)) {
+ if (isUnique(actualElement, (String) value)
+ && !isEmpty((String) value)) {
+ replace(actualElement, property, (String) value);
+
+ selectedColumnsViewer.refresh();
+ setMessage(DEFAULT_MESSAGE);
+ } else {
+ setMessage(
+ Messages.getString("error.duplicatedNameValueOrEmpty"), //$NON-NLS-1$
+ WARNING);
+ }
+ } else if (dataType.equals(property)) {
+ int index = ((Integer) value).intValue();
+ if (!(dataTypeDisplayNames[index])
+ .equals(actualElement[2])) {
+ replace(actualElement, property,
+ dataTypeDisplayNames[index]);
+ selectedColumnsViewer.refresh();
+ }
+ }
+ return;
+
+ } else
+ return;
+
+ }
+
+ });
+ }
+
+ /**
+ * see if the value in the selected element of the saved selected columns
+ * information is unique or not
+ *
+ * @param element
+ * the selected element
+ * @param value
+ * the value
+ * @return
+ */
+ private boolean isUnique(String[] element, String value) {
+ for (int i = 0; i < savedSelectedColumnsInfoList.size(); i++) {
+ if (i != savedSelectedColumnsInfoList.indexOf(element)
+ && value.equalsIgnoreCase(((String[]) savedSelectedColumnsInfoList
+ .get(i))[0]))
+ return false;
+ }
+ return true;
+ }
+
+ private boolean isEmpty(String value) {
+ return (value.trim().equals("")); //$NON-NLS-1$
+ }
+
+ /**
+ * get the count of hte existence of the given column name in the already
+ * saved selected columns information
+ *
+ * @param columnName
+ * given column name
+ * @return
+ */
+
+ private int getExistenceCount(String columnName) {
+ int count = 0;
+ java.util.List<Object> existedColumns = new ArrayList<Object>();
+
+ for (int i = 0; i < savedSelectedColumnsInfoList.size(); i++) {
+ if (columnName.equals(((String[]) savedSelectedColumnsInfoList
+ .get(i))[1])) {
+ count++;
+ existedColumns.add(savedSelectedColumnsInfoList.get(i));
+ }
+ }
+
+ for (int j = 0; j < existedColumns.size(); j++) {
+ if ((columnName + "_" + count).equals(((String[]) savedSelectedColumnsInfoList.get(j))[0])) //$NON-NLS-1$
+ {
+ count++;
+ j = -1;
+ }
+ }
+
+ return count;
+ }
+
+ /**
+ * replace the element in the saved selected columns information list
+ *
+ * @param element
+ * the selected element
+ * @param property
+ * the element's selected property
+ * @param value
+ * the value of the selected property in the element
+ */
+ private void replace(String[] element, String property, String value) {
+ int index = savedSelectedColumnsInfoList.indexOf((Object) element);
+
+ if (name.equals(property)) {
+ element[0] = value;
+ savedSelectedColumnsInfoList.set(index, element);
+ } else if (dataType.equals(property)) {
+ element[2] = value;
+ savedSelectedColumnsInfoList.set(index, element);
+ }
+ }
+
+ /*
+ * File Combo Viewer selection changed listener
+ *
+ * @see
+ * org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(
+ * org.eclipse.jface.viewers.SelectionChangedEvent)
+ */
+ public void selectionChanged(SelectionChangedEvent event) {
+ String sheetName = (String) ((IStructuredSelection) event
+ .getSelection()).getFirstElement();
+
+ if (!isNewFile && sheetName.equalsIgnoreCase(currentSheetName))
+ return;
+
+ else if (!isNewFile && !MessageDialog.openConfirm(worksheetsCombo.getControl()
+ .getShell(), Messages
+ .getString("confirm.reselectWorksheetTitle"), //$NON-NLS-1$
+ Messages.getString("confirm.reselectWorksheetMessage"))) //$NON-NLS-1$
+ {
+ worksheetsCombo.setSelection(new StructuredSelection(
+ currentSheetName));
+ return;
+ }
+
+ currentSheetName = sheetName;
+ setPageComplete(false);
+ selectedColumnsViewer.getTable().removeAll();
+ savedSelectedColumnsInfoList.clear();
+ availableList.removeAll();
+ nameOfFileWithErrorInLastAccess = null;
+
+ String fileName = selectedFile.getName();
+ String[] columnNames = getFileColumnNames(selectedFile);
+
+ if (columnNames != null && columnNames.length != 0) {
+ enableListAndViewer();
+ availableList.setItems(columnNames);
+ availableList.select(0);
+ btnRemove.setEnabled(false);
+ btnMoveUp.setEnabled(false);
+ btnMoveDown.setEnabled(false);
+ if (!(fileName.endsWith(ExcelODAConstants.XLS_FORMAT) || fileName
+ .endsWith(ExcelODAConstants.XLSX_FORMAT))) {
+ setMessage(Messages.getString("warning.fileExtensionInvalid"), //$NON-NLS-1$
+ WARNING);
+ } else
+ setMessage(DEFAULT_MESSAGE);
+ }
+ }
+
+ /**
+ * Load the custom properties
+ */
+ private void loadProperties() {
+ java.util.Properties dataSourceProps = null;
+ try {
+ dataSourceProps = DesignSessionUtil
+ .getEffectiveDataSourceProperties(getInitializationDesign()
+ .getDataSourceDesign());
+ } catch (OdaException e) {
+ this.setMessage(e.getLocalizedMessage(), ERROR);
+ return;
+ }
+
+ String sourcePath = dataSourceProps
+ .getProperty(ConnectionProfileProperty.PROFILE_STORE_FILE_PATH_PROP_KEY);
+ if (sourcePath != null) {
+ File cpFile = new File(sourcePath);
+ if (!cpFile.exists()) {
+ setMessage(
+ Messages.getFormattedString(
+ "error.invalidConnectionFilePath", new Object[] { cpFile.getPath() }), ERROR); //$NON-NLS-1$
+ return;
+ }
+ }
+
+ odaHome = dataSourceProps
+ .getProperty(ExcelODAConstants.CONN_HOME_DIR_PROP);
+ inclColumnNameLine = dataSourceProps
+ .getProperty(ExcelODAConstants.CONN_INCLCOLUMNNAME_PROP);
+ inclTypeLine = dataSourceProps
+ .getProperty(ExcelODAConstants.CONN_INCLTYPELINE_PROP);
+
+ DataSetDesign dataSetDesign = getInitializationDesign();
+ if (dataSetDesign == null)
+ return; // nothing to initialize
+
+ if (dataSetDesign.getPublicProperties() != null) {
+ currentSheetName = dataSetDesign.getPublicProperties().getProperty(
+ ExcelODAConstants.CONN_WORKSHEETS_PROP);
+ }
+ if (dataSetDesign.getPublicProperties() != null) {
+ dateFormat = dataSetDesign.getPublicProperties().getProperty(
+ ExcelODAConstants.CONN_DATE_FORMAT_PROP);
+ }
+ }
+
+ /**
+ * Update file list in combo viewer
+ */
+ private void updateFileList() {
+ if (fileViewer != null && !fileViewer.getControl().isDisposed()) {
+ if (odaHome == null) {
+ disableAll();
+ return;
+ }
+
+ File folder = new File(odaHome);
+ FilenameFilter filenameFilter = new FilenameFilter() {
+ @Override
+ public boolean accept(File dir, String fileName) {
+ File file = new File(dir + File.separator + fileName);
+ if (file.isFile() && !file.isHidden()) {
+ if (fileName.endsWith(ExcelODAConstants.XLS_FORMAT)
+ || fileName
+ .endsWith(ExcelODAConstants.XLSX_FORMAT))
+ return true;
+
+ return false;
+ } else
+ return false;
+ }
+ };
+ if (folder.isDirectory() && folder.exists()) {
+ File[] files = folder.getAbsoluteFile().listFiles(
+ filenameFilter);
+
+ if (files != null) {
+ fileViewer.setInput(files);
+ } else {
+ fileViewer.setInput(new File[] {});
+ }
+ } else {
+ fileViewer.setInput(new File[] {});
+ }
+ File[] files = (File[]) fileViewer.getInput();
+ if (files.length > 0) {
+ enableListAndViewer();
+ File toSelectFile = null;
+ if (selectedFile != null)
+ for (int i = 0; i < files.length; i++) {
+ if (files[i].equals(selectedFile)) {
+ toSelectFile = selectedFile;
+ break;
+ }
+ }
+ if (toSelectFile == null)
+ toSelectFile = files[0];
+
+ fileViewer.setSelection(new StructuredSelection(toSelectFile));
+ if (!(nameOfFileWithErrorInLastAccess != null && nameOfFileWithErrorInLastAccess
+ .equals(fileViewer.getCombo().getText())))
+ setMessage(DEFAULT_MESSAGE);
+ } else {
+ setMessage(Messages
+ .getFormattedString(
+ "error.noFiles", new Object[] { folder.getAbsolutePath() })); //$NON-NLS-1$
+ disableAll();
+ }
+ }
+ }
+
+ /**
+ * Returns all the column names found in given excelfile.
+ *
+ * @param file
+ * @return
+ */
+ private String[] getFileColumnNames(File file) {
+ java.util.List<String[]> propList = getQueryColumnsInfo(
+ "select * from " + QueryTextUtil.getQuotedName(file.getName()), file, currentSheetName); //$NON-NLS-1$
+
+ String[] result;
+ if (propList != null) {
+ originalFileColumnsInfoList = new ArrayList<String[]>(propList);
+ result = new String[propList.size()];
+ for (int i = 0; i < propList.size(); i++)
+ result[i] = ((String[]) propList.get(i))[1];
+ } else
+ result = new String[0];
+
+ return result;
+ }
+
+ /**
+ *
+ * @param queryText
+ * @param file
+ * @return
+ */
+ private java.util.List<String[]> getQueryColumnsInfo(String queryText,
+ File file, String sheetName) {
+ IDriver excelDriver = new Driver();
+ IConnection conn = null;
+ java.util.List<String[]> columnList = new ArrayList<String[]>();
+ try {
+ conn = excelDriver.getConnection(null);
+ IResultSetMetaData metadata = getResultSetMetaData(queryText, file,
+ conn, sheetName);
+
+ int columnCount = metadata.getColumnCount();
+ if (columnCount == 0)
+ return new ArrayList<String[]>();
+
+ for (int i = 0; i < columnCount; i++) {
+ String[] result = new String[3];
+ result[0] = metadata.getColumnName(i + 1);
+
+ result[1] = getOriginalColumnName(result[0],
+ savedSelectedColumnsInfoString, metadata);
+
+ result[2] = getDataTypeDisplayName(new Integer(
+ metadata.getColumnType(i + 1)));
+ columnList.add(result);
+ }
+ return columnList;
+ } catch (OdaException e) {
+ setMessage(e.getLocalizedMessage(), ERROR);
+ updateExceptionInfo();
+ return new ArrayList<String[]>();
+ } finally {
+ closeConnection(conn);
+ }
+
+ }
+
+ private void updateExceptionInfo() {
+ nameOfFileWithErrorInLastAccess = fileViewer.getCombo().getText();
+ if (availableList.getItemCount() == 0)
+ disableAvailableListAndButtons();
+ }
+
+ /**
+ *
+ *
+ */
+ private void disableAvailableListAndButtons() {
+ availableList.setEnabled(false);
+ btnAdd.setEnabled(false);
+ btnRemove.setEnabled(false);
+ btnMoveDown.setEnabled(false);
+ btnMoveUp.setEnabled(false);
+ }
+
+ /**
+ * get the data type display name
+ *
+ * @param type
+ * @return
+ */
+ private String getDataTypeDisplayName(Integer type) {
+ if (dataTypeDisplayNameMap.get(type) != null)
+ return (String) dataTypeDisplayNameMap.get(type);
+ else
+ return Messages.getString("datatypes.string"); //$NON-NLS-1$
+ }
+
+ /**
+ *
+ * @param displayName
+ * @return
+ */
+ private String getDataTypeValue(String displayName) {
+ if (dataTypeValueMape.get(displayName) != null)
+ return (String) dataTypeValueMape.get(displayName);
+ else
+ return "STRING"; //$NON-NLS-1$
+ }
+
+ /**
+ * Get the original column name in the excelfile of the given column name
+ *
+ * @param name
+ * @param columnsInfo
+ * @param metadata
+ * @return
+ */
+ private String getOriginalColumnName(String name, String columnsInfo,
+ IResultSetMetaData metadata) {
+ String originalName = null;
+ if (columnsInfo.length() != 0) {
+ ColumnsInfoUtil ciu = new ColumnsInfoUtil(columnsInfo);
+ String[] names = ciu.getColumnNames();
+ for (int i = 0; i < names.length; i++) {
+ if (name.equals(names[i])) {
+ originalName = ciu.getOriginalColumnNames()[i];
+ break;
+ }
+ }
+ }
+
+ // if this name was not selected in the viewer
+ if (originalName == null) {
+
+ try {
+ for (int j = 0; j < metadata.getColumnCount(); j++) {
+ if (name.equals(metadata.getColumnName(j + 1)))
+ originalName = name;
+ }
+ } catch (OdaException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ return originalName;
+ }
+
+ /**
+ * Attempts to close given ODA connection.
+ *
+ * @param conn
+ */
+ private void closeConnection(IConnection conn) {
+ try {
+ if (conn != null)
+ conn.close();
+ } catch (OdaException e) {
+ // ignore
+ }
+ }
+
+ /**
+ *
+ * @param queryText
+ * @param file
+ * @param conn
+ * @param sheetName
+ * @return
+ * @throws OdaException
+ */
+ private IResultSetMetaData getResultSetMetaData(String queryText,
+ File file, IConnection conn, String sheetName) throws OdaException {
+ java.util.Properties prop = new java.util.Properties();
+ if (file != null) {
+ if (file.getParent() == null) {
+ throw new OdaException(
+ Messages.getString("error.unexpectedError")); //$NON-NLS-1$
+ }
+ prop.put(ExcelODAConstants.CONN_HOME_DIR_PROP, file.getParent());
+ }
+ if (inclColumnNameLine != null) {
+ prop.put(ExcelODAConstants.CONN_INCLCOLUMNNAME_PROP,
+ inclColumnNameLine);
+ }
+ if (inclTypeLine != null) {
+ prop.put(ExcelODAConstants.CONN_INCLTYPELINE_PROP, inclTypeLine);
+ }
+
+ savedSelectedColumnsInfoString = (new QueryTextUtil(queryText))
+ .getColumnsInfo();
+
+ conn.open(prop);
+
+ IQuery query = conn.newQuery(null);
+ query.setProperty(ExcelODAConstants.CONN_WORKSHEETS_PROP, sheetName);
+ query.setMaxRows(1);
+ query.prepare(queryText);
+ query.executeQuery();
+
+ return query.getMetaData();
+ }
+
+ /**
+ * Enable all control of this page
+ */
+ private void enableListAndViewer() {
+ availableList.setEnabled(true);
+ selectedColumnsViewer.getTable().setEnabled(true);
+ }
+
+ /**
+ * Disable all control of this page
+ */
+ private void disableAll() {
+ availableList.setEnabled(false);
+ selectedColumnsViewer.getTable().setEnabled(false);
+ btnAdd.setEnabled(false);
+ btnRemove.setEnabled(false);
+ btnMoveUp.setEnabled(false);
+ btnMoveDown.setEnabled(false);
+ setPageComplete(false);
+ }
+
+ /**
+ * display the content of the list in the table viewer
+ *
+ * @param list
+ * list that contains the dispay content
+ * @param tViewer
+ * the table viewer
+ */
+ private void setDisplayContent(java.util.List<String[]> list,
+ TableViewer tViewer) {
+ tViewer.getTable().removeAll();
+ tViewer.setInput(list);
+ tViewer.getTable().select(tViewer.getTable().getTopIndex());
+ }
+
+ /**
+ * get the query text(select clause) of this data set
+ *
+ * @return query
+ *
+ */
+ private String getQuery() {
+ if (selectedColumnsViewer.getTable().getItemCount() == 0)
+ return ""; //$NON-NLS-1$
+
+ String tableName = null;
+ StringBuffer buf = new StringBuffer();
+ File file = (File) ((StructuredSelection) fileViewer.getSelection())
+ .getFirstElement();
+ if (file != null) {
+ tableName = file.getName();
+ }
+ if (tableName != null) {
+ tableName = QueryTextUtil.getQuotedName(tableName);
+ if (availableList.getItemCount() == 0) {
+ buf.append("select * from ").append(tableName); //$NON-NLS-1$
+ } else {
+ buf.append("select "); //$NON-NLS-1$
+ String[] columns = new String[selectedColumnsViewer.getTable()
+ .getItemCount()];
+ for (int m = 0; m < columns.length; m++)
+ columns[m] = selectedColumnsViewer.getTable().getItem(m)
+ .getText(1);
+
+ for (int n = 0; n < columns.length; n++) {
+ StringBuffer sb = new StringBuffer();
+ char[] columnChars = columns[n].toCharArray();
+ for (int i = 0; i < columnChars.length; i++) {
+ if (columnChars[i] == '"')
+ sb.append("\\\""); //$NON-NLS-1$
+ else if (columnChars[i] == '\\')
+ sb.append("\\\\"); //$NON-NLS-1$
+ else
+ sb.append(columnChars[i]);
+ }
+
+ buf.append(ExcelODAConstants.DELIMITER_DOUBLEQUOTE
+ + sb.toString()
+ + ExcelODAConstants.DELIMITER_DOUBLEQUOTE);
+ if (n < columns.length - 1) {
+ buf.append(", "); //$NON-NLS-1$
+ }
+ }
+ buf.append(" from ").append(tableName); //$NON-NLS-1$
+ }
+ }
+ return buf.toString();
+ }
+
+ /**
+ * Update value of query text
+ *
+ * @param queryText
+ */
+
+ private void updateValuesFromQuery(String queryText) {
+ if (queryText.length() == 0)
+ return;
+
+ try {
+ String query = (new QueryTextUtil(queryText)).getQuery();
+ String[] metadata = QueryTextUtil.getQueryMetaData(query);
+
+ // The query must have a table name and columns.
+ if (metadata != null && metadata[0] != null && metadata[2] != null) {
+ // Now select the table in the list. If it doesn't exists, no
+ // need to process the columns.
+ File f = selectTableFromQuery(metadata[2]);
+ if (f != null) {
+ updateColumnsFromQuery(queryText, f);
+ }
+ }
+ } catch (OdaException e) {
+ setMessage(e.getLocalizedMessage(), ERROR);
+ updateExceptionInfo();
+ }
+
+ if (selectedColumnsViewer.getTable().getItemCount() == 0) {
+ setPageComplete(false);
+ }
+ }
+
+ /**
+ *
+ * @param queryText
+ * @param file
+ */
+ private void updateColumnsFromQuery(String queryText, File file) {
+ availableList.setItems(getFileColumnNames(file));
+ selectedColumnsViewer.getTable().removeAll();
+
+ savedSelectedColumnsInfoList.clear();
+
+ savedSelectedColumnsInfoList = getQueryColumnsInfo(queryText, file,
+ currentSheetName);
+
+ setDisplayContent(savedSelectedColumnsInfoList, selectedColumnsViewer);
+
+ setPageComplete(true);
+ btnAdd.setEnabled(false);
+ btnRemove.setEnabled(false);
+ btnMoveUp.setEnabled(false);
+ btnMoveDown.setEnabled(false);
+ if (selectedColumnsViewer.getTable().getItemCount() == 0) {
+ setPageComplete(false);
+ }
+ }
+
+ /**
+ * @param tableName
+ * @return File
+ */
+ private File selectTableFromQuery(String tableName) {
+ // for page refresh
+ File[] files = (File[]) fileViewer.getInput();
+ if (files != null) {
+ for (int n = 0; n < files.length; n++) {
+ if (files[n].getName().equalsIgnoreCase(tableName)) {
+ fileViewer.setSelection(new StructuredSelection(files[n]));
+ isNewFile = false;
+ return files[n];
+ }
+ }
+ }
+ return null;
+ }
+
+ private void moveUpItem() {
+ int count = selectedColumnsViewer.getTable().getItemCount();
+ int index = selectedColumnsViewer.getTable().getSelectionIndex();
+
+ if (index > 0 && index < count) {
+ if (!btnMoveDown.isEnabled())
+ btnMoveDown.setEnabled(true);
+
+ String[] obj = savedSelectedColumnsInfoList.get(index);
+ savedSelectedColumnsInfoList.set(index,
+ savedSelectedColumnsInfoList.get(index - 1));
+ savedSelectedColumnsInfoList.set(index - 1, obj);
+ selectedColumnsViewer.refresh();
+ selectedColumnsViewer.getTable().setSelection(index - 1);
+ }
+
+ if (index == 1)
+ btnMoveUp.setEnabled(false);
+ }
+
+ private void moveDownItem() {
+ int count = selectedColumnsViewer.getTable().getItemCount();
+ int index = selectedColumnsViewer.getTable().getSelectionIndex();
+
+ if (index > -1 && index < count - 1) {
+ if (!btnMoveUp.isEnabled())
+ btnMoveUp.setEnabled(true);
+
+ String[] obj = savedSelectedColumnsInfoList.get(index);
+ savedSelectedColumnsInfoList.set(index,
+ savedSelectedColumnsInfoList.get(index + 1));
+ savedSelectedColumnsInfoList.set(index + 1, obj);
+ selectedColumnsViewer.refresh();
+ selectedColumnsViewer.getTable().setSelection(index + 1);
+ }
+
+ if (index == count - 2)
+ btnMoveDown.setEnabled(false);
+ }
+
+ /**
+ * Add selectd columns
+ */
+
+ private void addColumns() {
+ java.util.List<String[]> addedItems = createAddedColumnsInfo(availableList
+ .getSelection());
+
+ for (int i = 0; i < addedItems.size(); i++) {
+ savedSelectedColumnsInfoList.add(addedItems.get(i));
+ }
+
+ setDisplayContent(savedSelectedColumnsInfoList, selectedColumnsViewer);
+
+ selectedColumnsViewer.getTable().setSelection(
+ selectedColumnsViewer.getTable().getItemCount() - 1);
+
+ int nextSelectionIndex = availableList.getSelectionIndex() + 1;
+ if (nextSelectionIndex < availableList.getItemCount()) {
+ availableList.setSelection(nextSelectionIndex);
+ btnAdd.setEnabled(true);
+ } else if (availableList.getSelectionCount() == 0) {
+ btnAdd.setEnabled(false);
+ }
+
+ selectedColumnsViewer.getTable().setSelection(-1);
+
+ setMessage(DEFAULT_MESSAGE);
+ setPageComplete(true);
+ }
+
+ /**
+ * create a list of the columns info in accordience to the given column
+ * names
+ *
+ * @param addedColumnNames
+ * @return
+ */
+ private java.util.List<String[]> createAddedColumnsInfo(
+ String[] addedColumnNames) {
+ java.util.List<String[]> addedColumnsInfo = new ArrayList<String[]>();
+ int count = 0;
+
+ for (int i = 0; i < addedColumnNames.length; i++) {
+ count = getExistenceCount(addedColumnNames[i]);
+ String[] addedColumns;
+ addedColumns = new String[3];
+ if (count == 0)
+ addedColumns[0] = addedColumnNames[i];
+ else
+ addedColumns[0] = addedColumnNames[i] + "_" + count; //$NON-NLS-1$
+
+ addedColumns[1] = addedColumnNames[i];
+ addedColumns[2] = getColumnTypeName(addedColumnNames[i]);
+
+ addedColumnsInfo.add(addedColumns);
+ }
+
+ return addedColumnsInfo;
+ }
+
+ /**
+ *
+ * @param columnName
+ * @return
+ */
+ private String getColumnTypeName(String columnName) {
+ for (int i = 0; i < originalFileColumnsInfoList.size(); i++) {
+ if (columnName.equals(((String[]) originalFileColumnsInfoList
+ .get(i))[1]))
+ return ((String[]) originalFileColumnsInfoList.get(i))[2];
+ }
+ return null;
+ }
+
+ /**
+ * Remove selected columns
+ */
+ private void removeColumns() {
+ TableItem[] tis = selectedColumnsViewer.getTable().getSelection();
+ int index = selectedColumnsViewer.getTable().getSelectionIndex();
+ String[] removedColumnInfo = null;
+
+ java.util.List<String[]> removedItems = new ArrayList<String[]>();
+ for (int i = 0; i < tis.length; i++) {
+ removedColumnInfo = new String[3];
+ removedColumnInfo[0] = tis[i].getText(0);
+ removedColumnInfo[1] = tis[i].getText(1);
+ removedColumnInfo[2] = tis[i].getText(2);
+ removedItems.add(removedColumnInfo);
+ }
+
+ removeItemsFromSelectedOnes(removedItems);
+
+ selectedColumnsViewer.refresh();
+
+ if (index > 0)
+ selectedColumnsViewer.getTable().setSelection(index - 1);
+ else
+ selectedColumnsViewer.getTable().setSelection(index);
+
+ if (selectedColumnsViewer.getTable().getSelectionCount() == 0)
+ btnRemove.setEnabled(false);
+
+ if (savedSelectedColumnsInfoList.size() <= 1) {
+ btnMoveDown.setEnabled(false);
+ btnMoveUp.setEnabled(false);
+ }
+
+ if (selectedColumnsViewer.getTable().getItemCount() == 0) {
+ setPageComplete(false);
+ }
+ }
+
+ /**
+ * remove the given items from the saved selectedComlumnsInfo
+ *
+ * @param removedItemsList
+ * list that contains the given elements that are going to be
+ * removed
+ */
+ private void removeItemsFromSelectedOnes(
+ java.util.List<String[]> removedItemsList) {
+ for (int i = 0; i < removedItemsList.size(); i++) {
+ for (int j = 0; j < savedSelectedColumnsInfoList.size(); j++) {
+ if (removedItemsList.get(i)[0]
+ .equals(savedSelectedColumnsInfoList.get(j)[0])
+ && ((String[]) removedItemsList.get(i))[1]
+ .equals(((String[]) savedSelectedColumnsInfoList
+ .get(j))[1])
+ && ((String[]) removedItemsList.get(i))[2]
+ .equals(((String[]) savedSelectedColumnsInfoList
+ .get(j))[2])) {
+ savedSelectedColumnsInfoList.remove(j);
+ break;
+ }
+
+ }
+ }
+ }
+
+ /**
+ * Updates the given dataSetDesign with the query and its metadata defined
+ * in this page.
+ *
+ * @param dataSetDesign
+ */
+ private void savePage(DataSetDesign dataSetDesign) {
+ String queryText = getQueryText();
+ /*if (queryText.equals(dataSetDesign.getQueryText()))
+ return;*/
+ dataSetDesign.setQueryText(queryText);
+
+ // obtain query's result set metadata, and update
+ // the dataSetDesign with it
+ IConnection conn = null;
+ try {
+ IDriver excelDriver = new Driver();
+ conn = excelDriver.getConnection(null);
+ IResultSetMetaData metadata = getResultSetMetaData(queryText,
+ selectedFile, conn, currentSheetName);
+ savePublicProperties(dataSetDesign);
+ setResultSetMetaData(dataSetDesign, metadata);
+ } catch (OdaException e) {
+ // no result set definition available, reset in dataSetDesign
+ dataSetDesign.setResultSets(null);
+ } finally {
+ closeConnection(conn);
+ }
+
+ /*
+ * See DesignSessionUtil for more convenience methods to define a data
+ * set design instance.
+ */
+
+ /*
+ * Since this excelfile driver does not support query parameters and
+ * properties, there are no data set parameters and public/private
+ * properties to specify in the data set design instance
+ */
+ }
+
+ private void savePublicProperties(DataSetDesign dataSetDesign) {
+ if (dataSetDesign.getPublicProperties() == null) {
+ try {
+ String dsID = dataSetDesign.getOdaExtensionDataSourceId();
+ String dstID = dataSetDesign.getOdaExtensionDataSetId();
+ Properties dsProp = DesignSessionUtil
+ .createDataSetPublicProperties(dsID, dstID,
+ getPageProperties());
+ dataSetDesign.setPublicProperties(dsProp);
+ } catch (OdaException e) {
+ e.printStackTrace();
+ }
+ }
+
+ else if (dataSetDesign.getPublicProperties() != null) {
+ if (dataSetDesign.getPublicProperties().findProperty(
+ ExcelODAConstants.CONN_WORKSHEETS_PROP) != null)
+ dataSetDesign
+ .getPublicProperties()
+ .findProperty(ExcelODAConstants.CONN_WORKSHEETS_PROP)
+ .setNameValue(ExcelODAConstants.CONN_WORKSHEETS_PROP,
+ currentSheetName);
+ if (dataSetDesign.getPublicProperties().findProperty(
+ ExcelODAConstants.CONN_DATE_FORMAT_PROP) != null)
+ dateFormat = dateFormatText.getText();
+ dateFormat = dateFormat != null ? dateFormat.trim() : ExcelODAConstants.DEFAULT_DATE_FORMAT;
+ dataSetDesign
+ .getPublicProperties()
+ .findProperty(ExcelODAConstants.CONN_DATE_FORMAT_PROP)
+ .setNameValue(ExcelODAConstants.CONN_DATE_FORMAT_PROP,
+ dateFormat);
+ }
+
+ }
+
+ private java.util.Properties getPageProperties() {
+ java.util.Properties prop = new java.util.Properties();
+ if (inclColumnNameLine != null) {
+ prop.put(ExcelODAConstants.CONN_INCLCOLUMNNAME_PROP,
+ inclColumnNameLine);
+ }
+ if (inclTypeLine != null) {
+ prop.put(ExcelODAConstants.CONN_INCLTYPELINE_PROP, inclTypeLine);
+ }
+ if (currentSheetName != null) {
+ prop.put(ExcelODAConstants.CONN_WORKSHEETS_PROP, currentSheetName);
+ }
+
+ return prop;
+ }
+
+ /**
+ * Gets the query text
+ *
+ * @return query text
+ */
+ private String getQueryText() {
+ String query = getQuery();
+ String queryText = query.length() > 0 ? query
+ + ExcelODAConstants.DELIMITER_SPACE + queryTextDelimiter
+ + ExcelODAConstants.DELIMITER_SPACE + columnsInfoStartSymbol
+ + createSelectedColumnsInfoString() + columnsInfoEndSymbol : ""; //$NON-NLS-1$
+ return queryText;
+ }
+
+ /**
+ * create the SelectedColumnsinfo string
+ *
+ * @param dataSetDesign
+ * the current dataSetDesign
+ * @return String that contains the seleced columns infomation
+ */
+ private String createSelectedColumnsInfoString() {
+ String prop = ""; //$NON-NLS-1$
+ // If the length is equal to 2 then we have a valid query
+
+ for (int i = 0; i < savedSelectedColumnsInfoList.size(); i++) {
+ char[] columnNameChars = ((String[]) savedSelectedColumnsInfoList
+ .get(i))[0].toCharArray();
+ StringBuffer columnNameBuf = new StringBuffer();
+
+ char[] originalColumnNameChars = ((String[]) savedSelectedColumnsInfoList
+ .get(i))[1].toCharArray();
+ StringBuffer originalColumnNameBuf = new StringBuffer();
+ for (int m = 0; m < columnNameChars.length; m++) {
+ if (ColumnsInfoUtil.isColumnsInfoKeyWord(columnNameChars[m]))
+ columnNameBuf.append("\\" + columnNameChars[m]); //$NON-NLS-1$
+ else
+ columnNameBuf.append(columnNameChars[m]);
+
+ }
+
+ prop = prop + ExcelODAConstants.DELIMITER_DOUBLEQUOTE
+ + columnNameBuf.toString()
+ + ExcelODAConstants.DELIMITER_DOUBLEQUOTE
+ + ExcelODAConstants.DELIMITER_COMMA_VALUE;
+
+ for (int m = 0; m < originalColumnNameChars.length; m++) {
+ if (ColumnsInfoUtil
+ .isColumnsInfoKeyWord(originalColumnNameChars[m]))
+ originalColumnNameBuf.append("\\" //$NON-NLS-1$
+ + originalColumnNameChars[m]);
+ else
+ originalColumnNameBuf.append(originalColumnNameChars[m]);
+
+ }
+
+ prop = prop + ExcelODAConstants.DELIMITER_DOUBLEQUOTE
+ + originalColumnNameBuf.toString()
+ + ExcelODAConstants.DELIMITER_DOUBLEQUOTE
+ + ExcelODAConstants.DELIMITER_COMMA_VALUE;
+
+ if (i != savedSelectedColumnsInfoList.size() - 1) {
+ prop = prop
+ + getDataTypeValue(((String[]) savedSelectedColumnsInfoList
+ .get(i))[2])
+ + ExcelODAConstants.DELIMITER_SEMICOLON_VALUE;
+ } else {
+ prop = prop
+ + getDataTypeValue(((String[]) savedSelectedColumnsInfoList
+ .get(i))[2]);
+ }
+
+ }
+
+ savedSelectedColumnsInfoString = prop;
+
+ return savedSelectedColumnsInfoString;
+
+ }
+
+ /**
+ *
+ * @param dataSetDesign
+ * @param md
+ * @throws OdaException
+ */
+ private void setResultSetMetaData(DataSetDesign dataSetDesign,
+ IResultSetMetaData md) throws OdaException {
+ ResultSetColumns columns = DesignSessionUtil
+ .toResultSetColumnsDesign(md);
+
+ ResultSetDefinition resultSetDefn = DesignFactory.eINSTANCE
+ .createResultSetDefinition();
+ // excel file does not support result set name
+ resultSetDefn.setResultSetColumns(columns);
+
+ // no exception; go ahead and assign to specified dataSetDesign
+ dataSetDesign.setPrimaryResultSet(resultSetDefn);
+ dataSetDesign.getResultSets().setDerivedMetaData(true);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jface.dialogs.DialogPage#setVisible(boolean)
+ */
+ public void setVisible(boolean visible) {
+ super.setVisible(visible);
+ getControl().setFocus();
+ }
+
+ private void populateWorkSheetCombo() {
+ java.util.List<String> sheetNameList = ExcelFileReader
+ .getSheetNamesInExcelFile(selectedFile);
+ worksheetsCombo.setInput(sheetNameList.toArray());
+ for (String sheet : sheetNameList) {
+ if (sheet.equals(currentSheetName))
+ worksheetsCombo.setSelection(new StructuredSelection(
+ currentSheetName));
+ }
+ }
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/.classpath b/data/org.eclipse.birt.report.data.oda.excel/.classpath
new file mode 100644
index 0000000..45e8b66
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/.classpath
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry exported="true" kind="lib"
+ path="lib/lib/commons-logging-1.1.jar" />
+ <classpathentry exported="true" kind="lib"
+ path="lib/lib/junit-3.8.1.jar" />
+ <classpathentry exported="true" kind="lib"
+ path="lib/lib/log4j-1.2.13.jar" />
+ <classpathentry exported="true" kind="lib"
+ path="lib/ooxml-lib/dom4j-1.6.1.jar" />
+ <classpathentry exported="true" kind="lib"
+ path="lib/ooxml-lib/geronimo-stax-api_1.0_spec-1.0.jar" />
+ <classpathentry exported="true" kind="lib"
+ path="lib/ooxml-lib/xmlbeans-2.3.0.jar" />
+ <classpathentry exported="true" kind="lib"
+ path="lib/poi-3.7-20101029.jar" />
+ <classpathentry exported="true" kind="lib"
+ path="lib/poi-examples-3.7-20101029.jar" />
+ <classpathentry exported="true" kind="lib"
+ path="lib/poi-ooxml-3.7-20101029.jar" />
+ <classpathentry exported="true" kind="lib"
+ path="lib/poi-ooxml-schemas-3.7-20101029.jar" />
+ <classpathentry exported="true" kind="lib"
+ path="lib/poi-scratchpad-3.7-20101029.jar" />
+ <classpathentry exported="true" kind="lib" path="lib/resolver.jar" />
+ <classpathentry exported="true" kind="lib"
+ path="lib/serializer.jar" />
+ <classpathentry exported="true" kind="lib"
+ path="lib/xercesImpl.jar" />
+ <classpathentry exported="true" kind="lib"
+ path="lib/xercesSamples.jar" />
+ <classpathentry exported="true" kind="lib" path="lib/xml-apis.jar" />
+ <classpathentry kind="con"
+ path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6" />
+ <classpathentry kind="con"
+ path="org.eclipse.pde.core.requiredPlugins" />
+ <classpathentry kind="src" path="src" />
+ <classpathentry kind="output" path="bin" />
+</classpath>
diff --git a/data/org.eclipse.birt.report.data.oda.excel/.project b/data/org.eclipse.birt.report.data.oda.excel/.project
new file mode 100644
index 0000000..e71e6cb
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.birt.report.data.oda.excel</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/data/org.eclipse.birt.report.data.oda.excel/.settings/org.eclipse.jdt.core.prefs b/data/org.eclipse.birt.report.data.oda.excel/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000..ab0cf61
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,8 @@
+#Tue Aug 30 01:56:44 IST 2011
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
diff --git a/data/org.eclipse.birt.report.data.oda.excel/META-INF/MANIFEST.MF b/data/org.eclipse.birt.report.data.oda.excel/META-INF/MANIFEST.MF
new file mode 100644
index 0000000..1a6c6f5
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/META-INF/MANIFEST.MF
@@ -0,0 +1,30 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: %plugin.name
+Bundle-SymbolicName: org.eclipse.birt.report.data.oda.excel; singleton:=true
+Bundle-Version: 1.0.0.qualifier
+Bundle-ClassPath: .,
+ src,
+ lib/poi-3.7/poi-3.7-20101029.jar,
+ lib/poi-3.7/poi-examples-3.7-20101029.jar,
+ lib/poi-3.7/poi-ooxml-3.7-20101029.jar,
+ lib/poi-3.7/poi-ooxml-schemas-3.7-20101029.jar,
+ lib/poi-3.7/poi-scratchpad-3.7-20101029.jar,
+ lib/poi-3.7/lib/commons-logging-1.1.jar,
+ lib/poi-3.7/lib/junit-3.8.1.jar,
+ lib/poi-3.7/lib/log4j-1.2.13.jar,
+ lib/poi-3.7/ooxml-lib/dom4j-1.6.1.jar,
+ lib/poi-3.7/ooxml-lib/geronimo-stax-api_1.0_spec-1.0.jar,
+ lib/poi-3.7/ooxml-lib/xmlbeans-2.3.0.jar
+Bundle-Activator: org.eclipse.birt.report.data.oda.excel.Activator
+Bundle-Vendor: Megha Nidhi Dahal
+Bundle-Localization: plugin
+Export-Package: org.eclipse.birt.report.data.oda.excel,
+ org.eclipse.birt.report.data.oda.excel.impl;version="1.0.0.qualifier",
+ org.eclipse.birt.report.data.oda.excel.impl.util,
+ org.eclipse.birt.report.data.oda.excel.impl.util.querytextutil
+Require-Bundle: org.eclipse.core.runtime,
+ org.eclipse.datatools.connectivity.oda;bundle-version="[3.3.0,4.0.0)",
+ org.eclipse.datatools.connectivity.oda.profile;bundle-version="[3.2.0,4.0.0)"
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Bundle-ActivationPolicy: lazy
diff --git a/data/org.eclipse.birt.report.data.oda.excel/Readme.txt b/data/org.eclipse.birt.report.data.oda.excel/Readme.txt
new file mode 100644
index 0000000..31d5d48
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/Readme.txt
@@ -0,0 +1,46 @@
+************************************************org.eclipse.birt.report.data.oda.excel(v 1.0)******************************************************
+Plugin Name: org.eclipse.birt.report.data.oda.excel
+Contributor: Megha Nidhi Dahal (http://www.birt-exchange.org/org/forum/index.php/user/28183-arpan/)
+Tags: Native Excel ODA, xls, xlsx, open data access, ODA Framework, Excel ODA, BIRT, Eclipse BIRT
+
+Platform Dependencies: Eclipse v3.6.2 or higher
+Plugin Dependencies: POI(http://poi.apache.org/), org.eclipse.core.runtime, org.eclipse.datatools.connectivity.oda, org.eclipse.datatools.connectivity.oda.profile
+
+*******************************************************PLUGIN DESCRIPTION*******************************************************************
+org.eclipse.birt.report.data.oda.excel ODA extension supports Native Microsoft xls, xlsx workbook to be used as data source. It supports data spanning across multiple spreadsheets. However, number of columns and fields should be consistent for one set of data.
+
+Spreadsheet names can be passed as a ';' (colon) delimited string. Filename or workbook name cannot be changed, it should be the same used during configuration of the data set.
+
+*******************************************************DEPLOYMENT***************************************************************************
+The plugin is expected to be deployed along with 'org.eclipse.birt.report.data.oda.excel.ui' plugin.
+Extract the lib.zip into lib.
+Import both of these plugin projects in excel and export using the plugin manifest file. The exported jars are to be placed in the dropins folder of eclipse installation.
+
+Visit: http://wiki.eclipse.org/Birt_3.7_Migration_Guide#Custom_Extension_Point_Implementations
+
+********************************************************************LIMITATIONS**************************************************************
+Supports only one workbook per data set.
+Sheets can be identified only using names.
+Multiple sheet has to be delimited with ';', hence every ';' delimited text parameter linked to worksheets parameter of the data set will be treated as individual sheets.
+Sheet names cannot have ';' in them
+
+************************************************************************ENHANCEMENTS*********************************************************
+Support for multiple workbooks.
+An option to indicate the ODA to consider sheet indexes instead of names.
+Consider a fragment of data from every sheet, i.e. row start index and end index to be configurable.
+
+***********************************************************************FAQS******************************************************************
+Q1: Does this ODA support excel formats other than Microsoft's native format?
+A: No.
+
+Q2: Does this ODA support Microsoft Excel 2010 (xlsx) format?
+A: Yes.
+
+Q3: Can the listed enhancements be implemented by anyone interested?
+A: Yes. There might be many more enhancements that can be implemented not just the ones listed.
+
+Q4: Will this ODA work without the org.eclipse.birt.report.data.oda.excel.ui extension?
+A: No.
+
+Q5: Where can be the author of this extension contacted?
+A: The author of this plugin can be contacted at: http://www.birt-exchange.org/org/forum/index.php/user/28183-arpan/ \ No newline at end of file
diff --git a/data/org.eclipse.birt.report.data.oda.excel/build.properties b/data/org.eclipse.birt.report.data.oda.excel/build.properties
new file mode 100644
index 0000000..387f91a
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/build.properties
@@ -0,0 +1,22 @@
+source.. = src/
+output.. = bin/
+bin.includes = plugin.xml,\
+ META-INF/,\
+ .,\
+ plugin.properties,\
+ lib/lib/commons-logging-1.1.jar,\
+ lib/lib/junit-3.8.1.jar,\
+ lib/lib/log4j-1.2.13.jar,\
+ lib/ooxml-lib/dom4j-1.6.1.jar,\
+ lib/ooxml-lib/geronimo-stax-api_1.0_spec-1.0.jar,\
+ lib/ooxml-lib/xmlbeans-2.3.0.jar,\
+ lib/poi-3.7-20101029.jar,\
+ lib/poi-examples-3.7-20101029.jar,\
+ lib/poi-ooxml-3.7-20101029.jar,\
+ lib/poi-ooxml-schemas-3.7-20101029.jar,\
+ lib/poi-scratchpad-3.7-20101029.jar,\
+ lib/resolver.jar,\
+ lib/serializer.jar,\
+ lib/xercesImpl.jar,\
+ lib/xercesSamples.jar,\
+ lib/xml-apis.jar
diff --git a/data/org.eclipse.birt.report.data.oda.excel/plugin.properties b/data/org.eclipse.birt.report.data.oda.excel/plugin.properties
new file mode 100644
index 0000000..7b7442a
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/plugin.properties
@@ -0,0 +1,31 @@
+###############################################################################
+# Copyright (c) 2011 <<Megha Nidhi Dahal>>
+#
+###############################################################################
+# Plug-in Configuration
+#
+oda.data.source.id=org.eclipse.birt.report.data.oda.excel
+#
+###############################################################################
+# NLS String
+###############################################################################
+#
+plugin.name=Excel Data Source ODA Runtime Driver
+data.source.name=Excel Data Source
+data.set.name=Excel Data Set
+connection.profile.name=Excel Data Source Connection Profile
+
+datasource.property.home=Home &Folder
+datasource.property.incltypeline=Use Second Line as &Data Type Indicator
+datasource.property.inclcolumnnameline=Use First Line as Column &Name Indicator
+
+datasource.property.no=NO
+datasource.property.yes=YES
+
+###############################################################################
+# Date Set Properties
+datasource.property.excelFile=Select the excel file
+datasource.property.worksheets=Worksheet(s)
+dataset.property.worksheets.dateFormat=Date Format
+#
+############################################################################### \ No newline at end of file
diff --git a/data/org.eclipse.birt.report.data.oda.excel/plugin.xml b/data/org.eclipse.birt.report.data.oda.excel/plugin.xml
new file mode 100644
index 0000000..bdf1fd8
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/plugin.xml
@@ -0,0 +1,137 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?>
+<plugin>
+
+ <extension
+ point="org.eclipse.datatools.connectivity.oda.dataSource">
+ <dataSource
+ driverClass="org.eclipse.birt.report.data.oda.excel.impl.Driver"
+ defaultDisplayName="%data.source.name"
+ setThreadContextClassLoader="false"
+ odaVersion="3.2"
+ id="%oda.data.source.id">
+ <properties>
+ <property
+ allowsEmptyValueAsNull="true"
+ canInherit="true"
+ defaultDisplayName="%datasource.property.home"
+ isEncryptable="false"
+ name="HOME"
+ type="string">
+ </property>
+ <property
+ allowsEmptyValueAsNull="true"
+ canInherit="true"
+ defaultDisplayName="%datasource.property.inclcolumnnameline"
+ defaultValue="YES"
+ isEncryptable="false"
+ name="INCLCOLUMNNAME"
+ type="choice">
+ <choice name="no" value="no" defaultDisplayName="%datasource.property.no"/>
+ <choice name="yes" value="yes" defaultDisplayName="%datasource.property.yes"/>
+ </property>
+ <property
+ allowsEmptyValueAsNull="true"
+ canInherit="true"
+ defaultDisplayName="%datasource.property.incltypeline"
+ defaultValue="NO"
+ isEncryptable="false"
+ name="INCLTYPELINE"
+ type="choice">
+ <choice name="no" value="no" defaultDisplayName="%datasource.property.yes"/>
+ <choice name="yes" value="yes" defaultDisplayName="%datasource.property.no"/>
+ </property>
+ </properties>
+ </dataSource>
+ <dataSet
+ defaultDisplayName="%data.set.name"
+ id="org.eclipse.birt.report.data.oda.excel.dataSet">
+ <dataTypeMapping
+ nativeDataType="INT"
+ nativeDataTypeCode="4"
+ odaScalarDataType="Integer"/>
+ <dataTypeMapping
+ nativeDataType="DOUBLE"
+ nativeDataTypeCode="8"
+ odaScalarDataType="Double"/>
+ <dataTypeMapping
+ nativeDataType="STRING"
+ nativeDataTypeCode="12"
+ odaScalarDataType="String"/>
+ <dataTypeMapping
+ nativeDataType="DATE"
+ nativeDataTypeCode="91"
+ odaScalarDataType="Date"/>
+ <dataTypeMapping
+ nativeDataType="TIME"
+ nativeDataTypeCode="92"
+ odaScalarDataType="Time"/>
+ <dataTypeMapping
+ nativeDataType="TIMESTAMP"
+ nativeDataTypeCode="93"
+ odaScalarDataType="Timestamp"/>
+ <dataTypeMapping
+ nativeDataType="BLOB"
+ nativeDataTypeCode="2004"
+ odaScalarDataType="String"/>
+ <dataTypeMapping
+ nativeDataType="CLOB"
+ nativeDataTypeCode="2005"
+ odaScalarDataType="String"/>
+ <dataTypeMapping
+ nativeDataType="BIGDECIMAL"
+ nativeDataTypeCode="2"
+ odaScalarDataType="Decimal"/>
+ <dataTypeMapping
+ nativeDataType="BOOLEAN"
+ nativeDataTypeCode="16"
+ odaScalarDataType="Boolean"/>
+ <properties>
+ <propertyGroup
+ defaultDisplayName="Dataset Properties"
+ name="dateset properties">
+ <property
+ defaultDisplayName="%datasource.property.worksheets"
+ name="WORKSHEETS"
+ canInherit="true"
+ type="string"/>
+ <property
+ allowsEmptyValueAsNull="true"
+ canInherit="true"
+ defaultDisplayName="dataset.property.worksheets.dateFormat"
+ defaultValue="yyyy-MM-dd"
+ isEncryptable="false"
+ name="DATEFORMAT"
+ type="string">
+ </property>
+ </propertyGroup>
+ <propertyVisibility name="WORKSHEETS" visibility="change"/>
+ <propertyVisibility
+ name="DATEFORMAT"
+ visibility="change">
+ </propertyVisibility>
+ </properties>
+ </dataSet>
+ </extension>
+ <extension
+ point="org.eclipse.datatools.connectivity.connectionProfile">
+ <category
+ name="%data.source.name"
+ parentCategory="org.eclipse.datatools.connectivity.oda.profileCategory"
+ id="%oda.data.source.id">
+ </category>
+ <connectionProfile
+ pingFactory="org.eclipse.datatools.connectivity.oda.profile.OdaConnectionFactory"
+ name="%connection.profile.name"
+ category="%oda.data.source.id"
+ id="%oda.data.source.id">
+ </connectionProfile>
+ <connectionFactory
+ name="ODA Connection Factory"
+ profile="%oda.data.source.id"
+ class="org.eclipse.datatools.connectivity.oda.profile.OdaConnectionFactory"
+ id="org.eclipse.datatools.connectivity.oda.IConnection">
+ </connectionFactory>
+ </extension>
+
+</plugin>
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/Activator.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/Activator.java
new file mode 100644
index 0000000..50d9f20
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/Activator.java
@@ -0,0 +1,41 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+package org.eclipse.birt.report.data.oda.excel;
+
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+
+public class Activator implements BundleActivator {
+
+ private static BundleContext context;
+
+ static BundleContext getContext() {
+ return context;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
+ */
+ public void start(BundleContext bundleContext) throws Exception {
+ Activator.context = bundleContext;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
+ */
+ public void stop(BundleContext bundleContext) throws Exception {
+ Activator.context = null;
+ }
+
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/ExcelODAConstants.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/ExcelODAConstants.java
new file mode 100644
index 0000000..1fb7961
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/ExcelODAConstants.java
@@ -0,0 +1,43 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+
+package org.eclipse.birt.report.data.oda.excel;
+
+public class ExcelODAConstants {
+
+ public static final String CONN_HOME_DIR_PROP = "HOME";
+ public static final String XLS_FORMAT = "xls";
+ public static final String XLSX_FORMAT = "xlsx";
+ public static final String CONN_INCLCOLUMNNAME_PROP = "INCLCOLUMNNAME";
+ public static final String INC_COLUMN_NAME_YES = "YES";
+ public static final String CONN_INCLTYPELINE_PROP = "INCLTYPELINE";
+ public static final String INC_TYPE_LINE_YES = "YES";
+ public static final String INC_TYPE_LINE_NO = "NO";
+ public static final String INC_COLUMN_NAME_NO = "NO";
+
+ public static final String CONN_WORKSHEETS_PROP = "WORKSHEETS";
+ public static final String CONN_DATE_FORMAT_PROP = "DATEFORMAT";
+
+ public static final String DELIMITER_SPACE = " "; //$NON-NLS-1$
+ public static final char DELIMITER_DOUBLEQUOTE = '"';
+ public static final String DELIMITER_COMMA = "COMMA"; //$NON-NLS-1$
+ public static final String DELIMITER_COMMA_VALUE = ","; //$NON-NLS-1$
+ public static final String DELIMITER_SEMICOLON_VALUE = ";"; //$NON-NLS-1$
+
+ public static final String KEYWORD_SELECT = "SELECT"; //$NON-NLS-1$
+ public static final String KEYWORD_ASTERISK = "*";//$NON-NLS-1$
+ public static final String KEYWORD_AS = "AS"; //$NON-NLS-1$
+ public static final String KEYWORD_FROM = "FROM"; //$NON-NLS-1$
+ public static final String EMPTY_STRING = "";
+ public static final String ALL_SHEETS = "ALL";
+ public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/ResultSetMetaDataHelper.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/ResultSetMetaDataHelper.java
new file mode 100644
index 0000000..a12ff19
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/ResultSetMetaDataHelper.java
@@ -0,0 +1,147 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+
+package org.eclipse.birt.report.data.oda.excel;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.birt.report.data.oda.excel.impl.i18n.Messages;
+import org.eclipse.birt.report.data.oda.excel.impl.util.querytextutil.ColumnsInfoUtil;
+import org.eclipse.datatools.connectivity.oda.OdaException;
+
+/**
+ * A helper class that helps ResultSetMetaData to parse column information and
+ * provide a public access to ResultSet's original column names.
+ */
+
+public class ResultSetMetaDataHelper {
+ String savedSelectedColumnsInfoString;
+ String[] columnNames;
+ String[] columnTypes;
+ String[] originalColumnNames;
+ String[] columnLabels;
+
+ private Map<String, Integer> columnNameIndexMap = new HashMap<String, Integer>();
+
+ /**
+ * Constructor
+ *
+ * @param colNames
+ * @param colTypes
+ * @param colLabels
+ * @throws OdaException
+ */
+ public ResultSetMetaDataHelper(String[] colNames, String[] colTypes,
+ String[] colLabels) throws OdaException {
+ if (colNames == null)
+ throw new OdaException(
+ Messages.getString("common_ARGUMENT_CANNOT_BE_NULL")); //$NON-NLS-1$
+
+ this.columnNames = colNames;
+ this.columnTypes = colTypes;
+ this.columnLabels = colLabels;
+ this.originalColumnNames = colNames;
+ trimMetaDataStrings();
+ initMap();
+ }
+
+ /**
+ *
+ * @param savedSelectedColumnsInfoString
+ */
+ public ResultSetMetaDataHelper(String savedSelectedColumnsInfoString) {
+ this.savedSelectedColumnsInfoString = savedSelectedColumnsInfoString;
+ ColumnsInfoUtil ciu = new ColumnsInfoUtil(
+ savedSelectedColumnsInfoString);
+ this.columnNames = ciu.getColumnNames();
+ this.columnTypes = ciu.getColumnTypeNames();
+ this.originalColumnNames = ciu.getOriginalColumnNames();
+ this.columnLabels = this.columnNames;
+ trimMetaDataStrings();
+ initMap();
+ }
+
+ private void initMap() {
+ for (int i = 0; i < columnNames.length; i++) {
+ columnNameIndexMap.put(columnNames[i], Integer.valueOf(i));
+ }
+ }
+
+ /**
+ *
+ *
+ */
+ private void trimMetaDataStrings() {
+ assert columnNames.length == columnTypes.length
+ && columnTypes.length == originalColumnNames.length
+ && originalColumnNames.length == columnLabels.length;
+
+ for (int i = 0; i < columnNames.length; i++) {
+ columnNames[i] = columnNames[i].trim();
+ columnTypes[i] = columnTypes[i].trim();
+ columnLabels[i] = columnLabels[i].trim();
+ originalColumnNames[i] = originalColumnNames[i].trim();
+ }
+ }
+
+ /**
+ *
+ * @return
+ */
+ public String[] getColumnNames() {
+
+ return this.columnNames;
+ }
+
+ /**
+ *
+ * @return
+ */
+ public String[] getColumnTypes() {
+ return this.columnTypes;
+ }
+
+ /**
+ *
+ * @return
+ */
+ public String[] getColumnLabels() {
+ return this.columnLabels;
+ }
+
+ /**
+ * Get the orignal column names
+ *
+ * @return
+ */
+ public String[] getOriginalColumnNames() {
+ return this.originalColumnNames;
+ }
+
+ /**
+ * Get the original column name of the specified column name
+ *
+ * @return
+ */
+ public String getOriginalColumnName(String columnName) {
+ String originName = null;
+
+ Integer index = (Integer) columnNameIndexMap.get(columnName);
+
+ if (index != null) {
+ originName = originalColumnNames[index.intValue()];
+ }
+ return originName;
+ }
+
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/Connection.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/Connection.java
new file mode 100644
index 0000000..a5f6437
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/Connection.java
@@ -0,0 +1,150 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+
+package org.eclipse.birt.report.data.oda.excel.impl;
+
+import java.io.File;
+import java.util.Properties;
+
+import org.eclipse.birt.report.data.oda.excel.ExcelODAConstants;
+import org.eclipse.birt.report.data.oda.excel.impl.i18n.Messages;
+import org.eclipse.datatools.connectivity.oda.IConnection;
+import org.eclipse.datatools.connectivity.oda.IDataSetMetaData;
+import org.eclipse.datatools.connectivity.oda.IQuery;
+import org.eclipse.datatools.connectivity.oda.OdaException;
+
+import com.ibm.icu.util.ULocale;
+
+/**
+ * Implementation class of IConnection for an ODA runtime driver.
+ */
+public class Connection implements IConnection {
+ private boolean isOpen = false;
+ private Properties connProperties;
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IConnection#open(java.util.Properties
+ * )
+ */
+ public void open(Properties connProperties) throws OdaException {
+ if (connProperties == null)
+ throw new OdaException(
+ Messages.getString("connection_CONNECTION_PROPERTIES_MISSING")); //$NON-NLS-1$
+
+ this.connProperties = connProperties;
+ validateHomeDir();
+
+ isOpen = true;
+ }
+
+ private void validateHomeDir() throws OdaException {
+ String homeDir = connProperties
+ .getProperty(ExcelODAConstants.CONN_HOME_DIR_PROP);
+ if (homeDir != null) // found property
+ {
+ File file = new File(homeDir);
+ if (file.exists()) {
+ this.isOpen = true;
+ return; // is valid, done
+ }
+ }
+
+ throw new OdaException(
+ Messages.getString("connection_CANNOT_OPEN_EXCEL_FILE_DB_DIR") //$NON-NLS-1$
+ + homeDir);
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IConnection#setAppContext(java
+ * .lang.Object)
+ */
+ public void setAppContext(Object context) throws OdaException {
+ // do nothing; assumes no support for pass-through context
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IConnection#close()
+ */
+ public void close() throws OdaException {
+ // TODO replace with data source specific implementation
+ isOpen = false;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IConnection#isOpen()
+ */
+ public boolean isOpen() throws OdaException {
+ // TODO Auto-generated method stub
+ return isOpen;
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IConnection#getMetaData(java.lang
+ * .String)
+ */
+ public IDataSetMetaData getMetaData(String dataSetType) throws OdaException {
+ // assumes that this driver supports only one type of data set,
+ // ignores the specified dataSetType
+ return new DataSetMetaData(this);
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IConnection#newQuery(java.lang
+ * .String)
+ */
+ public IQuery newQuery(String dataSetType) throws OdaException {
+ // assumes that this driver supports only one type of data set,
+ // ignores the specified dataSetType
+ if (!isOpen())
+ throw new OdaException(
+ Messages.getString("common_CONNECTION_HAS_NOT_OPEN")); //$NON-NLS-1$
+
+ return new ExcelFileQuery(connProperties, this);
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IConnection#getMaxQueries()
+ */
+ public int getMaxQueries() throws OdaException {
+ return 0; // no limit
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IConnection#commit()
+ */
+ public void commit() throws OdaException {
+ // do nothing; assumes no transaction support needed
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IConnection#rollback()
+ */
+ public void rollback() throws OdaException {
+ // do nothing; assumes no transaction support needed
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IConnection#setLocale(com.ibm.
+ * icu.util.ULocale)
+ */
+ public void setLocale(ULocale locale) throws OdaException {
+ // do nothing; assumes no locale support
+ }
+
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/DataSetMetaData.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/DataSetMetaData.java
new file mode 100644
index 0000000..3bb9a38
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/DataSetMetaData.java
@@ -0,0 +1,158 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+package org.eclipse.birt.report.data.oda.excel.impl;
+
+import org.eclipse.datatools.connectivity.oda.IConnection;
+import org.eclipse.datatools.connectivity.oda.IDataSetMetaData;
+import org.eclipse.datatools.connectivity.oda.IResultSet;
+import org.eclipse.datatools.connectivity.oda.OdaException;
+
+/**
+ * Implementation class of IDataSetMetaData for an ODA runtime driver.
+ * <br>
+ * For demo purpose, the auto-generated method stubs have
+ * hard-coded implementation that assume this custom ODA data set
+ * is capable of handling a query that returns a single result set and
+ * accepts scalar input parameters by index.
+ * A custom ODA driver is expected to implement own data set specific
+ * behavior in its place.
+ */
+public class DataSetMetaData implements IDataSetMetaData
+{
+ private IConnection connection;
+
+ DataSetMetaData( IConnection connection )
+ {
+ this.connection = connection;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDataSetMetaData#getConnection()
+ */
+ public IConnection getConnection() throws OdaException
+ {
+ // TODO Auto-generated method stub
+ return connection;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDataSetMetaData#getDataSourceObjects(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
+ */
+ public IResultSet getDataSourceObjects( String catalog, String schema, String object, String version ) throws OdaException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDataSetMetaData#getDataSourceMajorVersion()
+ */
+ public int getDataSourceMajorVersion() throws OdaException
+ {
+ // TODO Auto-generated method stub
+ return 1;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDataSetMetaData#getDataSourceMinorVersion()
+ */
+ public int getDataSourceMinorVersion() throws OdaException
+ {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDataSetMetaData#getDataSourceProductName()
+ */
+ public String getDataSourceProductName() throws OdaException
+ {
+ // TODO Auto-generated method stub
+ return "MEGHA Excel Data Source";
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDataSetMetaData#getDataSourceProductVersion()
+ */
+ public String getDataSourceProductVersion() throws OdaException
+ {
+ return Integer.toString( getDataSourceMajorVersion() ) + "." + //$NON-NLS-1$
+ Integer.toString( getDataSourceMinorVersion() );
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDataSetMetaData#getSQLStateType()
+ */
+ public int getSQLStateType() throws OdaException
+ {
+ throw new UnsupportedOperationException( );
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDataSetMetaData#supportsMultipleResultSets()
+ */
+ public boolean supportsMultipleResultSets() throws OdaException
+ {
+ return false;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDataSetMetaData#supportsMultipleOpenResults()
+ */
+ public boolean supportsMultipleOpenResults() throws OdaException
+ {
+ return false;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDataSetMetaData#supportsNamedResultSets()
+ */
+ public boolean supportsNamedResultSets() throws OdaException
+ {
+ return false;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDataSetMetaData#supportsNamedParameters()
+ */
+ public boolean supportsNamedParameters() throws OdaException
+ {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDataSetMetaData#supportsInParameters()
+ */
+ public boolean supportsInParameters() throws OdaException
+ {
+ return false;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDataSetMetaData#supportsOutParameters()
+ */
+ public boolean supportsOutParameters() throws OdaException
+ {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDataSetMetaData#getSortMode()
+ */
+ public int getSortMode()
+ {
+ // TODO Auto-generated method stub
+ return IDataSetMetaData.sortModeNone;
+ }
+
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/Driver.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/Driver.java
new file mode 100644
index 0000000..3a44a44
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/Driver.java
@@ -0,0 +1,92 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+package org.eclipse.birt.report.data.oda.excel.impl;
+
+import org.eclipse.datatools.connectivity.oda.IConnection;
+import org.eclipse.datatools.connectivity.oda.IDriver;
+import org.eclipse.datatools.connectivity.oda.LogConfiguration;
+import org.eclipse.datatools.connectivity.oda.OdaException;
+import org.eclipse.datatools.connectivity.oda.util.manifest.DataTypeMapping;
+import org.eclipse.datatools.connectivity.oda.util.manifest.ExtensionManifest;
+import org.eclipse.datatools.connectivity.oda.util.manifest.ManifestExplorer;
+
+/**
+ * Implementation class of IDriver for an ODA runtime driver.
+ */
+public class Driver implements IDriver
+{
+ static String ODA_DATA_SOURCE_ID = "org.eclipse.birt.report.data.oda.excel"; //$NON-NLS-1$
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDriver#getConnection(java.lang.String)
+ */
+ public IConnection getConnection( String dataSourceType ) throws OdaException
+ {
+ // assumes that this driver supports only one type of data source,
+ // ignores the specified dataSourceType
+ return new Connection();
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDriver#setLogConfiguration(org.eclipse.datatools.connectivity.oda.LogConfiguration)
+ */
+ public void setLogConfiguration( LogConfiguration logConfig ) throws OdaException
+ {
+ // do nothing; assumes simple driver has no logging
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDriver#getMaxConnections()
+ */
+ public int getMaxConnections() throws OdaException
+ {
+ return 0; // no limit
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IDriver#setAppContext(java.lang.Object)
+ */
+ public void setAppContext( Object context ) throws OdaException
+ {
+ // do nothing; assumes no support for pass-through context
+ }
+
+ /**
+ * Returns the object that represents this extension's manifest.
+ * @throws OdaException
+ */
+ static ExtensionManifest getManifest()
+ throws OdaException
+ {
+ return ManifestExplorer.getInstance()
+ .getExtensionManifest( ODA_DATA_SOURCE_ID );
+ }
+
+ /**
+ * Returns the native data type name of the specified code, as
+ * defined in this data source extension's manifest.
+ * @param nativeTypeCode the native data type code
+ * @return corresponding native data type name
+ * @throws OdaException if lookup fails
+ */
+ static String getNativeDataTypeName( int nativeDataTypeCode )
+ throws OdaException
+ {
+ DataTypeMapping typeMapping =
+ getManifest().getDataSetType( null )
+ .getDataTypeMapping( nativeDataTypeCode );
+ if( typeMapping != null )
+ return typeMapping.getNativeType();
+ return "Non-defined";
+ }
+
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ExcelFileQuery.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ExcelFileQuery.java
new file mode 100644
index 0000000..8d2953c
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ExcelFileQuery.java
@@ -0,0 +1,989 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+package org.eclipse.birt.report.data.oda.excel.impl;
+
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.Vector;
+
+import org.eclipse.birt.report.data.oda.excel.ExcelODAConstants;
+import org.eclipse.birt.report.data.oda.excel.ResultSetMetaDataHelper;
+import org.eclipse.birt.report.data.oda.excel.impl.i18n.Messages;
+import org.eclipse.birt.report.data.oda.excel.impl.util.DataTypes;
+import org.eclipse.birt.report.data.oda.excel.impl.util.ExcelFileSource;
+import org.eclipse.birt.report.data.oda.excel.impl.util.querytextutil.QueryTextUtil;
+import org.eclipse.datatools.connectivity.oda.IConnection;
+import org.eclipse.datatools.connectivity.oda.IParameterMetaData;
+import org.eclipse.datatools.connectivity.oda.IQuery;
+import org.eclipse.datatools.connectivity.oda.IResultSet;
+import org.eclipse.datatools.connectivity.oda.IResultSetMetaData;
+import org.eclipse.datatools.connectivity.oda.OdaException;
+import org.eclipse.datatools.connectivity.oda.SortSpec;
+import org.eclipse.datatools.connectivity.oda.spec.QuerySpecification;
+
+/**
+ * Implementation class of IQuery for an ODA runtime driver. <br>
+ * For demo purpose, the auto-generated method stubs have hard-coded
+ * implementation that returns a pre-defined set of meta-data and query results.
+ * A custom ODA driver is expected to implement own data source specific
+ * behavior in its place.
+ */
+public class ExcelFileQuery implements IQuery {
+ private int maxRows;
+
+ private static final String NAME_LITERAL = "NAME"; //$NON-NLS-1$
+ private static final String TYPE_LITERAL = "TYPE"; //$NON-NLS-1$
+
+ // whether the Excel file has the column names
+ private boolean hasColumnNames;
+
+ // Whether to use 2nd line as Type line
+ private boolean hasTypeLine;
+
+ // The table that the query operates on
+ private String currentTableName;
+
+ // the properties of the connection
+ private Properties connProperties;
+
+ // The Connection instance associated with the Query.
+ private IConnection connection;
+
+ // The meta data of the query's result set.
+ // It is available only after a query is prepared.
+ private ResultSetMetaData resultSetMetaData;
+
+ private ResultSetMetaDataHelper resultSetMetaDataHelper;
+
+ private String worksheetNames;
+ private String dateFormatString = ExcelODAConstants.DEFAULT_DATE_FORMAT;
+
+ private String savedSelectedColInfo;
+
+ private String preparedColumnNames;
+
+ private String[] columnLabels;
+
+ private boolean isInvalidQuery;
+
+ public ExcelFileQuery(Properties connProperties, Connection connection)
+ throws OdaException {
+ if (connProperties == null
+ || connProperties
+ .getProperty(ExcelODAConstants.CONN_HOME_DIR_PROP) == null
+ || connection == null)
+ throw new OdaException(
+ Messages.getString("common_ARGUMENT_CANNOT_BE_NULL")); //$NON-NLS-1$
+ this.connProperties = connProperties;
+ this.connection = connection;
+
+ extractsHasColumnNamesInfo();
+ extractsHasColumnTypeLineInfo();
+ }
+
+ /**
+ *
+ *
+ */
+ private void extractsHasColumnNamesInfo() {
+ this.hasColumnNames = connProperties.getProperty(
+ ExcelODAConstants.CONN_INCLCOLUMNNAME_PROP).equalsIgnoreCase(
+ ExcelODAConstants.INC_COLUMN_NAME_NO) ? false : true;
+ }
+
+ /**
+ *
+ *
+ */
+ private void extractsHasColumnTypeLineInfo() {
+ this.hasTypeLine = connProperties.getProperty(
+ ExcelODAConstants.CONN_INCLTYPELINE_PROP).equalsIgnoreCase(
+ ExcelODAConstants.INC_TYPE_LINE_NO) ? false : true;
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#prepare(java.lang.String)
+ */
+ /**
+ * Prepare the meta data which will be used in execution of a query text. It
+ * sets the value of two member variables: resultSetMetaData and
+ * absoluteFileName
+ */
+ public void prepare(String queryText) throws OdaException {
+ validateOpenConnection();
+ if (queryText == null) {
+ throw new OdaException(Messages.getString("common_NULL_QUERY_TEXT")); //$NON-NLS-1$
+ }
+ validateOpenConnection();
+
+ QueryTextUtil qtu = new QueryTextUtil(queryText);
+ String query = formatQueryText(qtu.getQuery());
+ savedSelectedColInfo = qtu.getColumnsInfo();
+ validateNonEmptyQueryText(query);
+ String[] queryFragments = parsePreparedQueryText(query);
+ validateSingleTableQuery(queryFragments);
+
+ // the name of table against which the query will be executed
+ this.currentTableName = getPreparedTableNames(queryFragments);
+ this.preparedColumnNames = getPreparedColumnNames(queryFragments);
+ this.columnLabels = getColumnLabels(queryFragments);
+ }
+
+ /**
+ * Format the given query text. Eliminates redundant spaces and convert all
+ * keywords to uppercase.
+ *
+ * @param queryText
+ * @return
+ */
+ private String formatQueryText(String queryText) {
+ StringBuffer result = new StringBuffer();
+ String[] temp = queryText.trim().split(
+ ExcelODAConstants.DELIMITER_SPACE);
+ for (int i = 0; i < temp.length; i++) {
+ if (temp[i].equalsIgnoreCase(ExcelODAConstants.KEYWORD_AS))
+ temp[i] = temp[i].toUpperCase();
+ if (temp[i].equalsIgnoreCase(ExcelODAConstants.KEYWORD_FROM))
+ temp[i] = temp[i].toUpperCase();
+ if (temp[i].equalsIgnoreCase(ExcelODAConstants.KEYWORD_SELECT))
+ temp[i] = temp[i].toUpperCase();
+ result.append(temp[i]).append(ExcelODAConstants.DELIMITER_SPACE);
+ }
+ return result.toString().trim();
+ }
+
+ /**
+ * Validate whether the query's connection is open.
+ *
+ * @throws OdaException
+ * if connection is not open yet
+ */
+ private void validateOpenConnection() throws OdaException {
+ if (connection.isOpen() == false)
+ throw new OdaException(
+ Messages.getString("common_CONNECTION_IS_NOT_OPEN")); //$NON-NLS-1$
+ }
+
+ /**
+ * Prepare the meta data which will be used in execution of a query text. It
+ * sets the value of two member variables: resultSetMetaData and
+ * currentTableName
+ *
+ * @param queryText
+ * @throws OdaException
+ */
+ private void prepareMetaData() throws OdaException {
+ ExcelFileSource excelFileReader = new ExcelFileSource(connProperties,
+ currentTableName, worksheetNames, dateFormatString, 0, null,
+ null);
+
+ String[] allColumnNames;
+ String[] allColumnTypes;
+
+ allColumnNames = this.hasColumnNames ? discoverActualColumnMetaData(
+ NAME_LITERAL, currentTableName)
+ : createTempColumnNames(excelFileReader.getColumnCount());
+ allColumnTypes = this.hasTypeLine ? discoverActualColumnMetaData(
+ TYPE_LITERAL, currentTableName)
+ : createTempColumnTypes(excelFileReader.getColumnCount());
+ resultSetMetaData = new ResultSetMetaData(allColumnNames,
+ allColumnTypes);
+
+ if (allColumnNames.length != allColumnTypes.length)
+ throw new OdaException(
+ Messages.getString("invalid_excelfile_format")); //$NON-NLS-1$
+
+ // the array that contains the column names read from command
+ String[] queryColumnNames = null;
+ String[] queryColumnTypes = null;
+ String[] queryColumnLables = null;
+ // dealing with "*"
+ if (isWildCard(preparedColumnNames)) {
+ queryColumnNames = allColumnNames;
+ queryColumnTypes = allColumnTypes;
+ queryColumnLables = allColumnNames;
+ this.resultSetMetaDataHelper = new ResultSetMetaDataHelper(
+ queryColumnNames, queryColumnTypes, queryColumnLables);
+ this.resultSetMetaData = new ResultSetMetaData(
+ this.resultSetMetaDataHelper);
+ } else {
+ queryColumnNames = ExcelFileSource
+ .getStringArrayFromList(stripFormatInfoFromQueryColumnNames(getQueryColumnNamesVector((preparedColumnNames))));
+ validateColumnName(queryColumnNames, allColumnNames);
+ if (savedSelectedColInfo == null
+ || savedSelectedColInfo.length() == 0) {
+ queryColumnTypes = this.hasTypeLine ? getQueryColumnTypes(
+ allColumnNames, allColumnTypes, queryColumnNames)
+ : createTempColumnTypes(queryColumnNames.length);
+ queryColumnLables = this.hasColumnNames ? columnLabels
+ : queryColumnNames;
+ if (queryColumnLables == null)
+ queryColumnLables = queryColumnNames;
+ this.resultSetMetaDataHelper = new ResultSetMetaDataHelper(
+ queryColumnNames, queryColumnTypes, queryColumnLables);
+ this.resultSetMetaData = new ResultSetMetaData(
+ this.resultSetMetaDataHelper);
+ } else {
+ this.resultSetMetaDataHelper = new ResultSetMetaDataHelper(
+ savedSelectedColInfo);
+ this.resultSetMetaData = new ResultSetMetaData(
+ this.resultSetMetaDataHelper);
+
+ }
+ }
+ }
+
+ /**
+ * Validate whether the given query text is empty.
+ *
+ * @param formattedQuery
+ * the trimed query text
+ * @throws OdaException
+ * if the given text is empty
+ */
+ private void validateNonEmptyQueryText(String formattedQuery)
+ throws OdaException {
+ if (formattedQuery == null || formattedQuery.length() == 0)
+ throw new OdaException(Messages.getString("query_COMMAND_IS_EMPTY")); //$NON-NLS-1$
+ }
+
+ /**
+ * Parse the command by separating keywords and other parts of a SQL SELECT
+ * query text.
+ *
+ * @param formattedQuery
+ * SQL SELECT query: SELECT COLUMNNAME (AS ALIAS)[,COLUMNNAME2
+ * (AS ALIAS)] FROM TABLENAME
+ * @return a String array with first element that holds all the
+ * comma-separated column names, the second element that holds all
+ * the comma-separated column display labels, and the third element
+ * for table name(s) in FROM clause
+ * @throws OdaException
+ * if the given query is not valid.
+ */
+ private String[] parsePreparedQueryText(String formattedQuery)
+ throws OdaException {
+
+ return QueryTextUtil.getQueryMetaData(formattedQuery);
+ }
+
+ /**
+ *
+ * @param queryColumnNames
+ * @return
+ */
+ private Vector<String> getQueryColumnNamesVector(String queryColumnNames) {
+ Vector<String> result = new Vector<String>();
+ char[] chars = queryColumnNames.toCharArray();
+ List<Integer> indiceList = new ArrayList<Integer>();
+ boolean inQuote = false;
+ boolean isEscaped = false;
+ int beginIndex = 0;
+ int endIndex = 0;
+
+ for (int i = 0; i < chars.length; i++) {
+ if (chars[i] == '"') {
+ if (!isEscaped)
+ inQuote = !inQuote;
+ else
+ isEscaped = !isEscaped;
+ } else if (chars[i] == '\\') {
+ isEscaped = !isEscaped;
+ } else if (chars[i] == ',') {
+ if (inQuote)
+ continue;
+ else
+ indiceList.add(new Integer(i));
+ }
+ }
+
+ if (indiceList.size() > 0) {
+ for (int j = 0; j < indiceList.size(); j++) {
+
+ endIndex = ((Integer) indiceList.get(j)).intValue();
+
+ result.add(queryColumnNames.substring(beginIndex, endIndex)
+ .trim());
+ beginIndex = endIndex + 1;
+
+ if (j == indiceList.size() - 1) {
+ result.add(queryColumnNames.substring(beginIndex,
+ queryColumnNames.length()).trim());
+ }
+ }
+ } else
+ result.add(queryColumnNames);
+
+ return result;
+ }
+
+ /**
+ *
+ * @param queryColumnNames
+ * @return
+ */
+ private Vector<String> stripFormatInfoFromQueryColumnNames(
+ Vector<String> queryColumnNames) {
+ Vector<String> columnNames = new Vector<String>();
+
+ boolean isEscaped = false;
+
+ for (int i = 0; i < queryColumnNames.size(); i++) {
+ StringBuffer sb = new StringBuffer();
+ char[] chars = queryColumnNames.get(i).toCharArray();
+
+ if (chars[0] != ExcelODAConstants.DELIMITER_DOUBLEQUOTE) {
+ columnNames.add(queryColumnNames.get(i));
+ continue;
+ }
+
+ for (int j = 0; j < chars.length; j++) {
+ if (chars[j] == ExcelODAConstants.DELIMITER_DOUBLEQUOTE) {
+ if (isEscaped) {
+ sb.append(chars[j]);
+ isEscaped = !isEscaped;
+ }
+ } else if (chars[j] == '\\') {
+ if (isEscaped)
+ sb.append(chars[j]);
+
+ isEscaped = !isEscaped;
+ } else
+ sb.append(chars[j]);
+ }
+
+ columnNames.add(sb.toString());
+ }
+
+ return columnNames;
+ }
+
+ /**
+ * Returns the array that contains the types of column names read from a
+ * query text.
+ *
+ * @param allColumnNames
+ * The array contains all column names read from file
+ * @param allColumnTypes
+ * The array contains all column types read from file
+ * @param queryColumnNames
+ * The array contains those column names specified in a query
+ * @return
+ */
+ private String[] getQueryColumnTypes(String[] allColumnNames,
+ String[] allColumnTypes, String[] queryColumnNames) {
+ if (!this.hasTypeLine)
+ return null;
+
+ // the array that contains the types of column names read from a query
+ String[] queryColumnTypes = new String[queryColumnNames.length];
+
+ for (int i = 0; i < queryColumnNames.length; i++) {
+ for (int j = 0; j < allColumnNames.length; j++) {
+ if (queryColumnNames[i].trim().equalsIgnoreCase(
+ allColumnNames[j])) {
+ queryColumnTypes[i] = allColumnTypes[j];
+ break;
+ }
+ }
+
+ }
+ return queryColumnTypes;
+ }
+
+ /**
+ * Returns an array that contains column labels.
+ *
+ * @param queryFragments
+ * @return a String array that contains column labels
+ */
+ private String[] getColumnLabels(String[] queryFragments) {
+ String queryColumnLabels = getPreparedColumnLabels(queryFragments);
+ return queryColumnLabels != null ? queryColumnLabels
+ .split(ExcelODAConstants.DELIMITER_COMMA_VALUE) : null;
+ }
+
+ /**
+ * Return the String that contains column label(s) selected in a query.
+ * Multiple column labels, if any, are separated by comma.
+ *
+ * @param parsedQueryFragments
+ * the string array which is generated by the
+ * parsePreparedQueryText method
+ * @return the comma-separated column labels selected in a query
+ */
+ private String getPreparedColumnLabels(String[] parsedQueryFragments) {
+ return parsedQueryFragments[1];
+ }
+
+ /**
+ * Validate whether the given query segments contains a single table name.
+ *
+ * @param parsedQuerySegments
+ * @throws OdaException
+ * if the given query contains multiple table names
+ */
+ private void validateSingleTableQuery(String[] parsedQuerySegments)
+ throws OdaException {
+ if (getPreparedTableNames(parsedQuerySegments).split(
+ ExcelODAConstants.DELIMITER_COMMA_VALUE).length != 1)
+ throw new OdaException(
+ Messages.getString("query_DO_NOT_SUPPORT_CROSS_TABLE_QUERY")); //$NON-NLS-1$
+ }
+
+ /**
+ * Return the String which contains the identifiers in the FROM clause.
+ *
+ * @param parsedQueryFragments
+ * the string array which is generated by the
+ * parsePreparedQueryText method
+ * @return a String that contains table name(s) after the FROM keyword
+ */
+ private String getPreparedTableNames(String[] parsedQueryFragments) {
+ return parsedQueryFragments[2];
+ }
+
+ /**
+ * Return the String that contains column name(s) selected in a query.
+ * Multiple column names, if any, are separated by comma.
+ *
+ * @param parsedQueryFragments
+ * the string array which is generated by the
+ * parsePreparedQueryText method
+ * @return the comma-separated column names selected in a query
+ */
+ private String getPreparedColumnNames(String[] parsedQueryFragments) {
+ return parsedQueryFragments[0];
+ }
+
+ /**
+ * Returns a specified array of metadata info
+ *
+ * @param metaDataType
+ * : currently has two values: "NAME" and "TYPE"
+ * @param tableName
+ * @return String[] an array that holds the specified metadata
+ * @throws OdaException
+ */
+ private String[] discoverActualColumnMetaData(String metaDataType,
+ String tableName) throws OdaException {
+ ExcelFileSource excelFileSource = new ExcelFileSource(
+ this.connProperties, tableName, worksheetNames,
+ dateFormatString, 0, null, null);
+ try {
+ if (!(metaDataType.trim().equalsIgnoreCase(NAME_LITERAL) || metaDataType
+ .trim().equalsIgnoreCase(TYPE_LITERAL)))
+ throw new OdaException(
+ Messages.getString("query_ARGUMENT_ERROR")); //$NON-NLS-1$
+
+ // if want to discover type information then just skip all the empty
+ // lines and the first line
+ if (metaDataType.trim().equalsIgnoreCase(TYPE_LITERAL)) {
+ while (ExcelFileSource.isEmptyRow(excelFileSource.readLine()))
+ continue;
+ }
+ // Skip all the empty lines until reach the first line
+ List<String> columnNameLine;
+ while (ExcelFileSource.isEmptyRow(columnNameLine = excelFileSource
+ .readLine()))
+ continue;
+
+ String[] result = excelFileSource
+ .getColumnNameArray(columnNameLine);
+
+ if (metaDataType.trim().equalsIgnoreCase(NAME_LITERAL))
+ this.validateUniqueName(result);
+ if (metaDataType.trim().equalsIgnoreCase(TYPE_LITERAL))
+ validateColumnTypeConsistency(result);
+
+ return trimStringArray(result);
+
+ } catch (IOException e) {
+ throw new OdaException(e);
+ } finally {
+ if (excelFileSource != null)
+ excelFileSource.close();
+ }
+ }
+
+ private String[] createTempColumnNames(int columnCount) {
+ String[] tempColumnNames = new String[columnCount];
+
+ for (int i = 0; i < columnCount; i++) {
+ tempColumnNames[i] = "COLUMN_" + (i + 1); //$NON-NLS-1$
+ }
+
+ return tempColumnNames;
+ }
+
+ private String[] createTempColumnTypes(int columnCount) {
+ String[] tempColumnTypes = new String[columnCount];
+
+ for (int i = 0; i < columnCount; i++) {
+ tempColumnTypes[i] = "STRING"; //$NON-NLS-1$
+ }
+
+ return tempColumnTypes;
+ }
+
+ /**
+ * @param cCN
+ * @return
+ */
+ private boolean isWildCard(String cCN) {
+ if (cCN.equalsIgnoreCase(ExcelODAConstants.KEYWORD_ASTERISK))
+ return true;
+ return false;
+ }
+
+ private void validateUniqueName(String[] aCN) throws OdaException {
+ for (int i = 0; i < aCN.length; i++) {
+ if (this.findOccuranceOfValueInStringArray(aCN[i], aCN) > 1) {
+ throw new OdaException(
+ Messages.getString("query_SOURCE_DATA_ERROR")); //$NON-NLS-1$
+ }
+ }
+ }
+
+ private void validateColumnTypeConsistency(String[] aCT)
+ throws OdaException {
+ if (!this.hasTypeLine)
+ return;
+ for (int i = 0; i < aCT.length; i++) {
+ if (!DataTypes.isValidType(aCT[i])) {
+ throw new OdaException("TYPE_NAME_INVALID" + aCT[i]); //$NON-NLS-1$
+ }
+ }
+ }
+
+ private int findOccuranceOfValueInStringArray(String value, String[] array) {
+ int count = 0;
+ for (int i = 0; i < array.length; i++) {
+ if (value.trim().equalsIgnoreCase(array[i].trim()))
+ count++;
+ }
+ return count;
+ }
+
+ /**
+ * @param result
+ * @return
+ */
+ private String[] trimStringArray(String[] array) {
+ String[] result = new String[array.length];
+ for (int i = 0; i < result.length; i++)
+ result[i] = array[i].trim();
+ return result;
+ }
+
+ /**
+ * Check whether a column name given in query has exactly one occurance in
+ * actual table
+ *
+ * @param cCN
+ * the array of column names in query
+ * @param aCN
+ * the array of column names in actual table
+ * @throws OdaException
+ */
+ private void validateColumnName(String[] cCN, String[] aCN)
+ throws OdaException {
+ for (int i = 0; i < cCN.length; i++) {
+ if (this.findOccuranceOfValueInStringArray(cCN[i], aCN) != 1) {
+ this.isInvalidQuery = true;
+ throw new OdaException(
+ Messages.getString("query_COMMAND_NOT_VALID")); //$NON-NLS-1$
+ }
+ }
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#setAppContext(java.lang
+ * .Object)
+ */
+ public void setAppContext(Object context) throws OdaException {
+ // do nothing; assumes no support for pass-through context
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#close()
+ */
+ public void close() throws OdaException {
+ maxRows = 0;
+ connection = null;
+ resultSetMetaData = null;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#getMetaData()
+ */
+ public IResultSetMetaData getMetaData() throws OdaException {
+ if (resultSetMetaData == null)
+ prepareMetaData();
+ return resultSetMetaData;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#executeQuery()
+ */
+ public IResultSet executeQuery() throws OdaException {
+ if (this.isInvalidQuery)
+ throw new OdaException(
+ Messages.getString("query_COMMAND_NOT_VALID")); //$NON-NLS-1$
+
+ return new ResultSet(new ExcelFileSource(this.connProperties,
+ this.currentTableName, worksheetNames, this.dateFormatString,
+ this.maxRows, this.resultSetMetaData,
+ this.resultSetMetaDataHelper), this.resultSetMetaData);
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#setProperty(java.lang.String
+ * , java.lang.String)
+ */
+ public void setProperty(String name, String value) throws OdaException {
+ if (name.equals(ExcelODAConstants.CONN_WORKSHEETS_PROP))
+ this.worksheetNames = value;
+ if (name.equals(ExcelODAConstants.CONN_DATE_FORMAT_PROP)) {
+ if (name == null || name.trim().equals(""))
+ throw new OdaException(Messages.getString("date_format_null"));
+ this.dateFormatString = value;
+ }
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#setMaxRows(int)
+ */
+ public void setMaxRows(int max) throws OdaException {
+ maxRows = max;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#getMaxRows()
+ */
+ public int getMaxRows() throws OdaException {
+ return maxRows;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#clearInParameters()
+ */
+ public void clearInParameters() throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to input parameter
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#setInt(java.lang.String,
+ * int)
+ */
+ public void setInt(String parameterName, int value) throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to named input parameter
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#setInt(int, int)
+ */
+ public void setInt(int parameterId, int value) throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to input parameter
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#setDouble(java.lang.String,
+ * double)
+ */
+ public void setDouble(String parameterName, double value)
+ throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to named input parameter
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#setDouble(int, double)
+ */
+ public void setDouble(int parameterId, double value) throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to input parameter
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#setBigDecimal(java.lang
+ * .String, java.math.BigDecimal)
+ */
+ public void setBigDecimal(String parameterName, BigDecimal value)
+ throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to named input parameter
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#setBigDecimal(int,
+ * java.math.BigDecimal)
+ */
+ public void setBigDecimal(int parameterId, BigDecimal value)
+ throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to input parameter
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#setString(java.lang.String,
+ * java.lang.String)
+ */
+ public void setString(String parameterName, String value)
+ throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to named input parameter
+ System.out.println(parameterName);
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#setString(int,
+ * java.lang.String)
+ */
+ public void setString(int parameterId, String value) throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to input parameter
+ System.out.println(value);
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#setDate(java.lang.String,
+ * java.sql.Date)
+ */
+ public void setDate(String parameterName, Date value) throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to named input parameter
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#setDate(int,
+ * java.sql.Date)
+ */
+ public void setDate(int parameterId, Date value) throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to input parameter
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#setTime(java.lang.String,
+ * java.sql.Time)
+ */
+ public void setTime(String parameterName, Time value) throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to named input parameter
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#setTime(int,
+ * java.sql.Time)
+ */
+ public void setTime(int parameterId, Time value) throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to input parameter
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#setTimestamp(java.lang.
+ * String, java.sql.Timestamp)
+ */
+ public void setTimestamp(String parameterName, Timestamp value)
+ throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to named input parameter
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#setTimestamp(int,
+ * java.sql.Timestamp)
+ */
+ public void setTimestamp(int parameterId, Timestamp value)
+ throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to input parameter
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#setBoolean(java.lang.String
+ * , boolean)
+ */
+ public void setBoolean(String parameterName, boolean value)
+ throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to named input parameter
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#setBoolean(int,
+ * boolean)
+ */
+ public void setBoolean(int parameterId, boolean value) throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to input parameter
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#setObject(java.lang.String,
+ * java.lang.Object)
+ */
+ public void setObject(String parameterName, Object value)
+ throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to named input parameter
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#setObject(int,
+ * java.lang.Object)
+ */
+ public void setObject(int parameterId, Object value) throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to input parameter
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#setNull(java.lang.String)
+ */
+ public void setNull(String parameterName) throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to named input parameter
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#setNull(int)
+ */
+ public void setNull(int parameterId) throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to input parameter
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#findInParameter(java.lang
+ * .String)
+ */
+ public int findInParameter(String parameterName) throws OdaException {
+ // TODO Auto-generated method stub
+ // only applies to named input parameter
+ return 0;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#getParameterMetaData()
+ */
+ public IParameterMetaData getParameterMetaData() throws OdaException {
+ /*
+ * TODO Auto-generated method stub Replace with implementation to return
+ * an instance based on this prepared query.
+ */
+ return new ParameterMetaData();
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#setSortSpec(org.eclipse
+ * .datatools.connectivity.oda.SortSpec)
+ */
+ public void setSortSpec(SortSpec sortBy) throws OdaException {
+ // only applies to sorting, assumes not supported
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#getSortSpec()
+ */
+ public SortSpec getSortSpec() throws OdaException {
+ // only applies to sorting
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#setSpecification(org.eclipse
+ * .datatools.connectivity.oda.spec.QuerySpecification)
+ */
+ public void setSpecification(QuerySpecification querySpec)
+ throws OdaException, UnsupportedOperationException {
+ // assumes no support
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#getSpecification()
+ */
+ public QuerySpecification getSpecification() {
+ // assumes no support
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IQuery#getEffectiveQueryText()
+ */
+ public String getEffectiveQueryText() {
+ // TODO Auto-generated method stub
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.datatools.connectivity.oda.IQuery#cancel()
+ */
+ public void cancel() throws OdaException, UnsupportedOperationException {
+ // assumes unable to cancel while executing a query
+ throw new UnsupportedOperationException();
+ }
+
+ public Properties getConnectionProperties() {
+ return this.connProperties;
+ }
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ParameterMetaData.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ParameterMetaData.java
new file mode 100644
index 0000000..66b843d
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ParameterMetaData.java
@@ -0,0 +1,106 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+
+package org.eclipse.birt.report.data.oda.excel.impl;
+
+import org.eclipse.datatools.connectivity.oda.IParameterMetaData;
+import org.eclipse.datatools.connectivity.oda.OdaException;
+
+/**
+ * Implementation class of IParameterMetaData for an ODA runtime driver.
+ * <br>
+ * For demo purpose, the auto-generated method stubs have
+ * hard-coded implementation that returns a pre-defined set
+ * of meta-data and query results.
+ * A custom ODA driver is expected to implement own data source specific
+ * behavior in its place.
+ */
+public class ParameterMetaData implements IParameterMetaData
+{
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#getParameterCount()
+ */
+ public int getParameterCount() throws OdaException
+ {
+ // TODO replace with data source specific implementation
+
+ // hard-coded for demo purpose
+ return 1;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#getParameterMode(int)
+ */
+ public int getParameterMode( int param ) throws OdaException
+ {
+ // TODO Auto-generated method stub
+ return IParameterMetaData.parameterModeIn;
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#getParameterName(int)
+ */
+ public String getParameterName( int param ) throws OdaException
+ {
+ // TODO Auto-generated method stub
+ return null; // name is not available
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#getParameterType(int)
+ */
+ public int getParameterType( int param ) throws OdaException
+ {
+ // TODO replace with data source specific implementation
+
+ // hard-coded for demo purpose
+ return java.sql.Types.CHAR; // as defined in data set extension manifest
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#getParameterTypeName(int)
+ */
+ public String getParameterTypeName( int param ) throws OdaException
+ {
+ int nativeTypeCode = getParameterType( param );
+ return Driver.getNativeDataTypeName( nativeTypeCode );
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#getPrecision(int)
+ */
+ public int getPrecision( int param ) throws OdaException
+ {
+ // TODO Auto-generated method stub
+ return -1;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#getScale(int)
+ */
+ public int getScale( int param ) throws OdaException
+ {
+ // TODO Auto-generated method stub
+ return -1;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IParameterMetaData#isNullable(int)
+ */
+ public int isNullable( int param ) throws OdaException
+ {
+ // TODO Auto-generated method stub
+ return IParameterMetaData.parameterNullableUnknown;
+ }
+
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ResultSet.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ResultSet.java
new file mode 100644
index 0000000..3cac049
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ResultSet.java
@@ -0,0 +1,559 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+
+package org.eclipse.birt.report.data.oda.excel.impl;
+
+import java.math.BigDecimal;
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.TimeZone;
+
+import org.eclipse.birt.report.data.oda.excel.impl.i18n.Messages;
+import org.eclipse.birt.report.data.oda.excel.impl.util.ExcelFileSource;
+import org.eclipse.datatools.connectivity.oda.IBlob;
+import org.eclipse.datatools.connectivity.oda.IClob;
+import org.eclipse.datatools.connectivity.oda.IResultSet;
+import org.eclipse.datatools.connectivity.oda.IResultSetMetaData;
+import org.eclipse.datatools.connectivity.oda.OdaException;
+
+import com.ibm.icu.text.NumberFormat;
+import com.ibm.icu.util.ULocale;
+
+/**
+ * Flat file data provider's implementation of the ODA IResultSet interface.
+ */
+
+public class ResultSet implements IResultSet {
+
+ public static final int DEFAULT_MAX_ROWS = 1000;
+ private static final int CURSOR_INITIAL_VALUE = -1;
+ private String[][] sourceData = null;
+ private ResultSetMetaData resultSetMetaData = null;
+ private int maxRows = 0;
+ private int cursor = CURSOR_INITIAL_VALUE;
+ private ExcelFileSource excelFileSource;
+ // Boolean which marks whether it is successful of last call to getXXX();
+ private boolean wasNull = false;
+ // a counter that counts the total number of rows read from the excel file
+ private int fetchAccumulator = 0;
+
+ private boolean overFlow = false;
+
+ private static ULocale JRE_DEFAULT_LOCALE = ULocale.getDefault();
+
+ private DateFormat dateFormat;
+ /** The Excel epoch in milliseconds */
+ final static private long EXCEL_EPOCH_MILLIS = -2209161600000L;
+ /** The number of milliseconds in a day */
+ final static private BigDecimal MILLIS_IN_DAY = new BigDecimal(24 * 60 * 60 * 1000);
+ /**
+ * Constructor
+ *
+ * @param excelSource
+ * flat file data source reader
+ * @param rsmd
+ */
+ ResultSet(ExcelFileSource excelSource, ResultSetMetaData rsmd) {
+ assert excelSource != null;
+ this.excelFileSource = excelSource;
+ this.resultSetMetaData = rsmd;
+ this.maxRows = this.excelFileSource.getMaxRowsToRead(this.maxRows);
+ this.dateFormat = new SimpleDateFormat(
+ this.excelFileSource.getDateFormatString());
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#getMetaData()
+ */
+ public IResultSetMetaData getMetaData() throws OdaException {
+ return this.resultSetMetaData;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#close()
+ */
+ public void close() throws OdaException {
+ this.cursor = 0;
+ this.sourceData = null;
+ this.resultSetMetaData = null;
+ this.excelFileSource.closeFileSource();
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#setMaxRows(int)
+ */
+ public void setMaxRows(int max) throws OdaException {
+ this.maxRows = max;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#next()
+ */
+ public boolean next() throws OdaException {
+ if (overFlow) {
+ return false;
+ }
+ // first time to call next
+ if (cursor == CURSOR_INITIAL_VALUE) {
+ sourceData = this.excelFileSource.getSourceData();
+ }
+
+ if ((this.maxRows <= 0 ? false : fetchAccumulator >= this.maxRows)) {
+ this.excelFileSource.closeFileSource();
+ cursor = CURSOR_INITIAL_VALUE;
+ overFlow = true;
+ return false;
+ }
+
+ if (cursor == this.sourceData.length - 1) {
+ sourceData = this.excelFileSource.getSourceData();
+ cursor = CURSOR_INITIAL_VALUE;
+
+ if (sourceData.length == 0) {
+ this.excelFileSource.closeFileSource();
+ overFlow = true;
+ return false;
+ }
+ }
+
+ fetchAccumulator++;
+ cursor++;
+
+ return true;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#getRow()
+ */
+ public int getRow() throws OdaException {
+ validateCursorState();
+ return this.fetchAccumulator;
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#getString(int)
+ */
+ public String getString(int index) throws OdaException {
+ validateCursorState();
+ String result = sourceData[cursor][index - 1];
+ this.wasNull = result == null ? true : false;
+ return result;
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSet#getString(java.lang
+ * .String)
+ */
+ public String getString(String columnName) throws OdaException {
+ validateCursorState();
+ int columnIndex = findColumn(columnName);
+ return getString(columnIndex);
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#getInt(int)
+ */
+ public int getInt(int index) throws OdaException {
+ return stringToInt(getString(index));
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSet#getInt(java.lang.String
+ * )
+ */
+ public int getInt(String columnName) throws OdaException {
+ return stringToInt(getString(columnName));
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#getDouble(int)
+ */
+ public double getDouble(int index) throws OdaException {
+ return stringToDouble(getString(index));
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSet#getDouble(java.lang
+ * .String)
+ */
+ public double getDouble(String columnName) throws OdaException {
+ return stringToDouble(getString(columnName));
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#getBigDecimal(int)
+ */
+ public BigDecimal getBigDecimal(int index) throws OdaException {
+ return stringToBigDecimal(getString(index));
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSet#getBigDecimal(java.
+ * lang.String)
+ */
+ public BigDecimal getBigDecimal(String columnName) throws OdaException {
+ return stringToBigDecimal(getString(columnName));
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#getDate(int)
+ */
+ public Date getDate(int index) throws OdaException {
+ return stringToDate(getString(index));
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSet#getDate(java.lang.String
+ * )
+ */
+ public Date getDate(String columnName) throws OdaException {
+ return stringToDate(getString(columnName));
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#getTime(int)
+ */
+ public Time getTime(int index) throws OdaException {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSet#getTime(java.lang.String
+ * )
+ */
+ public Time getTime(String columnName) throws OdaException {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#getTimestamp(int)
+ */
+ public Timestamp getTimestamp(int index) throws OdaException {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSet#getTimestamp(java.lang
+ * .String)
+ */
+ public Timestamp getTimestamp(String columnName) throws OdaException {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#getBlob(int)
+ */
+ public IBlob getBlob(int index) throws OdaException {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSet#getBlob(java.lang.String
+ * )
+ */
+ public IBlob getBlob(String columnName) throws OdaException {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#getClob(int)
+ */
+ public IClob getClob(int index) throws OdaException {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSet#getClob(java.lang.String
+ * )
+ */
+ public IClob getClob(String columnName) throws OdaException {
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#getBoolean(int)
+ */
+ public boolean getBoolean(int index) throws OdaException {
+ return stringToBoolean(getString(index)).booleanValue();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSet#getBoolean(java.lang
+ * .String)
+ */
+ public boolean getBoolean(String columnName) throws OdaException {
+ return stringToBoolean(getString(columnName)).booleanValue();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#getObject(int)
+ */
+ public Object getObject(int index) throws OdaException {
+ // TODO Auto-generated method stub
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSet#getObject(java.lang
+ * .String)
+ */
+ public Object getObject(String columnName) throws OdaException {
+ // TODO Auto-generated method stub
+ throw new UnsupportedOperationException();
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IResultSet#wasNull()
+ */
+ public boolean wasNull() throws OdaException {
+ return this.wasNull;
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSet#findColumn(java.lang
+ * .String)
+ */
+ public int findColumn(String columnName) throws OdaException {
+ return resultSetMetaData.findColumn(columnName);
+ }
+
+ /**
+ * Validate whether the cursor has been initialized and at a valid row.
+ *
+ * @throws OdaException
+ * if the cursor is not initialized
+ */
+ private void validateCursorState() throws OdaException {
+ if (this.cursor < 0)
+ throw new OdaException(
+ Messages.getString("resultSet_CURSOR_HAS_NOT_BEEN_INITIALIZED")); //$NON-NLS-1$
+ }
+
+ /**
+ * Transform a String value to an int value
+ *
+ * @param stringValue
+ * String value
+ * @return Corresponding int value
+ */
+ private int stringToInt(String stringValue) {
+ if (stringValue != null) {
+ try {
+ return new Integer(stringValue).intValue();
+ } catch (NumberFormatException e) {
+ try {
+ Number number = NumberFormat
+ .getInstance(JRE_DEFAULT_LOCALE).parse(stringValue);
+ if (number != null) {
+ return number.intValue();
+ }
+ } catch (ParseException e1) {
+ }
+ }
+ }
+ this.wasNull = true;
+ return 0;
+ }
+
+ /**
+ * Transform a String value to a double value
+ *
+ * @param stringValue
+ * String value
+ * @return Corresponding double value
+ */
+ private double stringToDouble(String stringValue) {
+ if (stringValue != null) {
+ try {
+ return new Double(stringValue).doubleValue();
+ } catch (NumberFormatException e) {
+ try {
+ Number number = NumberFormat
+ .getInstance(JRE_DEFAULT_LOCALE).parse(stringValue);
+ if (number != null) {
+ return number.doubleValue();
+ }
+ } catch (ParseException e1) {
+ }
+ }
+ }
+ this.wasNull = true;
+ return 0;
+ }
+
+ /**
+ * Transform a String value to a big decimal value
+ *
+ * @param stringValue
+ * String value
+ * @return Corresponding BigDecimal value
+ */
+ private BigDecimal stringToBigDecimal(String stringValue) {
+ if (stringValue != null) {
+ try {
+ return new BigDecimal(stringValue);
+ } catch (NumberFormatException e) {
+ try {
+ Number number = NumberFormat
+ .getInstance(JRE_DEFAULT_LOCALE).parse(stringValue);
+ if (number != null) {
+ return new BigDecimal(number.toString());
+ }
+ } catch (ParseException e1) {
+ }
+ }
+ }
+ this.wasNull = true;
+ return null;
+ }
+
+ /**
+ * Transform a String value to a date value
+ *
+ * @param stringValue
+ * String value
+ * @return Corresponding date value
+ * @throws OdaException
+ */
+
+ private Date stringToDate(String stringValue) throws OdaException {
+ if (stringValue != null && stringValue.length() > 0) {
+ try {
+ java.util.Date date = dateFormat.parse(stringValue);
+ return new Date(date.getTime());
+ } catch (ParseException e) {
+ try{
+ return new Date (excelDateToDate(Double.parseDouble(stringValue)).getTime());
+
+
+ } catch( Exception ex){
+
+ throw new OdaException(Messages.getFormattedString(
+ "invalid_date_value", new String[] { stringValue }));
+ }
+ }
+ }
+
+ this.wasNull = true;
+ return null;
+ }
+
+ /**
+ * Transform a string to boolean value
+ *
+ * @param stringValue
+ * @return
+ */
+ private Boolean stringToBoolean(String stringValue) {
+ if (stringValue != null) {
+ if (stringValue.equalsIgnoreCase("true")) //$NON-NLS-1$
+ return Boolean.TRUE;
+ else if (stringValue.equalsIgnoreCase("false")) //$NON-NLS-1$
+ return Boolean.FALSE;
+ else {
+ try {
+ if (Integer.parseInt((String) stringValue) == 0)
+ return Boolean.FALSE;
+ else
+ return Boolean.TRUE;
+ } catch (NumberFormatException e) {
+ try {
+ Number number = NumberFormat.getInstance(
+ JRE_DEFAULT_LOCALE).parse(stringValue);
+ if (number != null) {
+ return number.intValue() == 0 ? Boolean.FALSE
+ : Boolean.TRUE;
+ }
+ } catch (ParseException e1) {
+ }
+ }
+ }
+ }
+ return Boolean.FALSE;
+ }
+
+
+ /**
+ * Creates a Java Date object from an Excel numeric date value
+ * @param number the Excel date to convert
+ * @return the Date object corresponding to the specified numeric Excel date
+ */
+ public static java.util.Date excelDateToDate(double number)
+ {
+ Calendar calendar = excelDateToCalendar(number, null);
+ return calendar.getTime();
+ }
+ /**
+ * Creates an Java Calendar object from an Excel numeric date value
+ * @param number the Excel date to convert
+ * @param tz the time-zone to use, or null for the default time-zone
+ * @return the Calendar object corresponding to the specified numeric date
+ */
+ private static Calendar excelDateToCalendar(double number, TimeZone tz)
+ {
+ if (tz == null)
+ {
+ tz = TimeZone.getDefault();
+ }
+ Calendar calendar = Calendar.getInstance(tz);
+ long millis = excelDateToMilliseconds(number);
+ millis -= calendar.getTimeZone().getOffset(millis);
+ calendar.setTimeInMillis(millis);
+ //Excel considers 1900 to be a leap year. Must correct for that.
+ final long dec311899 = -2209143600000L; //December 31, 1899
+ final long mar011900 = -2203873200000L; //March 1, 1900
+ if (millis >= dec311899 && millis < mar011900)
+ {
+ calendar.add(Calendar.DAY_OF_YEAR, 1);
+ }
+ return calendar;
+ }
+ /**
+ * @param number the Excel date value to convert
+ * @return the number of milliseconds since the 1970 (Java) epoch
+ */
+ private static long excelDateToMilliseconds(double number)
+ {
+ long millis = (long)(number * MILLIS_IN_DAY.doubleValue());
+ millis += EXCEL_EPOCH_MILLIS;
+ return millis;
+ }
+
+
+
+
+} \ No newline at end of file
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ResultSetMetaData.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ResultSetMetaData.java
new file mode 100644
index 0000000..d756072
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/ResultSetMetaData.java
@@ -0,0 +1,168 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+
+package org.eclipse.birt.report.data.oda.excel.impl;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.eclipse.birt.report.data.oda.excel.ResultSetMetaDataHelper;
+import org.eclipse.birt.report.data.oda.excel.impl.i18n.Messages;
+import org.eclipse.birt.report.data.oda.excel.impl.util.DataTypes;
+import org.eclipse.datatools.connectivity.oda.IResultSetMetaData;
+import org.eclipse.datatools.connectivity.oda.OdaException;
+
+/**
+ * Implementation class of IResultSetMetaData for an ODA runtime driver. <br>
+ * For demo purpose, the auto-generated method stubs have hard-coded
+ * implementation that returns a pre-defined set of meta-data and query results.
+ * A custom ODA driver is expected to implement own data source specific
+ * behavior in its place.
+ */
+public class ResultSetMetaData implements IResultSetMetaData {
+
+ private String[] columnNames = null;
+ private String[] columnTypeNames = null;
+
+ private Map<String, Integer> columnNameIndexMap = new HashMap<String, Integer>();
+
+ public ResultSetMetaData(String[] columnNames, String[] columnTypeNames) {
+ this.columnNames = columnNames;
+ this.columnTypeNames = columnTypeNames;
+
+ for (int i = 0; i < columnNames.length; i++) {
+ columnNameIndexMap.put(columnNames[i].toUpperCase(),
+ Integer.valueOf(i + 1));
+ }
+ }
+
+ public ResultSetMetaData(ResultSetMetaDataHelper rsmdHelper) throws OdaException {
+ if( rsmdHelper == null )
+ throw new OdaException( Messages.getString( "common_ARGUMENT_CANNOT_BE_NULL" ) ); //$NON-NLS-1$
+
+ this.columnNames = rsmdHelper.getColumnNames( );
+ this.columnTypeNames = rsmdHelper.getColumnTypes( );
+
+ for (int i = 0; i < columnNames.length; i++)
+ {
+ columnNameIndexMap.put( columnNames[i].toUpperCase( ), Integer.valueOf( i + 1 ) );
+ }
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSetMetaData#getColumnCount
+ * ()
+ */
+ public int getColumnCount() throws OdaException {
+ return this.columnNames.length;
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSetMetaData#getColumnName
+ * (int)
+ */
+ public String getColumnName(int index) throws OdaException {
+ validateColumnIndex(index);
+ return this.columnNames[index - 1].trim();
+ }
+
+ /**
+ * Evaluate whether the value of given column number is valid.
+ *
+ * @param index
+ * column number (1-based)
+ * @throws OdaException
+ * if the given index value is invalid
+ */
+ private void validateColumnIndex(int index) throws OdaException {
+ if (index > getColumnCount() || index < 1)
+ throw new OdaException("INVALID_COLUMN_INDEX" + index); //$NON-NLS-1$
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSetMetaData#getColumnLabel
+ * (int)
+ */
+ public String getColumnLabel(int index) throws OdaException {
+ return getColumnName(index); // default
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSetMetaData#getColumnType
+ * (int)
+ */
+ public int getColumnType(int index) throws OdaException {
+ validateColumnIndex(index);
+ return DataTypes.getTypeCode(columnTypeNames[index - 1]);
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSetMetaData#getColumnTypeName
+ * (int)
+ */
+ public String getColumnTypeName(int index) throws OdaException {
+ int nativeTypeCode = getColumnType(index);
+ return Driver.getNativeDataTypeName(nativeTypeCode);
+ }
+
+ /*
+ * @see org.eclipse.datatools.connectivity.oda.IResultSetMetaData#
+ * getColumnDisplayLength(int)
+ */
+ public int getColumnDisplayLength(int index) throws OdaException {
+ return(0);
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSetMetaData#getPrecision
+ * (int)
+ */
+ public int getPrecision(int index) throws OdaException {
+ // TODO Auto-generated method stub
+ return -1;
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSetMetaData#getScale(int)
+ */
+ public int getScale(int index) throws OdaException {
+ // TODO Auto-generated method stub
+ return -1;
+ }
+
+ /*
+ * @see
+ * org.eclipse.datatools.connectivity.oda.IResultSetMetaData#isNullable(int)
+ */
+ public int isNullable(int index) throws OdaException {
+ // TODO Auto-generated method stub
+ return IResultSetMetaData.columnNullableUnknown;
+ }
+
+ public int findColumn(String columnName) throws OdaException {
+ String trimmedColumnName = columnName.trim();
+ Integer index = (Integer) (columnNameIndexMap.get(trimmedColumnName
+ .toUpperCase()));
+ if (index == null) {
+ throw new OdaException("resultSet_COLUMN_NOT_FOUND " + columnName); //$NON-NLS-1$
+ } else {
+ return index.intValue();
+ }
+ }
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/i18n/Messages.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/i18n/Messages.java
new file mode 100644
index 0000000..0430a69
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/i18n/Messages.java
@@ -0,0 +1,44 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+package org.eclipse.birt.report.data.oda.excel.impl.i18n;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+public class Messages
+{
+ private static final String BUNDLE_NAME = "org.eclipse.birt.report.data.oda.excel.impl.i18n.messages"; //$NON-NLS-1$
+
+ private static final ResourceBundle RESOURCE_BUNDLE =
+ ResourceBundle.getBundle(BUNDLE_NAME);
+
+ private Messages()
+ {
+ }
+
+ public static String getString( String key )
+ {
+ try
+ {
+ return RESOURCE_BUNDLE.getString( key );
+ }
+ catch( MissingResourceException e )
+ {
+ return '!' + key + '!';
+ }
+ }
+
+ public static String getFormattedString( String key, Object[] arguments )
+ {
+ return MessageFormat.format( getString( key ), arguments );
+ }
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/i18n/messages.properties b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/i18n/messages.properties
new file mode 100644
index 0000000..3549518
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/i18n/messages.properties
@@ -0,0 +1,45 @@
+# Exception messages for the Oda Excel File Driver
+
+connection_CONNECTION_PROPERTIES_MISSING=Connection properties are missing.
+connection_CANNOT_OPEN_EXCEL_FILE_DB_DIR=Cannot open excel file database under directory:
+
+query_COMMAND_IS_EMPTY=Query command is empty.
+query_DO_NOT_SUPPORT_CROSS_TABLE_QUERY=Cross-table query is not supported.
+query_COMMAND_NOT_VALID=Invalid header information in the supplied excel file.
+query_ARGUMENT_ERROR=The argument should be either 'NAME' or 'TYPE'.
+query_IO_EXCEPTION=An I/O Exception occurred when reading the file.
+query_SOURCE_DATA_ERROR=Duplicate column names found in source data.
+query_COLUMN_NAME_ERROR=Column name error
+query_INVALID_EXCEL_FILE=The sheet does not contain any data. Please select a different sheet.
+query_text_error=Query-text format error
+query_WORKSHEET_CANNOT_BE_NULL=Worksheet name cannot be null.
+resultSet_COLUMN_NOT_FOUND=Column not found:
+resultSet_CURSOR_HAS_NOT_BEEN_INITIALIZED=Cursor has not been initialized yet.
+
+resultSetMetaData_INVALID_COLUMN_INDEX=Invalid column index:
+
+savedSelectedColumnsInfoString_INVALID=Invalid Saved Columns Information
+
+dataTypes_TYPE_NAME_INVALID=Invalid type name:
+
+dataSetMetaData_PRODUCT_NAME=DTP ODA Flat File Data Source Provider
+
+common_ARGUMENT_CANNOT_BE_NULL=Arguments cannot be null.
+common_CONNECTION_HAS_NOT_OPEN=Connection is not open.
+common_CANNOT_FIND_COLUMN=Cannot find any columns.
+common_NULL_QUERY_TEXT = Query text is null
+
+data_read_error=Cannot read data correctly, data source settings probably changed
+
+Invalid_column_name = Invalid column name
+
+invalid_excelfile_format = Invalid excel file format
+date_format_null = Date format cannot be null.
+invalid_date_value = {0} cannot be parsed as a valid date. Please check the date format in the data set properties.
+invalid_sheet_name = Supplied file does not contain any sheet by name {0}
+
+query_streamClosed=Stream closed
+query_invalidTableName=Invalid table name:
+
+dateUtil.ConvertFails=Convert to date fails. Source:
+dateFormatISO_cannotConvert=Cannot convert the value of {0}. \ No newline at end of file
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/DataTypes.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/DataTypes.java
new file mode 100644
index 0000000..bb9e2e7
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/DataTypes.java
@@ -0,0 +1,107 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+
+package org.eclipse.birt.report.data.oda.excel.impl.util;
+
+import java.sql.Types;
+
+import org.eclipse.birt.report.data.oda.excel.impl.i18n.Messages;
+import org.eclipse.datatools.connectivity.oda.OdaException;
+import org.eclipse.datatools.connectivity.oda.util.manifest.DataTypeMapping;
+import org.eclipse.datatools.connectivity.oda.util.manifest.ExtensionManifest;
+import org.eclipse.datatools.connectivity.oda.util.manifest.ManifestExplorer;
+
+/**
+ * Defines the data types that are supported by this driver.
+ */
+
+public final class DataTypes {
+
+ static final int STRING = Types.VARCHAR;
+ static final int NULL = Types.NULL;
+ static final String NULL_LITERAL = "NULL"; //$NON-NLS-1$
+ static final String STRING_LITERAL = "STRING"; //$NON-NLS-1$
+
+ private static final String EXCEL_DATA_SOURCE_ID = "org.eclipse.birt.report.data.oda.excel"; //$NON-NLS-1$
+
+ /**
+ * Returns the data type code that represents the given type name.
+ *
+ * @param typeName
+ * a data type name
+ * @return the data type code that represents the given type name
+ * @throws OdaException
+ * If the given data type name is invalid
+ */
+ public static int getTypeCode(String typeName) throws OdaException {
+ if (typeName == null || typeName.trim().length() == 0)
+ return STRING; // default data type
+
+ if (typeName.equals(STRING_LITERAL))
+ return STRING;
+
+ String preparedTypeName = typeName.trim().toUpperCase();
+
+ if (preparedTypeName.equals(NULL_LITERAL))
+ return NULL;
+
+ // get the data type definition from my plugin manifest for all other
+ // types
+ DataTypeMapping typeMapping = getManifest().getDataSetType(null)
+ .getDataTypeMapping(preparedTypeName);
+ if (typeMapping != null)
+ return typeMapping.getNativeTypeCode();
+
+ throw new OdaException(Messages
+ .getString( "dataTypes_TYPE_NAME_INVALID" ) + typeName); //$NON-NLS-1$
+ }
+
+ /**
+ * Evaluates whether the given data type name is a valid type supported by
+ * this driver.
+ *
+ * @param typeName
+ * a data type name
+ * @return true if the given data type name is supported by the driver
+ */
+ public static boolean isValidType(String typeName) {
+ String preparedTypeName = typeName.trim().toUpperCase();
+
+ if (preparedTypeName.equals(NULL_LITERAL))
+ return true;
+
+ // check the data type definition in my plugin manifest for all other
+ // types
+ DataTypeMapping typeMapping = null;
+ try {
+ typeMapping = getManifest().getDataSetType(null)
+ .getDataTypeMapping(preparedTypeName);
+ } catch (OdaException e) {
+ // ignore
+ }
+
+ return (typeMapping != null);
+ }
+
+ private DataTypes() {
+ }
+
+ /**
+ * Returns the object that represents this extension's manifest.
+ *
+ * @throws OdaException
+ */
+ static ExtensionManifest getManifest() throws OdaException {
+ return ManifestExplorer.getInstance().getExtensionManifest(
+ EXCEL_DATA_SOURCE_ID);
+ }
+
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/ExcelFileReader.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/ExcelFileReader.java
new file mode 100644
index 0000000..b788859
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/ExcelFileReader.java
@@ -0,0 +1,261 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+package org.eclipse.birt.report.data.oda.excel.impl.util;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.FormulaEvaluator;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.eclipse.birt.report.data.oda.excel.ExcelODAConstants;
+import org.eclipse.birt.report.data.oda.excel.impl.i18n.Messages;
+import org.eclipse.datatools.connectivity.oda.OdaException;
+import org.xml.sax.SAXException;
+
+public class ExcelFileReader {
+
+ private FileInputStream fis;
+ private String fileExtension;
+ private List<String> workSheetList;
+ static LinkedHashMap<String, String> xlsxWorkSheetList;
+ private int currentSheetIndex = 0;
+
+ private Workbook workBook;
+ private Sheet sheet;
+ private FormulaEvaluator formulaEvaluator;
+
+ private boolean isInitialised;
+
+ private int maxRowsInAllSheet;
+ private int maxRowsInThisSheet;
+ private int currentRowIndex = 0;
+ private int maxColumnIndex = 0;
+ private XlsxRowCallBack callback;
+ private XlsxFileReader xlsxread;
+ Map<String, String> xlsxSheetRidNameMap;
+
+ public void setMaxColumnIndex(int maxColumnIndex) {
+ this.maxColumnIndex = maxColumnIndex;
+ }
+
+ public ExcelFileReader(FileInputStream fis, String fileExtension,
+ List<String> sheetNameList, String dateFormatString) {
+ this.fis = fis;
+ this.fileExtension = fileExtension;
+ this.workSheetList = sheetNameList;
+ }
+
+ public List<String> readLine() throws IOException, OdaException {
+ if (!isInitialised)
+ initialise();
+
+ if (currentRowIndex >= maxRowsInThisSheet) {
+ if (!initialiseNextSheet())
+ return null;
+ }
+ List<String> rowData = new ArrayList<String>();
+ if (!isXlsxFile(fileExtension)) {
+ Row row = sheet.getRow(currentRowIndex);
+ if (row != null) {
+ if (maxColumnIndex == 0)
+ maxColumnIndex = row.getLastCellNum();
+
+ for (short colIx = 0; colIx < maxColumnIndex; colIx++) {
+ Cell cell = row.getCell(colIx);
+ rowData.add(getCellValue(cell));
+ }
+
+ } else {
+ return null;
+ }
+ } else {
+ rowData = callback.getRow(currentRowIndex);
+ }
+
+ currentRowIndex++;
+ return rowData;
+
+ }
+
+ public void close() throws IOException {
+ this.fis.close();
+ }
+
+ private void initialise() throws IOException, OdaException {
+ try {
+ if (isXlsxFile(fileExtension)) {
+ xlsxread = new XlsxFileReader(fis);
+ callback = new XlsxRowCallBack();
+ xlsxSheetRidNameMap = xlsxread.getSheetNames();
+ String rid = xlsxSheetRidNameMap.get(workSheetList.get(currentSheetIndex));
+ xlsxread.processSheet(rid, callback);
+ maxRowsInThisSheet = callback.getMaxRowsInSheet();
+
+ for (String sheetName : workSheetList) {
+ rid = xlsxSheetRidNameMap.get(sheetName);
+ if (rid == null)
+ throw new OdaException(
+ Messages.getString("invalid_sheet_name"));
+
+ XlsxRowCallBack newCallback = new XlsxRowCallBack();
+ xlsxread.processSheet(rid, newCallback);
+ maxRowsInAllSheet += newCallback.getMaxRowsInSheet();
+ }
+
+ } else {
+
+ workBook = new HSSFWorkbook(fis);
+ formulaEvaluator = workBook.getCreationHelper()
+ .createFormulaEvaluator();
+ workBook.setMissingCellPolicy(Row.RETURN_NULL_AND_BLANK);
+ sheet = workBook.getSheet(workSheetList.get(currentSheetIndex));
+ maxRowsInThisSheet = sheet.getPhysicalNumberOfRows();
+
+ for (String sheetName : workSheetList) {
+ Sheet localSheet = workBook.getSheet(sheetName);
+ maxRowsInAllSheet += localSheet.getPhysicalNumberOfRows();
+ }
+ }
+ isInitialised = true;
+ } catch (NullPointerException e) {
+ throw new OdaException(e);
+ } catch (OpenXML4JException e) {
+ throw new OdaException(e);
+ } catch (SAXException e) {
+ throw new OdaException(e);
+ }
+ }
+
+ private boolean initialiseNextSheet() throws IOException, OdaException {
+ if (workSheetList.size() <= ++currentSheetIndex) {
+ return false;
+ }
+ if (isXlsxFile(fileExtension)) {
+ try {
+ String rid = xlsxSheetRidNameMap.get(workSheetList.get(currentSheetIndex));
+ callback = new XlsxRowCallBack();
+ xlsxread.processSheet(rid, callback);
+ maxRowsInThisSheet = callback.getMaxRowsInSheet();
+ } catch (OpenXML4JException e) {
+ throw new OdaException(e);
+ } catch (SAXException e) {
+ throw new OdaException(e);
+ }
+ } else {
+ do {
+ sheet = workBook.getSheet(workSheetList.get(currentSheetIndex));
+ maxRowsInThisSheet = sheet.getPhysicalNumberOfRows();
+ } while (maxRowsInThisSheet == 0
+ && (workSheetList.size() < ++currentSheetIndex));
+ }
+ if (maxRowsInThisSheet == 0)
+ return false;
+
+ currentRowIndex = 0;
+ return true;
+ }
+
+ private static boolean isXlsxFile(String extension) {
+ return !extension.equals(ExcelODAConstants.XLS_FORMAT);
+ }
+
+ public String getCellValue(Cell cell) {
+ if (cell == null)
+ return ExcelODAConstants.EMPTY_STRING;
+
+ if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
+ return resolveFormula(cell);
+ }
+
+ if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
+ /*if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
+ Date date = cell.getDateCellValue();
+ return dateFormat.format(date);
+ }*/
+ return ((Double) cell.getNumericCellValue()).toString();
+ }
+
+ return cell.toString();
+ }
+
+ private String resolveFormula(Cell cell) {
+ if (formulaEvaluator == null)
+ return cell.toString();
+
+ switch (formulaEvaluator.evaluateFormulaCell(cell)) {
+ case Cell.CELL_TYPE_BOOLEAN:
+ return ((Boolean) cell.getBooleanCellValue()).toString();
+
+ case Cell.CELL_TYPE_NUMERIC:
+ /*if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
+ Date date = cell.getDateCellValue();
+ return dateFormat.format(date);
+ }*/
+ return ((Double) cell.getNumericCellValue()).toString();
+
+ case Cell.CELL_TYPE_STRING:
+ return cell.getStringCellValue();
+
+ default:
+ return null;
+ }
+ }
+
+ public int getMaxRows() throws IOException, OdaException {
+ if (!isInitialised)
+ initialise();
+ return maxRowsInAllSheet;
+ }
+
+ public static List<String> getSheetNamesInExcelFile(File file) {
+ String extension = file.getName();
+ extension = extension.substring(extension.lastIndexOf(".") + 1,
+ extension.length());
+ FileInputStream fis;
+ List<String> sheetNames = new ArrayList<String>();
+ try {
+ fis = new FileInputStream(file);
+
+ if (isXlsxFile(extension)) {
+ XlsxFileReader poiRdr = new XlsxFileReader(fis);
+ xlsxWorkSheetList = poiRdr.getSheetNames();
+ for (Map.Entry<String, String> entry : xlsxWorkSheetList
+ .entrySet()) {
+ sheetNames.add(entry.getKey());
+ }
+ } else {
+ Workbook workBook = new HSSFWorkbook(fis);
+ for (int i = 0; i < workBook.getNumberOfSheets(); i++) {
+ sheetNames.add(workBook.getSheetName(i));
+ }
+ }
+ } catch (FileNotFoundException e) {
+ // do nothing
+ } catch (IOException e) {
+ // do nothing
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return sheetNames;
+ }
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/ExcelFileSource.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/ExcelFileSource.java
new file mode 100644
index 0000000..b59584d
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/ExcelFileSource.java
@@ -0,0 +1,533 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+package org.eclipse.birt.report.data.oda.excel.impl.util;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Properties;
+
+import org.eclipse.birt.report.data.oda.excel.ExcelODAConstants;
+import org.eclipse.birt.report.data.oda.excel.ResultSetMetaDataHelper;
+import org.eclipse.birt.report.data.oda.excel.impl.i18n.Messages;
+import org.eclipse.datatools.connectivity.oda.IResultSetMetaData;
+import org.eclipse.datatools.connectivity.oda.OdaException;
+
+public class ExcelFileSource {
+ private String fileExtension;
+ private boolean isReaderInitialised;
+ private IResultSetMetaData rsmd;
+ private ResultSetMetaDataHelper rsmdHelper;
+ private int statementMaxRows;
+ private String currentTableName;
+ private String homeDir;
+ private boolean hasColumnNames;
+ private boolean hasTypeLine;
+ private List<String> sheetNameList = new ArrayList<String>();
+ private ExcelFileReader excelFileReader;
+ private int resultSetMaxRows = 0;
+ private int maxRowsToRead = 0;
+ private int fetchCounter = 0;
+ // Max number of rows fetched each time from data source
+ public static final int MAX_ROWS_PER_FETCH = 65535;
+ private int[] selectColumIndexes;
+ private String[] originalColumnNames;
+ private boolean isFirstTimeToReadSourceData = true;
+ private List<String> nextDataLine;
+ private String dateFormatString;
+
+ public String getDateFormatString() {
+ return dateFormatString;
+ }
+
+ /**
+ * Constructor
+ *
+ * @param connProperties
+ * Connection properties
+ * @param currentTableName
+ * The current table name of this connection
+ * @param dateFormatString
+ * @param statementMaxRows
+ * The max number of rows specified in the query
+ * @param rsmd
+ * ResultSet meta-data
+ * @param rsmdHelper
+ * ResultSet meta-data helper
+ * @throws OdaException
+ */
+ public ExcelFileSource(Properties connProperties, String currentTableName,
+ String workSheetNames, String dateFormatString,
+ int statementMaxRows, IResultSetMetaData rsmd,
+ ResultSetMetaDataHelper rsmdHelper) throws OdaException {
+ this.rsmd = rsmd;
+ this.rsmdHelper = rsmdHelper;
+ this.statementMaxRows = statementMaxRows;
+ this.currentTableName = currentTableName;
+ this.dateFormatString = dateFormatString;
+ this.fileExtension = extractFileExtension(currentTableName);
+ Properties properties = getCopyOfConnectionProperties(connProperties);
+ populateHomeDir(properties);
+ populateHasColumnNames(properties);
+ populateHasTypeLine(properties);
+ populateWorksheetNames(workSheetNames);
+ }
+
+ private static String extractFileExtension(String fileName) {
+ int lastIndexOfDot = fileName.lastIndexOf('.');
+ if (lastIndexOfDot == -1) {
+ return ExcelODAConstants.XLS_FORMAT;
+ } else {
+ return fileName.substring(lastIndexOfDot + 1, fileName.length());
+ }
+ }
+
+ /**
+ *
+ * @param connProperties
+ * @return
+ */
+ private Properties getCopyOfConnectionProperties(Properties connProperties) {
+ Properties copyConnProperites = new Properties();
+
+ copyConnProperites.setProperty(ExcelODAConstants.CONN_HOME_DIR_PROP,
+ connProperties
+ .getProperty(ExcelODAConstants.CONN_HOME_DIR_PROP));
+ copyConnProperites
+ .setProperty(
+ ExcelODAConstants.CONN_INCLCOLUMNNAME_PROP,
+ connProperties
+ .getProperty(ExcelODAConstants.CONN_INCLCOLUMNNAME_PROP));
+ copyConnProperites.setProperty(
+ ExcelODAConstants.CONN_INCLTYPELINE_PROP, connProperties
+ .getProperty(ExcelODAConstants.CONN_INCLTYPELINE_PROP));
+
+ return copyConnProperites;
+ }
+
+ /**
+ *
+ * @param connProperties
+ * @throws OdaException
+ */
+ private void populateHomeDir(Properties connProperties) throws OdaException {
+ this.homeDir = connProperties
+ .getProperty(ExcelODAConstants.CONN_HOME_DIR_PROP);
+ File file = new File(this.homeDir);
+ if (!file.exists())
+ throw new OdaException(
+ Messages.getString("connection_CANNOT_OPEN_EXCEL_FILE_DB_DIR") //$NON-NLS-1$
+ + this.homeDir);
+ }
+
+ /**
+ *
+ * @param connProperties
+ */
+ private void populateHasColumnNames(Properties connProperties) {
+ this.hasColumnNames = connProperties.getProperty(
+ ExcelODAConstants.CONN_INCLCOLUMNNAME_PROP).equalsIgnoreCase(
+ ExcelODAConstants.INC_COLUMN_NAME_NO) ? false : true;
+ }
+
+ /**
+ *
+ * @param connProperties
+ */
+ private void populateHasTypeLine(Properties connProperties) {
+ this.hasTypeLine = connProperties.getProperty(
+ ExcelODAConstants.CONN_INCLTYPELINE_PROP).equalsIgnoreCase(
+ ExcelODAConstants.INC_TYPE_LINE_NO) ? false : true;
+ }
+
+ /**
+ *
+ * @param connProperties
+ * @throws OdaException
+ */
+ private void populateWorksheetNames(String workSheetNames)
+ throws OdaException {
+ if (workSheetNames == null) {
+ throw new OdaException(
+ Messages.getString("query_WORKSHEET_CANNOT_BE_NULL") //$NON-NLS-1$
+ );
+ }
+ String[] workSheetNamesArray = workSheetNames
+ .split(ExcelODAConstants.DELIMITER_SEMICOLON_VALUE);
+ for (int index = 0; index < workSheetNamesArray.length; index++) {
+ sheetNameList.add(workSheetNamesArray[index]);
+ }
+ }
+
+ /**
+ *
+ * @param connProperties
+ * @param tableName
+ * @return
+ * @throws OdaException
+ */
+ public int getColumnCount() throws OdaException {
+ // this.currentTableName = tableName;
+
+ int count;
+ try {
+ String dataFilePath = findDataFileAbsolutePath();
+ FileInputStream fis = new FileInputStream(dataFilePath);
+ ExcelFileReader excelreader = new ExcelFileReader(fis,
+ fileExtension, sheetNameList, dateFormatString);
+ List<String> columnLine;
+ while (isEmptyRow(columnLine = excelreader.readLine())) {
+ continue;
+ }
+ count = columnLine.size();
+ fis.close();
+ } catch (IOException e) {
+ throw new OdaException(Messages.getString("query_IO_EXCEPTION") //$NON-NLS-1$
+ + findDataFileAbsolutePath());
+ }
+
+ return count;
+ }
+
+ /**
+ * Find the absolute path of the file in which a specific table resides.
+ *
+ * @param tableName
+ * the name of table
+ * @return the String which contains the absolute path of that table
+ * @throws OdaException
+ * if the table name cannot be found
+ */
+ public String findDataFileAbsolutePath() throws OdaException {
+ File file = new File(this.homeDir + File.separator
+ + this.currentTableName.trim());
+ if (!file.exists())
+ throw new OdaException(Messages.getString("query_invalidTableName")
+ + this.homeDir + File.separator + this.currentTableName); //$NON-NLS-1$
+ return file.getAbsolutePath();
+ }
+
+ /**
+ *
+ * @return
+ * @throws OdaException
+ */
+ public String[][] getSourceData() throws OdaException {
+ try {
+ initialiseReader();
+ List<String[]> v = fetchQueriedDataFromFileToList();
+ return copyDataFromListToTwoDimensionArray(v);
+ } catch (IOException e) {
+ throw new OdaException(e);
+ } finally {
+ try {
+ excelFileReader.close();
+ } catch (IOException e) {
+ //
+ }
+ }
+ }
+
+ /**
+ *
+ * @return
+ * @throws OdaException
+ */
+ private List<String[]> fetchQueriedDataFromFileToList() throws OdaException {
+ List<String[]> result = new ArrayList<String[]>();
+ try {
+ if (isFirstTimeToReadSourceData) {
+ // make a copy of column names if there are
+ if (this.hasColumnNames) {
+ List<String> columeNameLine;
+ while (isEmptyRow(columeNameLine = excelFileReader
+ .readLine())) {
+ continue;
+ }
+ this.originalColumnNames = getColumnNameArray(columeNameLine);
+ initNameIndexMap();
+ }
+
+ // skip Type information. The type information is in the second
+ // line
+ // of file
+ if (this.hasTypeLine) {
+ while (isEmptyRow(excelFileReader.readLine()))
+ continue;
+ }
+
+ if (!this.hasColumnNames) {
+ while (isEmptyRow(nextDataLine = excelFileReader.readLine())) {
+ continue;
+ }
+ this.originalColumnNames = createTempColumnNames(nextDataLine);
+ initNameIndexMap();
+ } else {
+ nextDataLine = excelFileReader.readLine();
+ }
+ excelFileReader.setMaxColumnIndex(originalColumnNames.length);
+ isFirstTimeToReadSourceData = false;
+ }
+
+ // temporary variable which is used to store the data of a row
+ // fetched from a the file
+
+ int counterLimitPerFetch = fetchCounter + MAX_ROWS_PER_FETCH;
+
+ while ((this.maxRowsToRead <= 0 ? true
+ : this.fetchCounter < this.maxRowsToRead)
+ && this.fetchCounter < counterLimitPerFetch
+ && nextDataLine != null) {
+ if (!isEmptyRow(nextDataLine)) {
+ fetchCounter++;
+ result.add(fetchQueriedDataFromRow(nextDataLine));
+ }
+ nextDataLine = excelFileReader.readLine();
+ }
+
+ return result;
+ } catch (IOException e) {
+ throw new OdaException(e.getMessage());
+ }
+ }
+
+ /**
+ * Feed the row data from a List to a two-dimension array. The string value
+ * is trimmed before being copied into array.
+ *
+ * @param v
+ * @return a String two dimension array with each horizontal array contains
+ * a row
+ * @throws OdaException
+ */
+ private String[][] copyDataFromListToTwoDimensionArray(List<String[]> v)
+ throws OdaException {
+ String[][] rowSet = new String[v.size()][this.rsmd.getColumnCount()];
+ for (int i = 0; i < v.size(); i++) {
+ String[] temp = (String[]) v.get(i);
+ for (int j = 0; j < temp.length; j++) {
+ if (temp[j] != null)
+ rowSet[i][j] = temp[j].trim();
+ else
+ throw new OdaException(
+ Messages.getString("data_read_error")); //$NON-NLS-1$
+ }
+ }
+ return rowSet;
+ }
+
+ private void initNameIndexMap() throws OdaException {
+ assert originalColumnNames != null;
+ HashMap<String, Integer> originalColumnNameIndexMap = new HashMap<String, Integer>();
+ for (int i = 0; i < originalColumnNames.length; i++) {
+ originalColumnNameIndexMap.put(originalColumnNames[i].trim()
+ .toUpperCase(), Integer.valueOf(i));
+ }
+ selectColumIndexes = new int[rsmd.getColumnCount()];
+
+ for (int i = 0; i < rsmd.getColumnCount(); i++) {
+ selectColumIndexes[i] = findIndex(
+ rsmdHelper.getOriginalColumnName(rsmd.getColumnName(i + 1)),
+ originalColumnNameIndexMap);
+ }
+ }
+
+ /**
+ *
+ * @param columnCount
+ * @return
+ * @throws OdaException
+ */
+ private String[] createTempColumnNames(List<String> aRow)
+ throws OdaException {
+ String[] tempColumnNames = new String[aRow.size()];
+
+ for (int i = 0; i < aRow.size(); i++) {
+ tempColumnNames[i] = "COLUMN_" + (i + 1); //$NON-NLS-1$
+ }
+
+ return tempColumnNames;
+ }
+
+ /**
+ * Fetch data from a row.
+ *
+ * @param aRow
+ * a row read from table
+ * @return an array of data values for each specified column names from a
+ * row. The "specified column names" are obtained from meta data
+ * @throws OdaException
+ */
+ private String[] fetchQueriedDataFromRow(List<String> aRow)
+ throws OdaException {
+ String[] sArray = new String[rsmd.getColumnCount()];
+ for (int i = 0; i < sArray.length; i++) {
+ int location = selectColumIndexes[i];
+ if (location != -1) {
+ if (location >= aRow.size()) {
+ throw new OdaException(
+ Messages.getString("query_INVALID_EXCEL_FILE")); //$NON-NLS-1$
+ } else {
+ sArray[i] = aRow.get(location).toString();
+ }
+ }
+ }
+ return sArray;
+ }
+
+ /**
+ * Return the 0-based position of a value in the given array
+ *
+ * @param value
+ * @param array
+ * @return
+ */
+ private int findIndex(String value,
+ HashMap<String, Integer> originalColumnNameIndexMap) {
+ Integer index = originalColumnNameIndexMap.get(value.trim()
+ .toUpperCase());
+ if (index == null) {
+ return -1;
+ } else {
+ return index.intValue();
+ }
+ }
+
+ public List<String> readLine() throws OdaException, IOException {
+ if (!isReaderInitialised) {
+ initialiseReader();
+ isReaderInitialised = true;
+ }
+
+ return excelFileReader.readLine();
+ }
+
+ /**
+ *
+ * @throws OdaException
+ * @throws IOException
+ */
+ private void initialiseReader() throws OdaException, IOException {
+
+ try {
+ if (this.excelFileReader == null) {
+ String dataFilePath = findDataFileAbsolutePath();
+ this.excelFileReader = new ExcelFileReader(new FileInputStream(
+ dataFilePath), this.fileExtension, this.sheetNameList,
+ dateFormatString);
+ }
+
+ } catch (IOException e) {
+ throw new OdaException(e.getMessage());
+ }
+ }
+
+ /**
+ * Extract the column name from the line into the format of string array
+ *
+ * @param line
+ * @param isFirstLine
+ * @return
+ * @throws OdaException
+ */
+ public String[] getColumnNameArray(List<?> line) throws OdaException {
+ if (line == null)
+ throw new OdaException(
+ Messages.getString("common_CANNOT_FIND_COLUMN")); //$NON-NLS-1$
+ return getStringArrayFromList(line);
+ }
+
+ /**
+ * Put the contants of the list into a string array
+ *
+ * @param list
+ * @return
+ */
+ public static String[] getStringArrayFromList(List<?> list) {
+ String[] array = null;
+ if (list != null) {
+ array = new String[list.size()];
+ for (int i = 0; i < list.size(); i++)
+ array[i] = (String) list.get(i);
+ }
+ return array;
+ }
+
+ /**
+ * See if this row is empty or not
+ *
+ * @param row
+ * @return
+ * @throws OdaException
+ */
+ public static boolean isEmptyRow(List<String> line) throws OdaException {
+ if (line == null)
+ throw new OdaException(
+ Messages.getString("query_INVALID_EXCEL_FILE")); //$NON-NLS-1$
+
+ return line.isEmpty() || (line.size() == 1 && line.get(0).equals("")); //$NON-NLS-1$
+ }
+
+ public void close() throws OdaException {
+ try {
+ if (isReaderInitialised)
+ excelFileReader.close();
+ } catch (IOException e) {
+ }
+ }
+
+ public int getMaxRows() throws OdaException {
+ try {
+ if (!isReaderInitialised)
+ initialiseReader();
+ return excelFileReader.getMaxRows();
+ } catch (IOException e) {
+ close();
+ throw new OdaException(e);
+ }
+ }
+
+ /**
+ *
+ * @param resultSetMaxRows
+ * @return
+ */
+ public int getMaxRowsToRead(int resultSetMaxRows) {
+ this.resultSetMaxRows = resultSetMaxRows;
+ return this.maxRowsToRead = ((this.statementMaxRows != 0 && this.statementMaxRows < this.resultSetMaxRows) || this.resultSetMaxRows == 0) ? this.statementMaxRows
+ : this.resultSetMaxRows;
+ }
+
+ /**
+ *
+ *
+ */
+ public void closeFileSource() {
+ try {
+ if (this.excelFileReader != null)
+ this.excelFileReader.close();
+ } catch (IOException e) {
+ }
+ this.excelFileReader = null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#finalize()
+ */
+ public void finalize() {
+ this.closeFileSource();
+ }
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/RowCallBack.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/RowCallBack.java
new file mode 100644
index 0000000..7160b35
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/RowCallBack.java
@@ -0,0 +1,17 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+package org.eclipse.birt.report.data.oda.excel.impl.util;
+
+import java.util.List;
+
+public interface RowCallBack {
+ void handleRow(List<Object> values);
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/XlsxFileReader.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/XlsxFileReader.java
new file mode 100644
index 0000000..15a23c7
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/XlsxFileReader.java
@@ -0,0 +1,214 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+package org.eclipse.birt.report.data.oda.excel.impl.util;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+
+import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
+import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
+import org.apache.poi.openxml4j.opc.OPCPackage;
+import org.apache.poi.xssf.eventusermodel.XSSFReader;
+import org.apache.poi.xssf.model.SharedStringsTable;
+import org.apache.poi.xssf.usermodel.XSSFRichTextString;
+import org.eclipse.birt.report.data.oda.excel.ExcelODAConstants;
+import org.xml.sax.Attributes;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
+import org.xml.sax.helpers.DefaultHandler;
+import org.xml.sax.helpers.XMLReaderFactory;
+
+public class XlsxFileReader {
+ final private XSSFReader reader;
+
+ public XlsxFileReader(FileInputStream fis) throws IOException,
+ OpenXML4JException {
+ OPCPackage pkg = OPCPackage.open(fis);
+ reader = new XSSFReader(pkg);
+ }
+
+ public LinkedHashMap<String, String> getSheetNames()
+ throws InvalidFormatException, IOException, SAXException {
+ InputStream wbData = reader.getWorkbookData();
+ LinkedHashMap<String, String> sheetMap = new LinkedHashMap<String, String>();
+ try {
+ InputSource wbSource = new InputSource(wbData);
+ XMLReader parser = fetchWorkbookParser(sheetMap);
+ parser.parse(wbSource);
+ } finally {
+ if (wbData != null)
+ wbData.close();
+ }
+ return sheetMap;
+ }
+
+ public void processSheet(String rid, RowCallBack callback)
+ throws InvalidFormatException, IOException, SAXException {
+ SharedStringsTable sst = reader.getSharedStringsTable();
+ XMLReader parser = fetchSheetParser(sst, callback);
+ InputStream sheet = reader.getSheet(rid);
+ try {
+ InputSource sheetSource = new InputSource(sheet);
+ parser.parse(sheetSource);
+ } finally {
+ if (sheet != null)
+ sheet.close();
+ }
+ }
+
+ private XMLReader fetchSheetParser(SharedStringsTable sst,
+ RowCallBack callback) throws SAXException {
+ XMLReader parser = XMLReaderFactory
+ .createXMLReader("org.apache.xerces.parsers.SAXParser");
+ ContentHandler handler = new SheetHandler(sst, callback);
+ parser.setContentHandler(handler);
+ return parser;
+ }
+
+ private XMLReader fetchWorkbookParser(LinkedHashMap<String, String> sheetMap)
+ throws SAXException {
+ XMLReader parser = XMLReaderFactory
+ .createXMLReader("org.apache.xerces.parsers.SAXParser");
+ ContentHandler handler = new WorkbookHandler(sheetMap);
+ parser.setContentHandler(handler);
+ return parser;
+ }
+
+ /**
+ * See org.xml.sax.helpers.DefaultHandler javadocs
+ */
+ private static class SheetHandler extends DefaultHandler {
+ static private enum CellType {
+ non, num, staticText, sharedText
+ };
+
+ final private SharedStringsTable sst;
+ final private RowCallBack callback;
+ private String lastContents;
+ private CellType cellType;
+ private ArrayList<Object> values;
+ private int currentIdx = -1;
+
+ private SheetHandler(SharedStringsTable sst, RowCallBack callback) {
+ this.sst = sst;
+ this.callback = callback;
+ values = new ArrayList<Object>();
+ }
+
+ public void startElement(String uri, String localName, String qName,
+ Attributes attributes) throws SAXException {
+ // c => cell
+ if (qName.equals("c")) {
+ // Figure out if the value is an index in the SST
+ String type = attributes.getValue("t");
+ if (type == null) {
+ cellType = CellType.num;
+ } else if (type.equals("s")) {
+ cellType = CellType.sharedText;
+ } else if (type.equals("str")) {
+ cellType = CellType.staticText;
+ } else {
+ cellType = CellType.non;
+ }
+ currentIdx++;
+ values.add(currentIdx, ExcelODAConstants.EMPTY_STRING);
+ }
+ if (qName.equals("row")) {
+ currentIdx = -1;
+ }
+ lastContents = "";
+ }
+
+ public void endElement(String uri, String localName, String name)
+ throws SAXException {
+ if (name.equals("row")) {
+ callback.handleRow(values);
+ values.clear();
+ return;
+ } else if (name.equals("c")) {
+ cellType = CellType.non;
+ return;
+ } else if (name.equals("v")) {
+
+ String val = null;
+
+ // Process the last contents as required.
+ // Do now, as characters() may be called more than once
+ if (cellType == CellType.sharedText) {
+ int idx;
+ idx = Integer.parseInt(lastContents);
+ val = new XSSFRichTextString(sst.getEntryAt(idx))
+ .toString();
+ } else if (cellType == CellType.staticText
+ || cellType == CellType.num) {
+ val = lastContents;
+ }
+
+ // v => contents of a cell
+ if (val != null) {
+ values.remove(currentIdx);
+ values.add(currentIdx, val);
+ }
+ }
+ }
+
+ public void characters(char[] ch, int start, int length)
+ throws SAXException {
+ lastContents += new String(ch, start, length);
+ }
+ }
+
+ /**
+ * See org.xml.sax.helpers.DefaultHandler javadocs
+ */
+ private static class WorkbookHandler extends DefaultHandler {
+ final private LinkedHashMap<String, String> sheetMap;
+
+ private WorkbookHandler(LinkedHashMap<String, String> sheetMap) {
+ this.sheetMap = sheetMap;
+ }
+
+ public void startElement(String uri, String localName, String qName,
+ Attributes attributes) throws SAXException {
+ // <sheet r:id="rId1" name="Sheet1" />
+ if (qName.equals("sheet")) {
+ String rid = attributes.getValue("r:id");
+ String sheetName = attributes.getValue("name");
+ sheetMap.put(sheetName, rid);
+ }
+ }
+ }
+
+ /*
+ * public static void main(String[] args) throws Exception { // String
+ * xlsxFileName = "test.xlsx"; String xlsxFileName =
+ * "c:/work/styles/LargeXls.xlsx"; FileInputStream fis = new
+ * FileInputStream(xlsxFileName); XlsxFileReader poiTest = new
+ * XlsxFileReader(fis);
+ *
+ * LinkedHashMap<String, String> sheetMap = poiTest.getSheetNames();
+ *
+ * XlsxRowCallback callback = new XlsxRowCallback(); String rid =
+ * sheetMap.get("Data"); poiTest.processSheet(rid, callback);
+ *
+ *
+ * for (String sheetName : sheetMap.keySet()) { String rid =
+ * sheetMap.get(sheetName); poiTest.processOneSheet(rid, callback); }
+ *
+ * }
+ */
+
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/XlsxRowCallBack.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/XlsxRowCallBack.java
new file mode 100644
index 0000000..290069a
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/XlsxRowCallBack.java
@@ -0,0 +1,47 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+package org.eclipse.birt.report.data.oda.excel.impl.util;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class XlsxRowCallBack implements RowCallBack {
+ private ArrayList<String[]> xlsxRowData = new ArrayList<String[]>();
+ private int rowNum;
+
+ public void handleRow(List<Object> values) {
+ ++rowNum;
+
+ if (values == null || values.size() == 0) {
+ return;
+ }
+ String[] valArray = new String[values.size()];
+ values.toArray(valArray);
+
+ xlsxRowData.add(valArray);
+ }
+
+ public ArrayList<String> initArrayList(String[] strings) {
+ ArrayList<String> list = new ArrayList<String>();
+ for (String i : strings) {
+ list.add(i);
+ }
+ return list;
+ }
+
+ public int getMaxRowsInSheet() {
+ return (xlsxRowData.size());
+ }
+
+ public ArrayList<String> getRow(int rownum) {
+ return (initArrayList(xlsxRowData.get(rownum)));
+ }
+} \ No newline at end of file
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/querytextutil/ColumnsInfoUtil.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/querytextutil/ColumnsInfoUtil.java
new file mode 100644
index 0000000..3c5dbe7
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/querytextutil/ColumnsInfoUtil.java
@@ -0,0 +1,183 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+package org.eclipse.birt.report.data.oda.excel.impl.util.querytextutil;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Utility class for extracting column names, original column names, and column
+ * types from columns information
+ */
+
+public class ColumnsInfoUtil
+{
+
+ private static String EMPTY_STRING = ""; //$NON-NLS-1$
+
+ private String[] columnNames;
+ private String[] columnTypeNames;
+ private String[] originalColumnNames;
+ /**
+ *
+ *
+ */
+ public ColumnsInfoUtil( String columnsInfo )
+ {
+ assert columnsInfo != null;
+ List<String[]> columnsInfoVector = getColumnsInfoList( columnsInfo );
+ columnNames = new String[columnsInfoVector.size( )];
+ columnTypeNames = new String[columnsInfoVector.size( )];
+ originalColumnNames = new String[columnsInfoVector.size( )];
+ for (int i = 0; i < columnsInfoVector.size( ); i++)
+ {
+ String[] items = columnsInfoVector.get( i );
+ columnNames[i] = items[0];
+ originalColumnNames[i] = items[1];
+ columnTypeNames[i] = items[2];
+ }
+ }
+
+ /**
+ * Extracts the column names from the columsInfo string
+ *
+ * @param columnsInfo
+ * @return
+ */
+ public String[] getColumnNames( )
+ {
+ return columnNames;
+ }
+
+ /**
+ * Extracts the column type names from the columsInfo string
+ *
+ * @param columnsInfo
+ * @return
+ */
+ public String[] getColumnTypeNames( )
+ {
+ return columnTypeNames;
+ }
+
+ /**
+ * Extracts the original column names from the columsInfo string
+ *
+ * @param columnsInfo
+ * @return
+ */
+ public String[] getOriginalColumnNames( )
+ {
+ return originalColumnNames;
+ }
+
+ /**
+ *
+ * @param columnsInfo
+ * @return
+ */
+ private static List<String[]> getColumnsInfoList( String columnsInfo )
+ {
+ List<String[]> columnsInfoList = new ArrayList<String[]>( );
+ char[] columnsInfoChars = columnsInfo.toCharArray( );
+ boolean isEscaped = false;
+ String[] columnInfo = {
+ EMPTY_STRING, EMPTY_STRING, EMPTY_STRING
+ };
+ int index = 0;
+
+ for ( int i = 0; i < columnsInfoChars.length; i++ )
+ {
+ if ( columnsInfoChars[i] == '"'
+ || columnsInfoChars[i] == '|' || columnsInfoChars[i] == ':'
+ || columnsInfoChars[i] == '<' || columnsInfoChars[i] == '>'
+ || columnsInfoChars[i] == '?' || columnsInfoChars[i] == '*'
+ || columnsInfoChars[i] == '{' || columnsInfoChars[i] == '/' )
+ {
+ if ( isEscaped )
+ {
+ columnInfo[index] = columnInfo[index] + columnsInfoChars[i];
+ isEscaped = !isEscaped;
+ }
+ }
+ else if ( columnsInfoChars[i] == '\\' )
+ {
+ if ( isEscaped )
+ {
+ columnInfo[index] = columnInfo[index] + columnsInfoChars[i];
+ isEscaped = !isEscaped;
+ }
+ else
+ isEscaped = !isEscaped;
+ }
+ else if ( columnsInfoChars[i] == ',' )
+ {
+ if ( isEscaped )
+ {
+ columnInfo[index] = columnInfo[index] + columnsInfoChars[i];
+ isEscaped = !isEscaped;
+ }
+ else
+ {
+ index++;
+ }
+ }
+ else if ( columnsInfoChars[i] == ';'
+ || i == ( columnsInfoChars.length - 1 ) )
+ {
+ if ( isEscaped )
+ {
+ columnInfo[index] = columnInfo[index] + columnsInfoChars[i];
+ isEscaped = !isEscaped;
+ }
+ else
+ {
+
+ if ( i == ( columnsInfoChars.length - 1 ) )
+ {
+ columnInfo[index] = columnInfo[index]
+ + columnsInfoChars[i];
+
+ columnsInfoList.add( columnInfo );
+ }
+ else
+ {
+ columnsInfoList.add( columnInfo );
+ index = 0;
+ columnInfo = new String[3];
+ columnInfo[0] = columnInfo[1] = columnInfo[2] = EMPTY_STRING;
+ }
+ }
+ }
+ else
+ {
+ columnInfo[index] = columnInfo[index] + columnsInfoChars[i];
+ }
+ }
+
+ return columnsInfoList;
+ }
+
+ /**
+ *
+ * @param charactor
+ * @return
+ */
+ public static boolean isColumnsInfoKeyWord( char charactor )
+ {
+ return ( charactor == '"'
+ || charactor == ';' || charactor == ',' || charactor == '|'
+ || charactor == '\\' || charactor == '/' || charactor == '<'
+ || charactor == '>' || charactor == '*' || charactor == ':'
+ || charactor == '?' || charactor == '{' );
+ }
+
+}
diff --git a/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/querytextutil/QueryTextUtil.java b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/querytextutil/QueryTextUtil.java
new file mode 100644
index 0000000..480b4a6
--- /dev/null
+++ b/data/org.eclipse.birt.report.data.oda.excel/src/org/eclipse/birt/report/data/oda/excel/impl/util/querytextutil/QueryTextUtil.java
@@ -0,0 +1,434 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Megha Nidhi Dahal.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Megha Nidhi Dahal - initial API and implementation and/or initial documentation
+ *******************************************************************************/
+package org.eclipse.birt.report.data.oda.excel.impl.util.querytextutil;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Vector;
+
+import org.eclipse.birt.report.data.oda.excel.ExcelODAConstants;
+import org.eclipse.birt.report.data.oda.excel.impl.i18n.Messages;
+import org.eclipse.birt.report.data.oda.excel.impl.util.ExcelFileSource;
+import org.eclipse.datatools.connectivity.oda.OdaException;
+
+/**
+ * Utility class for splitting query text into query and columns information
+ */
+
+public class QueryTextUtil
+{
+
+ private static final char QUERY_TEXT_DELIMITER = ':';
+
+ private static final char COLUMNSINFO_BEGIN_DELIMITER = '{';
+
+ private String query;
+
+ private String columnsInfo;
+
+ /**
+ *
+ */
+ public QueryTextUtil( String queryText ) throws OdaException
+ {
+ assert queryText != null;
+ String[] splits = splitQueryText( queryText );
+ query = splits[0];
+ columnsInfo = splits[1];
+ }
+
+
+ public String getQuery( )
+ {
+ return query;
+ }
+
+ public String getColumnsInfo( )
+ {
+ return columnsInfo;
+ }
+
+ /**
+ *
+ */
+ private String[] splitQueryText( String queryText )
+ throws OdaException
+ {
+ int delimiterIndex = -1;
+ int columnsInfoBeginIndex = -1;
+
+ String trimmedQueryText = queryText.trim( );
+
+ String[] splittedQueryText = {
+ "", "" //$NON-NLS-1$ //$NON-NLS-2$
+ };
+ boolean inQuote = false;
+ boolean isEscaped = false;
+ char[] chars = trimmedQueryText.toCharArray( );
+
+ for ( int i = 0; i < chars.length; i++ )
+ {
+ if ( chars[i] == '"' )
+ {
+ if ( !isEscaped )
+ inQuote = !inQuote;
+ else
+ isEscaped = !isEscaped;
+ }
+ else if ( chars[i] == '\\' )
+ {
+ isEscaped = !isEscaped;
+ }
+ else if ( ( !inQuote ) && chars[i] == QUERY_TEXT_DELIMITER )
+ delimiterIndex = i;
+ else if ( ( !inQuote ) && chars[i] == COLUMNSINFO_BEGIN_DELIMITER )
+ {
+ columnsInfoBeginIndex = i;
+ break;
+ }
+ }
+
+ if ( inQuote )
+ throw new OdaException( Messages.getString( "query_text_error" ) ); //$NON-NLS-1$
+
+ if ( delimiterIndex != -1
+ && columnsInfoBeginIndex != -1 )
+ {
+ splittedQueryText[0] = trimmedQueryText.substring( 0, delimiterIndex )
+ .trim( );
+ splittedQueryText[1] = trimmedQueryText.substring( columnsInfoBeginIndex + 1,
+ trimmedQueryText.length( )-1 )
+ .trim( );
+ }
+ else if ( delimiterIndex == -1
+ && columnsInfoBeginIndex == -1 )
+ splittedQueryText[0] = trimmedQueryText;
+ else
+ throw new OdaException( Messages.getString( "query_text_error" ) ); //$NON-NLS-1$
+
+ return splittedQueryText;
+ }
+
+ /**
+ * Strip off keyword "SELECT" from the given query.
+ *
+ * @param formattedQuery
+ * a trimed query text; cannot be null.
+ * @return the given text stripped the SELECT keyword
+ * @throws OdaException
+ */
+ protected static String stripSELECTKeyword( String formattedQuery )
+ throws OdaException
+ {
+ // This array stores two values: "SELECT" keyword and other part of a
+ // command
+ String[] array = formattedQuery.split( ExcelODAConstants.DELIMITER_SPACE,
+ 2 );
+ if ( array == null
+ || array.length != 2
+ || !array[0].trim( )
+ .equalsIgnoreCase( ExcelODAConstants.KEYWORD_SELECT ) )
+ throw new OdaException( Messages.getString( "query_COMMAND_NOT_VALID" ) ); //$NON-NLS-1$
+
+ return array[1];
+ }
+
+ /**
+ * Split the given query fragments before and after the FROM keyword
+ *
+ * @param query
+ * Query text without heading SELECT keyword
+ * @return A String array with two elements: column names (may include alias
+ * with the AS keyword), and table names after the FROM clause.
+ * @throws OdaException
+ */
+ protected static String[] stripFROMKeyword( String query )
+ throws OdaException
+ {
+ char[] chars = query.toCharArray( );
+ List<Integer> indiceList = new ArrayList<Integer>( );
+ boolean inQuote = false;
+ boolean isEscaped = false;
+ LookAheadMacher matcher = new LookAheadMacher( "FROM ", " ", true );
+ for ( int i = 0; i < chars.length; i++ )
+ {
+ if ( chars[i] == '"' )
+ {
+ if ( !isEscaped )
+ inQuote = !inQuote;
+ else
+ isEscaped = !isEscaped;
+ }
+ else if ( chars[i] == '\\' )
+ {
+ isEscaped = !isEscaped;
+ }
+ else if (inQuote)
+ {
+ continue;
+ }
+ else
+ {
+ if ( matcher.match( chars, i ) )
+ {
+ indiceList.add( i - 1 );
+ }
+ }
+ }
+
+ String[] result = new String[2];
+ if ( indiceList.size( ) > 0 )
+ {
+ int splitInd = indiceList.get( indiceList.size( ) - 1 );
+ result[0] = query.substring( 0, splitInd );
+ result[1] = getUnQuotedName( query.substring( splitInd
+ + matcher.getPatternLength( ) ) );
+ }
+ else
+ throw new OdaException( Messages.getString( "query_COMMAND_NOT_VALID" ) ); //$NON-NLS-1$
+
+ return result;
+ }
+
+ public static String getQuotedName( String name )
+ {
+ if ( name == null
+ || ( name.charAt( 0 ) == '\"' && name.charAt( name.length( ) - 1 ) == '\"' ) )
+ return name;
+
+ StringBuffer sb = new StringBuffer( "\"" ).append( name ).append( "\"" );
+ return sb.toString( );
+ }
+
+ public static String getUnQuotedName( String name )
+ {
+ if ( name == null || name.length( ) == 0 )
+ return name;
+
+ int head = 0;
+ int end = name.length( );
+ if ( name.charAt( head ) == '\"' )
+ head++;
+ if ( name.charAt( name.length( ) - 1 ) == '\"' )
+ end--;
+
+ return name.substring( head, end );
+ }
+
+ static class LookAheadMacher
+ {
+
+ private String pattern = "";
+ private String heading = "";
+ private boolean caseInsensitive = false;
+
+ LookAheadMacher( String pattern, String heading,
+ boolean caseInsensitive )
+ {
+ this.pattern = pattern;
+ this.heading = heading;
+ this.caseInsensitive = caseInsensitive;
+ }
+
+ int getPatternLength( )
+ {
+ return pattern.length( ) + heading.length( );
+ }
+
+ boolean match( char[] ch, int ind )
+ {
+ boolean first = false;
+ if ( caseInsensitive )
+ {
+ first = Character.toUpperCase( pattern.charAt( 0 ) ) == Character.toUpperCase( ch[ind] );
+ }
+ else
+ {
+ first = pattern.charAt( 0 ) == ch[ind];
+ }
+
+ if ( !first )
+ return false;
+
+ return match(String.valueOf( ch ), ind);
+ }
+
+ boolean match( String toMatch, int start )
+ {
+ if ( toMatch == null
+ || ( toMatch.length( ) - start ) < pattern.length( ) )
+ return false;
+
+ if ( start < heading.length( ) - 1 )
+ return false;
+
+ String to = toMatch.substring( start - heading.length( ), start );
+ if ( caseInsensitive )
+ {
+ if ( !heading.equalsIgnoreCase( to ) )
+ return false;
+ }
+ else if ( !heading.equals( to ) )
+ {
+ return false;
+ }
+
+ to = toMatch.substring( start, start + pattern.length( ) );
+ if ( to.length( ) != pattern.length( ) )
+ return false;
+
+ if ( caseInsensitive )
+ {
+ if ( !pattern.equalsIgnoreCase( to ) )
+ return false;
+ }
+ else if ( !pattern.equals( to ) )
+ {
+ return false;
+ }
+
+ return true;
+ }
+ }
+
+ /**
+ * Split the column name from alias, stripping the "AS" keyword, from given
+ * query fragments.
+ *
+ * @param querySelectAndFromFragments
+ * @return a String array with three elements: first element contains column
+ * names separated by comma, second element contains column
+ * aliases(labels) separated by comma, third element contains the
+ * table name(s) in FROM clause
+ */
+ protected static String[] stripASKeyword( String[] querySelectAndFromFragments )
+ {
+ String[] result = new String[3];
+ // store the table name in given last element as the third element
+ result[2] = querySelectAndFromFragments[1];
+
+ // split the columns specified in the SELECT clause
+ String selectedColumns = querySelectAndFromFragments[0];
+ if ( !isWildCard( selectedColumns ) )
+ {
+ String[] columns = ExcelFileSource.getStringArrayFromList( getQueryColumnNamesVector( selectedColumns ) );
+
+ for ( int i = 0; i < columns.length; i++ )
+ {
+ String[] columnNameAlias = columns[i].split( ExcelODAConstants.DELIMITER_SPACE
+ + ExcelODAConstants.KEYWORD_AS
+ + ExcelODAConstants.DELIMITER_SPACE );
+ if ( columnNameAlias != null )
+ {
+ // append column name to comma-separated column names in
+ // result[0]
+ result[0] = ( i == 0 ? columnNameAlias[0] : result[0]
+ + ExcelODAConstants.DELIMITER_COMMA_VALUE
+ + columnNameAlias[0].trim( ) );
+
+ // append column alias, if exists, or null to
+ // comma-separated column aliases in result[1]
+ if ( columnNameAlias.length == 2 )
+ result[1] = ( i == 0 ? columnNameAlias[1] : result[1]
+ + ExcelODAConstants.DELIMITER_COMMA_VALUE
+ + columnNameAlias[1].trim( ) );
+ else
+ result[1] = ( i == 0 ? null : result[1]
+ + ExcelODAConstants.DELIMITER_COMMA_VALUE + null );
+ }
+ }
+ }
+ else
+ {
+ result[0] = ExcelODAConstants.KEYWORD_ASTERISK;
+ result[1] = null;
+ }
+
+ return result;
+ }
+
+ public static String[] getQueryMetaData(String query) throws OdaException
+ {
+ return stripASKeyword(stripFROMKeyword(stripSELECTKeyword(query)));
+ }
+
+ /**
+ * @param cCN
+ * @return
+ */
+ static boolean isWildCard( String cCN )
+ {
+ if ( cCN.equalsIgnoreCase( ExcelODAConstants.KEYWORD_ASTERISK ) )
+ return true;
+ return false;
+ }
+
+ /**
+ *
+ * @param queryColumnNames
+ * @return
+ */
+ static Vector<String> getQueryColumnNamesVector( String queryColumnNames )
+ {
+ Vector<String> result = new Vector<String>( );
+ char[] chars = queryColumnNames.toCharArray( );
+ List<Integer> indiceList = new ArrayList<Integer>( );
+ boolean inQuote = false;
+ boolean isEscaped = false;
+ int beginIndex = 0;
+ int endIndex = 0;
+
+ for ( int i = 0; i < chars.length; i++ )
+ {
+ if ( chars[i] == '"' )
+ {
+ if ( !isEscaped )
+ inQuote = !inQuote;
+ else
+ isEscaped = !isEscaped;
+ }
+ else if ( chars[i] == '\\' )
+ {
+ isEscaped = !isEscaped;
+ }
+ else if ( chars[i] == ',' )
+ {
+ if ( inQuote )
+ continue;
+ else
+ indiceList.add( new Integer( i ) );
+ }
+ }
+
+ if ( indiceList.size( ) > 0 )
+ {
+ for ( int j = 0; j < indiceList.size( ); j++ )
+ {
+
+ endIndex = ( (Integer) indiceList.get( j ) ).intValue( );
+
+ result.add( queryColumnNames.substring( beginIndex,
+ endIndex ).trim( ) );
+ beginIndex = endIndex + 1;
+
+ if ( j == indiceList.size( ) - 1 )
+ {
+ result.add( queryColumnNames.substring( beginIndex,
+ queryColumnNames.length( ) ).trim( ) );
+ }
+ }
+ }
+ else
+ result.add( queryColumnNames );
+
+ return result;
+ }
+}