KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > genimen > djeneric > tools > modeler > userperspective > ResourceManagerPanel


1 /*
2  * Copyright (c) 2001-2005 by Genimen BV (www.genimen.com) All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without modification, is permitted
5  * provided that the following conditions are met:
6  * - Redistributions of source code must retain the above copyright notice, this list of conditions
7  * and the following disclaimer.
8  * - Redistributions in binary form must reproduce the above copyright notice, this list of
9  * conditions and the following disclaimer in the documentation and/or other materials
10  * provided with the distribution.
11  * - All advertising materials mentioning features or use of this software must display the
12  * following acknowledgment: "This product includes Djeneric."
13  * - Products derived from this software may not be called "Djeneric" nor may
14  * "Djeneric" appear in their names without prior written permission of Genimen BV.
15  * - Redistributions of any form whatsoever must retain the following acknowledgment: "This
16  * product includes Djeneric."
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL GENIMEN BV, DJENERIC.ORG,
22  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */

30 package com.genimen.djeneric.tools.modeler.userperspective;
31
32 import java.awt.BorderLayout JavaDoc;
33 import java.awt.Color JavaDoc;
34 import java.awt.Dimension JavaDoc;
35 import java.awt.event.ActionEvent JavaDoc;
36 import java.awt.event.ActionListener JavaDoc;
37 import java.io.BufferedInputStream JavaDoc;
38 import java.io.File JavaDoc;
39 import java.io.FileInputStream JavaDoc;
40 import java.io.IOException JavaDoc;
41 import java.util.ArrayList JavaDoc;
42
43 import javax.swing.BorderFactory JavaDoc;
44 import javax.swing.DefaultListModel JavaDoc;
45 import javax.swing.JButton JavaDoc;
46 import javax.swing.JFileChooser JavaDoc;
47 import javax.swing.JList JavaDoc;
48 import javax.swing.JOptionPane JavaDoc;
49 import javax.swing.JPanel JavaDoc;
50 import javax.swing.JScrollPane JavaDoc;
51 import javax.swing.JSplitPane JavaDoc;
52 import javax.swing.JTree JavaDoc;
53 import javax.swing.border.BevelBorder JavaDoc;
54 import javax.swing.border.Border JavaDoc;
55 import javax.swing.event.TreeSelectionEvent JavaDoc;
56 import javax.swing.tree.DefaultMutableTreeNode JavaDoc;
57 import javax.swing.tree.DefaultTreeModel JavaDoc;
58 import javax.swing.tree.TreePath JavaDoc;
59
60 import com.genimen.djeneric.language.Messages;
61 import com.genimen.djeneric.repository.exceptions.DjenericException;
62 import com.genimen.djeneric.structure.ResourceDefinition;
63 import com.genimen.djeneric.tools.modeler.ModelEditor;
64 import com.genimen.djeneric.ui.DjVerticalFlowLayout;
65 import com.genimen.djeneric.util.DjClassInspector;
66 import com.genimen.djeneric.util.DjFileFilter;
67 import com.genimen.djeneric.util.DjFileUtil;
68 import com.genimen.djeneric.util.DjLogger;
69 import com.genimen.djeneric.util.DjStringReplacer;
70
71 public class ResourceManagerPanel extends JPanel JavaDoc
72 {
73   private static final long serialVersionUID = 1L;
74   private static final String JavaDoc JARS_PATH = "/jars/";
75   DefaultTreeModel JavaDoc _treeModel;
76   ViewEditor _viewEditor;
77   ModelEditor _editor;
78   ResourceFolderNode _root;
79
80   BorderLayout JavaDoc borderLayout1 = new BorderLayout JavaDoc();
81   JSplitPane JavaDoc jSplitPane1 = new JSplitPane JavaDoc();
82   JPanel JavaDoc jPanel1 = new JPanel JavaDoc();
83   BorderLayout JavaDoc borderLayout2 = new BorderLayout JavaDoc();
84   JScrollPane JavaDoc jScrollPane1 = new JScrollPane JavaDoc();
85   JTree JavaDoc _tree = new JTree JavaDoc();
86   JScrollPane JavaDoc jScrollPane2 = new JScrollPane JavaDoc();
87   JList JavaDoc _lstContents = new JList JavaDoc();
88   JPanel JavaDoc jPanel2 = new JPanel JavaDoc();
89   JButton JavaDoc _butAdd = new JButton JavaDoc();
90   JButton JavaDoc _butDelete = new JButton JavaDoc();
91   BorderLayout JavaDoc borderLayout3 = new BorderLayout JavaDoc();
92   ResourceFolderRenderer _renderer = new ResourceFolderRenderer();
93   JPanel JavaDoc jPanel4 = new JPanel JavaDoc();
94   DjVerticalFlowLayout verticalFlowLayout1 = new DjVerticalFlowLayout();
95   JButton JavaDoc _butCreateFolder = new JButton JavaDoc();
96   JButton JavaDoc _butSave = new JButton JavaDoc();
97   JPanel JavaDoc jPanel3 = new JPanel JavaDoc();
98   BorderLayout JavaDoc borderLayout4 = new BorderLayout JavaDoc();
99   Border JavaDoc border1 = BorderFactory.createBevelBorder(BevelBorder.LOWERED, Color.white,
100                                                                                     Color.white, new Color JavaDoc(109, 109,
101                                                                                         110), new Color JavaDoc(156, 156, 158));
102
103   public ResourceManagerPanel()
104   {
105     try
106     {
107       jbInit();
108       _butAdd.setIcon(ModelEditor.getImageIcon("add.gif"));
109       _butSave.setIcon(ModelEditor.getImageIcon("save.gif"));
110       _butDelete.setIcon(ModelEditor.getImageIcon("remove.gif"));
111       _butCreateFolder.setIcon(ModelEditor.getImageIcon("addfolder.gif"));
112       _tree.putClientProperty("JTree.lineStyle", "Angled");
113       _tree.setRootVisible(false);
114       _tree.setCellRenderer(_renderer);
115       _lstContents.setCellRenderer(new ResourceListRenderer());
116       synchronize();
117     }
118     catch (Exception JavaDoc ex)
119     {
120       DjLogger.log(ex);
121     }
122   }
123
124   protected void updateModel()
125   {
126     _root = new ResourceFolderNode();
127     _treeModel = new DefaultTreeModel JavaDoc(_root);
128     _root.setModel(_treeModel);
129     _root.setTree(_tree);
130     _tree.setModel(_treeModel);
131
132     if (_viewEditor != null)
133     {
134       ResourceDefinition[] allDefs = _viewEditor.getResources();
135       for (int i = 0; i < allDefs.length; i++)
136       {
137         if (!allDefs[i].isMarkedForDelete()) addToTree(allDefs[i]);
138       }
139     }
140     _treeModel.nodeStructureChanged(_root);
141
142     createFolder(JARS_PATH);
143     createFolder("/images/");
144
145     _root.sortResources();
146   }
147
148   protected ResourceDefinition addToTree(ResourceDefinition definition)
149   {
150     String JavaDoc path = definition.getPath();
151     ResourceFolderNode folder = createOrRetrieveFolder(_root, path);
152     return folder.addOrReplaceResource(definition);
153   }
154
155   protected ResourceFolderNode createOrRetrieveFolder(ResourceFolderNode parent, String JavaDoc path)
156   {
157     int idx = path.indexOf("/");
158     String JavaDoc name = path;
159
160     if (idx != -1)
161     {
162       name = path.substring(0, idx);
163       path = path.substring(idx + 1).trim();
164     }
165     else path = "";
166
167     if (name.length() == 0 && path.length() == 0) return parent;
168
169     if (name.trim().length() == 0) name = "/";
170
171     ResourceFolderNode existing = parent.getChild(name);
172     ResourceFolderNode newNode;
173
174     if (existing != null) newNode = existing;
175     else
176     {
177       newNode = new ResourceFolderNode(_tree, _treeModel, name);
178       parent.add(newNode);
179     }
180
181     if (path.length() > 0)
182     {
183       return createOrRetrieveFolder(newNode, path);
184     }
185     return newNode;
186   }
187
188   /**
189    * Sets the editorReferences of the EditorEditor object
190    *
191    *@param navigatorEditor The new editorReferences value
192    *@param editor The new editorReferences value
193    */

194   public void setEditorReferences(ViewEditor viewEditor)
195   {
196     _editor = viewEditor.getModelEditor();
197     _viewEditor = viewEditor;
198   }
199
200   void jbInit() throws Exception JavaDoc
201   {
202     this.setLayout(borderLayout1);
203     jPanel1.setLayout(borderLayout2);
204     _lstContents.setFont(new java.awt.Font JavaDoc("Monospaced", 0, 12));
205     _tree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener JavaDoc()
206     {
207       public void valueChanged(TreeSelectionEvent JavaDoc e)
208       {
209         _tree_valueChanged(e);
210       }
211     });
212     _butAdd.setPreferredSize(new Dimension JavaDoc(24, 24));
213     _butAdd.setToolTipText(Messages.getString("ResourceManagerPanel.AddResource"));
214     _butAdd.addActionListener(new java.awt.event.ActionListener JavaDoc()
215     {
216       public void actionPerformed(ActionEvent JavaDoc e)
217       {
218         _butAdd_actionPerformed(e);
219       }
220     });
221     _butDelete.setPreferredSize(new Dimension JavaDoc(24, 24));
222     _butDelete.setToolTipText("Delete selected resource(s)");
223     _butDelete.addActionListener(new java.awt.event.ActionListener JavaDoc()
224     {
225       public void actionPerformed(ActionEvent JavaDoc e)
226       {
227         butDelete_actionPerformed(e);
228       }
229     });
230     _butCreateFolder.setPreferredSize(new Dimension JavaDoc(24, 24));
231     _butCreateFolder.setToolTipText(Messages.getString("ResourceManagerPanel.CreateFolder"));
232     _butCreateFolder.addActionListener(new java.awt.event.ActionListener JavaDoc()
233     {
234       public void actionPerformed(ActionEvent JavaDoc e)
235       {
236         _butCreateFolder_actionPerformed(e);
237       }
238     });
239     _butSave.setPreferredSize(new Dimension JavaDoc(24, 24));
240     _butSave.setToolTipText(Messages.getString("ResourceManagerPanel.SaveSelectedResource"));
241     _butSave.addActionListener(new ActionListener JavaDoc()
242     {
243       public void actionPerformed(ActionEvent JavaDoc e)
244       {
245         _butSave_actionPerformed(e);
246       }
247     });
248
249     jPanel2.setLayout(borderLayout3);
250     jPanel4.setLayout(verticalFlowLayout1);
251     jSplitPane1.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
252     jPanel3.setLayout(borderLayout4);
253     jPanel4.setBorder(border1);
254     this.add(jSplitPane1, BorderLayout.CENTER);
255     jPanel1.add(jScrollPane2, BorderLayout.CENTER);
256     jSplitPane1.add(jPanel3, JSplitPane.TOP);
257     jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
258     jScrollPane1.getViewport().add(_tree, null);
259     jScrollPane2.getViewport().add(_lstContents, null);
260     this.add(jPanel2, BorderLayout.SOUTH);
261     jPanel4.add(_butAdd, null);
262     jPanel4.add(_butDelete, null);
263     jPanel4.add(_butSave);
264     jPanel4.add(_butCreateFolder);
265     jSplitPane1.add(jPanel1, JSplitPane.BOTTOM);
266     jPanel3.add(jPanel4, java.awt.BorderLayout.WEST);
267   }
268
269   public ResourceFolderNode[] getSelectedNodes()
270   {
271     if (_tree.getSelectionPath() == null) return new ResourceFolderNode[0];
272     ArrayList JavaDoc result = new ArrayList JavaDoc(10);
273
274     TreePath JavaDoc[] tp = _tree.getSelectionPaths();
275
276     for (int qq = 0; qq < tp.length; qq++)
277     {
278       DefaultMutableTreeNode JavaDoc node = (DefaultMutableTreeNode JavaDoc) (tp[qq].getLastPathComponent());
279       if (node instanceof ResourceFolderNode) result.add(node);
280     }
281     return (ResourceFolderNode[]) result.toArray(new ResourceFolderNode[0]);
282   }
283
284   void _butAdd_actionPerformed(ActionEvent JavaDoc e)
285   {
286     ResourceFolderNode[] sels = getSelectedNodes();
287     if (sels.length == 0)
288     {
289       JOptionPane.showMessageDialog(this, Messages.getString("ResourceManagerPanel.CreateSelectFolder"), Messages
290           .getString("ResourceManagerPanel.NoFolderSelected"), JOptionPane.INFORMATION_MESSAGE);
291       return;
292     }
293
294     JFileChooser JavaDoc fc = new JFileChooser JavaDoc();
295     initFileChooser(fc);
296     DjFileFilter filter = new DjFileFilter(new String JavaDoc[]{"gif", "class", "jar"}, Messages.getString("global.Resources"));
297     fc.setFileFilter(filter);
298     fc.setDialogTitle(Messages.getString("ResourceManagerPanel.LoadResource"));
299     fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
300     fc.setMultiSelectionEnabled(true);
301
302     if (fc.showOpenDialog(this) != JFileChooser.CANCEL_OPTION)
303     {
304       recordFileChooserSettings(fc);
305       try
306       {
307         File JavaDoc[] files = fc.getSelectedFiles();
308         ArrayList JavaDoc added = new ArrayList JavaDoc();
309         for (int i = 0; i < files.length; i++)
310         {
311           ResourceDefinition def = loadResource(sels[0], files[i].getAbsolutePath());
312           if (def.getBytes().length > 20000)
313           {
314             if (JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog(this, Messages
315                 .getString("ResourceManagerPanel.LargeResource"), Messages
316                 .getString("ResourceManagerPanel.LargeResourceTitle"), JOptionPane.YES_NO_OPTION,
317                                                                        JOptionPane.WARNING_MESSAGE))
318             {
319               continue;
320             }
321
322           }
323           if (def.isJar())
324           {
325             def.setPath(JARS_PATH);
326           }
327           added.add(def);
328           _viewEditor.addResource(def);
329         }
330
331         // If something was done here, synch the display
332
if (added.size() > 0)
333         {
334           ResourceDefinition res = (ResourceDefinition) added.get(0);
335           synchronize();
336           ResourceFolderNode folder = createOrRetrieveFolder(_root, res.getPath());
337           selectNode(folder);
338           selectResources((ResourceDefinition[]) added.toArray(new ResourceDefinition[0]));
339           _viewEditor.updateSelectedNodeData();
340         }
341       }
342       catch (Exception JavaDoc e1)
343       {
344         DjLogger.log(e1);
345       }
346     }
347
348   }
349
350   protected void selectResources(ResourceDefinition[] definitions)
351   {
352     _lstContents.setSelectedIndex(-1);
353     int[] indices = new int[definitions.length];
354     for (int x = 0; x < definitions.length; x++)
355     {
356       for (int i = 0; i < _lstContents.getModel().getSize(); i++)
357       {
358         if (_lstContents.getModel().getElementAt(i) == definitions[x])
359         {
360           indices[x] = i;
361         }
362       }
363       _lstContents.setSelectedIndices(indices);
364     }
365   }
366
367   protected ResourceDefinition loadResource(ResourceFolderNode dest, String JavaDoc filename) throws IOException JavaDoc,
368       DjenericException
369   {
370     File JavaDoc infile = new File JavaDoc(filename);
371     long size = infile.length();
372
373     FileInputStream JavaDoc fis = new FileInputStream JavaDoc(infile);
374     BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc(fis);
375
376     byte[] buffer = new byte[(int) size];
377     int offset = 0;
378     int totalRead = 0;
379     while (totalRead < size)
380     {
381       totalRead += bis.read(buffer, offset, (int) (size - totalRead));
382     }
383     ResourceDefinition def = new ResourceDefinition();
384     def.setBytes(buffer);
385     boolean pathIsSet = false;
386     if (filename.toLowerCase().endsWith(".class"))
387     {
388       DjClassInspector inspector = new DjClassInspector(buffer);
389       if (inspector.isValidClass())
390       {
391         pathIsSet = true;
392         def.setAbsolutePath(inspector.getClassName() + ".class");
393       }
394     }
395     if (!pathIsSet)
396     {
397       def.setAbsolutePath(filename);
398       def.setPath(dest.getPathString());
399     }
400     bis.close();
401     return dest.addOrReplaceResource(def);
402   }
403
404   protected void initFileChooser(JFileChooser JavaDoc fc)
405   {
406     fc
407         .setCurrentDirectory(new File JavaDoc(_editor.getProperty("filelocation", System.getProperties()
408             .getProperty("user.dir"))));
409   }
410
411   protected void recordFileChooserSettings(JFileChooser JavaDoc fc)
412   {
413     _editor.setProperty("filelocation", fc.getCurrentDirectory().getAbsolutePath());
414   }
415
416   void _tree_valueChanged(TreeSelectionEvent JavaDoc e)
417   {
418     updateSelectedFolderData();
419   }
420
421   public void updateSelectedFolderData()
422   {
423     DefaultListModel JavaDoc listModel = new DefaultListModel JavaDoc();
424
425     _lstContents.setModel(listModel);
426     ResourceFolderNode[] sels = getSelectedNodes();
427
428     if (sels.length > 0)
429     {
430       ResourceDefinition[] resources = sels[0].getResources();
431       for (int i = 0; i < resources.length; i++)
432       {
433         listModel.addElement(resources[i]);
434       }
435     }
436   }
437
438   public void synchronize()
439   {
440     updateModel();
441     updateSelectedFolderData();
442     _root.expandAll();
443   }
444
445   void butDelete_actionPerformed(ActionEvent JavaDoc e)
446   {
447     ResourceFolderNode[] sels = getSelectedNodes();
448     if (sels.length == 0) return;
449
450     Object JavaDoc[] defs = _lstContents.getSelectedValues();
451     boolean killAll = false;
452     for (int i = 0; i < defs.length; i++)
453     {
454       ResourceDefinition def = (ResourceDefinition) defs[i];
455       int result = 0;
456       if (!killAll)
457       {
458         result = JOptionPane.showOptionDialog(this, Messages.getString("ResourceManagerPanel.Want2Delete", def
459             .getName()), Messages.getString("ResourceManagerPanel.DeleteResource"), JOptionPane.DEFAULT_OPTION,
460                                               JOptionPane.INFORMATION_MESSAGE, null, new String JavaDoc[]{
461                                                   Messages.getString("global.Delete"),
462                                                   Messages.getString("ResourceManagerPanel.All"),
463                                                   Messages.getString("global.Cancel")}, null);
464         killAll = result == 1;
465       }
466       if (killAll || result == 0)
467       {
468         sels[0].removeResource(def);
469         def.markDeleted(true);
470       }
471       if (result == 2)
472       {
473         updateSelectedFolderData();
474         _viewEditor.updateSelectedNodeData();
475         return;
476       }
477     }
478     updateSelectedFolderData();
479     _viewEditor.updateSelectedNodeData();
480   }
481
482   public void selectNode(ResourceFolderNode node)
483   {
484     _tree.setSelectionPath(new TreePath JavaDoc(node.getPath()));
485     updateSelectedFolderData();
486   }
487
488   private void createFolder(String JavaDoc txt)
489   {
490     txt = createValidPath(txt);
491
492     ResourceFolderNode node = createOrRetrieveFolder(_root, txt);
493     _treeModel.nodeStructureChanged(_root);
494     _root.expandAll();
495     selectNode(node);
496   }
497
498   protected String JavaDoc createValidPath(String JavaDoc path)
499   {
500     if (!path.startsWith("/")) path = "/" + path;
501
502     DjStringReplacer sr = new DjStringReplacer(path);
503     sr.replace("\\", "/");
504     sr.replace("//", "/");
505     path = sr.toString();
506     return path;
507   }
508
509   void _butCreateFolder_actionPerformed(ActionEvent JavaDoc e)
510   {
511     String JavaDoc path = "";
512     ResourceFolderNode[] sels = getSelectedNodes();
513     if (sels.length != 0) path = sels[0].getPathString() + "/";
514
515     String JavaDoc folder = JOptionPane.showInputDialog(this, Messages.getString("ResourceManagerPanel.CreateFolder"), path);
516     if (folder != null && folder.trim().length() > 0) createFolder(folder);
517   }
518
519   public void _butSave_actionPerformed(ActionEvent JavaDoc e)
520   {
521     ResourceFolderNode[] sels = getSelectedNodes();
522     if (sels.length == 0) return;
523
524     try
525     {
526       JFileChooser JavaDoc fc = new JFileChooser JavaDoc();
527       fc.setDialogTitle(Messages.getString("ModelEditor.SaveResource"));
528       initFileChooser(fc);
529       fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
530       if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
531       {
532         String JavaDoc destpath = fc.getSelectedFile().getAbsolutePath();
533         if (!destpath.endsWith("/") && !destpath.endsWith("\\")) destpath += "/";
534
535         Object JavaDoc[] defs = _lstContents.getSelectedValues();
536         for (int i = 0; i < defs.length; i++)
537         {
538           ResourceDefinition def = (ResourceDefinition) defs[i];
539
540           byte[] bytes = def.getBytes();
541
542           String JavaDoc dirname = destpath + def.getPath();
543           DjFileUtil.createDirectory(dirname);
544           String JavaDoc filename = dirname + def.getName() + "." + def.getType();
545           DjFileUtil.writeFile(filename, bytes);
546           new File JavaDoc(dirname + def.getName() + "." + def.getType()).setLastModified(def.getTime());
547         }
548         _editor.setStatusMessage(Messages
549             .getString("ModelEditor.ResourcesSaved", String.valueOf(defs.length), destpath));
550       }
551     }
552     catch (Exception JavaDoc e1)
553     {
554       _editor.setStatusMessage(e1);
555     }
556   }
557
558 }
559
Popular Tags