Revision 40350 branches/v2_0_0_prep/libraries/org.gvsig.symbology/org.gvsig.symbology.swing/org.gvsig.symbology.swing.api/src/main/java/org/gvsig/app/gui/styling/SymbolLibrary.java

View differences:

SymbolLibrary.java
43 43
import java.awt.Component;
44 44
import java.io.File;
45 45
import java.io.FileFilter;
46
import java.io.IOException;
47
import java.net.URI;
48
import java.net.URL;
49
import java.util.ArrayList;
46 50
import java.util.Arrays;
47 51
import java.util.Comparator;
48 52
import java.util.ConcurrentModificationException;
53
import java.util.HashMap;
49 54
import java.util.Iterator;
55
import java.util.List;
56
import java.util.Map;
50 57
import java.util.Vector;
51 58

  
52 59
import javax.swing.JOptionPane;
......
57 64
import javax.swing.tree.TreePath;
58 65

  
59 66
import org.apache.commons.io.FileUtils;
67
import org.slf4j.Logger;
68
import org.slf4j.LoggerFactory;
69

  
60 70
import org.gvsig.andami.PluginServices;
61 71
import org.gvsig.andami.messages.NotificationManager;
62 72
import org.gvsig.fmap.mapcontext.MapContextLocator;
......
65 75
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolManager;
66 76
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolPreferences;
67 77
import org.gvsig.i18n.Messages;
78
import org.gvsig.tools.ToolsLocator;
79
import org.gvsig.tools.dataTypes.DataTypes;
80
import org.gvsig.tools.dynobject.DynField;
81
import org.gvsig.tools.dynobject.DynStruct;
82
import org.gvsig.tools.persistence.PersistenceManager;
83
import org.gvsig.tools.persistence.PersistentContext;
84
import org.gvsig.tools.persistence.PersistentState;
85
import org.gvsig.tools.persistence.spi.PersistentContextServices;
68 86

  
69 87
/**
70 88
 * 
......
75 93
 * 
76 94
 */
77 95
public class SymbolLibrary extends DefaultTreeModel implements ILibraryModel {
96
    
97
    private static Logger logger =
98
        LoggerFactory.getLogger(SymbolLibrary.class);
78 99
	/**
79 100
	 * 
80 101
	 */
......
257 278
			ISymbol sym = (ISymbol) element;
258 279
			File folder = containerFolder == null ? rootDir
259 280
					: (File) containerFolder;
260
			// if (containerFolder == null) {
261
			// containerFolder = rootDir;
262
			// }
263 281

  
282
			// copy files and update fields
283
			try {
284
			    sym = (ISymbol) copyFilesToFolder(
285
			        sym, folder, new HashMap());
286
			} catch (Exception exc) {
287
			    logger.info("Error while copying symbol files.", exc);
288
			    return;
289
			}
290

  
264 291
			String fExtension = getPreferences().getSymbolFileExtension();
265 292
			if (!elementName.toLowerCase().endsWith(fExtension)) {
266 293
				elementName = elementName.concat(fExtension);
......
286 313
				NotificationManager.addError(Messages.getText(
287 314
						"save_error"), e);
288 315
			}
289
			// // save it
290
			// XMLEntity xml = null;
291
			// // XMLENTITY-UPDATED
292
			// // try {
293
			// // xml = sym.getXMLEntity();
294
			// // } catch (XMLException e) {
295
			// // NotificationManager.addWarning("Symbol layer", e);
296
			// // }
297
			// FileWriter writer;
298
			// try {
299
			// writer = new FileWriter(targetFile.getAbsolutePath());
300
			// Marshaller m = new Marshaller(writer);
301
			// m.setEncoding("ISO-8859-1");
302
			// m.marshal(xml.getXmlTag());
303
			//
304
			// } catch (Exception ex) {
305
			// NotificationManager.addError(
306
			// PluginServices.getText(this, "save_error"), ex);
307
			// }
308 316
		} else {
309 317
			throw new IllegalArgumentException(Messages.getText(
310 318
					"adding_a_non_symbol_as_element"));
......
394 402
			iterator.next().treeNodesRemoved(e);
395 403
		}
396 404
	}
405
	
406
	
407
    private static Object copyFilesToFolder(
408
        Object sym,
409
        File theFolder,
410
        Map processedFilesMap
411
        // Set processedObjSet,
412
        /*int dep*/) throws Exception {
413
        
414
        PersistenceManager manager =
415
            ToolsLocator.getPersistenceManager();
416
        PersistentState state = null;
417
        state = manager.getState(sym, true);
418
        PersistentContext context = state.getContext();
419
        
420
        List<PersistentState> states_list = getList(context);
421
        int len = states_list.size();
397 422

  
423
        for (int i=0; i<len; i++) {
424
            
425
            PersistentState aState = states_list.get(i);
426
            DynStruct definition = aState.getDefinition();
427
            DynField[] fields = definition.getDynFields();
428
            
429
            File value_file = null;
430
            File value_file_new = null;
431
            URL value_url = null;
432
            URI value_uri = null;
433
            File donefile = null;
434
            Object value_obj = null;
435
            Object value_obj_new = null;
436
            
437
            for (DynField field : fields) {
438
                if (field.getType() == DataTypes.FILE) {
439
                    
440
                    value_file = aState.getFile(field.getName());
441
                    
442
                    donefile = (File) processedFilesMap.get(value_file);
443
                    if (donefile == null) {
444
                        /*
445
                         * It was NOT processed before
446
                         */
447
                        value_file_new = copyFile(value_file, theFolder);
448
                        aState.set(field.getName(), value_file_new);
449
                        processedFilesMap.put(value_file, value_file_new);
450
                    } else {
451
                        /*
452
                         * It was processed before
453
                         */
454
                        aState.set(field.getName(), donefile);
455
                    }
456
                    
457
                    
458
                } else if (field.getType() == DataTypes.URL) {
459
                    
460
                    value_url = aState.getURL(field.getName());
461
                    if ("FILE".equalsIgnoreCase(value_url.getProtocol())) {
462
                        
463
                        File urlfile = new File(value_url.getFile());
464
                        donefile = (File) processedFilesMap.get(urlfile);
465
                        if (donefile == null) {
466
                            value_file_new = copyFile(urlfile, theFolder);
467
                            value_url = value_file_new.toURI().toURL();
468
                            aState.set(field.getName(), value_url);
469
                            processedFilesMap.put(urlfile, value_file_new);
470
                        } else {
471
                            value_url = donefile.toURI().toURL();
472
                            aState.set(field.getName(), value_url);
473
                        }
474
                        
475
                    }
476
                    
477
                } else if (field.getType() == DataTypes.URI) {
478
                    
479
                    value_uri = aState.getURI(field.getName());
480
                    if (value_uri.getScheme() == null ||
481
                        "FILE".equalsIgnoreCase(value_uri.getScheme())) {
482
                        
483
                        File urifile = new File(value_uri.toURL().getFile());
484
                        donefile = (File) processedFilesMap.get(urifile);
485
                        if (donefile == null) {
486
                            value_file_new = copyFile(urifile, theFolder);
487
                            value_uri = value_file_new.toURI();
488
                            aState.set(field.getName(), value_uri);
489
                            processedFilesMap.put(urifile, value_file_new);
490
                        } else {
491
                            value_uri = donefile.toURI();
492
                            aState.set(field.getName(), value_uri);
493
                        }
494
                        
495
                    }
496
                }
497
            }
498
        }
499
        
500
        // ================================
501
        if (context instanceof PersistentContextServices) {
502
            /*
503
             * Ensure that previous instances are not used,
504
             * so objects are recreated
505
             */
506
            ((PersistentContextServices) context).clear();
507
        }
508
        Object resp = manager.create(state);
509
        return resp;
510
    }
511
    
512
    /**
513
     * @param context
514
     * @return
515
     */
516
    private static List<PersistentState> getList(PersistentContext context) {
517

  
518
        Iterator<PersistentState> iter = context.iterator();
519
        List<PersistentState> resp = new ArrayList<PersistentState>();
520
        while (iter.hasNext()) {
521
            resp.add(iter.next());
522
        }
523
        return resp;
524
    }
525

  
526
    /*
527
    private static Object recreate(PersistentState stat)
528
        throws Exception {
529
        
530
        File tmp = File.createTempFile("sym" + System.currentTimeMillis(), ".xml");
531
        FileOutputStream fos = new FileOutputStream(tmp);
532
        PersistenceManager mana = ToolsLocator.getPersistenceManager();
533
        mana.saveState(stat, fos);
534
        fos.flush();
535
        fos.close();
536
        FileInputStream fis = new FileInputStream(tmp);
537
        PersistentState nstat = mana.loadState(fis);
538
        fis.close();
539
        Object resp = mana.create(nstat);
540
        return resp;
541
    }
542
    */
543
    
544
    /**
545
     * Copies file to destination folder. If a file with same name
546
     * exists, destination name is changed. The final destination
547
     * file is returned.
548
     * 
549
     * @param srcfile
550
     * @param dstfolder
551
     * @return
552
     * @throws IOException
553
     */
554
    private static File copyFile(File srcfile, File dstfolder) 
555
    throws IOException {
556
        
557
        if (srcfile == null || dstfolder == null
558
            || !srcfile.isFile() || !dstfolder.isDirectory()
559
            || !srcfile.exists()) {
560
            
561
            throw new IOException("Bad parameters in copyFile method");
562
        }
563
        
564
        if (srcfile.getParentFile().equals(dstfolder)) {
565
            // already in place, nothing to do
566
            return srcfile;
567
        }
568

  
569
        if (!dstfolder.exists()) {
570
            dstfolder.mkdirs();
571
        }
572
        
573
        String checkfile = dstfolder.getCanonicalPath()
574
            + File.separator + srcfile.getName();
575
        File aux = new File(checkfile);
576
        File targetFile = null;
577
        if (aux.exists()) {
578
            // a file with that name exists and is not the same file
579
            // so we must create a new target file name
580
            targetFile = getAvailableFileName(dstfolder, srcfile.getName());
581
        } else {
582
            targetFile = aux;
583
        }
584
        
585
        FileUtils.copyFile(srcfile, targetFile);
586
        return targetFile;
587
    }
588

  
589
    /**
590
     * 
591
     * Gets an available file name in the folder, using
592
     * the name provided. It will add an index until an
593
     * unused name is found
594
     * 
595
     * @param dstfolder
596
     * @param name
597
     * @return
598
     */
599
    private static File getAvailableFileName(
600
        File dstfolder, String name) throws IOException {
601
        
602
        int index = -1;
603
        boolean exists = true;
604
        String tryname = null;
605
        String checkfile = null;
606
        File tryfile = null;
607
        
608
        while (exists) {
609
            index++;
610
            tryname = "" + index + "_" + name;
611
            checkfile = dstfolder.getCanonicalPath()
612
                + File.separator + tryname;
613
            tryfile = new File(checkfile);
614
            exists = tryfile.exists();
615
        }
616
        return tryfile;
617
    }
618
    
619
    
620
    
621

  
622

  
398 623
}

Also available in: Unified diff