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.impl.wsdl.submit.transports.http.support.attachments;
14  
15  import java.io.ByteArrayOutputStream;
16  import java.io.IOException;
17  import java.io.OutputStream;
18  
19  import javax.mail.MessagingException;
20  import javax.mail.internet.MimeMessage;
21  import javax.mail.internet.MimeMultipart;
22  
23  import org.apache.commons.httpclient.methods.RequestEntity;
24  
25  import com.eviware.soapui.SoapUI;
26  import com.eviware.soapui.impl.support.http.HttpRequestInterface;
27  
28  /***
29   * MimeMessage request class
30   * 
31   * @author ole.matzura
32   */
33  
34  public class RestRequestMimeMessageRequestEntity implements RequestEntity
35  {
36  	private final MimeMessage message;
37  	private byte[] buffer;
38  	private final HttpRequestInterface<?> restRequest;
39  
40  	public RestRequestMimeMessageRequestEntity( MimeMessage message, HttpRequestInterface<?> restRequest )
41  	{
42  		this.message = message;
43  		this.restRequest = restRequest;
44  	}
45  
46  	public long getContentLength()
47  	{
48  		try
49  		{
50  			ByteArrayOutputStream out = new ByteArrayOutputStream();
51  			writeRequest( out );
52  			buffer = out.toByteArray();
53  			return buffer.length;
54  		}
55  		catch( Exception e )
56  		{
57  			SoapUI.logError( e );
58  			return -1;
59  		}
60  	}
61  
62  	public String getContentType()
63  	{
64  		try
65  		{
66  			String header = message.getHeader( "Content-Type" )[0];
67  			int ix = header.indexOf( "boundary" );
68  
69  			return restRequest.getMediaType() + "; " + header.substring( ix );
70  		}
71  		catch( MessagingException e )
72  		{
73  			SoapUI.logError( e );
74  		}
75  
76  		return restRequest.getMediaType();
77  	}
78  
79  	public boolean isRepeatable()
80  	{
81  		return true;
82  	}
83  
84  	public void writeRequest( OutputStream arg0 ) throws IOException
85  	{
86  		try
87  		{
88  			if( buffer == null )
89  			{
90  				arg0.write( "\r\n".getBytes() );
91  				( ( MimeMultipart )message.getContent() ).writeTo( arg0 );
92  			}
93  			else
94  				arg0.write( buffer );
95  		}
96  		catch( Exception e )
97  		{
98  			SoapUI.logError( e );
99  		}
100 	}
101 }