KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > j2ee > persistence > unit > PUDataObject


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.j2ee.persistence.unit;
21
22 import java.awt.Image JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.StringWriter JavaDoc;
25 import java.io.Writer JavaDoc;
26 import javax.swing.SwingUtilities JavaDoc;
27 import org.netbeans.api.project.FileOwnerQuery;
28 import org.netbeans.modules.j2ee.persistence.dd.PersistenceMetadata;
29 import org.netbeans.modules.j2ee.persistence.dd.persistence.model_1_0.Persistence;
30 import org.netbeans.modules.j2ee.persistence.dd.persistence.model_1_0.PersistenceUnit;
31 import org.netbeans.modules.j2ee.persistence.provider.ProviderUtil;
32 import org.openide.DialogDisplayer;
33 import org.openide.ErrorManager;
34 import org.netbeans.api.xml.cookies.CheckXMLCookie;
35 import org.netbeans.api.xml.cookies.ValidateXMLCookie;
36 import org.netbeans.modules.schema2beans.Schema2BeansException;
37 import org.netbeans.modules.xml.multiview.DesignMultiViewDesc;
38 import org.netbeans.modules.xml.multiview.ToolBarMultiViewElement;
39 import org.netbeans.modules.xml.multiview.XmlMultiViewDataObject;
40 import org.netbeans.modules.xml.multiview.XmlMultiViewDataSynchronizer;
41 import org.netbeans.spi.xml.cookies.CheckXMLSupport;
42 import org.netbeans.spi.xml.cookies.DataObjectAdapters;
43 import org.netbeans.spi.xml.cookies.ValidateXMLSupport;
44 import org.openide.NotifyDescriptor;
45 import org.openide.cookies.EditorCookie;
46 import org.openide.filesystems.FileLock;
47 import org.openide.filesystems.FileObject;
48 import org.openide.loaders.DataObjectExistsException;
49 import org.openide.nodes.Node;
50 import org.openide.util.HelpCtx;
51 import org.openide.util.NbBundle;
52
53 /**
54  * Multiview data object for persistence.xml.
55  *
56  * @author Martin Adamek
57  * @author Erno Mononen
58  */

59
60 public class PUDataObject extends XmlMultiViewDataObject {
61     
62     public static final String JavaDoc HELP_ID_DESIGN_PERSISTENCE_UNIT
63             = "persistence_multiview_design_persistenceUnitNode"; // NO18N
64
private ModelSynchronizer modelSynchronizer;
65     /**
66      * Update delay for model synchronizer.
67      */

68     public static final int UPDATE_DELAY = 200;
69     private static final int TYPE_TOOLBAR = 0;
70     private Persistence persistence;
71     private static final String JavaDoc DESIGN_VIEW_ID = "persistence_multiview_design"; // NO18N
72

73     /**
74      * Creates a new instance of PUDataObject.
75      */

76     public PUDataObject(FileObject pf, PUDataLoader loader, boolean parse) throws DataObjectExistsException {
77         super(pf, loader);
78         modelSynchronizer = new ModelSynchronizer(this);
79         org.xml.sax.InputSource JavaDoc in = DataObjectAdapters.inputSource(this);
80         CheckXMLCookie checkCookie = new CheckXMLSupport(in);
81         getCookieSet().add(checkCookie);
82         ValidateXMLCookie validateCookie = new ValidateXMLSupport(in);
83         getCookieSet().add(validateCookie);
84         if(parse){
85             parseDocument();
86         }
87     }
88     
89     protected Node createNodeDelegate() {
90         return new PUDataNode(this);
91     }
92     
93     /**
94      * Saves the document.
95      * @see EditorCookie#saveDocument
96      */

97     public void save(){
98         EditorCookie edit = (EditorCookie) getCookie(EditorCookie.class);
99         if (edit != null){
100             try {
101                 edit.saveDocument();
102             } catch (IOException JavaDoc ex) {
103                 ErrorManager.getDefault().notify(ex);
104             }
105         }
106     }
107     
108     /**
109      * Parses the document.
110      * @return true if document could be parsed (it was valid), false otwherwise.
111      */

112     public boolean parseDocument() {
113         if (persistence==null) {
114             try {
115                 persistence = getPersistence();
116             } catch (RuntimeException JavaDoc ex) { // must catch RTE (thrown by schema2beans when document is not valid)
117
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
118                 return false;
119             }
120         } else {
121             try{
122                 java.io.InputStream JavaDoc is = getEditorSupport().getInputStream();
123                 Persistence newPersistence = null;
124                 try {
125                     newPersistence = Persistence.createGraph(is, true);
126                 } catch (RuntimeException JavaDoc ex) { // must catch RTE (thrown by schema2beans when document is not valid)
127
ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
128                     return false;
129                 }
130                 if (newPersistence!=null) {
131                     persistence.merge(newPersistence, org.netbeans.modules.schema2beans.BaseBean.MERGE_UPDATE);
132                 }
133             } catch (IOException JavaDoc ioe){
134                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ioe);
135                 return false;
136             }
137         }
138         return true;
139     }
140     
141     
142     /**
143      * Checks whether the preferred view can be displayed and switches to the
144      * xml view and displays an appropriate warning if not. In case that
145      * the preferred view is the design view, it
146      * can be displayed if <ol><li>document is valid (parseable) and</li>
147      *<li>the target server is attached></li></ol>.
148      *@return true if the preferred view can be displayed.
149      */

150     public void viewCanBeDisplayed() {
151         
152         boolean switchView = false;
153         NotifyDescriptor nd = null;
154         
155         if (!parseDocument() && getSelectedPerspective().preferredID().startsWith(DESIGN_VIEW_ID)) {
156             nd = new org.openide.NotifyDescriptor.Message(
157                     NbBundle.getMessage(PUDataObject.class, "TXT_DocumentUnparsable",
158                     getPrimaryFile().getNameExt()), NotifyDescriptor.WARNING_MESSAGE);
159             switchView = true;
160             
161         } else if (!ProviderUtil.isValidServerInstanceOrNone(FileOwnerQuery.getOwner(getPrimaryFile()))
162         && getSelectedPerspective().preferredID().startsWith(DESIGN_VIEW_ID)){
163             
164             nd = new org.openide.NotifyDescriptor.Message(
165                     NbBundle.getMessage(PUDataObject.class, "TXT_ServerMissing"),
166                     NotifyDescriptor.WARNING_MESSAGE);
167             switchView = true;
168         }
169         
170         if (switchView){
171             DialogDisplayer.getDefault().notify(nd);
172             // postpone the "Switch to XML View" action to the end of event dispatching thread
173
// this enables to finish the current action first (e.g. painting particular view)
174
// see the issue 67580
175
SwingUtilities.invokeLater(new Runnable JavaDoc(){
176                 public void run() {
177                     goToXmlView();
178                 }
179             });
180             
181         }
182     }
183     
184     
185     /**
186      * @return the persistence object associated with this.
187      */

188     public Persistence getPersistence(){
189         if (persistence==null) {
190             try {
191                 persistence = PersistenceMetadata.getDefault().getRoot(getPrimaryFile());
192             } catch (IOException JavaDoc ex) {
193                 ErrorManager.getDefault().notify(ex);
194             }
195         }
196         assert persistence != null;
197         return persistence;
198     }
199     
200     /**
201      * Adds given persistence unit and schedules update of data.
202      */

203     public void addPersistenceUnit(PersistenceUnit persistenceUnit){
204         ProviderUtil.makePortableIfPossible(FileOwnerQuery.getOwner(getPrimaryFile()), persistenceUnit);
205         getPersistence().addPersistenceUnit(persistenceUnit);
206         modelUpdatedFromUI();
207     }
208     
209     /**
210      * Removes given persistence unit and schedules update of data.
211      */

212     public void removePersistenceUnit(PersistenceUnit persistenceUnit){
213         getPersistence().removePersistenceUnit(persistenceUnit);
214         modelUpdatedFromUI();
215     }
216     
217     /**
218      * Adds given clazz to the list of given persistence unit's managed
219      * classes and schedules update of data.
220      * @param persistenceUnit
221      * @param clazz fully qualified name of the class to be added.
222      * @return true if given class was added, false otherwise (for example when
223      * it was already added).
224      */

225     public boolean addClass(PersistenceUnit persistenceUnit, String JavaDoc clazz){
226         String JavaDoc[] existing = persistenceUnit.getClass2();
227         for (int i = 0; i < existing.length; i++) {
228             if (clazz.equals(existing[i])){
229                 return false;
230             }
231         }
232         persistenceUnit.addClass2(clazz);
233         modelUpdatedFromUI();
234         return true;
235     }
236     
237     /**
238      * Removes given class from the list of given persistence unit's managed
239      * classes and schedules update of data.
240      * @param persistenceUnit
241      * @param clazz fully qualified name of the class to be removed.
242      */

243     public void removeClass(PersistenceUnit persistenceUnit, String JavaDoc clazz){
244         persistenceUnit.removeClass2(clazz);
245         
246         modelUpdatedFromUI();
247     }
248     
249     
250     
251     
252     protected DesignMultiViewDesc[] getMultiViewDesc() {
253         return new DesignMultiViewDesc[]{new DesignView(this,TYPE_TOOLBAR)};
254     }
255     
256     private static class DesignView extends DesignMultiViewDesc {
257         
258         private static final long serialVersionUID = 1L;
259         private int type;
260         
261         DesignView(PUDataObject dObj, int type) {
262             super(dObj, NbBundle.getMessage(PUDataObject.class, "LBL_Design"));
263             this.type=type;
264         }
265         
266         public org.netbeans.core.spi.multiview.MultiViewElement createElement() {
267             PUDataObject dObj = (PUDataObject)getDataObject();
268             return new PersistenceToolBarMVElement(dObj);
269         }
270         
271         public java.awt.Image JavaDoc getIcon() {
272             return org.openide.util.Utilities.loadImage("org/netbeans/modules/j2ee/persistence/unit/PersistenceIcon.gif"); //NOI18N
273
}
274         
275         public String JavaDoc preferredID() {
276             return DESIGN_VIEW_ID + String.valueOf(type);
277         }
278         
279         public HelpCtx getHelpCtx() {
280             return new HelpCtx(HELP_ID_DESIGN_PERSISTENCE_UNIT); //NOI18N
281
}
282         
283     }
284     
285     public void showElement(Object JavaDoc element) {
286         Object JavaDoc target=null;
287         if (element instanceof PersistenceUnit) {
288             openView(0);
289             target=element;
290         }
291         if (target!=null) {
292             final Object JavaDoc key=target;
293             org.netbeans.modules.xml.multiview.Utils.runInAwtDispatchThread(new Runnable JavaDoc() {
294                 public void run() {
295                     getActiveMultiViewElement0().getSectionView().openPanel(key);
296                 }
297             });
298         }
299     }
300     
301     protected String JavaDoc getPrefixMark() {
302         return null;
303     }
304     
305     /** Enable to get active MultiViewElement object
306      */

307     public ToolBarMultiViewElement getActiveMultiViewElement0() {
308         return (ToolBarMultiViewElement)super.getActiveMultiViewElement();
309     }
310     
311     public void modelUpdatedFromUI() {
312         setModified(true);
313         modelSynchronizer.requestUpdateData();
314     }
315     
316     public void updateDataFromModel(FileLock lock) throws IOException JavaDoc{
317         modelSynchronizer.updateDataFromModel(getPersistence(), lock, true);
318     }
319     
320     public boolean isDeleteAllowed() {
321         return true;
322     }
323     
324     public boolean isCopyAllowed() {
325         return true;
326     }
327     
328     public boolean isMoveAllowed(){
329         return true;
330     }
331     
332     protected Image JavaDoc getXmlViewIcon() {
333         return org.openide.util.Utilities.loadImage("org/netbeans/modules/j2ee/persistence/unit/PersistenceIcon.gif"); //NOI18N
334
}
335     
336     private class ModelSynchronizer extends XmlMultiViewDataSynchronizer {
337         
338         public ModelSynchronizer(XmlMultiViewDataObject dataObject) {
339             super(dataObject, UPDATE_DELAY);
340         }
341         
342         protected boolean mayUpdateData(boolean allowDialog) {
343             return true;
344         }
345         
346         protected void updateDataFromModel(Object JavaDoc model, FileLock lock, boolean modify) {
347             if (model == null) {
348                 return;
349             }
350             try {
351                 Writer JavaDoc out = new StringWriter JavaDoc();
352                 ((Persistence) model).write(out);
353                 out.close();
354                 getDataCache().setData(lock, out.toString(), modify);
355             } catch (IOException JavaDoc e) {
356                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
357             } catch (Schema2BeansException e) {
358                 ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
359             } finally {
360                 if (lock != null){
361                     lock.releaseLock();
362                 }
363             }
364         }
365         
366         protected Object JavaDoc getModel() {
367             return getPersistence();
368         }
369         
370         protected void reloadModelFromData() {
371             parseDocument();
372         }
373         
374     }
375 }
376
Popular Tags