View Javadoc

1   /*
2    *  soapUI, copyright (C) 2004-2009 eviware.com 
3    *
4    *  soapUI is free software; you can redistribute it and/or modify it under the 
5    *  terms of version 2.1 of the GNU Lesser General Public License as published by 
6    *  the Free Software Foundation.
7    *
8    *  soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
9    *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
10   *  See the GNU Lesser General Public License for more details at gnu.org.
11   */
12  
13  package com.eviware.soapui.support.xml.actions;
14  
15  import java.awt.event.ActionEvent;
16  import java.io.File;
17  import java.io.FileWriter;
18  import java.io.IOException;
19  
20  import javax.swing.AbstractAction;
21  import javax.swing.Action;
22  
23  import org.apache.log4j.Logger;
24  import org.apache.xmlbeans.XmlException;
25  import org.apache.xmlbeans.XmlObject;
26  
27  import com.eviware.soapui.SoapUI;
28  import com.eviware.soapui.support.UISupport;
29  import com.eviware.soapui.support.xml.JXEditTextArea;
30  
31  /***
32   * Saves the XML of a JXmlTextArea to a file
33   * 
34   * @author Ole.Matzura
35   */
36  
37  public class SaveXmlTextAreaAction extends AbstractAction
38  {
39  	private final JXEditTextArea textArea;
40  	private String dialogTitle;
41  	private static final Logger log = Logger.getLogger( SaveXmlTextAreaAction.class );
42  
43  	public SaveXmlTextAreaAction( JXEditTextArea textArea, String dialogTitle )
44  	{
45  		super( "Save as.." );
46  		this.textArea = textArea;
47  		this.dialogTitle = dialogTitle;
48  		putValue( Action.ACCELERATOR_KEY, UISupport.getKeyStroke( "menu S" ) );
49  	}
50  
51  	public void actionPerformed( ActionEvent e )
52  	{
53  		File file = UISupport.getFileDialogs().saveAs( this, dialogTitle, ".xml", "XML Files (*.xml)", null );
54  		if( file == null )
55  			return;
56  
57  		FileWriter writer = null;
58  
59  		try
60  		{
61  			try
62  			{
63  				XmlObject xml = XmlObject.Factory.parse( textArea.getText() );
64  				xml.save( file );
65  			}
66  			catch( XmlException e1 )
67  			{
68  				writer = new FileWriter( file );
69  				writer.write( textArea.getText() );
70  				writer.close();
71  			}
72  
73  			log.info( "XML written to [" + file.getAbsolutePath() + "]" );
74  		}
75  		catch( IOException e1 )
76  		{
77  			UISupport.showErrorMessage( "Error saving xml to file: " + e1.getMessage() );
78  		}
79  		finally
80  		{
81  			if( writer != null )
82  			{
83  				try
84  				{
85  					writer.close();
86  				}
87  				catch( IOException e1 )
88  				{
89  					SoapUI.logError( e1 );
90  				}
91  			}
92  		}
93  	}
94  }