View Javadoc

1   package org.semanticgov.ui.repository;
2   
3   import java.io.FileInputStream;
4   import java.util.*;
5   import java.util.List;
6   
7   import javax.wsdl.Definition;
8   import javax.wsdl.factory.WSDLFactory;
9   import javax.wsdl.xml.WSDLReader;
10  
11  import org.eclipse.jface.dialogs.MessageDialog;
12  import org.eclipse.jface.resource.JFaceResources;
13  import org.eclipse.swt.SWT;
14  import org.eclipse.swt.events.SelectionAdapter;
15  import org.eclipse.swt.events.SelectionEvent;
16  import org.eclipse.swt.graphics.Image;
17  import org.eclipse.swt.graphics.Point;
18  import org.eclipse.swt.layout.*;
19  import org.eclipse.swt.widgets.*;
20  import org.omwg.ontology.Ontology;
21  import org.semanticgov.ui.Activator;
22  import org.semanticgov.ui.editor.PAServiceModel;
23  import org.semanticgov.ui.wsdl.WSDLCache;
24  import org.wsmo.common.IRI;
25  import org.wsmo.common.TopEntity;
26  import org.wsmo.common.exception.SynchronisationException;
27  import org.wsmo.datastore.WsmoRepository;
28  import org.wsmo.execution.common.nonwsmo.WSDLDocument;
29  import org.wsmo.service.WebService;
30  import org.wsmostudio.repository.Registry;
31  import org.wsmostudio.runtime.*;
32  import org.wsmostudio.ui.Utils;
33  
34  import com.softwareag.repository.interfaces.CentraSiteWSDLRepository;
35  
36  public class RepositoryDialog {
37  
38      public static final String TARGET_REPOSITORY = "targetRepository";
39  	private PAServiceModel model;
40      
41      private Shell shell;
42      private Button uploadButton, 
43                     uploadServiceButton, 
44                     uploadOntologyButton, 
45                     uploadWSDLButton,
46                     uploadImportOntosButton;
47      private Combo chooser;
48      private Text callbackField;
49      private Map<String, WsmoRepository> repositoryMap = new HashMap<String, WsmoRepository>();
50      
51      
52      public RepositoryDialog(Shell parentShell, PAServiceModel uiModel, Text repositoryField) {
53          this.model = uiModel;
54          this.callbackField = repositoryField;
55          shell = new Shell(parentShell, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.SYSTEM_MODAL);
56          Image icon = JFaceResources.getImageRegistry().get(WsmoImageRegistry.DEFAULT_WINDOW_ICON);
57          shell.setImage(icon);
58          shell.setText("Repository Upload");
59          shell.setSize(500, 250);
60          shell.setLayout(new GridLayout(1, false));
61          
62          createContentPanel(shell);
63  
64          Composite buttons = new Composite(shell, SWT.NONE);
65          buttons.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END));
66          FillLayout layout = new FillLayout(SWT.HORIZONTAL);
67          layout.spacing = 3;
68          buttons.setLayout(layout);
69          
70          uploadButton = new Button(buttons, SWT.PUSH);
71          uploadButton.setText("Upload");
72          uploadButton.addSelectionListener(new SelectionAdapter() {
73              public void widgetSelected(SelectionEvent e) {
74                  try {
75                      doUploadService();
76                  }
77                  catch(Exception ime) {
78                      MessageDialog.openError(shell, "Error", ime.getMessage());
79                      LogManager.logError(ime);
80                      return;
81                  }
82              }
83          });
84          updateUploadButton();
85          Button closeButton = new Button(buttons, SWT.PUSH);
86          closeButton.setText("Close");
87          closeButton.addSelectionListener(new SelectionAdapter() {
88              public void widgetSelected(SelectionEvent e) {
89                  shell.dispose();
90              }
91          });
92          
93          Point pLocation = parentShell.getLocation();
94          Point pSize = parentShell.getSize();
95          shell.setLocation(pLocation.x + pSize.x / 2 - shell.getSize().x / 2,
96                  pLocation.y + pSize.y / 2 - shell.getSize().y / 2);
97  
98      }
99      
100     public void open() {
101         shell.open();
102         Display display = shell.getDisplay();
103         while (!shell.isDisposed()) {
104             if (!display.readAndDispatch()) {
105                 display.sleep();
106             }
107         }
108     }
109     
110     private void createContentPanel(Composite parent) {
111         Group uploadPreferencesPanel = new Group(parent, SWT.NONE);
112         uploadPreferencesPanel.setLayoutData(new GridData(GridData.FILL_BOTH));
113         uploadPreferencesPanel.setLayout(new GridLayout(2, false));
114         new Label(uploadPreferencesPanel, SWT.NONE).setText("Target Repository : ");
115         chooser = new Combo(uploadPreferencesPanel, SWT.DROP_DOWN | SWT.READ_ONLY);
116         
117         List<String> allNames = new LinkedList<String>();  
118         for (WsmoRepository rep : Registry.getInstance().getRepositoriesData().keySet()) {
119         	allNames.add(rep.getDescription());
120         	this.repositoryMap.put(rep.getDescription(), rep);
121         }
122         chooser.setItems(allNames.toArray(new String[allNames.size()]));
123         chooser.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
124         String sel = 
125         	Activator.getDefault().getPreferenceStore().getString(TARGET_REPOSITORY);
126         if (allNames.indexOf(sel) != -1) {
127         	chooser.select(allNames.indexOf(sel));
128         }
129         chooser.addSelectionListener(new SelectionAdapter() {
130         	public void widgetSelected(SelectionEvent e) {
131         		Activator.getDefault().getPreferenceStore().setValue(TARGET_REPOSITORY, 
132         				chooser.getItem(chooser.getSelectionIndex()));
133         		callbackField.setText(chooser.getItem(chooser.getSelectionIndex()));
134         		uploadButton.setEnabled(true);
135         		updateWSDLUpload();
136         	}
137         });
138         
139         
140         new Label(uploadPreferencesPanel, SWT.NONE);
141         new Label(uploadPreferencesPanel, SWT.NONE);
142         
143         Group optionsPanel = new Group(uploadPreferencesPanel, SWT.NONE);
144         optionsPanel.setText("Options");
145         GridData gData = new GridData(GridData.FILL_BOTH);
146         gData.horizontalSpan = 2;
147         optionsPanel.setLayoutData(gData);
148         optionsPanel.setLayout(new GridLayout(1, false));
149         
150         uploadServiceButton = new Button(optionsPanel, SWT.CHECK);
151         uploadServiceButton.setText("Upload WebService (" 
152         		+ model.getServiceDescription().getIdentifier().toString() + ")");
153         uploadServiceButton.setSelection(true);
154         uploadServiceButton.addSelectionListener(new SelectionAdapter() {
155         	public void widgetSelected(SelectionEvent e) {
156         		updateUploadButton();
157         	}
158         });
159         
160         uploadOntologyButton = new Button(optionsPanel, SWT.CHECK);
161         uploadOntologyButton.setText("Upload Ontology (" 
162         		+ model.getInstanceOntology().getIdentifier().toString() + ")");
163         uploadOntologyButton.setSelection(true);
164         uploadOntologyButton.addSelectionListener(new SelectionAdapter() {
165         	public void widgetSelected(SelectionEvent e) {
166         		updateUploadButton();
167         	}
168         });
169 
170         uploadWSDLButton = new Button(optionsPanel, SWT.CHECK);
171         String wsdlLabel = "Upload WSDL";
172         if (model.getWSDL() != null 
173         		&& model.getWSDL().length() > 0) {
174         	wsdlLabel += " (" + model.getWSDL() + ')';
175         }
176         updateWSDLUpload();
177         uploadWSDLButton.setText(wsdlLabel);
178         uploadWSDLButton.setSelection(uploadWSDLButton.isEnabled());
179         uploadWSDLButton.addSelectionListener(new SelectionAdapter() {
180         	public void widgetSelected(SelectionEvent e) {
181         		updateUploadButton();
182         	}
183         });
184         
185         uploadImportOntosButton = new Button(optionsPanel, SWT.CHECK);
186 
187         uploadImportOntosButton.setText("Upload imported ontologies (if necessary)");
188         uploadImportOntosButton.setSelection(true);
189         
190         updateUploadButton();
191     }
192     
193     private void doUploadService() {
194     	Ontology onto = null;
195     	if (uploadOntologyButton.getSelection()) {
196     		onto = model.getInstanceOntology();
197     	}
198     	WebService service = null;
199     	if (uploadServiceButton.getSelection()) {
200     		service = (WebService)model.getServiceDescription();
201     	}
202     	String wsdlTargetNamespace = null;
203     	WSDLDocument wsdlDoc = null;
204     	if (uploadWSDLButton.getSelection() 
205     			&& uploadWSDLButton.getEnabled()) {
206     		wsdlTargetNamespace = model.getWSDL();
207     		try {
208     		    wsdlDoc = readWSDLDocument(wsdlTargetNamespace);
209     		}
210     		catch(Exception ex) {
211     			if (false == MessageDialog.openConfirm(shell, 
212     					"Error Loading WSDL", 
213     					"Loading WSDL document failed:\n" 
214     					+ ex.getMessage()
215     					+ "\nProceed uploading wsmo descriptions?")) {
216     				return;
217     			}
218     		}
219     	}
220     	
221     	boolean uploadImportedOntos = 
222     	    (onto != null || service != null) 
223     	        && this.uploadImportOntosButton.getSelection();
224     	
225         WsmoRepository targetRepository = this.repositoryMap.get(
226             	Activator.getDefault().getPreferenceStore().getString(TARGET_REPOSITORY));
227     	if (targetRepository == null) {
228     	    return;
229     	}
230     	if (false == Registry.getInstance().configureRepository(targetRepository, false)) {
231             return; // cancelled or error reported
232         }
233     	
234     	List<IRI> existingOntos = null;
235     	Set<String> failures = null;
236     	if (uploadImportedOntos) {
237     	    existingOntos = targetRepository.listOntologies();
238     	    failures = new HashSet<String>();
239     	}
240     	
241     	StringBuffer reportMsg = new StringBuffer("Uploading process report:\n\n");
242     	if (onto != null) {
243     		reportMsg.append("   - ontology (").append(onto.getIdentifier().toString()).append(" ) ... ");
244         	try {
245     	    	targetRepository.addOntology(onto);
246     	    	reportMsg.append("done.\n");
247     	    	if (uploadImportedOntos) {
248     	    	    uploadImportedOntos(onto, 
249     	    	            targetRepository, 
250     	    	            existingOntos,
251                             failures);
252     	    	}
253     	    }
254         	catch(SynchronisationException ex) {
255         		LogManager.logError(ex);
256         		MessageDialog.openError(shell, "Upload Ontology", 
257         				"Error uploading ontology:\n" + ex.getMessage());
258     	    	reportMsg.append("failed!\n");
259         	}
260     	}
261     	if (service != null) {
262     		reportMsg.append("   - webservice (").append(service.getIdentifier().toString()).append(" ) ... ");
263         	
264     		boolean uploadSuccess = false;
265     		if (wsdlDoc != null 
266     				&& targetRepository instanceof CentraSiteWSDLRepository) {
267     			// a specific case for the CentraSite repository/registry 
268         		try {
269         	    	((CentraSiteWSDLRepository)targetRepository).registerWSDL(
270         	    			service, wsdlDoc);
271             		reportMsg.append("done.\n   - WSDL( ").append(wsdlTargetNamespace).append(" )... done.\n");
272             		uploadSuccess = true;
273         	    }
274             	catch(Exception ex) {
275             		LogManager.logError(ex);
276             		MessageDialog.openError(shell, "Upload WebService", 
277             				"Error registering webservice and WSDL at CentraSite:\n" + ex.getMessage());
278         	    	reportMsg.append("failed!\n   - WSDL( ").append(wsdlTargetNamespace).append(" )... failed.\n");
279             	}
280     			
281     		}
282     		else {
283         		try {
284         	    	targetRepository.addWebService(service);
285     	        	reportMsg.append("done.\n");
286                     uploadSuccess = true;
287     	        }
288         	    catch(SynchronisationException ex) {
289         		    LogManager.logError(ex);
290         		    MessageDialog.openError(shell, "Upload WebService", 
291         			    	"Error uploading webservice:\n" + ex.getMessage());
292     	    	    reportMsg.append("failed!\n");
293         	    }
294     		}
295             if (uploadImportedOntos 
296                     && uploadSuccess) {
297                 uploadImportedOntos(service, 
298                         targetRepository, 
299                         existingOntos,
300                         failures);
301             }
302     	}
303     	
304     	if (wsdlDoc != null 
305     			&& service == null 
306     			&& targetRepository instanceof CentraSiteWSDLRepository) {
307     		reportMsg.append("   - WSDL( ").append(wsdlTargetNamespace).append(" )... ");
308     		try {
309     			((CentraSiteWSDLRepository)targetRepository).registerWSDL(null, 
310     					wsdlDoc);
311     			reportMsg.append("done.\n");
312     		}
313     		catch(Exception ex) {
314         		LogManager.logError(ex);
315         		MessageDialog.openError(shell, "Upload WSDL", 
316         				"Error uploading WSDL file:\n" + ex.getMessage());
317     	    	reportMsg.append("failed!\n");
318     		}
319     		
320     		MessageDialog.openWarning(shell, "Unsupported Operation", 
321     				"WSDL files can not be uploaded on regular WSMO repositories.");
322     		reportMsg.append("   - WSDL( ").append(wsdlTargetNamespace).append(" )... not supported!");
323     	}
324     	
325     	if (uploadImportedOntos 
326     	        && failures.size() > 0) {
327     	    StringBuffer warnMsg = 
328     	        new StringBuffer("One or more imported ontologies were not sucessfully uploaded"
329     	                + " (either not found in workspace or unsuccessfully parsed):\n");
330     	    for(String ontoRef : failures) {
331     	        warnMsg.append('\n').append('-').append(ontoRef);
332     	    }
333     	    warnMsg.append("\n\nCheck error log files for details!");
334     	    MessageDialog.openWarning(shell, 
335     	            "Upload Imported Ontologies", 
336     	            warnMsg.toString());
337     	}
338     	
339     	if (reportMsg.toString().length() > 27) {
340     		MessageDialog.openInformation(shell, "Upload Results", reportMsg.toString());
341     		shell.dispose();
342     	}
343     	else {
344     		MessageDialog.openWarning(shell, "Upload Results", "Nothing selected for uploading!");
345     	}
346     }
347     
348     private void updateUploadButton() {
349     	if (uploadButton == null) {
350     		return;
351     	}
352         uploadButton.setEnabled(
353         		this.chooser.getSelectionIndex() >= 0 
354         		&& this.chooser.getItem(this.chooser.getSelectionIndex()).trim().length() > 0
355         		&& (this.uploadOntologyButton.getSelection() 
356         				|| this.uploadServiceButton.getSelection() 
357         				|| this.uploadWSDLButton.getSelection()));
358     }
359     
360     private void updateWSDLUpload() {
361     	if (this.uploadWSDLButton == null) {
362     		return;
363     	}
364     	if (this.chooser.getSelectionIndex() < 0 
365         		|| this.chooser.getItem(this.chooser.getSelectionIndex()).trim().length() == 0
366         		|| this.model.getWSDL() == null
367         		|| this.model.getWSDL().trim().length() == 0) {
368     		this.uploadWSDLButton.setEnabled(false);
369     		return;
370     	}
371     	
372     	WsmoRepository selectedRepo = this.repositoryMap.get(this.chooser.getSelectionIndex());
373         this.uploadWSDLButton.setEnabled(selectedRepo instanceof CentraSiteWSDLRepository);
374     }
375     
376     private WSDLDocument readWSDLDocument(String uri) throws Exception {
377 
378     	WSDLReader wsdlReader = WSDLFactory.newInstance().newWSDLReader();
379     	String filePath = WSDLCache.getCache().getWSDLFile(uri);
380     	// get the definition ... the main root of the wsdl file
381     	Definition wsdlDef = wsdlReader.readWSDL(filePath);
382     	if (wsdlDef == null) {
383     		throw new Exception("Unable to read the input file or URL (" + filePath + ")");
384     	}
385     	
386     	FileInputStream inStream = new FileInputStream(filePath);
387     	byte[] data = new byte[inStream.available()];
388     	inStream.read(data);
389     	return new WSDLDocument(new String(data));
390     }
391     
392     private void uploadImportedOntos(TopEntity te, 
393                                      WsmoRepository repo, 
394                                      List<IRI> oldOntos,
395                                      Set<String> failures) {
396         for(Ontology iOnto : te.listOntologies()) {
397             if (oldOntos.contains(iOnto.getIdentifier())) {
398                 continue; // already exists in the remote repository
399             }
400             if (Utils.isAProxy(iOnto)) {
401                 WSMORuntime.getIOManager().doLoadOntology(iOnto.getIdentifier(), true);
402             }
403             if (Utils.isAProxy(iOnto)) { // ontology not found in workspace ?
404                 failures.add(iOnto.getIdentifier().toString());
405                 continue;
406             }
407             try {
408                 repo.addOntology(iOnto);
409                 oldOntos.add((IRI)iOnto.getIdentifier());
410             }
411             catch(Throwable error) {
412                 LogManager.logError(error);
413                 failures.add(iOnto.getIdentifier().toString());
414             }
415         }
416     }
417 }