View Javadoc

1   /*
2    *  soapUI, copyright (C) 2004-2010 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.IOException;
18  
19  import javax.swing.AbstractAction;
20  import javax.swing.Action;
21  
22  import org.apache.commons.codec.binary.Base64;
23  import org.apache.commons.io.FileUtils;
24  
25  import com.eviware.soapui.support.UISupport;
26  import com.eviware.soapui.support.xml.JXEditTextArea;
27  
28  /***
29   * Inserts a file as base64 into a JXmlTextArea at the current cursor position.
30   * 
31   * @author Cory Lewis
32   * @author Ole.Matzura
33   */
34  
35  public class InsertBase64FileTextAreaAction extends AbstractAction
36  {
37  	private final JXEditTextArea textArea;
38  	private String dialogTitle;
39  
40  	public InsertBase64FileTextAreaAction( JXEditTextArea textArea, String dialogTitle )
41  	{
42  		super( "Insert file as Base64" );
43  
44  		this.textArea = textArea;
45  		this.dialogTitle = dialogTitle;
46  		putValue( Action.ACCELERATOR_KEY, UISupport.getKeyStroke( "menu G" ) );
47  	}
48  
49  	public void actionPerformed( ActionEvent e )
50  	{
51  		File file = UISupport.getFileDialogs().open( this, dialogTitle, null, null, null );
52  		if( file == null )
53  			return;
54  
55  		try
56  		{
57  			// read file
58  			byte[] ba = FileUtils.readFileToByteArray( file );
59  
60  			// convert to base 64
61  			Base64 b64 = new Base64();
62  			String hex = new String( b64.encode( ba ) );
63  			// insert into text at cursor position
64  			int pos = textArea.getCaretPosition();
65  			StringBuffer text = new StringBuffer( textArea.getText() );
66  			text.insert( pos, hex );
67  			textArea.setText( text.toString() );
68  
69  		}
70  		catch( IOException e1 )
71  		{
72  			UISupport.showErrorMessage( "Error reading from file: " + e1.getMessage() );
73  		}
74  	}
75  
76  }