Revision 256

View differences:

org.gvsig.jexcel/tags/org.gvsig.jexcel-1.0.47/org.gvsig.jexcel.provider/src/main/resources/org/gvsig/fmap/dal/store/jexcel/JExcelMetadata.xml
1
<?xml version="1.0"?>
2
<!--
3
Definitions of metadata fields of a shp file.  
4
 -->
5
<definitions>
6
  <version>1.0.0</version>
7
  <classes>
8
    
9
    <class name="JExcel" namespace="Metadata">
10
      <extends>
11
      	<class namespace="Metadata" name="SpatialProvider"/>
12
      </extends>
13
      <description>Metadata of a JExcel store</description>
14
      <fields>
15
      </fields>
16
    </class>
17

  
18
  </classes>
19
</definitions>  
org.gvsig.jexcel/tags/org.gvsig.jexcel-1.0.47/org.gvsig.jexcel.provider/src/main/resources/org/gvsig/fmap/dal/store/jexcel/JExcelParameters.xml
1
<?xml version= "1.0 "?>
2
<definitions>
3
    <version>1.0.0</version>
4
    <classes>
5
        <class name="JExcel">
6
            <extends>
7
                <class namespace="dal" name="ProviderParameters"/>
8
            </extends>
9
            <description>Store the parameters need to open a Excel file</description>
10
            <fields>
11
                <field name="file" label="File" type="file" mandatory="true">
12
                    <description>Excel file</description>
13
                </field>
14
                <field name="locale" label="Locale" type="string" mandatory="true" defaultValue="DEFAULT">
15
                    <description>Locale used to parse double and float values (BCP47 language tag representing the locale)</description>
16
                    <availableValues>
17
                        <value label="Default (use system locale)">DEFAULT</value>
18
                        <value label="Canada (english)">en-CA</value>
19
                        <value label="Canada (french)">fr-CA</value>
20
                        <value label="Chinese">zh</value>
21
                        <value label="English">en</value>
22
                        <value label="French">fr</value>
23
                        <value label="German">de</value>
24
                        <value label="Italian">it</value>
25
                        <value label="Japanese">ja</value>
26
                        <value label="Korea">ko</value>
27
                        <value label="Spain">es</value>
28
                        <value label="Uk">en-GB</value>
29
                        <value label="Us">en-US</value>
30
                    </availableValues>          
31
                </field>
32
                <field name="sheet" label="Sheet to load" type="integer" subtype="jexcel.sheet.selector" mandatory="false" defaultValue="0">
33
                    <description>Sheet to use.</description>
34
                </field>
35
                <field name="isFirstRowHeadeer" label="Use first row as header" type="boolean" mandatory="false" defaultValue="false">
36
                    <description>Check for use first row as header.</description>
37
                </field>
38
                <field name="CRS" type="crs" mandatory="false">
39
                    <description>The coordinate reference system used when use the point parameter to generate a layer</description>
40
                </field>
41
                <field name="point" label="Point (X,Y,Z)" type="string" mandatory="false" defaultValue="" >
42
                    <description>This field allow to add a Geometry column to the table. It is a list of field names separated by commas used as dimensions for the attribute GEOM of type point to add to the table.</description>
43
                </field>
44

  
45
                <field name="header" label="Header" type="string" mandatory="false" defaultValue="" group="Advanced">
46
                    <description>The header or empty if parsed automatically</description>
47
                </field>
48
                <field name="fieldtypes" label="Field types" type="string" mandatory="false" defaultValue="" group="Advanced">
49
                    <description>Comma separated list of field types. If empty strings are assumed (Eg: integer,string,double,boolean,float,geometry).</description>
50
                </field>
51
                <field name="automaticTypesDetection" label="Automatic types detection" type="boolean" mandatory="false" defaultValue="true" group="Advanced">
52
                    <description>This flag activate the autodetection of types in the CSV. Can be slow.</description>
53
                </field>
54
                <field name="ignoreErrors" label="Ignore errors" type="boolean" mandatory="false" defaultValue="false" group="Advanced">
55
                    <description>Set to true to ignore errors during load of data.</description>
56
                </field>
57
            </fields>
58
      
59
        </class>
60
    </classes>
61
</definitions>  
org.gvsig.jexcel/tags/org.gvsig.jexcel-1.0.47/org.gvsig.jexcel.provider/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.fmap.dal.store.jexcel.JExcelLibrary
org.gvsig.jexcel/tags/org.gvsig.jexcel-1.0.47/org.gvsig.jexcel.provider/src/main/java/org/gvsig/fmap/dal/store/jexcel/JExcelStoreProviderFactory.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.fmap.dal.store.jexcel;
25

  
26
import org.gvsig.fmap.dal.DataParameters;
27
import org.gvsig.fmap.dal.DataStoreProvider;
28
import org.gvsig.fmap.dal.exception.InitializeException;
29
import org.gvsig.fmap.dal.feature.FeatureStoreProviderFactory;
30
import org.gvsig.fmap.dal.feature.spi.AbstractFeatureStoreProviderFactory;
31
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
32
import org.gvsig.tools.dynobject.DynObject;
33

  
34
public class JExcelStoreProviderFactory extends AbstractFeatureStoreProviderFactory implements FeatureStoreProviderFactory{
35

  
36
	protected JExcelStoreProviderFactory(String name, String description) {
37
		super(name, description);
38
	}
39

  
40
	public DataStoreProvider createProvider(DataParameters parameters,
41
			DataStoreProviderServices providerServices)
42
			throws InitializeException {
43
		return new JExcelStoreProvider((JExcelStoreParameters) parameters, providerServices);
44
	}
45

  
46
	public DynObject createParameters() {
47
		return new JExcelStoreParameters();
48
	}
49
	
50
	public int allowCreate() {
51
		return NO;
52
	}
53
	
54
	public int allowWrite() {
55
		return NO;
56
	}
57

  
58
	public int allowRead() {
59
		return YES;
60
	}
61
	
62
	public int hasRasterSupport() {
63
		return NO;
64
	}
65
	
66
	public int hasTabularSupport() {
67
		return YES;
68
	}
69
	
70
	public int hasVectorialSupport() {
71
		return YES;
72
	}
73

  
74
	public int allowMultipleGeometryTypes() {
75
		return YES;
76
	}
77
	
78
	public int allowEditableFeatureType() {
79
		return NO;
80
	}
81

  
82
}
org.gvsig.jexcel/tags/org.gvsig.jexcel-1.0.47/org.gvsig.jexcel.provider/src/main/java/org/gvsig/fmap/dal/store/jexcel/JExcelStoreParameters.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA 02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.fmap.dal.store.jexcel;
25

  
26
import java.io.File;
27
import java.util.Locale;
28
import org.apache.commons.lang3.StringEscapeUtils;
29
import org.apache.commons.lang3.StringUtils;
30
import org.cresques.cts.IProjection;
31
import org.gvsig.fmap.dal.DataStoreParameters;
32
import org.gvsig.fmap.dal.FileHelper;
33
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemStoreParameters;
34
import org.gvsig.fmap.dal.spi.AbstractDataParameters;
35
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
36
import org.gvsig.tools.ToolsLocator;
37
import org.gvsig.tools.dataTypes.DataTypesManager;
38
import org.gvsig.tools.dynobject.DelegatedDynObject;
39
import org.gvsig.tools.dynobject.DynObject;
40
import org.slf4j.Logger;
41
import org.slf4j.LoggerFactory;
42

  
43
public class JExcelStoreParameters extends AbstractDataParameters implements
44
        DataStoreParameters, FilesystemStoreParameters {
45

  
46
    private static final Logger logger = LoggerFactory.getLogger(JExcelStoreParameters.class);
47

  
48
    public static final String PARAMETERS_DEFINITION_NAME = "JExcel";
49

  
50
    private static final String FILE = "file";
51
    private static final String IGNOREERRORS = "ignoreErrors";
52
    private static final String CRS = "CRS";
53
    private static final String FIELDTYPES = "fieldtypes";
54
    private static final String LOCALE = "locale";
55
    private static final String SHEET = "sheet";
56
    private static final String ISFIRSTROWHEADER = "isFirstRowHeadeer";
57
    private static final String AUTOMATICTYPESDETECTION = "automaticTypesDetection";
58
    private static final String HEADER = "header";
59

  
60
    private DelegatedDynObject parameters;
61

  
62
    public JExcelStoreParameters() {
63
        this(PARAMETERS_DEFINITION_NAME);
64
    }
65

  
66
    protected JExcelStoreParameters(String parametersDefinitionName) {
67
        this(parametersDefinitionName, JExcelStoreProvider.NAME);
68
    }
69

  
70
    public JExcelStoreParameters(String parametersDefinitionName, String name) {
71
        super();
72
        this.parameters = (DelegatedDynObject) FileHelper.newParameters(parametersDefinitionName);
73
        this.setDynValue(DataStoreProviderServices.PROVIDER_PARAMTER_NAME, name);
74
    }
75

  
76
    public String getDataStoreName() {
77
        return (String) this.getDynValue(DataStoreProviderServices.PROVIDER_PARAMTER_NAME);
78
    }
79

  
80
    public String getDescription() {
81
        return this.getDynClass().getDescription();
82
    }
83

  
84
    protected DelegatedDynObject getDelegatedDynObject() {
85
        return parameters;
86
    }
87

  
88
    public boolean isValid() {
89
        if ( getFileName(this) == null ) {
90
            return false;
91
        }
92
        return true;
93
    }
94

  
95
    public File getFile() {
96
        return (File) this.getDynValue(FILE);
97
    }
98

  
99
    public void setFile(File file) {
100
        this.setDynValue(FILE, file);
101
    }
102

  
103
    static IProjection getCRS(DynObject dynobj) {
104
        return (IProjection) dynobj.getDynValue(CRS);
105
    }
106

  
107
    static String getFileName(DynObject dynobj) {
108
        File f = (File) dynobj.getDynValue(FILE);
109
        if ( f == null ) {
110
            return null;
111
        }
112
        return f.getPath();
113
    }
114

  
115
    static File getFile(DynObject dynobj) {
116
        File f = (File) dynobj.getDynValue(FILE);
117
        return f;
118
    }
119

  
120
    static Locale getLocale(DynObject dynobj) {
121
        try {
122
            String s = (String) dynobj.getDynValue(LOCALE);
123
            if ( s.trim().length() == 0 ) {
124
                return null;
125
            }
126
            if ( "DEFAULT".equalsIgnoreCase(s.trim()) ) {
127
                return Locale.getDefault();
128
            }
129
            Locale locale = null;
130
            // locale = Locale.forLanguageTag(s); // Since java 1.7
131
            String[] ss = s.split("-");
132
            switch (ss.length) {
133
            case 1:
134
                locale = new Locale(ss[0]);
135
                break;
136
            case 2:
137
                locale = new Locale(ss[0], ss[1]);
138
                break;
139
            case 3:
140
            default:
141
                locale = new Locale(ss[0], ss[1], ss[2]);
142
                break;
143
            }
144
            return locale;
145
        } catch (Exception ex) {
146
            logger.warn("Can't get locale from JExcel parameters.", ex);
147
            return null;
148
        }
149
    }
150

  
151
    private static String getDelimiter(String line) {
152
        String sep = null;
153
        // Cuiaddo con los ":", los he puesto al final a proposito
154
        // ya que podian estar en la cadena para separar el size
155
        // size de cada tipo.
156
        String seps = ",;-|@#/+$%&!:";
157
        for ( int i = 0; i < seps.length(); i++ ) {
158
            sep = seps.substring(i, 1);
159
            if ( line.contains(seps.substring(i, 1)) ) {
160
                break;
161
            }
162
            sep = null;
163
        }
164
        return sep;
165
    }
166

  
167
    static String[] getPointDimensionNames(DynObject dynobj) {
168
        String s = (String) dynobj.getDynValue("point");
169
        if ( StringUtils.isEmpty(s) ) {
170
            return null;
171
        }
172
        return s.split(",");
173
    }
174

  
175
    static boolean getIgnoreErrors(DynObject dynobj) {
176
        Boolean b = (Boolean) dynobj.getDynValue(IGNOREERRORS);
177
        if ( b == null ) {
178
            return false;
179
        }
180
        return b.booleanValue();
181
    }
182

  
183
    static int[] getFieldTypes(DynObject dynobj) {
184
        String s = (String) dynobj.getDynValue(FIELDTYPES);
185
        if ( StringUtils.isEmpty(s) ) {
186
            return null;
187
        }
188
        String sep = getDelimiter(s);
189
        if ( sep == null ) {
190
            return null;
191
        }
192
        DataTypesManager dataTypeManager = ToolsLocator.getDataTypesManager();
193
        String fieldTypeNames[] = s.split("[" + sep + "]");
194
        int fieldTypes[] = new int[fieldTypeNames.length];
195
        for ( int i = 0; i < fieldTypeNames.length; i++ ) {
196
            s = fieldTypeNames[i].trim();
197
            if ( s.contains(":") ) {
198
                s = s.split(":")[0];
199
            }
200
            fieldTypes[i] = dataTypeManager.getType(s);
201
        }
202
        return fieldTypes;
203
    }
204

  
205
    static int[] getFieldSizes(DynObject dynobj) {
206
        String s = (String) dynobj.getDynValue(FIELDTYPES);
207
        if ( StringUtils.isEmpty(s) ) {
208
            return null;
209
        }
210
        String sep = getDelimiter(s);
211
        if ( sep == null ) {
212
            return null;
213
        }
214
        String fieldTypeNames[] = s.split("[" + sep + "]");
215
        int fieldSizes[] = new int[fieldTypeNames.length];
216
        for ( int i = 0; i < fieldTypeNames.length; i++ ) {
217
            String fieldtype = fieldTypeNames[i].trim();
218
            if ( fieldtype.contains(":") ) {
219
                try {
220
                    s = fieldtype.split(":")[1];
221
                    fieldSizes[i] = Integer.parseInt(s);
222
                } catch (Exception ex) {
223
                    logger.warn("Can't get size of field " + i + " (" + fieldtype + ").", ex);
224
                }
225
            } else {
226
                fieldSizes[i] = 0;
227
            }
228
        }
229
        return fieldSizes;
230
    }
231

  
232
    static int getSheetIndex(DynObject dynobj) {
233
        Integer sheet = (Integer) dynobj.getDynValue(SHEET);
234
        if ( sheet == null ) {
235
            return 0;
236
        }
237
        return sheet.intValue();
238
    }
239

  
240
    static String getHeader(DynObject dynobj) {
241
        String s = (String) dynobj.getDynValue(HEADER);
242
        s = StringEscapeUtils.unescapeJava(s);
243
        if ( StringUtils.isBlank(s) ) {
244
            return null;
245
        }
246
        return s;
247
    }
248

  
249
    static String[] getHeaders(DynObject dynobj) {
250
        String s = getHeader(dynobj);
251
        if ( StringUtils.isBlank(s) ) {
252
            return null;
253
        }
254
        String sep = getDelimiter(s);
255
        if ( sep == null ) {
256
            // Chungo
257
            return null;
258
        }
259
        String[] ss = s.split("[" + sep + "]");
260
        return ss;
261
    }
262

  
263
    static boolean getAutomaticTypesDetection(DynObject dynobj) {
264
        Boolean b = (Boolean) dynobj.getDynValue(AUTOMATICTYPESDETECTION);
265
        if ( b == null ) {
266
            return false;
267
        }
268
        return b.booleanValue();
269
    }
270

  
271
    static boolean isFirstRowHeader(DynObject dynobj) {
272
        Boolean b = (Boolean) dynobj.getDynValue(ISFIRSTROWHEADER);
273
        if ( b == null ) {
274
            return false;
275
        }
276
        return b.booleanValue();
277
    }
278

  
279
}
org.gvsig.jexcel/tags/org.gvsig.jexcel-1.0.47/org.gvsig.jexcel.provider/src/main/java/org/gvsig/fmap/dal/store/jexcel/JExcelLibrary.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.fmap.dal.store.jexcel;
25

  
26
import java.util.ArrayList;
27
import java.util.List;
28

  
29
import org.gvsig.fmap.dal.DALFileLibrary;
30
import org.gvsig.fmap.dal.DALFileLocator;
31
import org.gvsig.fmap.dal.DALLibrary;
32
import org.gvsig.fmap.dal.DALLocator;
33
import org.gvsig.fmap.dal.FileHelper;
34
import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
35
import org.gvsig.metadata.exceptions.MetadataException;
36
import org.gvsig.tools.library.AbstractLibrary;
37
import org.gvsig.tools.library.LibraryException;
38

  
39
public class JExcelLibrary extends AbstractLibrary {
40

  
41
    @Override
42
    public void doRegistration() {
43
        registerAsServiceOf(DALLibrary.class);
44
        require(DALFileLibrary.class);
45
    }
46

  
47
	@Override
48
	protected void doInitialize() throws LibraryException {
49
	}
50

  
51
	@Override
52
	protected void doPostInitialize() throws LibraryException {
53
		List<Throwable> exs = new ArrayList<Throwable>();
54

  
55
		FileHelper.registerParametersDefinition(
56
				JExcelStoreParameters.PARAMETERS_DEFINITION_NAME,
57
				JExcelStoreParameters.class, "JExcelParameters.xml");
58
		try {
59
			FileHelper.registerMetadataDefinition(
60
					JExcelStoreProvider.METADATA_DEFINITION_NAME,
61
					JExcelStoreProvider.class, "JExcelMetadata.xml");
62
		} catch (MetadataException e) {
63
			exs.add(e);
64
		}
65

  
66
		DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator
67
				.getDataManager();
68

  
69
		try {
70
			if (!dataman.getStoreProviders().contains(JExcelStoreProvider.NAME)) {
71
				dataman.registerStoreProviderFactory(new JExcelStoreProviderFactory(JExcelStoreProvider.NAME, JExcelStoreProvider.DESCRIPTION));
72

  
73
			}
74
		} catch (RuntimeException e) {
75
			exs.add(e);
76
		}
77

  
78
		try {
79
			DALFileLocator.getFilesystemServerExplorerManager()
80
					.registerProvider(JExcelStoreProvider.NAME,
81
							JExcelStoreProvider.DESCRIPTION,
82
							JExcelFilesystemServerProvider.class);
83
		} catch (RuntimeException e) {
84
			exs.add(e);
85
		}
86

  
87
		if (exs.size() > 0) {
88
			throw new LibraryException(this.getClass(), exs);
89
		}
90
	}
91
}
org.gvsig.jexcel/tags/org.gvsig.jexcel-1.0.47/org.gvsig.jexcel.provider/src/main/java/org/gvsig/fmap/dal/store/jexcel/JExcelFilesystemServerProvider.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.fmap.dal.store.jexcel;
25

  
26
import java.io.File;
27

  
28
import org.gvsig.fmap.dal.DALLocator;
29
import org.gvsig.fmap.dal.DataManager;
30
import org.gvsig.fmap.dal.DataServerExplorer;
31
import org.gvsig.fmap.dal.DataStoreParameters;
32
import org.gvsig.fmap.dal.NewDataStoreParameters;
33
import org.gvsig.fmap.dal.exception.CreateException;
34
import org.gvsig.fmap.dal.exception.DataException;
35
import org.gvsig.fmap.dal.exception.FileNotFoundException;
36
import org.gvsig.fmap.dal.exception.RemoveException;
37
import org.gvsig.fmap.dal.resource.spi.ResourceConsumer;
38
import org.gvsig.fmap.dal.resource.spi.ResourceProvider;
39
import org.gvsig.fmap.dal.serverexplorer.filesystem.impl.AbstractFilesystemServerExplorerProvider;
40
import org.gvsig.fmap.dal.serverexplorer.filesystem.spi.FilesystemServerExplorerProvider;
41
import org.gvsig.fmap.dal.serverexplorer.filesystem.spi.FilesystemServerExplorerProviderServices;
42

  
43
public class JExcelFilesystemServerProvider extends AbstractFilesystemServerExplorerProvider 
44
	implements FilesystemServerExplorerProvider, ResourceConsumer {
45

  
46
	private FilesystemServerExplorerProviderServices serverExplorer;
47

  
48
	public String getDataStoreProviderName() {
49
		return JExcelStoreProvider.NAME;
50
	}
51

  
52
	public int getMode() {
53
		return DataServerExplorer.MODE_FEATURE | DataServerExplorer.MODE_GEOMETRY;
54
	}
55

  
56
	public boolean accept(File pathname) {
57
		return (pathname.getName().toLowerCase().endsWith(".xls"));
58
	}
59

  
60
	public String getDescription() {
61
		return JExcelStoreProvider.DESCRIPTION;
62
	}
63

  
64
	public DataStoreParameters getParameters(File file) throws DataException {
65
		DataManager manager = DALLocator.getDataManager();
66
		JExcelStoreParameters params = (JExcelStoreParameters) manager
67
				.createStoreParameters(this
68
				.getDataStoreProviderName());
69
		params.setFile(file);
70
		return params;
71
	}
72

  
73
	public boolean canCreate() {
74
		return false;
75
	}
76

  
77
	public boolean canCreate(NewDataStoreParameters parameters) {
78
			throw new UnsupportedOperationException(); 
79
	}
80

  
81
	public void create(NewDataStoreParameters parameters, boolean overwrite)
82
			throws CreateException {
83
		throw new UnsupportedOperationException(); 
84
	}
85

  
86
	public NewDataStoreParameters getCreateParameters() throws DataException {
87
		throw new UnsupportedOperationException(); 
88
	}
89

  
90
	public void initialize(
91
			FilesystemServerExplorerProviderServices serverExplorer) {
92
		this.serverExplorer = serverExplorer;
93
	}
94

  
95
	public void remove(DataStoreParameters parameters) throws RemoveException {
96
		File file = ((JExcelStoreParameters) parameters).getFile();
97
		if (!file.exists()) {
98
			throw new RemoveException(this.getDataStoreProviderName(),
99
					new FileNotFoundException(file));
100
		}
101
		if (!file.delete()) {
102
			// FIXME throws ???
103
		}
104

  
105
	}
106

  
107
	public boolean closeResourceRequested(ResourceProvider resource) {
108
		// while it is using a resource anyone can't close it
109
		return false;
110
	}
111

  
112
	public void resourceChanged(ResourceProvider resource) {
113
		//Do nothing
114

  
115
	}
116

  
117

  
118
}
org.gvsig.jexcel/tags/org.gvsig.jexcel-1.0.47/org.gvsig.jexcel.provider/src/main/java/org/gvsig/fmap/dal/store/jexcel/JExcelStoreProvider.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA 02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.fmap.dal.store.jexcel;
25

  
26
import java.io.File;
27
import java.io.FileReader;
28
import java.io.IOException;
29
import java.net.URL;
30
import java.text.SimpleDateFormat;
31
import java.util.ArrayList;
32
import java.util.HashMap;
33
import java.util.Iterator;
34
import java.util.List;
35
import java.util.Locale;
36
import java.util.logging.Level;
37
import jxl.Cell;
38
import jxl.Sheet;
39
import jxl.Workbook;
40
import jxl.read.biff.BiffException;
41

  
42
import org.apache.commons.io.FilenameUtils;
43
import org.apache.commons.lang3.StringUtils;
44
import org.cresques.cts.IProjection;
45
import org.gvsig.fmap.dal.DALLocator;
46
import org.gvsig.fmap.dal.DataManager;
47
import org.gvsig.fmap.dal.DataServerExplorer;
48
import org.gvsig.fmap.dal.DataStore;
49
import org.gvsig.fmap.dal.DataStoreNotification;
50
import org.gvsig.fmap.dal.DataTypes;
51
import org.gvsig.fmap.dal.FileHelper;
52
import org.gvsig.fmap.dal.exception.DataException;
53
import org.gvsig.fmap.dal.exception.InitializeException;
54
import org.gvsig.fmap.dal.exception.OpenException;
55
import org.gvsig.fmap.dal.exception.ReadException;
56
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
57
import org.gvsig.fmap.dal.feature.EditableFeature;
58
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
59
import org.gvsig.fmap.dal.feature.EditableFeatureType;
60
import org.gvsig.fmap.dal.feature.Feature;
61
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
62
import org.gvsig.fmap.dal.feature.FeatureAttributeEmulator;
63
import org.gvsig.fmap.dal.feature.FeatureStore;
64
import org.gvsig.fmap.dal.feature.FeatureType;
65
import org.gvsig.fmap.dal.feature.exception.PerformEditingException;
66
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
67
import org.gvsig.fmap.dal.feature.spi.FeatureStoreProviderServices;
68
import org.gvsig.fmap.dal.feature.spi.memory.AbstractMemoryStoreProvider;
69
import org.gvsig.fmap.dal.resource.file.FileResource;
70
import org.gvsig.fmap.dal.resource.spi.ResourceConsumer;
71
import org.gvsig.fmap.dal.resource.spi.ResourceProvider;
72
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorer;
73
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorerParameters;
74
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
75
import org.gvsig.fmap.geom.Geometry;
76
import org.gvsig.fmap.geom.GeometryLocator;
77
import org.gvsig.fmap.geom.GeometryManager;
78
import org.gvsig.fmap.geom.aggregate.MultiPoint;
79
import org.gvsig.fmap.geom.primitive.Envelope;
80
import org.gvsig.fmap.geom.primitive.Point;
81
import org.gvsig.fmap.geom.type.GeometryType;
82
import org.gvsig.tools.ToolsLocator;
83
import org.gvsig.tools.dataTypes.CoercionException;
84
import org.gvsig.tools.dataTypes.DataType;
85
import org.gvsig.tools.dataTypes.DataTypesManager;
86
import org.gvsig.tools.dataTypes.DataTypesManager.Coercion;
87
import org.gvsig.tools.dataTypes.DataTypesManager.CoercionWithLocale;
88
import org.gvsig.tools.dynobject.exception.DynFieldNotFoundException;
89
import org.gvsig.tools.exception.BaseException;
90
import org.gvsig.tools.exception.NotYetImplemented;
91
import org.gvsig.tools.persistence.PersistentState;
92
import org.gvsig.tools.persistence.exception.PersistenceException;
93
import org.gvsig.tools.task.SimpleTaskStatus;
94
import org.gvsig.tools.task.TaskStatusManager;
95
import org.gvsig.tools.visitor.VisitCanceledException;
96
import org.gvsig.tools.visitor.Visitor;
97
import org.slf4j.Logger;
98
import org.slf4j.LoggerFactory;
99

  
100
public class JExcelStoreProvider extends AbstractMemoryStoreProvider implements
101
        ResourceConsumer {
102

  
103
    private static final Logger logger = LoggerFactory.getLogger(JExcelStoreProvider.class);
104

  
105
    public static final String NAME = "JExcel";
106
    public static final String DESCRIPTION = "JExcel file";
107

  
108
    public static final String METADATA_DEFINITION_NAME = NAME;
109

  
110
    private ResourceProvider resource;
111

  
112
    private long counterNewsOIDs = 0;
113
    private Envelope envelope;
114
    private boolean need_calculate_envelope = false;
115
    private SimpleTaskStatus taskStatus;
116
    private String sheetName = "";
117

  
118
    public JExcelStoreProvider(JExcelStoreParameters parameters,
119
            DataStoreProviderServices storeServices) throws InitializeException {
120
        super(
121
                parameters,
122
                storeServices,
123
                FileHelper.newMetadataContainer(METADATA_DEFINITION_NAME)
124
        );
125

  
126
        TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
127
        this.taskStatus = manager.createDefaultSimpleTaskStatus("JExcel");
128

  
129
        counterNewsOIDs = 0;
130

  
131
        File file = getJExcelParameters().getFile();
132
        resource = this.createResource(
133
                FileResource.NAME,
134
                new Object[]{file.getAbsolutePath()}
135
        );
136

  
137
        resource.addConsumer(this);
138
        initializeFeatureTypes();
139
    }
140

  
141
    private JExcelStoreParameters getJExcelParameters() {
142
        return (JExcelStoreParameters) this.getParameters();
143
    }
144

  
145
    public String getProviderName() {
146
        return NAME;
147
    }
148

  
149
    public boolean allowWrite() {
150
        return false;
151
    }
152

  
153
    private String getFullFileName() {
154
        // Usar solo para mostrar mensajes en el logger.
155
        String s = "(unknow)";
156
        try {
157
            s = getJExcelParameters().getFile().getAbsolutePath();
158
        } catch (Exception e2) {
159
            s = "(unknow)";
160
        }
161
        return s;
162
    }
163

  
164
    public void open() throws OpenException {
165
        if ( this.data != null ) {
166
            return;
167
        }
168
        this.data = new ArrayList<FeatureProvider>();
169
        resource.setData(new HashMap());
170
        counterNewsOIDs = 0;
171
        try {
172
            loadFeatures();
173
        } catch (RuntimeException e) {
174
            logger.warn("Can't load features from JExcel '" + getFullFileName() + "'.", e);
175
            throw e;
176
        } catch (Exception e) {
177
            logger.warn("Can't load features from JExcel '" + getFullFileName() + "'.", e);
178
            throw new RuntimeException(e);
179
        }
180
    }
181

  
182
    public DataServerExplorer getExplorer() throws ReadException {
183
        DataManager manager = DALLocator.getDataManager();
184
        FilesystemServerExplorerParameters params;
185
        try {
186
            params = (FilesystemServerExplorerParameters) manager
187
                    .createServerExplorerParameters(FilesystemServerExplorer.NAME);
188
            params.setRoot(this.getJExcelParameters().getFile().getParent());
189
            return manager.openServerExplorer(FilesystemServerExplorer.NAME, params);
190
        } catch (DataException e) {
191
            throw new ReadException(this.getProviderName(), e);
192
        } catch (ValidateDataParametersException e) {
193
            throw new ReadException(this.getProviderName(), e);
194
        }
195

  
196
    }
197

  
198
    public void performChanges(Iterator deleteds, Iterator inserteds, Iterator updateds, Iterator originalFeatureTypesUpdated) throws PerformEditingException {
199
        throw new UnsupportedOperationException();
200
    }
201

  
202
    public boolean closeResourceRequested(ResourceProvider resource) {
203
        return true;
204
    }
205

  
206
    public int getOIDType() {
207
        return DataTypes.LONG;
208
    }
209

  
210
    public boolean supportsAppendMode() {
211
        return false;
212
    }
213

  
214
    public void append(FeatureProvider featureProvider) {
215
        throw new UnsupportedOperationException();
216
    }
217

  
218
    public void beginAppend() {
219
        throw new UnsupportedOperationException();
220
    }
221

  
222
    public void endAppend() {
223
        throw new UnsupportedOperationException();
224
    }
225

  
226
    public void saveToState(PersistentState state) throws PersistenceException {
227
        throw new NotYetImplemented();
228
    }
229

  
230
    public void loadFromState(PersistentState state) throws PersistenceException {
231
        throw new NotYetImplemented();
232
    }
233

  
234
    public Object createNewOID() {
235
        return new Long(counterNewsOIDs++);
236
    }
237

  
238
    protected void initializeFeatureTypes() throws InitializeException {
239
        try {
240
            this.open();
241
        } catch (OpenException e) {
242
            throw new InitializeException(this.getProviderName(), e);
243
        }
244
    }
245

  
246
    public Envelope getEnvelope() throws DataException {
247
        this.open();
248
        if ( this.envelope != null ) {
249
            return this.envelope;
250
        }
251
        if ( !this.need_calculate_envelope ) {
252
            return null;
253
        }
254
        FeatureStore fs = this.getFeatureStore();
255
        FeatureType ft = fs.getDefaultFeatureType();
256
        FeatureAttributeDescriptor fad = ft.getAttributeDescriptor(ft.getDefaultGeometryAttributeIndex());
257

  
258
        try {
259
            this.envelope = GeometryLocator.getGeometryManager().createEnvelope(fad.getGeomType().getSubType());
260
            fs.accept(new Visitor() {
261
                public void visit(Object obj) throws VisitCanceledException, BaseException {
262
                    Feature f = (Feature) obj;
263
                    Geometry geom = f.getDefaultGeometry();
264
                    if ( geom != null ) {
265
                        envelope.add(geom.getEnvelope());
266
                    }
267
                }
268
            });
269
        } catch (BaseException e) {
270
            logger.warn("Can't calculate the envelope of JExcel file '" + this.getFullName() + "'.", e);
271
            this.envelope = null;
272
        }
273

  
274
        this.need_calculate_envelope = false;
275
        return this.envelope;
276
    }
277

  
278
    public Object getDynValue(String name) throws DynFieldNotFoundException {
279
        if ( DataStore.METADATA_ENVELOPE.equalsIgnoreCase(name) ) {
280
            try {
281
                return this.getEnvelope();
282
            } catch (DataException e) {
283
                return null;
284
            }
285
        } else {
286
            if ( DataStore.METADATA_CRS.equalsIgnoreCase(name) ) {
287
                IProjection pro = JExcelStoreParameters.getCRS(this.getJExcelParameters());
288
                if ( pro != null ) {
289
                    return pro;
290
                }
291
            }
292
        }
293
        return super.getDynValue(name);
294
    }
295

  
296
    public void resourceChanged(ResourceProvider resource) {
297
        this.getStoreServices().notifyChange(
298
                DataStoreNotification.RESOURCE_CHANGED,
299
                resource);
300
    }
301

  
302
    public Object getSourceId() {
303
        return this.getJExcelParameters().getFile();
304
    }
305

  
306
    public String getName() {
307
        String name = this.getJExcelParameters().getFile().getName();
308
        if( StringUtils.isBlank(this.sheetName) ) {
309
            return FilenameUtils.getBaseName(name);
310
        }
311
        return FilenameUtils.getBaseName(name)+"."+this.sheetName;
312
    }
313

  
314
    public String getFullName() {
315
        return this.getJExcelParameters().getFile().getAbsolutePath();
316
    }
317

  
318
    public ResourceProvider getResource() {
319
        return resource;
320
    }
321

  
322
    private class FieldTypeParser {
323

  
324
        public String name = null;
325
        public int type = DataTypes.STRING;
326
        public int size = 0;
327
        public boolean allowNulls = true;
328

  
329
        private String typename = "string";
330

  
331
        FieldTypeParser() {
332
        }
333

  
334
        private int getType(String value) {
335
            DataTypesManager dataTypesManager = ToolsLocator.getDataTypesManager();
336
            return dataTypesManager.getType(typename);
337
        }
338

  
339
        // El formato seria:
340
        //   name[:typename[:size[:notnull|null]]]
341
        //   name[__typename[__size[__notnull|null]]]
342
        //
343
        public boolean parse(String value) {
344
            String typename = null;
345
            String[] ss = null;
346
            if ( value.contains(":") ) {
347
                ss = value.split(":");
348
            } else if ( value.contains("__") ) {
349
                ss = value.split("__");
350
            }
351
            if ( ss == null ) {
352
                this.name = value;
353
                return true;
354
            }
355
            switch (ss.length) {
356
            case 4:
357
                if ( ss[3].length() > 0 ) {
358
                    if ( "notnull".equalsIgnoreCase(ss[3]) ) {
359
                        this.allowNulls = false;
360
                    } else {
361
                        this.allowNulls = true;
362
                    }
363
                }
364
            case 3:
365
                if ( ss[2].length() > 0 ) {
366
                    try {
367
                        this.size = Integer.parseInt(ss[2]);
368
                    } catch (Exception ex) {
369
                        logger.warn("Ignore incorrect field size for field " + value + " in JExcel header of '" + getFullFileName() + "'.", ex);
370
                    }
371
                }
372
            case 2:
373
                if ( ss[1].length() > 0 ) {
374
                    this.typename = ss[1];
375
                    this.type = this.getType(this.typename);
376
                    if ( this.type == DataTypes.INVALID ) {
377
                        this.type = DataTypes.STRING;
378
                        logger.info("Type '" + typename + "' not valid for attribute '" + value + "' in JExcel file '" + getFullFileName() + "'.");
379
                    }
380
                }
381
            case 1:
382
                this.name = ss[0];
383
                break;
384
            }
385

  
386
            if ( this.type != DataTypes.STRING ) {
387
                this.size = 0;
388
            }
389
            return true;
390
        }
391

  
392
    }
393

  
394
    private EditableFeatureType getFeatureType(String headers[], int automaticTypes[]) {
395
        EditableFeatureType fType = getStoreServices().createFeatureType(this.getName());
396
        fType.setHasOID(true);
397
        DataTypesManager dataTypesManager = ToolsLocator.getDataTypesManager();
398

  
399
        FieldTypeParser[] fieldTypes = new FieldTypeParser[headers.length];
400
        //
401
        // Calculamos cuales pueden ser los tipos de datos
402
        //
403
        for ( int i = 0; i < fieldTypes.length; i++ ) {
404
            fieldTypes[i] = new FieldTypeParser();
405
        }
406

  
407
        // Asuminos los tipos pasados por parametro, que se supone
408
        // son los detectados automaticamente.
409
        if ( automaticTypes != null ) {
410
            for ( int i = 0; i < fieldTypes.length && i < automaticTypes.length; i++ ) {
411
                fieldTypes[i].type = automaticTypes[i];
412
            }
413
        }
414
        // Luego probamos con lo que diga las cabezeras del CVS, sobreescribiendo
415
        // los tipos anteriores en caso de definirse en la cabezara.
416
        for ( int i = 0; i < fieldTypes.length; i++ ) {
417
            if ( !fieldTypes[i].parse(headers[i]) ) {
418
                continue;
419
            }
420

  
421
        }
422

  
423
        // Y por ultimo hacemos caso a lo que se haya especificado en los parametros
424
        // de apertura del JExcel, teniendo esto prioridad sobre todo.
425
        int[] param_types = JExcelStoreParameters.getFieldTypes(this.getParameters());
426
        if ( param_types != null ) {
427
            for ( int i = 0; i < fieldTypes.length && i < param_types.length; i++ ) {
428
                fieldTypes[i].type = param_types[i];
429
            }
430
        }
431

  
432
        int[] param_sizes = JExcelStoreParameters.getFieldSizes(this.getParameters());
433
        if ( param_sizes != null ) {
434
            for ( int i = 0; i < param_sizes.length; i++ ) {
435
                if ( param_sizes[i] > 0 ) {
436
                    fieldTypes[i].size = param_sizes[i];
437
                }
438
            }
439
        }
440
        //
441
        // Una vez ya sabemos los tipos de datos rellenamos el feature-type
442
        //
443
        for ( int i = 0; i < fieldTypes.length; i++ ) {
444
            EditableFeatureAttributeDescriptor fad = fType.add(
445
                    fieldTypes[i].name,
446
                    fieldTypes[i].type
447
            );
448
            fad.setSize(fieldTypes[i].size);
449
            fad.setAllowNull(fieldTypes[i].allowNulls);
450
            if ( fieldTypes[i].type == DataTypes.GEOMETRY
451
                    && fType.getDefaultGeometryAttributeName() == null ) {
452
                fType.setDefaultGeometryAttributeName(fieldTypes[i].name);
453
            }
454
        }
455
        String[] pointDimensionNames = JExcelStoreParameters.getPointDimensionNames(this.getParameters());
456
        if ( pointDimensionNames != null ) {
457
//            ToPointEvaluaror evaluator = new ToPointEvaluaror(pointDimensionNames);
458
            PointAttributeEmulator emulator = new PointAttributeEmulator(pointDimensionNames);
459
            EditableFeatureAttributeDescriptor attr = fType.add("GEOM", DataTypes.GEOMETRY, emulator);
460
            GeometryManager geommgr = GeometryLocator.getGeometryManager();
461
            GeometryType gt;
462
            try {
463
                if ( emulator.fieldNames != null && emulator.fieldNames.length <= 2 ) {
464
                	gt = geommgr.getGeometryType(Geometry.TYPES.GEOMETRY, Geometry.SUBTYPES.GEOM2D);
465
                } else {
466
                	gt = geommgr.getGeometryType(Geometry.TYPES.GEOMETRY, Geometry.SUBTYPES.GEOM3D);
467
                }
468
                attr.setGeometryType(gt);
469
            } catch (Exception e) {
470
                logger.warn("Can't set geometry type for the calculated field in JExcel file '" + getFullFileName() + "'.", e);
471
            }
472
        }
473
        return fType;
474
    }
475

  
476
    static class PointAttributeEmulator implements FeatureAttributeEmulator {
477

  
478
        private static final Logger logger = LoggerFactory.getLogger(PointAttributeEmulator.class);
479

  
480
        private static final int XNAME = 0;
481
        private static final int YNAME = 1;
482
        private static final int ZNAME = 2;
483

  
484
        private final GeometryManager geommgr;
485
        private final String[] fieldNames;
486
        private final Coercion toDouble;
487
        private final DataType dataType;
488
        private int errorcount = 0;
489

  
490
        public PointAttributeEmulator(String[] pointDimensionNames) {
491
            if ( pointDimensionNames.length > 2 ) {
492
                this.fieldNames = new String[3];
493
                this.fieldNames[ZNAME] = pointDimensionNames[2];
494
            } else {
495
                this.fieldNames = new String[2];
496
            }
497
            this.fieldNames[XNAME] = pointDimensionNames[0];
498
            this.fieldNames[YNAME] = pointDimensionNames[1];
499
            this.geommgr = GeometryLocator.getGeometryManager();
500
            DataTypesManager datatypeManager = ToolsLocator.getDataTypesManager();
501

  
502
            this.toDouble = datatypeManager.getCoercion(DataTypes.DOUBLE);
503
            this.dataType = datatypeManager.get(DataTypes.GEOMETRY);
504
        }
505

  
506
        public Object get(Feature feature) {
507
            try {
508
                Object valueX = feature.get(this.fieldNames[XNAME]);
509
                valueX = toDouble.coerce(valueX);
510
                if ( valueX == null ) {
511
                    return null;
512
                }
513
                Object valueY = feature.get(this.fieldNames[YNAME]);
514
                valueY = toDouble.coerce(valueY);
515
                if ( valueY == null ) {
516
                    return null;
517
                }
518
                Object valueZ = null;
519
                if ( this.fieldNames.length > 2 ) {
520
                    valueZ = toDouble.coerce(feature.get(this.fieldNames[ZNAME]));
521
                    if ( valueZ == null ) {
522
                        return null;
523
                    }
524
                }
525

  
526
                double x = ((Double) valueX).doubleValue();
527
                double y = ((Double) valueY).doubleValue();
528
                Point point = null;
529
                if ( this.fieldNames.length > 2 ) {
530
                    point = geommgr.createPoint(x, y, Geometry.SUBTYPES.GEOM3D);
531
                    double z = ((Double) valueZ).doubleValue();
532
                    point.setCoordinateAt(2, z);
533
                } else {
534
                    point = geommgr.createPoint(x, y, Geometry.SUBTYPES.GEOM2D);
535
                }
536
                return point;
537
            } catch (Exception ex) {
538
                if ( ++errorcount < 5 ) {
539
                    logger.warn("[" + errorcount + "] Can't create point in JExcel provider. XNAME='"
540
                            + this.fieldNames[XNAME] + "', YNAME='" + this.fieldNames[XNAME] + "' feature=" + feature.toString(), ex);
541
                }
542
                return null;
543
            }
544
        }
545

  
546
        public void set(EditableFeature feature, Object value) {
547
            if ( value == null ) {
548
                return;
549
            }
550
            Point point = null;
551
            if ( value instanceof MultiPoint ) {
552
                point = (Point) ((MultiPoint) value).getPrimitiveAt(0);
553
            } else {
554
                point = (Point) value;
555
            }
556
            feature.set(this.fieldNames[XNAME], point.getX());
557
            feature.set(this.fieldNames[YNAME], point.getY());
558
            if ( this.fieldNames.length > 2 ) {
559
                feature.set(this.fieldNames[ZNAME], point.getCoordinateAt(2));
560
            }
561
        }
562

  
563
        public boolean allowSetting() {
564
            return true;
565
        }
566

  
567
        public String[] getRequiredFieldNames() {
568
            return this.fieldNames;
569
        }
570

  
571
    }
572

  
573
    static class JExcelReader {
574

  
575
        Workbook workbook = null;
576
        Sheet sheet = null;
577
        boolean isFirstLineHedaer = false;
578
        int currentRow = 0;
579
        String[] row = null;
580
        private int sheetIndex;
581

  
582
        public JExcelReader(File f, int sheet, boolean isFirstLineHedaer)
583
                throws IOException, BiffException {
584
            this.currentRow = 0;
585
            this.sheetIndex = sheet;
586
            this.workbook = Workbook.getWorkbook(f);
587
            this.sheet = this.workbook.getSheet(sheet);
588
            this.row = new String[this.sheet.getColumns()];
589
            this.isFirstLineHedaer = isFirstLineHedaer;
590
            if ( this.isFirstLineHedaer ) {
591
                this.currentRow++;
592
            }
593
        }
594

  
595
        public String[] getHeader() {
596
            int columns = this.sheet.getColumns();
597
            String header[] = new String[columns];
598
            String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
599
            if ( columns > abc.length() ) {
600
                for ( int i = 0; i < columns; i++ ) {
601
                    header[i] = "C" + i;
602
                }
603
            } else {
604
                for ( int i = 0; i < columns; i++ ) {
605
                    header[i] = abc.substring(i, i+1);
606
                }
607
            }
608
            if ( this.isFirstLineHedaer ) {
609
                for ( int col = 0; col < columns; col++ ) {
610
                    Cell cell = this.sheet.getCell(col, 0);
611
                    String s = cell.getContents().trim();
612
                    if ( !StringUtils.isBlank(s) ) {
613
                        header[col] = s;
614
                    }
615
                }
616
            }
617
            return header;
618
        }
619

  
620
        public String[] read() {
621
            if( this.currentRow>=this.sheet.getRows() ) {
622
                return null;
623
            }
624
            int columns = this.sheet.getColumns();
625
            for ( int col = 0; col < columns; col++ ) {
626
                Cell cell = this.sheet.getCell(col, this.currentRow);
627
                this.row[col] = cell.getContents();
628
            }
629
            this.currentRow++;
630
            return row;
631
        }
632

  
633
        public void close() {
634
            this.workbook.close();
635
        }
636
        
637
        public String getSheetName() {
638
            String[] names = this.workbook.getSheetNames();
639
            return names[this.sheetIndex];
640
        }
641
    }
642

  
643
    private void loadFeatures() throws IOException, DataException,
644
            CoercionException, CloneNotSupportedException {
645
        JExcelReader reader = null;
646

  
647
        try {
648
            String headers[] = null;
649
            FeatureStoreProviderServices store = this.getStoreServices();
650

  
651
            boolean ignore_errors = JExcelStoreParameters.getIgnoreErrors(getJExcelParameters());
652

  
653
            reader = new JExcelReader(
654
                    this.getJExcelParameters().getFile(),
655
                    JExcelStoreParameters.getSheetIndex(getJExcelParameters()),
656
                    JExcelStoreParameters.isFirstRowHeader(getJExcelParameters())
657
            );
658
            this.sheetName = reader.getSheetName();
659
            
660
            headers = JExcelStoreParameters.getHeaders(getJExcelParameters());
661
            if ( headers == null ) {
662
                headers = reader.getHeader();
663
            }
664

  
665
            // Initialize the feature types
666
            EditableFeatureType edftype = this.getFeatureType(headers, automaticDetectionOfTypes());
667
            FeatureType ftype = edftype.getNotEditableCopy();
668
            List<FeatureType> ftypes = new ArrayList<FeatureType>();
669
            ftypes.add(ftype);
670
            store.setFeatureTypes(ftypes, ftype);
671

  
672
            Coercion coercion[] = new Coercion[ftype.size()];
673
            int sizes[] = new int[ftype.size()];
674
            for ( int i = 0; i < ftype.size(); i++ ) {
675
                sizes[i] = -1;
676
                FeatureAttributeDescriptor ad = ftype.getAttributeDescriptor(i);
677
                coercion[i] = ad.getDataType().getCoercion();
678
                if ( ad.getDataType().getType() == DataTypes.STRING ) {
679
                    if ( ad.getSize() == 0 ) {
680
                        // Es un string y no tiene un size asignado.
681
                        // Lo ponemos a cero para calcularlo.
682
                        sizes[i] = 0;
683
                    }
684
                }
685
            }
686
            if ( ftype.getDefaultGeometryAttributeName() != null ) {
687
                this.need_calculate_envelope = true;
688
            }
689

  
690
            Locale locale = JExcelStoreParameters.getLocale(getJExcelParameters());
691
            taskStatus.message("_loading");
692
            int count = 0;
693

  
694
            int count_errors = 0;
695
            String[] row = reader.read();
696

  
697
            Object rawvalue = null;
698
            while ( row != null ) {
699
                taskStatus.setCurValue(++count);
700
                FeatureProvider feature = this.createFeatureProvider(ftype);
701
                for ( int i = 0; i < row.length; i++ ) {
702
                    rawvalue = row [i];
703
                    if( rawvalue instanceof String && StringUtils.isBlank((String)rawvalue) ) {
704
                        rawvalue = null;
705
                    }
706
                    try {
707
                        Object value = null;
708
                        if ( locale != null && coercion[i] instanceof CoercionWithLocale ) {
709
                            value = ((CoercionWithLocale) (coercion[i])).coerce(rawvalue, locale);
710
                        } else {
711
                            value = coercion[i].coerce(rawvalue);
712
                        }
713
                        feature.set(i, value);
714
                        if ( sizes[i] >= 0 && value != null ) {
715
                            int x = ((String) value).length();
716
                            if ( sizes[i] < x ) {
717
                                sizes[i] = x;
718
                            }
719
                        }
720
                    } catch (RuntimeException ex) {
721
                        if ( !ignore_errors ) {
722
                            throw ex;
723
                        }
724
                        if ( count_errors++ < 10 ) {
725
                            logger.warn("Can't load value of attribute " + i + " in row " + count + ".", ex);
726
                        }
727
                        if ( count_errors == 10 ) {
728
                            logger.info("Too many errors, suppress messages.");
729
                        }
730
                    }
731
                }
732
                this.addFeatureProvider(feature);
733
                row = reader.read();
734
            }
735
            for ( int i = 0; i < ftype.size(); i++ ) {
736
                if ( sizes[i] > 0 ) {
737
                    EditableFeatureAttributeDescriptor efad = ((EditableFeatureAttributeDescriptor) edftype.getAttributeDescriptor(i));
738
                    efad.setSize(sizes[i]);
739
                }
740
            }
741
            // Volvemos a asignar al store el featuretype, ya que puede
742
            // haber cambiado.
743
            ftype = edftype.getNotEditableCopy();
744
            ftypes = new ArrayList<FeatureType>();
745
            ftypes.add(ftype);
746
            store.setFeatureTypes(ftypes, ftype);
747

  
748
            taskStatus.terminate();
749
        } catch (Exception ex) {
750
            logger.warn("Can't load features from excel file '" + getFullFileName() + "'.", ex);
751
        } finally {
752
            if ( reader != null ) {
753
                try {
754
                    reader.close();
755
                } catch (Exception ex) {
756
                    // Do nothing
757
                }
758
                reader = null;
759
            }
760

  
761
        }
762
    }
763

  
764
    private int[] automaticDetectionOfTypes() throws IOException {
765
        boolean automatic_types_detection = JExcelStoreParameters.getAutomaticTypesDetection(getJExcelParameters());
766
        if ( !automatic_types_detection ) {
767
            return null;
768
        }
769
        final int T_INT = 0;
770
        final int T_FLOAT = 1;
771
        final int T_DOUBLE = 2;
772
        final int T_LONG = 3;
773
        final int T_URL = 4;
774
        final int T_DATE = 5;
775
        boolean possibleDataTypes[][] = null;
776
        Locale locale = null;
777
        JExcelReader reader = null;
778
        int[] types = null;
779

  
780
        String headers[] = null;
781
        SimpleDateFormat dateFormat = new SimpleDateFormat();
782

  
783
        try {
784
            reader = new JExcelReader(
785
                    this.getJExcelParameters().getFile(),
786
                    JExcelStoreParameters.getSheetIndex(getJExcelParameters()),
787
                    JExcelStoreParameters.isFirstRowHeader(getJExcelParameters())
788
            );
789

  
790
            headers = reader.getHeader();
791
            if ( headers == null ) {
792
                headers = JExcelStoreParameters.getHeaders(getJExcelParameters());
793
            }
794
            types = new int[headers.length];
795

  
796
            
797
            
798
            possibleDataTypes = new boolean[headers.length][6];
799
            for ( int i = 0; i < possibleDataTypes.length; i++ ) {
800
                for ( int j = 0; j < 4; j++ ) {
801
                    possibleDataTypes[i][j] = true;
802
                }
803
            }
804
            locale = JExcelStoreParameters.getLocale(getJExcelParameters());
805
            if ( locale == null ) {
806
                locale = Locale.getDefault();
807
            }
808

  
809
            Coercion coercion[] = new Coercion[6];
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff