Revision 20029 trunk/libraries/libDataSourceDBBaseDrivers/src/org/gvsig/data/datastores/vectorial/db/jdbc/h2/H2FeaturesWriter.java

View differences:

H2FeaturesWriter.java
38 38
import com.iver.cit.gvsig.fmap.core.IGeometry;
39 39
import com.iver.cit.gvsig.fmap.core.IGeometry3D;
40 40
import com.iver.cit.gvsig.fmap.core.ShapeFactory;
41
import com.vividsolutions.jts.io.WKBWriter;
41 42

  
42 43
class H2FeaturesWriter extends JDBCFeaturesWriter implements ISelectiveWriter {
43 44
	DBFeatureType featureType;
......
49 50
	private PreparedStatement insertSt;
50 51
	private PreparedStatement updateSt;
51 52

  
53
	private static WKBWriter wkbWriter = new WKBWriter();
52 54

  
55
	H2FeaturesWriter(){
56

  
57
	}
58

  
53 59
	public void init(IFeatureStore store) {
54
		Statement st;
55 60
		this.store = (H2Store)store;
56 61
		this.parameters=(H2StoreParameters)store.getParameters();
57 62

  
58 63
		this.featureType = (DBFeatureType)this.store.getDefaultFeatureType();
59 64
		conex = this.store.getConnection();
65
	}
66

  
67
	public void postProcess() throws OpenException, WriteException {
60 68
		try {
69
			conex.commit();
70
		} catch (SQLException e) {
71
			throw new WriteException(this.store.getName(),e);
72
		}
73
	}
74

  
75
	public void cancelActions() throws WriteException{
76
		try {
77
			conex.rollback();
78
		} catch (SQLException e) {
79
			throw new WriteException(this.store.getName(),e);
80
		}
81
	}
82

  
83
	public void preProcess() throws OpenException, InitializeWriterException {
84
		Statement st;
85

  
86

  
87
		try {
88
			conex.setAutoCommit(false);
61 89
			st = conex.createStatement();
62 90

  
63 91
			if (bCreateTable) {
......
67 95
				System.out.println("sqlCreate =" + sqlCreate);
68 96
				st.execute(sqlCreate);
69 97

  
70
				conex.commit();
98
//				conex.commit();
71 99
			}
72
			conex.setAutoCommit(false);
100

  
73 101
//			fieldManager = new JdbcFieldManager(((ConnectionJDBC)conex).getConnection(), lyrDef.getTableName());
74 102

  
75 103
		} catch (SQLException e) {
......
77 105
//			throw new InitializeWriterException(getName(),e);
78 106
		}
79 107

  
108
//        ResultSet rsAux;
109
//		try {
110
////				conex.setAutoCommit(false);
111
////			alterTable();
112
//
113
////			rsAux = st.executeQuery("SHOW server_encoding;");
114
////	        rsAux.next();
115
////	        String serverEncoding = rsAux.getString(1);
116
////	        System.out.println("Server encoding = " + serverEncoding);
117
//	        // st.execute("SET CLIENT_ENCODING TO 'UNICODE';");
118
//	        // Intentamos convertir nuestras cadenas a ese encode.
119
////	        setEncoding(serverEncoding);
120
//		} catch (SQLException e) {
121
//			throw new InitializeWriterException("H2",e);
122
//		}
80 123
	}
81 124

  
82
	public void postProcess() throws OpenException, WriteException {
83
		try {
84
			conex.setAutoCommit(true);
85
		} catch (SQLException e) {
86
			throw new WriteException("H2",e);
87
		}
88
	}
89

  
90
	public void preProcess() throws OpenException, InitializeWriterException {
91
		// ATENTION: We will transform (in PostGIS class; doubleQuote())
92
        // to UTF-8 strings. Then, we tell the PostgreSQL server
93
        // that we will use UTF-8, and it can translate
94
        // to its charset
95
        // Note: we have to translate to UTF-8 because
96
        // the server cannot manage UTF-16
97

  
98
        ResultSet rsAux;
99
		try {
100
				conex.rollback();
101
//			alterTable();
102

  
103
//			rsAux = st.executeQuery("SHOW server_encoding;");
104
//	        rsAux.next();
105
//	        String serverEncoding = rsAux.getString(1);
106
//	        System.out.println("Server encoding = " + serverEncoding);
107
	        // st.execute("SET CLIENT_ENCODING TO 'UNICODE';");
108
	        // Intentamos convertir nuestras cadenas a ese encode.
109
//	        setEncoding(serverEncoding);
110
		} catch (SQLException e) {
111
			throw new InitializeWriterException("H2",e);
112
		}
113
	}
114

  
115 125
	public void deleteFeature(IFeature feature) throws WriteException {
116 126
		Statement st;
117 127
		String sqlDelete = getSqlDeleteFeature(featureType, feature);
......
120 130
			st = this.conex.createStatement();
121 131
			st.execute(sqlDelete);
122 132
		} catch (SQLException e) {
123
			throw new WriteException("H2",e);
133
			throw new WriteException(this.store.getName(),e);
124 134
		}
125 135

  
126 136
	}
......
140 150
					continue;
141 151

  
142 152

  
143
				H2Utils.loadValueInPreparedStatement(ps, index, fad, feature);
153
				loadValueInPreparedStatement(ps, index, fad, feature);
144 154
				index++;
145 155
			}
146 156
//			ps.setObject(index, feature.get(ftype.getFieldIdIndex()));
......
148 158
			ps.execute();
149 159

  
150 160
		} catch (SQLException e) {
151
			throw new WriteException("H2",e);
161
			throw new WriteException(this.store.getName(),e);
152 162
		}
153 163
	}
154 164

  
......
187 197
		this.featureType=(DBFeatureType)featureType;
188 198
	}
189 199

  
190
	protected WritableByteChannel getWriteChannel(String path) throws IOException {
191
		WritableByteChannel channel;
192

  
193
		File f = new File(path);
194

  
195
		if (!f.exists()) {
196
//			System.out.println("Creando fichero " + f.getAbsolutePath());
197

  
198
			if (!f.createNewFile()) {
199
				System.err.print("Error al crear el fichero "
200
						+ f.getAbsolutePath());
201
				throw new IOException("Cannot create file " + f);
202
			}
203
		}
204

  
205
		RandomAccessFile raf = new RandomAccessFile(f, "rw");
206
		channel = raf.getChannel();
207

  
208
		return channel;
209
	}
210

  
211 200
	/**
212 201
	 * @param createTable
213 202
	 *            The bCreateTable to set.
......
215 204
	public void setCreateTable(boolean createTable) {
216 205
		bCreateTable = createTable;
217 206
	}
207

  
218 208
	boolean dropTableIfExist() throws SQLException{
219 209
		if (!this.existTable(parameters.getSchema(), parameters.getTableName())){
220 210
			return false;
......
249 239
				JDBCAttributeDescriptor fad=(JDBCAttributeDescriptor)it.next();
250 240
				if (fad.isPrimaryKey())
251 241
					continue;
252
				H2Utils.loadValueInPreparedStatement(ps, index, fad, feature);
242
				loadValueInPreparedStatement(ps, index, fad, feature);
253 243
				index++;
254 244
			}
255 245

  
256
			H2Utils.loadPkInPreparedStatement(ps, index, ftype, feature);
246
			loadPkInPreparedStatement(ps, index, ftype, feature);
257 247

  
258 248
			ps.execute();
259 249

  
260 250
		} catch (SQLException e) {
261
			throw new WriteException("H2",e);
251
			throw new WriteException(this.store.getName(),e);
262 252
		}
263 253
	}
264 254

  
......
269 259
				+ attribute.getName() + ";";
270 260
			st.execute(sql);
271 261
		} catch (SQLException e) {
272
			throw new WriteException("H2",e);
262
			throw new WriteException(this.store.getName(),e);
273 263
		}
274 264
	}
275 265

  
......
280 270
			+ oldAttribute.getName() + " TO " + attribute.getName() + ";";
281 271
			st.execute(sql);
282 272
		} catch (SQLException e) {
283
			throw new WriteException("H2",e);
273
			throw new WriteException(this.store.getName(),e);
284 274
		}
285 275
	}
286 276

  
......
299 289
				+ ";";
300 290
			st.execute(sql);
301 291
		} catch (SQLException e) {
302
			throw new WriteException("H2",e);
292
			throw new WriteException(this.store.getName(),e);
303 293
		}
304 294
	}
305 295

  
......
337 327
		return resul;
338 328
	}
339 329

  
340
	public void setEncoding(String toEncode){
341
		if (toEncode.compareToIgnoreCase("SQL_ASCII") == 0){
342
		   this.toEncode = "ASCII";
343
		  } else {
344
			  this.toEncode = toEncode;
345
		  }
346
	}
347
	public String getEncoding() {
348
		return toEncode;
349
	}
350 330
	public boolean canWriteGeometry(int gvSIGgeometryType) {
351 331
		switch (gvSIGgeometryType) {
352 332
		case FShape.POINT:
......
367 347
		return false;
368 348
	}
369 349

  
370
	public boolean canWriteAttribute(int sqlType) {
371
		switch (sqlType) {
372
		case Types.DOUBLE:
373
		case Types.FLOAT:
374
		case Types.INTEGER:
375
		case Types.BIGINT:
376
			return true;
377
		case Types.DATE:
378
			return true;
379
		case Types.BIT:
380
		case Types.BOOLEAN:
381
			return true;
382
		case Types.VARCHAR:
383
		case Types.CHAR:
384
		case Types.LONGVARCHAR:
385
			return true;
386 350

  
387
		}
388

  
389
		return false;
390
	}
391
	public String getSqlInsertFeature(DBFeatureType dbFeatureType,
392
			IFeature feat) {
393
		StringBuffer sqlBuf = new StringBuffer("INSERT INTO "
394
				+ this.parameters.tableID() + " (");
395
		String sql = null;
396
		int numAlphanumericFields = dbFeatureType.size();
397

  
398
		for (int i = 0; i < numAlphanumericFields; i++) {
399
			IFeatureAttributeDescriptor fad=(IFeatureAttributeDescriptor)dbFeatureType.get(i);
400
			String name = fad.getName();
401
			// if (cols.contains(name) && (!name.equals(uniqueCol) ||
402
			// existsUnique)) {
403
			if (name.equals(dbFeatureType.getFieldId()))
404
				continue;
405
			sqlBuf.append(" " + name + ",");
406
			// }
407
		}
408
		sqlBuf.append(" " + dbFeatureType.getDefaultGeometry());
409
		// sqlBuf.deleteCharAt(sqlBuf.lastIndexOf(","));
410
		sqlBuf.append(" ) VALUES (");
411
		String insertQueryHead = sqlBuf.toString();
412
		sqlBuf = new StringBuffer(insertQueryHead);
413
		for (int j = 0; j < numAlphanumericFields; j++) {
414
			IFeatureAttributeDescriptor fad=(IFeatureAttributeDescriptor)dbFeatureType.get(j);
415

  
416
			String name = fad.getName();
417
			if (name.equals(dbFeatureType.getFieldId()))
418
				continue;
419

  
420
			if (isNumeric(feat.get(j)))
421
				sqlBuf.append(feat.get(j).toString() + ", ");
422
			else
423
				sqlBuf.append(addQuotes(feat.get(j)) + ", ");
424
		}
425
		IGeometry geometry=(IGeometry)feat.getDefaultGeometry();
426
		int type=dbFeatureType.getGeometryTypes()[0];
427
		if (geometry.getGeometryType()!=type){
428
			if (type==FShape.POLYGON){
429
				geometry=ShapeFactory.createPolygon2D(new GeneralPathX(geometry.getInternalShape()));
430
			}else if (type==FShape.LINE){
431
				geometry=ShapeFactory.createPolyline2D(new GeneralPathX(geometry.getInternalShape()));
432
			}else if (type==(FShape.POLYGON|FShape.Z)){
433
				geometry=ShapeFactory.createPolygon3D(new GeneralPathX(geometry.getInternalShape()),((IGeometry3D)geometry).getZs());
434
			}else if (type==(FShape.LINE|FShape.Z)){
435
				geometry=ShapeFactory.createPolyline3D(new GeneralPathX(geometry.getInternalShape()),((IGeometry3D)geometry).getZs());
436
			}
437
		}
438
		sqlBuf.append(" GeometryFromText( '"
439
				+ geometry.toJTSGeometry().toText() + "', "
440
				+ removePrefix(dbFeatureType.getDefaultSRS()) + ")");
441

  
442
		// sqlBuf.deleteCharAt(sqlBuf.lastIndexOf(","));
443
		sqlBuf.append(" ) ");
444
		sql = sqlBuf.toString();
445
		return sql;
446
	}
447
	public boolean isNumeric(Object obj) {
448

  
449
		if (obj instanceof Number){
450
			return true;
451
		}
452
		return false;
453
	}
454
	protected String addQuotes(Object value) {
455
		String retString;
456

  
457
		if (value != null) {
458
			retString = "'" + doubleQuote(value) + "'";
459

  
460
		} else {
461
			retString = "null";
462
		}
463

  
464
		return retString;
465
	}
466
	private String doubleQuote(Object obj) {
467
		String aux = obj.toString().replaceAll("'", "''");
468
		StringBuffer strBuf = new StringBuffer(aux);
469
		ByteArrayOutputStream out = new ByteArrayOutputStream(strBuf.length());
470
		PrintStream printStream = new PrintStream(out);
471
		printStream.print(aux);
472
		String aux2 = "ERROR";
473
		try {
474
			aux2 = out.toString(toEncode);
475
			System.out.println(aux + " " + aux2);
476
		} catch (UnsupportedEncodingException e) {
477
			// TODO Auto-generated catch block
478
			e.printStackTrace();
479
		}
480

  
481
		return aux2;
482
	}
483
	public static String removePrefix(String str) {
484

  
485
		int colon_ind = str.indexOf(":");
486
		if (colon_ind != -1) {
487
			return str.substring(colon_ind + 1);
488
		} else {
489
			return str;
490
		}
491
	}
492

  
493 351
	private PreparedStatement getUpdateFeatureStatement(DBFeatureType dbFeatureType) throws SQLException{
494 352
		if (this.updateSt == null){
495 353
			StringBuffer sqlBuf = new StringBuffer("UPDATE "
......
508 366
			}
509 367
			sqlBuf.deleteCharAt(sqlBuf.lastIndexOf(","));
510 368
			sqlBuf.append(" WHERE ");
511
			sqlBuf.append(H2Utils.getFliterForIDForPStatement(dbFeatureType));
369
			sqlBuf.append(getFliterForIDForPStatement(dbFeatureType));
512 370
			sql = sqlBuf.toString();
513 371

  
514 372

  
......
524 382
		StringBuffer sqlBuf = new StringBuffer("DELETE FROM "
525 383
				+ this.parameters.tableID() + " WHERE ");
526 384
		String sql = null;
527
		sqlBuf.append(H2Utils.getFliterForID(dbFeatureType, feature));
385
		sqlBuf.append(H2Utils.getFilterForID(dbFeatureType, feature));
528 386
		sql = sqlBuf.toString();
529 387

  
530 388
		return sql;
......
583 441
			st.close();
584 442
		}
585 443
		catch(SQLException except){
586
			throw new InitializeWriterException("H2 Feature Writer",except);
444
			throw new InitializeWriterException(parameters.getDataStoreName(),except);
587 445

  
588 446
		}
589 447
	}
448

  
449
	protected void loadPkInPreparedStatement(PreparedStatement ps,int paramIndex,DBFeatureType fType,IFeature feature) throws java.sql.SQLException{
450
		if (fType.getFieldsId().length != 1)
451
			throw new UnsupportedOperationException("ID fields > 1");
452
		String id =fType.getFieldsId()[0];
453
		loadValueInPreparedStatement(ps, paramIndex, (JDBCAttributeDescriptor)fType.get(fType.getFieldIndex(id)), feature);
454
	}
455

  
456
	protected void loadValueInPreparedStatement(PreparedStatement ps,int paramIndex,JDBCAttributeDescriptor attr,IFeature feature) throws java.sql.SQLException{
457
		Object value = feature.get(attr.ordinal());
458
		if (value == null){
459
			ps.setNull(paramIndex, attr.getSqlType());
460
			return;
461
		}
462

  
463
		if (attr.getDataType() == IFeatureAttributeDescriptor.TYPE_GEOMETRY){
464
			IGeometry geom =(IGeometry)feature.get(attr.ordinal());
465
			ps.setBytes(
466
				paramIndex,	wkbWriter.write(geom.toJTSGeometry())
467
			);
468
			return;
469
		}
470
		ps.setObject(paramIndex, feature.get(attr.ordinal()));
471
	}
472

  
473
	protected static String getFliterForIDForPStatement(DBFeatureType fType) {
474
		if (fType.getFieldsId().length != 1)
475
			throw new UnsupportedOperationException("ID fields > 1");
476
		String id =fType.getFieldsId()[0];
477
		return id + " = ?";
478
	}
590 479
}

Also available in: Unified diff