Revision 515

View differences:

org.gvsig.jexcel/tags/org.gvsig.jexcel-1.0.83/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.83/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.83/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.83/org.gvsig.jexcel.provider/src/main/java/org/gvsig/jexcel/Spread.java
1
package org.gvsig.jexcel;
2

  
3
import java.awt.Rectangle;
4
import java.io.File;
5
import java.util.List;
6

  
7
/**
8
 *
9
 * @author jjdelcerro
10
 */
11
public interface Spread {
12

  
13
    public static String NAME = "Excel";
14

  
15
    public static Spread create(File file, Object... args) {
16
        JExcelSpread spread = new JExcelSpread();
17
        spread.open(file);
18
        return spread;
19
    }
20

  
21
    public interface Sheet {
22

  
23
        int getColumnCount();
24

  
25
        List<String> getColumnNames(boolean isFirstLineHedaer);
26

  
27
        File getFile();
28

  
29
        String getName();
30

  
31
        int getRowCount();
32

  
33
        int getSheetIndex();
34

  
35
        Object getValueAt(int col, int row);
36

  
37
        public Rectangle getUsedRange();
38
    }
39

  
40
    public void open(File spreadFile);
41

  
42
    public File getFile();
43

  
44
    public Sheet getSheet(int sheetIndex);
45

  
46
    public List<String> getSheetNames();
47
}
org.gvsig.jexcel/tags/org.gvsig.jexcel-1.0.83/org.gvsig.jexcel.provider/src/main/java/org/gvsig/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.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.jexcel.dal.provider.JExcelFilesystemServerProvider;
36
import org.gvsig.jexcel.dal.provider.JExcelStoreParameters;
37
import org.gvsig.jexcel.dal.provider.JExcelStoreProvider;
38
import org.gvsig.jexcel.dal.provider.JExcelStoreProviderFactory;
39
import org.gvsig.jexcel.dynformfield.point.JDynFormFieldExcelPointFieldsFactory;
40
import org.gvsig.jexcel.dynformfield.sheet.JDynFormFieldExcelSheetFactory;
41
import org.gvsig.metadata.exceptions.MetadataException;
42
import org.gvsig.tools.dynform.spi.DynFormSPILocator;
43
import org.gvsig.tools.dynform.spi.DynFormSPIManager;
44
import org.gvsig.tools.library.AbstractLibrary;
45
import org.gvsig.tools.library.LibraryException;
46

  
47
public class JExcelLibrary extends AbstractLibrary {
48

  
49
    @Override
50
    public void doRegistration() {
51
        registerAsServiceOf(DALLibrary.class);
52
        require(DALFileLibrary.class);
53
    }
54

  
55
    @Override
56
    protected void doInitialize() throws LibraryException {
57
    }
58

  
59
    @Override
60
    protected void doPostInitialize() throws LibraryException {
61
        List<Throwable> exs = new ArrayList<Throwable>();
62

  
63
        FileHelper.registerParametersDefinition(
64
                JExcelStoreParameters.PARAMETERS_DEFINITION_NAME,
65
                JExcelStoreParameters.class, "JExcelParameters.xml");
66
        try {
67
            FileHelper.registerMetadataDefinition(
68
                    JExcelStoreProvider.METADATA_DEFINITION_NAME,
69
                    JExcelStoreProvider.class, "JExcelMetadata.xml");
70
        } catch (MetadataException e) {
71
            exs.add(e);
72
        }
73

  
74
        DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator
75
                .getDataManager();
76

  
77
        try {
78
            if (!dataman.getStoreProviders().contains(JExcelStoreProvider.NAME)) {
79
                dataman.registerStoreProviderFactory(new JExcelStoreProviderFactory(JExcelStoreProvider.NAME, JExcelStoreProvider.DESCRIPTION));
80

  
81
            }
82
        } catch (RuntimeException e) {
83
            exs.add(e);
84
        }
85

  
86
        try {
87
            DALFileLocator.getFilesystemServerExplorerManager()
88
                    .registerProvider(JExcelStoreProvider.NAME,
89
                            JExcelStoreProvider.DESCRIPTION,
90
                            JExcelFilesystemServerProvider.class);
91
        } catch (RuntimeException e) {
92
            exs.add(e);
93
        }
94

  
95
        DynFormSPIManager manager = DynFormSPILocator.getDynFormSPIManager();
96
        manager.registerDynFieldFactory(new JDynFormFieldExcelSheetFactory());
97
        manager.registerDynFieldFactory(new JDynFormFieldExcelPointFieldsFactory());
98

  
99
        if (exs.size() > 0) {
100
            throw new LibraryException(this.getClass(), exs);
101
        }
102
    }
103
}
org.gvsig.jexcel/tags/org.gvsig.jexcel-1.0.83/org.gvsig.jexcel.provider/src/main/java/org/gvsig/jexcel/dal/provider/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.jexcel.dal.provider;
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
	public 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.83/org.gvsig.jexcel.provider/src/main/java/org/gvsig/jexcel/dal/provider/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.jexcel.dal.provider;
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.FileHelper;
32
import org.gvsig.fmap.dal.OpenDataStoreParameters;
33
import org.gvsig.fmap.dal.feature.OpenFeatureStoreParameters;
34
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemStoreParameters;
35
import org.gvsig.fmap.dal.spi.AbstractDataParameters;
36
import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
37
import org.gvsig.tools.ToolsLocator;
38
import org.gvsig.tools.dataTypes.DataTypesManager;
39
import org.gvsig.tools.dynobject.DelegatedDynObject;
40
import org.gvsig.tools.dynobject.DynObject;
41
import org.slf4j.Logger;
42
import org.slf4j.LoggerFactory;
43

  
44
public class JExcelStoreParameters extends AbstractDataParameters implements
45
        OpenFeatureStoreParameters, FilesystemStoreParameters {
46

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

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

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

  
61
    private DelegatedDynObject parameters;
62

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  
280
}
org.gvsig.jexcel/tags/org.gvsig.jexcel-1.0.83/org.gvsig.jexcel.provider/src/main/java/org/gvsig/jexcel/dal/provider/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.jexcel.dal.provider;
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.83/org.gvsig.jexcel.provider/src/main/java/org/gvsig/jexcel/dal/provider/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.jexcel.dal.provider;
25

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

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

  
97
public class JExcelStoreProvider extends AbstractMemoryStoreProvider implements
98
        ResourceConsumer {
99

  
100
    private static final Logger logger = LoggerFactory.getLogger(JExcelStoreProvider.class);
101

  
102
    public static final String NAME = "JExcel";
103
    public static final String DESCRIPTION = "JExcel file";
104

  
105
    public static final String METADATA_DEFINITION_NAME = NAME;
106

  
107
    private ResourceProvider resource;
108

  
109
    private long counterNewsOIDs = 0;
110
    private Envelope envelope;
111
    private boolean need_calculate_envelope = false;
112
    private SimpleTaskStatus taskStatus;
113
    private String sheetName = "";
114

  
115
    public JExcelStoreProvider(JExcelStoreParameters parameters,
116
            DataStoreProviderServices storeServices) throws InitializeException {
117
        super(
118
                parameters,
119
                storeServices,
120
                FileHelper.newMetadataContainer(METADATA_DEFINITION_NAME)
121
        );
122

  
123
        TaskStatusManager manager = ToolsLocator.getTaskStatusManager();
124
        this.taskStatus = manager.createDefaultSimpleTaskStatus("JExcel");
125

  
126
        counterNewsOIDs = 0;
127

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

  
134
        resource.addConsumer(this);
135
        initializeFeatureTypes();
136
    }
137

  
138
    private JExcelStoreParameters getJExcelParameters() {
139
        return (JExcelStoreParameters) this.getParameters();
140
    }
141

  
142
    public String getProviderName() {
143
        return NAME;
144
    }
145

  
146
    public boolean allowWrite() {
147
        return false;
148
    }
149

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

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

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

  
194
    }
195

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

  
200
    public boolean closeResourceRequested(ResourceProvider resource) {
201
        return true;
202
    }
203

  
204
    public int getOIDType() {
205
        return DataTypes.LONG;
206
    }
207

  
208
    public boolean supportsAppendMode() {
209
        return false;
210
    }
211

  
212
    public void append(FeatureProvider featureProvider) {
213
        throw new UnsupportedOperationException();
214
    }
215

  
216
    public void beginAppend() {
217
        throw new UnsupportedOperationException();
218
    }
219

  
220
    public void endAppend() {
221
        throw new UnsupportedOperationException();
222
    }
223

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

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

  
232
    public Object createNewOID() {
233
        return new Long(counterNewsOIDs++);
234
    }
235

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

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

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

  
272
        this.need_calculate_envelope = false;
273
        return this.envelope;
274
    }
275

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

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

  
300
    public Object getSourceId() {
301
        return this.getJExcelParameters().getFile();
302
    }
303

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

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

  
316
    public ResourceProvider getResource() {
317
        return resource;
318
    }
319

  
320
    private class FieldTypeParser {
321

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

  
327
        private String typename = "string";
328

  
329
        FieldTypeParser() {
330
        }
331

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

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

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

  
390
    }
391

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

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

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

  
419
        }
420

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

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

  
474
    static class PointAttributeEmulator implements FeatureAttributeEmulator {
475

  
476
        private static final Logger logger = LoggerFactory.getLogger(PointAttributeEmulator.class);
477

  
478
        private static final int XNAME = 0;
479
        private static final int YNAME = 1;
480
        private static final int ZNAME = 2;
481

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

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

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

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

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

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

  
561
        public boolean allowSetting() {
562
            return true;
563
        }
564

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

  
569
    }
570

  
571
    static class JExcelReader {
572

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

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

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

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

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

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

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

  
649
            boolean ignore_errors = JExcelStoreParameters.getIgnoreErrors(getJExcelParameters());
650

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

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

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

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

  
692
            int count_errors = 0;
693
            String[] row = reader.read();
694

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

Also available in: Unified diff