/**
 *  Copyright 2005-2016 Red Hat, Inc.
 *
 *  Red Hat licenses this file to you under the Apache License, version
 *  2.0 (the "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 *  implied.  See the License for the specific language governing
 *  permissions and limitations under the License.
 */
package io.fabric8.git.http;

import io.fabric8.zookeeper.ZkPath;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

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

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.shared.SharedCount;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.http.server.GitServlet;
import org.eclipse.jgit.lib.Ref;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings("serial")
public class FabricGitServlet extends GitServlet {

    private static final Logger LOGGER = LoggerFactory.getLogger(FabricGitServlet.class);
    
    private final CuratorFramework curator;
    private SharedCount counter;
    private Git git;

    FabricGitServlet(Git git, CuratorFramework curator) {
        this.curator = curator;
        this.git = git;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        try {
            counter = new SharedCount(curator, ZkPath.GIT_TRIGGER.getPath(), 0);
            counter.start();
        } catch (Exception ex) {
            handleException(ex);
        }
    }

    protected void handleException(Exception ex) throws ServletException {
        if(ex instanceof IllegalStateException && "Client is not started".equals(ex.getMessage())){
            LOGGER.debug("", ex);
            throw new ServletException("Error starting SharedCount. ZK Client is not Started");
        }else{
            LOGGER.error("Error starting SharedCount", ex);
            throw new ServletException("Error starting SharedCount", ex);
        }
    }

    @Override
    public void destroy() {
        super.destroy();
        try {
            counter.close();
        } catch (IOException ex) {
            LOGGER.warn("Error closing SharedCount due to: " + ex + ". This exception is ignored.");
        }
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        LOGGER.debug("GitHttp service req={}", req);
        super.service(req, res);
        LOGGER.debug("GitHttp service res={}", res);
        
        // Ignore unwanted service requests
        String resContentType = res.getContentType();
        if (resContentType.contains("x-git-receive-pack-result")) {
            
            LOGGER.info("GitHttp service res={}", res);
            
            int httpStatus = 0;
            try {
                Method method = res.getClass().getMethod("getStatus");
                httpStatus = (Integer) method.invoke(res, new Object[] {});
            } catch (Exception ex) {
                LOGGER.error("Cannot obtain http response code: " + ex);
            }
            
            if (httpStatus == HttpServletResponse.SC_OK) {
                try {
                    List<Ref> refs = git.branchList().call();
                    LOGGER.info("Remote git content updated: {}", refs);
                    while (!counter.trySetCount(counter.getCount() + 1));
                } catch (Exception ex) {
                    LOGGER.debug("Error incrementing shared counter: " + ex + ". This exception is ignored.", ex);
                    LOGGER.warn("Error incrementing shared counter: " + ex + ". This exception is ignored.");
                }
            }
        } 
    }
}

@@ -1413,20 +1413,16 @@
 class);%0A
-    
 %0A    pri
@@ -2814,16 +2814,653 @@
 eption %7B
+%0A        /*%0A         * %60git push%60 uses two exchanges in smart http protocol:%0A         * 1) preparing for push - this checks current state of branches on remote side%0A         *   %3E GET /jgit/_test-repo/info/refs?service=git-receive-pack HTTP/1.1%0A         *%0A         *   %3C Content-Type: application/x-git-receive-pack-advertisement%0A         * 2) actual push of crafted PACK file with changes to references being pushed%0A         *   %3E POST /jgit/_test-repo/git-receive-pack HTTP/1.1%0A         *   %3E Content-Type: application/x-git-receive-pack-request%0A         *%0A         *   %3C Content-Type: application/x-git-receive-pack-result%0A         */
 %0A%0A      
@@ -3592,24 +3592,16 @@
 , res);%0A
-        
 %0A       
@@ -3759,29 +3759,16 @@
 lt%22)) %7B%0A
-            %0A
         
@@ -3815,28 +3815,16 @@
 , res);%0A
-            
 %0A       
@@ -3997,25 +3997,8 @@
 (res
-, new Object%5B%5D %7B%7D
 );%0A 
@@ -4120,28 +4120,16 @@
       %7D%0A
-            
 %0A       
@@ -4176,24 +4176,75 @@
 se.SC_OK) %7B%0A
+                if (LOGGER.isDebugEnabled()) %7B%0A    
             
@@ -4245,32 +4245,36 @@
           try %7B%0A
+    
                 
@@ -4339,27 +4339,32 @@
         
+    
 LOGGER.
-info
+debug
 (%22Remote
@@ -4393,24 +4393,136 @@
 %7B%7D%22, refs);%0A
+                    %7D catch (Exception ignored) %7B%0A                    %7D%0A                %7D%0A                try %7B%0A
             
@@ -4581,16 +4581,17 @@
 () + 1))
+ 
 ;%0A      
@@ -4617,32 +4617,87 @@
 Exception ex) %7B%0A
+                    if (LOGGER.isDebugEnabled()) %7B%0A    
                 
@@ -4787,32 +4787,54 @@
 ignored.%22, ex);%0A
+                    %7D%0A
                 
@@ -4972,14 +4972,14 @@
    %7D
- 
 %0A    %7D%0A
+%0A
 %7D%0A

Optimize git access in FabricGitServlet