package de.saumya.mojo.rubygems;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.sonatype.nexus.ruby.FileType;
import org.sonatype.nexus.ruby.GemArtifactFile;
import org.sonatype.nexus.ruby.RubygemsFile;
import org.sonatype.nexus.ruby.cuba.RubygemsFileSystem;
import org.sonatype.nexus.ruby.layout.Storage;

public class LegacyRubygemsServlet extends RubygemsServlet
{
    private static final long serialVersionUID = 2441264980328145654L;

    private static final String RUBYGEMS_S3_URL = "http://s3.amazonaws.com/production.s3.rubygems.org/gems/";
 
    @Override
    public void init() throws ServletException {
        super.init();
        
        this.fileSystem = (RubygemsFileSystem) getServletContext().getAttribute( RubygemsFileSystem.class.getName() );
        this.storage = (Storage) getServletContext().getAttribute( Storage.class.getName());
    }
    
    protected void handle( HttpServletRequest req, HttpServletResponse resp, RubygemsFile file ) 
            throws IOException, ServletException
    {
        if ( file.type() == FileType.GEM_ARTIFACT )
        {
            // use a non https url here since IVY can not handle
            // redirects from https to http
            // https://github.com/torquebox/rubygems-servlets/issues/11
            resp.sendRedirect( RUBYGEMS_S3_URL + ((GemArtifactFile) file ).gem( null ).filename() + ".gem" );
        }
        else
        {
            super.handle( req, resp, file );
        }
    }
}

@@ -54,16 +54,103 @@
 ception;
+%0Aimport java.net.HttpURLConnection;%0Aimport java.net.URL;%0Aimport java.net.URLConnection;
 %0A%0Aimport
@@ -1488,26 +1488,474 @@
     
-resp.sendRedirect(
+URL url = new URL(%22https://rubygems.org/gems/%22 + ((GemArtifactFile) file ).gem( null ).filename() + %22.gem%22 );%0A            HttpURLConnection con = (HttpURLConnection) url.openConnection();%0A            con.setRequestMethod(%22HEAD%22);%0A            con.setInstanceFollowRedirects(false);%0A            String location = con.getHeaderField(%22Location%22);%0A            if (location == null) %7B%0A                // use the old hardcoded storage as fallback%0A                location =
  RUB
@@ -2018,32 +2018,87 @@
 ename() + %22.gem%22
+;%0A            %7D%0A            resp.sendRedirect( location
  );%0A        %7D%0A  

make the redirect to rubygems.org manually for legacy servlet