Statistics
| Revision:

svn-gvsig-desktop / branches / Mobile_Compatible_Hito_1 / libFMap_mobile_shp_driver / src-file / org / gvsig / data / datastores / vectorial / file / shp_util / Utils.java @ 22037

History | View | Annotate | Download (17.9 KB)

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;
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
import org.gvsig.fmap.geom.primitive.DefaultEnvelope;
85
import org.gvsig.fmap.geom.primitive.Envelope;
86

    
87

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

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

    
114
        private static Logger logger = Logger.getLogger(Utils.class);
115

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

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

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

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

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

    
126
        public final static String png = "png";
127

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

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

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

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

    
170

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

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

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

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

    
205
                int all_bytes_ind = 0;
206

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

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

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

    
243
                ArrayList resp = new ArrayList();
244

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

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

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

    
262
                resp.add(top_row);
263
                resp.add(bottom_row);
264
                resp.add(right_col);
265
                resp.add(left_col);
266

    
267
                return null;
268

    
269
        }
270

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

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

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

    
305

    
306

    
307

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

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

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

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

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

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

    
360
                String item = "";
361
                String new_str = "";
362

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

    
374
        private static AffineTransform readWldFile(File wf) {
375

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

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

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

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

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

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

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

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

    
447
                return new Rectangle2D.Double(x, y, w, h);
448
        }
449

    
450
        private static GraphicsEnvironment _ge = GraphicsEnvironment
451
                        .getLocalGraphicsEnvironment();
452

    
453
        private static GraphicsDevice _dev = _ge.getDefaultScreenDevice();
454

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

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

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

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

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

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

    
539

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

    
564
        private static void writeCurrentTime(File f, long _t) {
565

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

    
580
        }
581

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

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

    
604
                logger.debug("currtime = " + currtime);
605

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

    
614
                long last_exe = readLastExeLog(f);
615

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

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

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

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

    
684
        public static Envelope rectToEnvelope(Rectangle2D bb) {
685
                
686
                if (bb == null) return null;
687
                
688
                double[] min = new double[2];
689
                double[] max = new double[2];
690
                
691
                min[0] = bb.getMinX();
692
                min[1] = bb.getMinY();
693
                max[0] = bb.getMaxX();
694
                max[1] = bb.getMaxY();
695

    
696
                return new DefaultEnvelope(2, min, max);
697
        }
698

    
699
}