KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > jawe > actions > Save


1 /*
2  * Authors:
3  * Stefanovic Nenad chupo@iis.ns.ac.yu
4  * Bojanic Sasa sasaboy@neobee.net
5  * Puskas Vladimir vpuskas@eunet.yu
6  * Pilipovic Goran zboniek@uns.ac.yu
7  *
8  */

9
10 package org.enhydra.jawe.actions;
11
12 import org.enhydra.jawe.*;
13 import org.enhydra.jawe.graph.*;
14 import org.enhydra.jawe.misc.*;
15 import org.enhydra.jawe.xml.*;
16
17 import org.enhydra.jawe.xml.elements.ExternalPackage;
18 import org.enhydra.jawe.xml.elements.PackageHeader;
19 import org.enhydra.jawe.xml.elements.WorkflowProcess;
20 import org.enhydra.jawe.xml.elements.WorkflowProcesses;
21
22 import org.jgraph.graph.GraphConstants;
23
24 import java.awt.event.ActionEvent JavaDoc;
25
26 import java.io.*;
27 import java.nio.channels.FileLock JavaDoc;
28 import java.util.*;
29 import java.awt.*;
30 import javax.swing.*;
31
32
33 import javax.xml.parsers.*;
34 import javax.xml.transform.*;
35 import javax.xml.transform.dom.*;
36 import javax.xml.transform.stream.*;
37 import org.w3c.dom.*;
38
39 /**
40  * Class that realizes <B>save</B> action.
41  */

42 public class Save extends ActionBase {
43
44    public Save (PackageEditor editor) {
45       super(editor);
46    }
47
48    public Save (PackageEditor editor,String JavaDoc name) {
49       super(editor,name);
50    }
51
52    public void actionPerformed(ActionEvent JavaDoc e) {
53       saveDocumentIfPossible();
54    }
55
56    private void saveDocumentIfPossible () {
57       PackageEditor packageEditor=JaWE.getInstance().getPackageEditor();
58       if (!packageEditor.isInitialized()) {
59          packageEditor.enterPackageID();
60       }
61       packageEditor.displayPackage(packageEditor.getRealXMLPackage());
62
63       // check graph
64
boolean val=JaWEConfig.getInstance().getValidationStatus();
65       JaWE.getInstance().getXMLInterface().setValidation(true);
66       boolean isXPDLSchemaValidationError=!packageEditor.getGraph().validateAgainsXPDLSchema();
67       JaWE.getInstance().getXMLInterface().setValidation(val);
68       boolean isConnectionError=!packageEditor.getGraph().checkConnections(true);
69       boolean isGraphConformanceError=!packageEditor.getGraph().checkGraphConformance(true);
70       boolean isLogicError=!packageEditor.getGraph().checkLogic(true);
71
72       boolean isModelOK=!(isXPDLSchemaValidationError || isConnectionError ||
73             isGraphConformanceError || isLogicError);
74
75       if (!isModelOK) {
76          // gets Hashtable with error messages
77
Map connectionErrors=editor.getGraph().getConnectionErrorMessages();
78          java.util.List JavaDoc basicGraphConformanceErrors=editor.getGraph().getBasicGraphConformanceErrorMessages();
79          Map graphConformanceErrors=editor.getGraph().getGraphConformanceErrorMessages();
80          Map logicErrors=editor.getGraph().getLogicErrorMessages();
81
82          // Prints connection error messages contained in a given Hashtable.
83
// Hashtable has activity elements as a keys and it's error
84
// connection messages as a values.
85
String JavaDoc title=ResourceManager.getLanguageDependentString("DialogValidationReport");
86          ValidationErrorDisplay ved=new ValidationErrorDisplay(null, connectionErrors,
87                basicGraphConformanceErrors,graphConformanceErrors,logicErrors,
88                (JFrame)packageEditor.getWindow(),title,true);
89          if (ved.hasBeenStoped()) {
90             return;
91          }
92
93          //String msg=ResourceManager.getLanguageDependentString("WarningIncorrectPackageSaving");
94
//JaWE.getInstance().message(msg,JOptionPane.WARNING_MESSAGE);
95
}
96
97       if (packageEditor.allowInvalidPackageSaving() || isModelOK) {
98          String JavaDoc oldFilename=JaWE.getInstance().getFilename();
99          if (oldFilename==null) {
100             JaWE.getInstance().setFilename(
101                   JaWE.getInstance().saveDialog(
102                   ResourceManager.getLanguageDependentString("SaveAsLabel"),0,
103                   packageEditor.getGraph().get("Id").toString()));
104             packageEditor.update();
105          }
106          if (JaWE.getInstance().getFilename() != null) {
107             String JavaDoc filename=JaWE.getInstance().getFilename();
108
109             try {
110                org.enhydra.jawe.xml.elements.Package pkg=packageEditor.getRealXMLPackage();
111
112                // if SaveAs was performed and the document was previously saved,
113
// change ExternalPackage's relative paths
114
if (oldFilename==null && JaWE.getInstance().getXMLInterface().getAbsoluteFilePath(pkg)!=null) {
115                   boolean crossRefs=doesCrossreferenceExist(pkg);
116                   int r = JOptionPane.YES_OPTION;
117                   if (crossRefs) {
118                      r=JOptionPane.showConfirmDialog(packageEditor.getWindow(),
119                            ResourceManager.getLanguageDependentString("MessageCrossReferenceExistDoYouWantToProceed"),
120                            JaWE.getAppTitle(),JOptionPane.YES_NO_OPTION);
121                   }
122                   if (r==JOptionPane.YES_OPTION) {
123                      updateExternalPackagesRelativePaths(pkg,filename);
124                   } else {
125                      JaWE.getInstance().setFilename(null);
126                      return;
127                   }
128                }
129                // The extended attributes for all package elements must
130
// be updated.
131
Save.updateExtendedAttributesForWorkflowProcesses();
132                // set the XPDL version to 1.0
133
PackageHeader ph=(PackageHeader)pkg.get("PackageHeader");
134                ph.set("XPDLVersion","1.0");
135
136                Document document = null;
137
138                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
139                DocumentBuilder dbuilder = dbf.newDocumentBuilder();
140                document = dbuilder.newDocument();
141
142                // retrieve the file writter
143
RandomAccessFile raf=null;
144                if (JaWE.getInstance().getXMLInterface() instanceof XML) {
145                   raf=((XML)JaWE.getInstance().getXMLInterface()).getRaf(pkg);
146                }
147
148                // output stream will either be the FileOutputStream in the
149
// case of save as, or the ByteArrayOutputStream if we are
150
// saving an existing file
151
OutputStream os;
152                if (oldFilename==null) {
153                   if (JaWE.getInstance().getXMLInterface() instanceof XML) {
154                      // try to open random access file as rw, if it fails
155
// the saving shouldn't occur
156
try {
157                         File f=new File(filename);
158                         RandomAccessFile r=new RandomAccessFile(f,"rw");
159                         FileLock JavaDoc flck=r.getChannel().tryLock();
160                         flck.release();
161                         r.close(); // Harald Meister
162
// this exception happens when using jdk1.4 under Linux
163
// if it happens, just catch it and proceed with saving
164
// because Linux with jdk1.4.0 doesn't support locking
165
} catch (IOException ioe) {
166                      // this happens when the locking fails, and null is returned,
167
// and after that release method is called on the null;
168
// This means that the file we want to save the given
169
// package as, is already locked, so we do not allow saving
170
} catch (NullPointerException JavaDoc npe) {
171                         JaWE.getInstance().setFilename(null);
172                         throw new Exception JavaDoc();
173                      }
174                      // if we are at this point, this means either the locking
175
// succeeded, or we use jdk1.4 under Linux that does not
176
// support locking
177
os=new FileOutputStream(filename);
178                   } else {
179                      os=new FileOutputStream(filename);
180                   }
181                } else {
182                   if (JaWE.getInstance().getXMLInterface() instanceof XML) {
183                      os=new ByteArrayOutputStream();
184                   } else {
185                      os=new FileOutputStream(filename);
186                   }
187                }
188
189                // Here we get all document elements set
190
pkg.toXML(document);
191
192                // Use a Transformer for output
193
TransformerFactory tFactory =
194                      TransformerFactory.newInstance();
195                Transformer transformer = tFactory.newTransformer();
196                transformer.setOutputProperty("indent","yes");
197                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
198                transformer.setOutputProperty("encoding",JaWEConfig.getInstance().getEncoding());
199                DOMSource source = new DOMSource(document);
200                StreamResult result = new StreamResult(os);
201                transformer.transform(source,result);
202
203                if (oldFilename!=null && raf!=null && os instanceof ByteArrayOutputStream) {
204                   if (raf!=null) {
205                      // must go to the begining - otherwise, it will not
206
// truncate the file correctly in some Java-OS combination
207
raf.seek(0);
208                      raf.getChannel().truncate(0);
209                      raf.write(((ByteArrayOutputStream)os).toByteArray());
210                   }
211                }
212
213                os.close();
214
215                JaWE.getInstance().setModified(false);
216
217                if (oldFilename==null) {
218                   JaWE.getInstance().getXMLInterface().registerPackageFilename(filename,pkg);
219                }
220                try {
221                   System.setProperty("user.dir",JaWE.getInstance().getXMLInterface().getParentDirectory(pkg));
222                } catch (Exception JavaDoc ex) {}
223
224                try {
225                   JaWE.getInstance().addToRecentFiles(filename);
226                } catch (Exception JavaDoc ex) {}
227             } catch (Exception JavaDoc ex) {
228 //ex.printStackTrace();
229
JaWE.getInstance().message(
230                      ResourceManager.getLanguageDependentString("ErrorCannotSaveDocument"),
231                      JOptionPane.ERROR_MESSAGE);
232 //ex.printStackTrace();
233
}
234          }
235          packageEditor.update();
236          packageEditor.invalidate();
237       } else {
238          String JavaDoc msg=ResourceManager.getLanguageDependentString("ErrorCannotSaveIncorrectPackage");
239          JaWE.getInstance().message(msg,JOptionPane.ERROR_MESSAGE);
240       }
241    }
242
243    public static void updateExtendedAttributesForWorkflowProcesses () {
244       PackageEditor pkgEd=JaWE.getInstance().getPackageEditor();
245       org.enhydra.jawe.xml.elements.Package pkg=
246             pkgEd.getRealXMLPackage();
247       WorkflowProcess wp;
248       org.enhydra.jawe.graph.Process pr;
249       ProcessEditor pe;
250
251
252       Iterator wps=((WorkflowProcesses)pkg.get("WorkflowProcesses")).
253          toCollection().iterator();
254       while (wps.hasNext()) {
255          wp=(WorkflowProcess)wps.next();
256          pr=pkgEd.getProcessObject(wp);
257          pe=pr.getImplementationEditor();
258          updateExtendedAttributesForWorkflowProcess(wp,pe);
259       }
260    }
261
262    public static void updateExtendedAttributesForWorkflowProcess(WorkflowProcess wp,
263          ProcessEditor pe) {
264       updateActivitySets(pe);
265       updateActivitiesExtendedAttributes(pe);
266       updateTransitionsExtendedAttributes(pe);
267       wp.setVisuallySortedParticipantIDs(getParticipantsVisualOrder(pe));
268       wp.setStartDescriptions(Utils.getStartDescriptions(pe));
269       wp.setEndDescriptions(Utils.getEndDescriptions(pe));
270    }
271
272    private static void updateActivitySets (ProcessEditor pe) {
273       if (pe!=null) {
274          WorkflowManager wm=pe.getGraph().getWorkflowManager();
275          Set blockActs=wm.getBlockActivities(true);
276          Iterator it=blockActs.iterator();
277          while (it.hasNext()) {
278             BlockActivity ba=(BlockActivity)it.next();
279             ProcessEditor bwe=ba.getImplementationEditor();
280             updateActivitiesExtendedAttributes(bwe);
281             updateTransitionsExtendedAttributes(bwe);
282             org.enhydra.jawe.xml.elements.Activity bap=
283                (org.enhydra.jawe.xml.elements.Activity)
284                   ba.getUserObject();
285             bap.setVisuallySortedParticipantIDs(getParticipantsVisualOrder(bwe));
286             bap.setStartDescriptions(Utils.getStartDescriptions(bwe));
287             bap.setEndDescriptions(Utils.getEndDescriptions(bwe));
288          }
289       }
290    }
291
292    private static void updateActivitiesExtendedAttributes (ProcessEditor pe) {
293       if (pe!=null) {
294          WorkflowManager wm=pe.getGraph().getWorkflowManager();
295          Set allActs=JaWEGraphModel.getAllActivitiesInModel(wm.graphModel());
296          if (allActs!=null) {
297             Iterator it=allActs.iterator();
298             while (it.hasNext()) {
299                Activity a=(Activity)it.next();
300                // RECREATE OUTGOING TRANSITIONS OF ACTIVITY LOGIC TO SAVE
301
// TRANSITION REFS CORRECTLY
302
a.recreatePropertyObjectTransitions();
303                if (!(a instanceof Start) && !(a instanceof End)) {
304                   org.enhydra.jawe.xml.elements.Activity ap=
305                      (org.enhydra.jawe.xml.elements.Activity)a.getUserObject();
306                   // position
307
Point pOffset=wm.getOffset(a);
308                   ap.setXOffset(pOffset.x);
309                   ap.setYOffset(pOffset.y);
310                   // participant that is holding activities graph object
311
String JavaDoc Id=
312                      ((org.enhydra.jawe.xml.elements.Participant)
313                         ((Participant)a.getParent()).getUserObject()).getID();
314                   ap.setParticipantID(Id);
315                }
316             }
317          }
318       }
319    }
320
321    private static void updateTransitionsExtendedAttributes (ProcessEditor pe) {
322       if (pe!=null) {
323          WorkflowManager wm=pe.getGraph().getWorkflowManager();
324          Set allTransitions=JaWEGraphModel.getAllTransitionsInModel(wm.graphModel());
325          if (allTransitions!=null) {
326             Iterator it=allTransitions.iterator();
327             while (it.hasNext()) {
328                Transition tr=(Transition)it.next();
329                org.enhydra.jawe.xml.elements.Transition xmlT=
330                   (org.enhydra.jawe.xml.elements.Transition)
331                      tr.getUserObject();
332                Activity s=tr.getSourceActivity();
333                Activity t=tr.getTargetActivity();
334                if (s.getUserObject() instanceof XMLElement
335                      && t.getUserObject() instanceof XMLElement) {
336
337                   boolean isRouting=Utils.isRoutingTransition(tr.getAttributes());
338
339                   if (isRouting) {
340                      xmlT.setRoutingType(xmlT.SIMPLE_ROUTING);
341                   } else {
342                      xmlT.setRoutingType(xmlT.NO_ROUTING);
343                      TransitionView tv=(TransitionView)wm.getView(tr);
344                      int noOfPoints=tv.getPointCount();
345                      Hashtable pnts=new Hashtable();
346                      for (int j=1; j<noOfPoints-1; j++) {
347                         pnts.put(new Integer JavaDoc(j),new Point((int)tv.getPoint(j).getX(),(int)tv.getPoint(j).getY()));//HM, JGraph3.4.1
348
}
349                      xmlT.setBreakPoints(pnts);
350                   }
351                }
352             }
353          }
354       }
355    }
356
357    private static String JavaDoc getParticipantsVisualOrder (ProcessEditor pe) {
358       String JavaDoc visuallySortedParticipantIDs="";
359
360       if (pe!=null) {
361          WorkflowManager wm=pe.getGraph().getWorkflowManager();
362          ParticipantComparator pc=new ParticipantComparator(wm);
363          // gathering all visible participants in the WORKFLOW graph
364
Set allDeps=JaWEGraphModel.
365             getAllParticipantsInModel(pe.getGraph().getModel());
366          if (allDeps!=null) {
367             ArrayList gparts=new ArrayList();
368             gparts.addAll(allDeps);
369
370             Collections.sort(gparts,pc);
371
372             Iterator it=gparts.iterator();
373             String JavaDoc participantID;
374             while (it.hasNext()) {
375                participantID=((Participant)it.next()).get("Id").toString();
376                visuallySortedParticipantIDs+=(participantID+";");
377             }
378          }
379       }
380       return visuallySortedParticipantIDs;
381    }
382
383    private void updateExternalPackagesRelativePaths (
384    org.enhydra.jawe.xml.elements.Package pkg,String JavaDoc newFilename) {
385
386       File f=new File(newFilename);
387       String JavaDoc parentF=f.getParent();
388       Path newPath=new Path(parentF);
389
390       Iterator eps=((XMLCollection)pkg.get("ExternalPackages")).toCollection().iterator();
391       while (eps.hasNext()) {
392          ExternalPackage ep=(ExternalPackage)eps.next();
393          String JavaDoc oldRelativePath=ep.toString();
394          try {
395             org.enhydra.jawe.xml.elements.Package extP=
396                JaWE.getInstance().getXMLInterface()
397                   .getExternalPackageByRelativeFilePath(oldRelativePath,pkg);
398             String JavaDoc oldFullPath=JaWE.getInstance().getXMLInterface().getAbsoluteFilePath(extP);
399             String JavaDoc relativePath=Path.getRelativePath(new Path(oldFullPath),newPath);
400 //System.out.println("RP="+relativePath);
401
ExternalPackage.AttrHref HREF=(ExternalPackage.AttrHref)ep.get("href");
402             href.setPathDirectly(relativePath);
403          } catch (Exception JavaDoc ex) {
404 //ex.printStackTrace();
405
}
406       }
407 //XMLInterfaceFactory.getInstance().getXMLInterface().printDebug();
408
}
409
410    /**
411     * Returns <code>true</code> if there are crosreferences.
412     */

413    private boolean doesCrossreferenceExist (org.enhydra.jawe.xml.elements.Package pkg) {
414
415       boolean crossRefs=false;
416
417       Iterator eps=((XMLCollection)pkg.get("ExternalPackages")).toCollection().iterator();
418       while (eps.hasNext()) {
419          ExternalPackage ep=(ExternalPackage)eps.next();
420          String JavaDoc relativePath=ep.toString();
421          try {
422             org.enhydra.jawe.xml.elements.Package extP=
423                JaWE.getInstance().getXMLInterface().
424                   getExternalPackageByRelativeFilePath(relativePath,pkg);
425             if (extP.getAllExternalPackages().contains(pkg)) {
426                crossRefs=true;
427                break;
428             }
429          } catch (Exception JavaDoc ex) {}
430       }
431       return crossRefs;
432    }
433
434    //******************* PARTICIPANTCOMPARATOR CLASS **********************
435
/**
436    * Used to properly sort visual objects that represents Participant's
437    * contained within graph.
438    */

439    private static class ParticipantComparator implements Comparator {
440       WorkflowManager workflowManager;
441       public ParticipantComparator (WorkflowManager workflowManager) {
442          this.workflowManager=workflowManager;
443       }
444
445       public int compare(Object JavaDoc o1, Object JavaDoc o2) {
446          Participant p1=(Participant)o1;
447          Participant p2=(Participant)o2;
448          int y1=workflowManager.getBounds(p1,null).getBounds().y;//HM, JGraph3.4.1
449
int y2=workflowManager.getBounds(p2,null).getBounds().y;//HM, JGraph3.4.1
450

451          return (y1<y2 ? -1 : (y1==y2 ? 0 : 1));
452       }
453    }
454    //**************** END OF PARTICIPANTCOMPARATOR CLASS ******************
455

456
457 }
458
Popular Tags