package org.guvnor.common.services.backend.archive;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.guvnor.common.services.shared.file.upload.FileManagerFields;
import org.uberfire.server.BaseFilteredServlet;

public class ArchiveServlet
        extends BaseFilteredServlet {

    @Inject
    private Archiver archiver;

    protected void doGet( final HttpServletRequest request,
                          final HttpServletResponse response ) throws ServletException, IOException {
        final String uri = request.getParameter( FileManagerFields.FORM_FIELD_PATH );

        try {
            if ( uri != null ) {

                if ( !validateAccess( new URI( uri ), response ) ) {
                    return;
                }

                final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

                archiver.archive( outputStream, uri );

                response.setContentType( "application/zip" );
                response.setHeader( "Content-Disposition",
                                    "attachment; filename=download.zip" );

                response.setContentLength( outputStream.size() );
                response.getOutputStream().write( outputStream.toByteArray() );
                response.getOutputStream().flush();
            } else {
                response.sendError( HttpServletResponse.SC_BAD_REQUEST );
            }
        } catch ( URISyntaxException e ) {
            response.sendError( HttpServletResponse.SC_BAD_REQUEST );
        }
    }

}

@@ -975,16 +975,572 @@
      %7D%0A%0A
+                // Try to extract a meaningful name for the zip-file from the URI.%0A                int index = uri.lastIndexOf( %22@%22 ) + 1;%0A                if ( index %3C 0 ) index = 0;%0A                String downLoadFileName = uri.substring( index );%0A                if ( downLoadFileName.startsWith( %22/%22 ) ) downLoadFileName = downLoadFileName.substring( 1 );%0A                if ( downLoadFileName.endsWith( %22/%22 ) ) downLoadFileName = downLoadFileName.substring( 0, downLoadFileName.length() - 1 );%0A                downLoadFileName.replaceAll( %22/%22, %22_%22 );%0A%0A
         
@@ -1619,16 +1619,16 @@
 ream();%0A
-
 %0A       
@@ -1821,28 +1821,16 @@
         
-            
 %22attachm
@@ -1847,16 +1847,32 @@
 ame=
+%22 + 
 down
-l
+L
 oad
+FileName + %22
 .zip

Fix for BZ-1178731: give a more meaningful name to project explorer zip downloads.