001    package railo.commons.io.res.type.s3;
002    
003    import java.io.IOException;
004    import java.io.OutputStream;
005    import java.net.SocketException;
006    
007    import railo.commons.io.TemporaryStream;
008    import railo.commons.lang.ExceptionUtil;
009    import railo.commons.lang.StringUtil;
010    import railo.commons.net.http.httpclient3.HTTPEngine3Impl;
011    
012    public final class S3ResourceOutputStream extends OutputStream {
013            
014            private final S3 s3;
015            
016            private final String contentType="application";
017            private final String bucketName;
018            private final String objectName;
019            private final int acl;
020    
021            private TemporaryStream ts;
022            
023            public S3ResourceOutputStream(S3 s3,String bucketName,String objectName,int acl) {
024                    this.s3=s3;
025                    this.bucketName=bucketName;
026                    this.objectName=objectName;
027                    this.acl=acl;
028                    
029                    ts = new TemporaryStream();
030            }
031            
032            @Override
033            public void close() throws IOException {
034                    ts.close();
035                    
036                    //InputStream is = ts.getInputStream();
037                    try {
038                            s3.put(bucketName, objectName, acl, HTTPEngine3Impl.getTemporaryStreamEntity(ts,contentType));
039                    } 
040    
041                    catch (SocketException se) {
042                            String msg = StringUtil.emptyIfNull(se.getMessage());
043                            if(StringUtil.indexOfIgnoreCase(msg, "Socket closed")==-1)
044                                    throw se;
045                    }
046                    catch (Exception e) {
047                            throw ExceptionUtil.toIOException(e);
048                    }
049            }
050    
051            @Override
052            public void flush() throws IOException {
053                    ts.flush();
054            }
055    
056            @Override
057            public void write(byte[] b, int off, int len) throws IOException {
058                    ts.write(b, off, len);
059            }
060    
061            @Override
062            public void write(byte[] b) throws IOException {
063                    ts.write(b);
064            }
065    
066            @Override
067            public void write(int b) throws IOException {
068                    ts.write(b);
069            }
070    }