Revision 22037

View differences:

branches/Mobile_Compatible_Hito_1/libFMap_mobile_shp_driver/src-file/org/gvsig/data/datastores/vectorial/file/FalseByteBuffer.java
1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 Prodevelop and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *   Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *   +34 963862235
28
 *   gvsig@gva.es
29
 *   http://www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   Prodevelop Integraci?n de Tecnolog?as SL
34
 *   Conde Salvatierra de ?lava , 34-10
35
 *   46004 Valencia
36
 *   Spain
37
 *
38
 *   +34 963 510 612
39
 *   +34 963 510 968
40
 *   gis@prodevelop.es
41
 *   http://www.prodevelop.es
42
 *
43
 *    or
44
 *
45
 *   Instituto de Rob?tica
46
 *   Apartado de correos 2085
47
 *   46071 Valencia
48
 *   (Spain)
49
 *   
50
 *   +34 963 543 577
51
 *   jjordan@robotica.uv.es
52
 *   http://robotica.uv.es
53
 *   
54
 */
55

  
56
package org.gvsig.data.datastores.vectorial.file;
57

  
58
import java.nio.ByteOrder;
59

  
60
/**
61
 * This class replaces the byte buffer used in J2SE to store a file in memory.
62
 * 
63
 * @see java.nio.ByteOrder
64
 * 
65
 * @author jldominguez
66
 *
67
 */
68
public class FalseByteBuffer {
69
	
70
	private byte[] bytes;
71
	private ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN;
72
	private int pos = 0;
73
	
74
	/**
75
	 * Constructor
76
	 * @param bb array of bytes to be stored
77
	 */
78
	public FalseByteBuffer(byte[] bb) {
79
		bytes = bb;
80
	}
81
	
82
	/**
83
	 * Moves file cursor to position p 
84
	 * @param p the new position
85
	 */
86
	public void position(int p) {
87
		pos = p;
88
	}
89
	
90
	/**
91
	 * 
92
	 * @return current cursor position
93
	 */
94
	public int getPosition() {
95
		return pos;
96
	}
97
	
98
	/**
99
	 * @return byte pointed by cursor then increases cursor
100
	 */
101
	public byte getByte() {
102
		byte resp = bytes[pos];
103
		pos++;
104
		return resp;
105
	}
106
	
107
	/**
108
	 * Gets one byte
109
	 * @param ind index of the byte of interest 
110
	 * @return the byte of interest
111
	 */
112
	public byte getByte(int ind) {
113
		return bytes[ind];
114
	}
115

  
116
	/**
117
	 * @return integer pointed by cursor then increases cursor
118
	 */
119
	public int getInt() {
120
		int resp = getInt(bytes, pos);
121
		pos = pos + 4;
122
		return resp;
123
	}
124
	
125
	/**
126
	 * @return short pointed by cursor then increases cursor
127
	 */
128
	public short getShort() {
129
		short resp = getShort(bytes, pos);
130
		pos = pos + 2;
131
		return resp;
132
	}
133
	
134
	/**
135
	 * Gets the integer at a certain position
136
	 * @param index the index of interest
137
	 * @return the integer at a certain position
138
	 */
139
	public int getInt(int index) {
140
		int resp = getInt(bytes, index);
141
		return resp;
142
	}
143
	
144
	/**
145
	 * Gets some bytes.
146
	 * @param out the array of bytes to be filled
147
	 */
148
	public void getBytes(byte[] out) {
149
		for (int i=0; i<out.length; i++) {
150
			out[i] = getByte(pos + i);
151
		}
152
		pos = pos + out.length;
153
	}
154
	
155
	/**
156
	 * @return double pointed by cursor then increases cursor
157
	 */
158
	public double getDouble() {
159
		double resp = getDouble(bytes, pos);
160
		pos = pos + 8;
161
		return resp;
162
	}
163
	
164
	private int getInt(final byte[] data, final int offset) {
165
        return (int) getNumber(data, offset, 4);
166
    }
167
	
168

  
169
	private short getShort(final byte[] data, final int offset) {
170
        return (short) getNumber(data, offset, 2);
171
    }
172

  
173
	
174
	private long getNumber(final byte[] data, final int offset, final int size) {
175
        long result = 0;
176
        
177
        if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
178
        	
179
            for (int j = offset + size - 1; j >= offset; j--) {
180
                result <<= 8;
181
                result |= 0xff & data[j];
182
            }
183
            
184
        } else {
185

  
186
            for (int j = offset; j <= offset + size - 1; j++) {
187
                result <<= 8;
188
                result |= 0xff & data[j];
189
            }
190

  
191
        }
192

  
193
        return result;
194
    }
195
	
196
	private double getDouble(final byte[] data, final int offset) {
197
        return Double.longBitsToDouble(getNumber(data, offset, 8));
198
    }
199

  
200
	/**
201
	 * Sets byte order (big endian, little endian)
202
	 * @param o byte order (big endian, little endian)
203
	 */
204
	public void setByteOrder(ByteOrder o) {
205
		byteOrder = o;
206
	}
207

  
208

  
209

  
210
}
branches/Mobile_Compatible_Hito_1/libFMap_mobile_shp_driver/src-file/org/gvsig/data/datastores/vectorial/file/ResourceReader.java
1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 Prodevelop and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *   Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *   +34 963862235
28
 *   gvsig@gva.es
29
 *   http://www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   Prodevelop Integraci?n de Tecnolog?as SL
34
 *   Conde Salvatierra de ?lava , 34-10
35
 *   46004 Valencia
36
 *   Spain
37
 *
38
 *   +34 963 510 612
39
 *   +34 963 510 968
40
 *   gis@prodevelop.es
41
 *   http://www.prodevelop.es
42
 *
43
 *    or
44
 *
45
 *   Instituto de Rob?tica
46
 *   Apartado de correos 2085
47
 *   46071 Valencia
48
 *   (Spain)
49
 *   
50
 *   +34 963 543 577
51
 *   jjordan@robotica.uv.es
52
 *   http://robotica.uv.es
53
 *   
54
 */
55

  
56
package org.gvsig.data.datastores.vectorial.file;
57

  
58
import java.awt.Container;
59
import java.awt.Image;
60
import java.awt.MediaTracker;
61
import java.awt.Toolkit;
62
import java.io.File;
63

  
64
import org.apache.log4j.Logger;
65

  
66
/**
67
 * Utility class to read resource files.
68
 * 
69
 * @see java.awt.MediaTracker
70
 * 
71
 * @author jldominguez
72
 *
73
 */
74
public class ResourceReader {
75
	
76
	private static final String WORKSPACE = "D:/PROYECTOS/Filtros2/libFMap_data_shape";
77
	
78
	private static Logger logger = Logger.getLogger(ResourceReader.class);
79
	private static String resourceDir = "";
80
	
81
	private static int IMAGE_LOAD_TIMEOUT = 1200;
82
	
83
	/**
84
	 * Icon shown while the app is processing.
85
	 */
86
	public static Image PROCESSING_ICON;
87
	/**
88
	 * Array of GPS icons (16 positions)
89
	 */
90
	public static Image[] GPS_CURSOR_ICON;
91
	/**
92
	 * number of positions of the GPS cursor
93
	 */
94
	public static int GPS_CURSOR_ICON_COUNT = 16;
95
	
96
	public static int PROCESS_ICON_X = 90;
97
	public static int PROCESS_ICON_Y = 105; //110;
98
	public static int PROCESS_ICON_SIZE = 60;
99
	
100
	/**
101
	 * Used to read images
102
	 */
103
	public static MediaTracker mt = new MediaTracker(new Container());
104
	public static int imageCount = 0;
105

  
106
	static {
107
		
108
		String base = System.getProperty("java.class.path");
109
		
110
		int ind = base.indexOf(File.pathSeparator);
111
		if (ind != -1) base = base.substring(0, ind);
112
		ind = base.lastIndexOf(File.separator);
113
		base = base.substring(0, ind);
114
		//logger.debug("Base directory: " + base);
115
		ind = base.lastIndexOf(File.separator);
116
		resourceDir = base.substring(0, ind) + File.separator + "resources";
117
		PROCESSING_ICON = getResourceImage("img", "processing.png");
118
		
119
		GPS_CURSOR_ICON = new Image[GPS_CURSOR_ICON_COUNT];
120
		for (int i=0; i<GPS_CURSOR_ICON_COUNT; i++) {
121
			try {
122
				GPS_CURSOR_ICON[i] = getResourceImage("img", "gps_cursor_" + i + ".png");
123
			} catch (Exception ex) {
124
				logger.error("Unable to read GPS icon # " + i + " : " + ex.getMessage());
125
			}
126
		}
127
	}
128
	
129
	/**
130
	 * Gets the GPS icon index  for a given angle
131
	 * @param angle heading 
132
	 * @param in_radians whether it is radians or degrees
133
	 * @return the GPS icon index
134
	 */
135
	public static int getGpsIconIndexForAngle(double angle, boolean in_radians) {
136
		
137
		double a_in_degrees = (in_radians) ? (angle * 180.0 / Math.PI) : angle;
138
		
139
		double step = 360.0 / GPS_CURSOR_ICON_COUNT;
140
		
141
		if (Math.abs(a_in_degrees) > 1000) {
142
			logger.error("Absurd angle: " + angle + "; in_radians = " + in_radians);
143
			logger.error("Returned North icon (0)");
144
			return 0;
145
		}
146
		
147
		// normalize
148
		while (step >= 360) step = step - 360.0;
149
		while (step < 0) step = step + 360.0;
150

  
151
		int n = Math.round((float) Math.floor(0.5 + a_in_degrees / step));
152
		
153
		if ((n < 0) || (n >= GPS_CURSOR_ICON_COUNT)) {
154
			logger.error("Bad n = " + n + "; GPS_CURSOR_ICON_COUNT = " + GPS_CURSOR_ICON_COUNT);
155
			logger.error("Forced n = n MOD GPS_CURSOR_ICON_COUNT");
156
			n = n % GPS_CURSOR_ICON_COUNT;
157
		}
158

  
159
		logger.debug("-------------- GPS icon index for icon: -----------------");
160
		logger.debug("angle = " + angle + "; radians = " + in_radians);
161
		logger.debug("returned: " + n);
162
		return n;
163
	}
164
	
165
	/**
166
	 * Gets an image from the resources folder 
167
	 * @param dir the resources subfolder
168
	 * @param file_name the file name
169
	 * @return the image from the resources folder
170
	 */
171
	public static Image getResourceImage(String dir, String file_name) {
172
		String imgPath = resourceDir + File.separator + dir + File.separator + file_name;
173
		Image img = Toolkit.getDefaultToolkit().createImage(imgPath);
174
		mt.addImage(img,imageCount);
175
		try{
176
			mt.waitForID(imageCount, IMAGE_LOAD_TIMEOUT);
177
			mt.removeImage(img);
178
			return img;
179
		} catch (InterruptedException e) {
180
			logger.error("While downloading: " + e.getMessage());
181
			return null;
182
		}
183
		
184
	}
185
	
186
	/**
187
	 * Gets an image from an array of bytes for a well known format (png, jpg, gif)
188
	 * @param data the byte array 
189
	 * @return the image
190
	 */
191
	public static Image getImage(byte[] data) {
192
		Image img = Toolkit.getDefaultToolkit().createImage(data);
193
		mt.addImage(img,imageCount);
194
		try {
195
			mt.waitForID(imageCount, IMAGE_LOAD_TIMEOUT);
196
			mt.removeImage(img);
197
			return img;
198
		} catch (InterruptedException e) {
199
			logger.error("While downloading: " + e.getMessage());
200
			return null;
201
		}
202
	}
203

  
204
	/**
205
	 * Gets scaled version of image with Media Tracker.
206
	 * 
207
	 * @param img source image
208
	 * @param newwidth new width
209
	 * @param newheight new height
210
	 * @return re sampled image
211
	 */
212
	public static Image getScaled(Image img, int newwidth, int newheight) {
213
		
214
		Image newimage = img.getScaledInstance(newwidth, newheight, Image.SCALE_FAST);
215
		mt.addImage(newimage, imageCount);
216
		try {
217
			mt.waitForID(imageCount, IMAGE_LOAD_TIMEOUT);
218
			mt.removeImage(newimage);
219
			return newimage;
220
		} catch (InterruptedException e) {
221
			logger.error("While resampling: " + e.getMessage());
222
			return null;
223
		}
224
	}
225
	
226
	/**
227
	 * Gets an image from a file in a well known format (png, jpg, gif)
228
	 * @param data the image file 
229
	 * @return the image object
230
	 */
231
	public static Image getImage(File data) {
232
		try {
233
			logger.debug("Getting image with Media Tracker: " + data.getAbsolutePath());
234
			logger.debug("Getting image with Media Tracker, imagecount = " + imageCount);
235
			Image img = Toolkit.getDefaultToolkit().createImage(data.getAbsolutePath());
236
			mt.addImage(img, imageCount);
237
			mt.waitForID(imageCount, IMAGE_LOAD_TIMEOUT);
238
			mt.removeImage(img);
239

  
240
			return img;
241
		} catch (Throwable th) {
242
			logger.error("While getting downloaded image: " + th.getMessage());
243
			return null;
244
		}
245
	}
246

  
247
	/**
248
	 * gets a file from the working directory
249
	 * @param dir subfolder
250
	 * @param file_name file name
251
	 * @return the file object
252
	 */
253
	public static File getWorkingDirFile(String dir, String file_name) {
254
		File resp = new File(
255
				WORKSPACE
256
				+ File.separator
257
				+ dir
258
				+ File.separator
259
				+ file_name);
260
		return resp;
261
	}
262
	
263
	/**
264
	 * Gets the working subfolder
265
	 * @param dir subfolder name
266
	 * @return the working subfolder
267
	 */
268
	public static File getWorkingDir(String dir) {
269
		File resp = new File(
270
				WORKSPACE
271
				+ File.separator
272
				+ dir);
273
		return resp;
274
	}
275
	
276
	/**
277
	 * Gets a file from the resource folder 
278
	 * @param dir
279
	 * @param file_name
280
	 * @return the file object
281
	 */
282
	public static File getResourceFile(String dir, String file_name) {
283
		String filePath = resourceDir + File.separator + dir + File.separator + file_name;
284
		File resp = new File(filePath);
285
		return resp;
286
	}
287
	
288
	/**
289
	 * Gets a file from the pda sd card folder 
290
	 * @param dir
291
	 * @param file_name
292
	 * @return the file object
293
	 */
294
	public static File getPdaTestFile(String sdfolder, String dir, String file_name) {
295
		String filePath = File.separator + sdfolder + File.separator + dir + File.separator + file_name;
296
		File resp = new File(filePath);
297
		return resp;
298
	}
299
	
300
	
301
	/**
302
	 * gets a subfolder from the resources folder
303
	 * @param dir the subfolder name
304
	 * @return the file object
305
	 */
306
	public static File getResourceFolder(String dir) {
307
		String filePath = resourceDir + File.separator + dir;
308
		File resp = new File(filePath);
309
		return resp;
310
	}
311
}
branches/Mobile_Compatible_Hito_1/libFMap_mobile_shp_driver/src-file/org/gvsig/data/datastores/vectorial/file/Utils.java
1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 Prodevelop and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *   Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *   +34 963862235
28
 *   gvsig@gva.es
29
 *   http://www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   Prodevelop Integraci?n de Tecnolog?as SL
34
 *   Conde Salvatierra de ?lava , 34-10
35
 *   46004 Valencia
36
 *   Spain
37
 *
38
 *   +34 963 510 612
39
 *   +34 963 510 968
40
 *   gis@prodevelop.es
41
 *   http://www.prodevelop.es
42
 *
43
 *    or
44
 *
45
 *   Instituto de Rob?tica
46
 *   Apartado de correos 2085
47
 *   46071 Valencia
48
 *   (Spain)
49
 *   
50
 *   +34 963 543 577
51
 *   jjordan@robotica.uv.es
52
 *   http://robotica.uv.es
53
 *   
54
 */
55

  
56
package org.gvsig.data.datastores.vectorial.file;
57

  
58
import java.awt.Color;
59
import java.awt.Component;
60
import java.awt.Font;
61
import java.awt.GraphicsConfiguration;
62
import java.awt.GraphicsDevice;
63
import java.awt.GraphicsEnvironment;
64
import java.awt.Image;
65
import java.awt.event.MouseEvent;
66
import java.awt.geom.AffineTransform;
67
import java.awt.geom.Rectangle2D;
68
import java.awt.image.BufferedImage;
69
import java.io.BufferedReader;
70
import java.io.File;
71
import java.io.FileInputStream;
72
import java.io.FileOutputStream;
73
import java.io.FileReader;
74
import java.io.IOException;
75
import java.io.InputStream;
76
import java.text.DecimalFormat;
77
import java.text.DecimalFormatSymbols;
78
import java.text.ParseException;
79
import java.text.SimpleDateFormat;
80
import java.util.ArrayList;
81
import java.util.Date;
82

  
83
import org.apache.log4j.Logger;
84

  
85

  
86
/**
87
 * Utility static methods.
88
 * 
89
 * @see es.prodevelop.gvsig.mobile.fmap.util.bytebuffer.FalseByteBuffer
90
 * 
91
 * @author jcarras
92
 * @author jldominguez
93
 *
94
 */
95
public class Utils {
96

  
97
	/**
98
	 * Whether the PDA is being used (false when running a PC)
99
	 */
100
	public static boolean USING_PDA = false;
101
	static {
102
		if (System.getProperty("os.name").equalsIgnoreCase("WINDOWS CE"))
103
			USING_PDA = true;
104
	}
105
	
106
	/**
107
	 * Utility methos to force the execution of the static section
108
	 *
109
	 */
110
	public static void touch() { }
111

  
112
	private static Logger logger = Logger.getLogger(Utils.class);
113

  
114
	public final static String jpeg = "jpeg";
115

  
116
	public final static String jpg = "jpg";
117

  
118
	public final static String gif = "gif";
119

  
120
	public final static String tiff = "tiff";
121

  
122
	public final static String tif = "tif";
123

  
124
	public final static String png = "png";
125

  
126
	public static final String DATE_FORMAT = "yyyy/MM/dd hh:mm";
127
	public static final String CACHED_FILES_EXT = ".cac";
128

  
129
	public static final AffineTransform IDENTITY_AT = AffineTransform
130
			.getTranslateInstance(0, 0);
131
	
132
	public static final Font TILE_PROBLEM_FONT = new Font("Dialog", 3, 12);
133
	public static final String TILE_PROBLEM_MSG_403 = "403 Forbidden";
134
	public static final String TILE_PROBLEM_MSG_ERROR = "Error";
135
	public static final String TILE_PROBLEM_MSG_NODATA = "No data";
136
	public static final Color TILE_PROBLEM_403_COLOR = Color.RED;
137
	public static final Color TILE_PROBLEM_COLOR = Color.GRAY;
138
	public static final int TILE_PROBLEM_X_OFFSET = 10;
139
	public static final int TILE_PROBLEM_Y_OFFSET = 21;
140
	
141
	
142

  
143
	/**
144
	 * Get the extension of a file.
145
	 */
146
	public static String getExtension(File f) {
147
		String ext = null;
148
		String s = f.getName();
149
		int i = s.lastIndexOf('.');
150
		if (i > 0 && i < s.length() - 1) {
151
			ext = s.substring(i + 1).toLowerCase();
152
		}
153
		return ext;
154
	}
155

  
156
	/**
157
	 * Returns an ImageIcon, or null if the path was invalid.
158
	 */
159
	protected static Image createImageIcon(String path) {
160
		return java.awt.Toolkit.getDefaultToolkit().createImage(path);
161
		/*
162
		 * java.net.URL imgURL = Utils.class.getResource(path); if (imgURL !=
163
		 * null) { return new ImageIcon(imgURL); } else {
164
		 * System.err.println("Couldn't find file: " + path); return null; }
165
		 */
166
	}
167

  
168

  
169
	/**
170
	 * Loads a file into a byte buffer
171
	 * 
172
	 * @param in input stream
173
	 * @param size file size
174
	 * @return a byte buffer
175
	 * @throws IOException
176
	 */
177
	public static FalseByteBuffer loadFileInputStream(FileInputStream in,
178
			int size) throws IOException {
179

  
180
		byte[] resp = null;
181
		try {
182
			resp = getFileBytes(in, size, 10000);
183
		} catch (Throwable thr) {
184
			logger.error("Did not load file (size = " + size + ")");
185
			throw new IOException("Not enough memory (?). Message: "
186
					+ thr.getMessage());
187
		}
188
		in.close();
189
		return new FalseByteBuffer(resp);
190
	}
191

  
192
	/**
193
	 * 
194
	 * @return current time as a string  
195
	 */
196
	public static String time() {
197
		return System.currentTimeMillis() + " - ";
198
	}
199

  
200
	private static byte[] getFileBytes(FileInputStream in, int size,
201
			int BUFFER_SIZE) throws IOException {
202

  
203
		int all_bytes_ind = 0;
204

  
205
		byte[] all_bytes = new byte[size];
206
		byte[] buffer = new byte[BUFFER_SIZE];
207
		int read;
208
		while ((read = in.read(buffer)) != -1) {
209
			System.arraycopy(buffer, 0, all_bytes, all_bytes_ind, read);
210
			all_bytes_ind = all_bytes_ind + read;
211
		}
212
		return all_bytes;
213
	}
214

  
215
	/**
216
	 * Returns whether these rectangles intersect (this was necessary because the original
217
	 * metod behaves in a strabge way)
218
	 * 
219
	 * @param r_1 
220
	 * @param r_2
221
	 * @return whether these rectangles intersect
222
	 */
223
	public static boolean rectanglesItersect(Rectangle2D r_1, Rectangle2D r_2) {
224

  
225
		if ((r_1 == null) || (r_2 == null))
226
			return false;
227
		if (r_1.getMinX() >= r_2.getMaxX())
228
			return false;
229
		if (r_2.getMinX() >= r_1.getMaxX())
230
			return false;
231
		if (r_1.getMinY() >= r_2.getMaxY())
232
			return false;
233
		if (r_2.getMinY() >= r_1.getMaxY())
234
			return false;
235
		return true;
236
	}
237
	
238
	private static ArrayList replacePixels(BufferedImage img, int x_offset,
239
			int y_offset, int w, int h, ArrayList previous) {
240

  
241
		ArrayList resp = new ArrayList();
242

  
243
		int[] new_col = new int[h];
244
		int[] new_row = new int[w];
245
		for (int i = 0; i < h; i++)
246
			new_col[i] = 0;
247
		for (int i = 0; i < w; i++)
248
			new_row[i] = 0;
249

  
250
		int[] top_row = img.getRGB(x_offset, y_offset, w, 1, null, 0, w);
251
		int[] bottom_row = img.getRGB(x_offset, y_offset + h, w, 1, null, 0, w);
252
		int[] right_col = img.getRGB(x_offset + w, y_offset, 1, h, null, 0, 1);
253
		int[] left_col = img.getRGB(x_offset, y_offset, 1, h, null, 0, 1);
254

  
255
		img.setRGB(x_offset, y_offset, w, 1, new_row, 0, w);
256
		img.setRGB(x_offset, y_offset + h, w, 1, new_row, 0, w);
257
		img.setRGB(x_offset + w, y_offset, 1, h, new_col, 0, 1);
258
		img.setRGB(x_offset, y_offset, 1, h, new_col, 0, 1);
259

  
260
		resp.add(top_row);
261
		resp.add(bottom_row);
262
		resp.add(right_col);
263
		resp.add(left_col);
264

  
265
		return null;
266

  
267
	}
268

  
269
	private static String getFormattedInteger(int n) {
270
		DecimalFormat df = new DecimalFormat();
271
		df.setGroupingUsed(true);
272
		df.setGroupingSize(3);
273
		DecimalFormatSymbols dfs = new DecimalFormatSymbols();
274
		dfs.setGroupingSeparator('.');
275
		df.setDecimalFormatSymbols(dfs);
276
		return df.format(n);
277
	}
278

  
279
	/**
280
	 * Gets a double as a formatted string
281
	 * 
282
	 * @param d value
283
	 * @param decimals number of decimal
284
	 * @return the formatted string 
285
	 */
286
	public static String getFormattedDouble(double d, int decimals) {
287
		
288
		if (false)  return "" + round(d, decimals);
289
		// /*
290
		DecimalFormat df = new DecimalFormat();
291
		df.setGroupingUsed(true);
292
		df.setGroupingSize(3);
293
		df.setMaximumFractionDigits(decimals);
294
		DecimalFormatSymbols dfs = new DecimalFormatSymbols();
295
		dfs.setGroupingSeparator(',');
296
		dfs.setDecimalSeparator('.');
297

  
298
		df.setDecimalFormatSymbols(dfs);
299
		return df.format(d);
300
		// */
301
	}
302

  
303

  
304

  
305

  
306
	/**
307
	 * Gets a scaled version of a given rectangle centered in the same point
308
	 * 
309
	 * @param r input rectangle
310
	 * @param d scale
311
	 * @return a scaled version of a given rectangle centered in the same point
312
	 */
313
	public static Rectangle2D getScaledCenteredRectangle(Rectangle2D r, double d) {
314
		double w = r.getWidth() * d;
315
		double h = r.getHeight() * d;
316
		double x = r.getCenterX() - 0.5 * w;
317
		double y = r.getCenterY() - 0.5 * h;
318
		Rectangle2D resp = new Rectangle2D.Double(x, y, w, h);
319
		return resp;
320
	}
321

  
322
	/**
323
	 * Performs  a product and returns the maximum
324
	 * 
325
	 */
326
	public static int smallerInteger(int a, double f, int minimum) {
327
		return Math.max(minimum, (int) Math.round(Math.floor(f * a)));
328
	}
329

  
330
	public static double smallerDouble(double a, double f, double minimum) {
331
		return Math.max(minimum, a * f);
332
	}
333

  
334
	/**
335
	 * Swap objects in a list
336
	 * @param _list input list 
337
	 * @param firstInd index
338
	 * @param secondInd index
339
	 */
340
	public static void swap(ArrayList _list, int firstInd, int secondInd) {
341
		Object temp = _list.get(firstInd);
342
		_list.set(firstInd, _list.get(secondInd));
343
		_list.set(secondInd, temp);
344
	}
345

  
346
	/**
347
	 * Reads the affine transform from a WLD file
348
	 * @param imageFile image file
349
	 * @param valid_ext valid extensions for WLD files
350
	 * @return the affine transform from a WLD file
351
	 */
352
	public static AffineTransform readWldFile(File imageFile, String[] valid_ext) {
353

  
354
		String img_file_str = imageFile.getAbsolutePath();
355
		int point_ind = img_file_str.lastIndexOf(".");
356
		File wldFile = null;
357

  
358
		String item = "";
359
		String new_str = "";
360

  
361
		for (int i = 0; i < valid_ext.length; i++) {
362
			item = valid_ext[i];
363
			new_str = img_file_str.substring(0, point_ind) + "." + item;
364
			wldFile = new File(new_str);
365
			if (wldFile.exists())
366
				return readWldFile(wldFile);
367
		}
368
		logger.error("World file not found, assumed identity transformation.");
369
		return Utils.IDENTITY_AT;
370
	}
371

  
372
	private static AffineTransform readWldFile(File wf) {
373

  
374
		AffineTransform resp = Utils.IDENTITY_AT;
375
		String item = "";
376
		double[] params = new double[6];
377

  
378
		try {
379
			FileReader fr = new FileReader(wf);
380
			BufferedReader br = new BufferedReader(fr);
381
			for (int i = 0; i < 6; i++) {
382
				item = br.readLine();
383
				params[i] = Double.parseDouble(item);
384
			}
385
			resp.setTransform(params[0], params[1], params[2], params[3],
386
					params[4], params[5]);
387

  
388
		} catch (Exception ex) {
389
			logger.error("While opening WLD file: " + ex.getMessage());
390
		}
391
		return resp;
392
	}
393

  
394
//	/**
395
//	 * Gets XML text description of booelan value
396
//	 * 
397
//	 * @param name element name
398
//	 * @param obj boolean value
399
//	 * @return the XML text description of booelan value
400
//	 */
401
//	public static StringBuffer toXML(String name, boolean obj) {
402
//		return toXML(name, new Boolean(obj));
403
//	}
404

  
405
//	/**
406
//	 * Gets XML text description of a int value
407
//	 * 
408
//	 * @param name element name
409
//	 * @param obj int value
410
//	 * @return the XML text description of a int value
411
//	 */
412
//	public static StringBuffer toXML(String name, int obj) {
413
//		return toXML(name, new Integer(obj));
414
//	}
415

  
416
//	/**
417
//	 * Gets XML text description of a double value
418
//	 * 
419
//	 * @param name element name
420
//	 * @param obj double value
421
//	 * @return the XML text description of a double value
422
//	 */
423
//	public static StringBuffer toXML(String name, double obj) {
424
//		return toXML(name, new Double(obj));
425
//	}
426

  
427
	
428
	/**
429
	 * gets the extent for a given rectangle and affine transform
430
	 * 
431
	 * @param at teh affinte transform
432
	 * @param iw image width
433
	 * @param ih image height
434
	 * @return the extent in map units
435
	 */
436
	public static Rectangle2D getExtent(AffineTransform at, int iw, int ih) {
437
		double x = at.getTranslateX();
438
		double _y = at.getTranslateY();
439
		double w = iw * at.getScaleX();
440
		double _h = ih * at.getScaleY();
441

  
442
		double y = Math.min(_y, _y + _h);
443
		double h = Math.abs(_h);
444

  
445
		return new Rectangle2D.Double(x, y, w, h);
446
	}
447

  
448
	private static GraphicsEnvironment _ge = GraphicsEnvironment
449
			.getLocalGraphicsEnvironment();
450

  
451
	private static GraphicsDevice _dev = _ge.getDefaultScreenDevice();
452

  
453
	/**
454
	 * Device-dependant graphics configuration object
455
	 */
456
	public static GraphicsConfiguration graphConfig = _dev
457
			.getDefaultConfiguration();
458

  
459
	/**
460
	 * Creates a buffered image
461
	 * @param w width
462
	 * @param h height
463
	 * @return a buffered image
464
	 */
465
	public static BufferedImage createBufferedImage(int w, int h) {
466
		return graphConfig.createCompatibleImage(w, h);
467
	}
468
	
469
	/**
470
	 * Creates a buffered image
471
	 * @param w width
472
	 * @param h height
473
	 * @param type the image type
474
	 * @return a buffered image
475
	 */
476
	public static BufferedImage createBufferedImage(int w, int h, int type) {
477
		return graphConfig.createCompatibleImage(w, h, type);
478
	}
479

  
480
	/**
481
	 * reads file into byte array
482
	 * @param f the file 
483
	 * @return a byte array with the same data
484
	 */
485
	public static byte[] readFileIntoByteArray(File f) {
486

  
487
		byte[] data = null;
488
		try {
489
			InputStream in = new FileInputStream(f);
490
			data = new byte[in.available()];
491
			in.read(data);
492
		} catch (IOException ex) {
493
			logger.error("While reading file " + f.getAbsolutePath() + " : "
494
					+ ex.getMessage());
495
			data = null;
496
		}
497
		return data;
498
	}
499

  
500
	/**
501
	 * @param projectPath
502
	 * @param absPath
503
	 * @return Path relative to find absPath from projectPath
504
	 */
505
	public static String relPath(String projectPath, String absPath) {
506
		String proj = projectPath;
507
		String breadCrumb = "";
508
		while (absPath.indexOf(proj) < 0) {
509
			int ind = proj.lastIndexOf(File.separator);
510
			if (ind < 0)
511
				return null; // Imposible to make relative
512
			proj = proj.substring(0, ind);
513
			breadCrumb += ".." + File.separator;
514
			// System.out.println(proj);
515
		}
516
		return breadCrumb
517
				+ absPath.substring(proj.length() + 1, absPath.length());
518
	}
519

  
520
	/**
521
	 * Finds out the index until which two strings are equal
522
	 * @param a
523
	 * @param b
524
	 * @return the index until which two strings are equal
525
	 */
526
	public int minCommon(String a, String b) {
527
		int i = 0;
528
		int min = a.length();
529
		if (b.length() < min)
530
			min = b.length();
531
		while (i < min && a.charAt(i) == b.charAt(i))
532
			i++;
533
		return i;
534
	}
535
	
536

  
537

  
538
	/**
539
	 * Writes byte array to file
540
	 * @param data 
541
	 * @param path file path
542
	 * @return whether the writing was successful
543
	 */
544
	public static boolean writeBytesToFile(byte[] data, String path) {
545
		try {
546
			//createWorkspaceFolder("screenshots");
547
			
548
			File f = new File(path);
549
			if (f.exists())
550
				f.delete();
551
			FileOutputStream fos = new FileOutputStream(f);
552
			fos.write(data);
553
			fos.flush();
554
			fos.close();
555
			return true;
556
		} catch (IOException ex) {
557
			logger.error("While writing data to file: " + ex.getMessage());
558
			return false;
559
		}
560
	}
561

  
562
	private static void writeCurrentTime(File f, long _t) {
563

  
564
		try {
565
			if (f.exists())
566
				f.delete();
567
			FileOutputStream fos = new FileOutputStream(f);
568
			String t = "" + _t;
569
			fos.write(t.getBytes());
570
			logger.debug("current time = " + t + " written to file");
571
			fos.flush();
572
			fos.close();
573
		} catch (IOException ex) {
574
			logger.error("While writing current time to log file: "
575
					+ ex.getMessage());
576
		}
577

  
578
	}
579

  
580
	private static long readLastExeLog(File f) {
581
		try {
582
			FileReader fr = new FileReader(f);
583
			BufferedReader br = new BufferedReader(fr);
584
			String item = br.readLine();
585
			logger.debug("first line in last exe log file: " + item);
586
			return Long.parseLong(item);
587
		} catch (Exception ex) {
588
			logger.error("While reading last exe log file: " + ex.getMessage());
589
			return 0;
590
		}
591
	}
592

  
593
	/**
594
	 * This method finds out if the application is already running. Used to prevent double 
595
	 * application instantiation
596
	 * @param path path of the exe log file
597
	 * @param currtime current time in miliseconds
598
	 * @return whether the application can be launched
599
	 */
600
	public static boolean executionAllowed(String path, long currtime) {
601

  
602
		logger.debug("currtime = " + currtime);
603

  
604
		File f = new File(path);
605
		if (!f.exists()) {
606
			logger.debug("last exe log file does not exist...");
607
			writeCurrentTime(f, currtime);
608
			logger.debug("execution allowed.");
609
			return true;
610
		}
611

  
612
		long last_exe = readLastExeLog(f);
613

  
614
		if ((currtime - last_exe) > LAST_EXECUTION_INTERVAL) {
615
			logger.debug("A long time since last exe.");
616
			writeCurrentTime(f, currtime);
617
			logger.debug("Execution allowed.");
618
			return true;
619
		} else {
620
			logger.debug("Short time since last exe, execution not allowed.");
621
			return false;
622
		}
623
	}
624

  
625
	/**
626
	 * Interval used to check if the application can be launched or not
627
	 */
628
	public static long LAST_EXECUTION_INTERVAL = 10000;
629
	
630
	/**
631
	 * Gets string representation of a date
632
	 * @param date
633
	 * @return string representation of a date
634
	 */
635
	public static String dateToString(Date date){
636
		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
637
		String res =format.format(date); 
638
		return res;
639
	}
640
	
641
	/**
642
	 * Instantiates a Date object from a string
643
	 * @param date date as a sring
644
	 * @return a Date object 
645
	 * @throws ParseException
646
	 */
647
	public static Date dateFromString(String date) throws ParseException{
648
		SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
649
		Date res = format.parse(date);
650
		return res;
651
	}
652
	
653
	/**
654
	 * Rounds a double value keeping the requested decimal positions 
655
	 * @param val input value
656
	 * @param decimals decimal positions requested
657
	 * @return rounded value
658
	 */
659
	private static double round(double val, int decimals){
660
		double positions = Math.pow(10 ,decimals);
661
		double aux = Math.round((val*positions))/positions;
662
		return aux;
663
	}
664
	
665

  
666
	
667
	private static String limitString(String str, int n) {
668
		
669
		int l = str.length();
670
		if (l <= n) return str;
671
		int head_l = n / 2;
672
		int tail_l = n - head_l;
673
		return str.substring(0, head_l) + str.substring(l - tail_l, l);
674
	}
675

  
676
	public static MouseEvent recreateMouseEvent(Component src, int x, int y) {
677
		
678
		MouseEvent resp = new MouseEvent(src, 0, 0, 0, x, y, 0, false);
679
		return resp;
680
	}
681

  
682
}
branches/Mobile_Compatible_Hito_1/libFMap_mobile_shp_driver/src-file/org/gvsig/data/datastores/vectorial/file/shp_inst/InstSHPStore.java
1
package org.gvsig.data.datastores.vectorial.file.shp_inst;
2

  
3
import java.util.ArrayList;
4
import java.util.Iterator;
5

  
6
import org.apache.log4j.Logger;
7
import org.gvsig.data.CloseException;
8
import org.gvsig.data.DataCollection;
9
import org.gvsig.data.DataStoreParameters;
10
import org.gvsig.data.InitializeException;
11
import org.gvsig.data.OpenException;
12
import org.gvsig.data.ReadException;
13
import org.gvsig.data.datastores.vectorial.file.shp.SHPStore;
14
import org.gvsig.data.vectorial.Feature;
15
import org.gvsig.data.vectorial.FeatureType;
16

  
17
/**
18
 * This data store creates an array of fully instantiated features when it is opened. Should be by far the fastest
19
 * and the most memory-consuming
20
 *  
21
 * @author jldominguez
22
 *
23
 */
24
public class InstSHPStore extends SHPStore {
25

  
26
	private static Logger logger = Logger.getLogger(InstSHPStore.class);
27

  
28
	public static String DATASTORE_NAME = "InstSHPStore";
29

  
30
	static {
31
		InstSHPRegister.selfRegister();
32
	}
33

  
34
	private Feature[] features;
35
	private int theSize = 0;
36

  
37
	public void init(DataStoreParameters p) throws InitializeException {
38
		super.init(p);
39
		theSize = dbf.getRecordCount();
40
	}
41
	
42
	public void doOpen() throws OpenException {
43
		super.doOpen();
44
		
45
		
46
		// ----------------- get all features: ----------------------
47
		features = new Feature[theSize];
48
		
49
		try {
50
			for (int i=0; i<theSize; i++)
51
				features[i] = super.getFeatureByPosition(featureType, (long) i); 	
52
		} catch (ReadException ex) {
53
			logger.error("While getting all features: " + ex.getMessage());
54
		}
55
		logger.debug("Created array in memory with: " + theSize + " features.");
56
		// ------------------------
57
		
58
		try {
59
			super.doClose();
60
		} catch (CloseException e) {
61
			logger.error("While closing after loading: " + e.getMessage());
62
			throw new OpenException("hile closing after loading.", e);
63
		}
64
	}
65
	
66

  
67
	protected Feature getFeatureByPosition(FeatureType featureType,
68
			long position) throws ReadException {
69
		return features[(int) position];
70
	}
71

  
72
	protected long getFeatureCount() {
73
		return theSize;
74
	}
75

  
76
}
0 77

  
branches/Mobile_Compatible_Hito_1/libFMap_mobile_shp_driver/src-file/org/gvsig/data/datastores/vectorial/file/shp_inst/InstSHPRegister.java
1
package org.gvsig.data.datastores.vectorial.file.shp_inst;
2

  
3
import org.gvsig.data.DataManager;
4
import org.gvsig.data.datastores.vectorial.file.shp.SHPStoreParameters;
5

  
6

  
7
/**
8
 * Utility class to register the Inst SHP data store.
9
 * 
10
 * @see org.gvsig.data.datastores.vectorial.file.shp_inst.InstSHPStore
11
 * 
12
 * @author jldominguez
13
 *
14
 */
15
public class InstSHPRegister {
16
	public static void selfRegister() {
17
		DataManager dsm = DataManager.getManager();
18

  
19
		dsm.registerDataStore(InstSHPStore.DATASTORE_NAME, InstSHPStore.class,
20
				SHPStoreParameters.class);
21
	}
22
}
0 23

  
branches/Mobile_Compatible_Hito_1/libFMap_mobile_shp_driver/src-file/org/gvsig/data/datastores/vectorial/file/shp_util/NewSHPFeature.java
1 1
package org.gvsig.data.datastores.vectorial.file.shp_util;
2 2

  
3
import java.awt.geom.Rectangle2D;
3 4
import java.util.List;
4 5
import java.util.Locale;
5 6

  
......
16 17
import org.gvsig.fmap.geom.Geometry;
17 18
import org.gvsig.fmap.geom.primitive.Envelope;
18 19

  
20
/**
21
 * A subclass of AbstractFeature that allows instantiation with data stores other than SHPStore.
22
 * 
23
 * @see org.gvsig.data.datastores.vectorial.file.shp.ShpFeature
24
 * 
25
 * @author jldominguez
26
 *
27
 */
19 28
public class NewSHPFeature extends AbstractFeature {
20 29

  
21 30
	private static Logger logger = Logger.getLogger(NewSHPFeature.class);
......
24 33

  
25 34
	private int featureIndex = 0;
26 35
	private IGeometricDataStore store;
36
	
37
	private Envelope extent = null;
27 38

  
39
	/**
40
	 * 
41
	 * @param ftype feature type
42
	 * @param feat_ind feature index
43
	 * @param _store the data store to be used
44
	 * @throws ReadException
45
	 */
28 46
	public NewSHPFeature(
29 47
			FeatureType ftype,
30 48
			int feat_ind,
......
41 59

  
42 60
	public Envelope getExtent() {
43 61
		// TODO Auto-generated method stub
44
		return null;
62
		return extent;
45 63
	}
46 64

  
47 65
	public List getAllSRS() {
......
100 118

  
101 119
				set(i, value);
102 120
			} catch (Exception ex) {
103

  
104
				logger.error("While loading feature: " + ex.getMessage());			}
121
				logger.error("While loading feature: " + ex.getMessage());			
122
			}
105 123
		}
106 124

  
125
		Rectangle2D bb = geometry.getBounds2D(); 
126
		extent = Utils.rectToEnvelope(bb);
127

  
107 128
		stopLoading();
108 129
	}
109 130

  
......
125 146
			}
126 147
		}
127 148
		
149
		Rectangle2D bb = geometry.getBounds2D(); 
150
		extent = Utils.rectToEnvelope(bb);
151
		
128 152
		stopLoading();
129 153

  
130 154
	}
branches/Mobile_Compatible_Hito_1/libFMap_mobile_shp_driver/src-file/org/gvsig/data/datastores/vectorial/file/shp_util/Utils.java
1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 Prodevelop and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *   Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *   +34 963862235
28
 *   gvsig@gva.es
29
 *   http://www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   Prodevelop Integraci?n de Tecnolog?as SL
34
 *   Conde Salvatierra de ?lava , 34-10
35
 *   46004 Valencia
36
 *   Spain
37
 *
38
 *   +34 963 510 612
39
 *   +34 963 510 968
40
 *   gis@prodevelop.es
41
 *   http://www.prodevelop.es
42
 *
43
 *    or
44
 *
45
 *   Instituto de Rob?tica
46
 *   Apartado de correos 2085
47
 *   46071 Valencia
48
 *   (Spain)
49
 *   
50
 *   +34 963 543 577
51
 *   jjordan@robotica.uv.es
52
 *   http://robotica.uv.es
53
 *   
54
 */
55

  
56
package org.gvsig.data.datastores.vectorial.file.shp_util;
57

  
58
import java.awt.Color;
59
import java.awt.Component;
60
import java.awt.Font;
61
import java.awt.GraphicsConfiguration;
62
import java.awt.GraphicsDevice;
63
import java.awt.GraphicsEnvironment;
64
import java.awt.Image;
65
import java.awt.event.MouseEvent;
66
import java.awt.geom.AffineTransform;
67
import java.awt.geom.Rectangle2D;
68
import java.awt.image.BufferedImage;
69
import java.io.BufferedReader;
70
import java.io.File;
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff