View Javadoc

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