package org.netmelody.cii.witness.jenkins;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.netmelody.cii.witness.protocol.RestRequester;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JenkinsCommunicator {

    private static final Log LOG = LogFactory.getLog(JenkinsCommunicator.class);
    
    private final Gson json = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create();
    private final RestRequester restRequester = new RestRequester();
    private final String endpoint;

    public JenkinsCommunicator(String endpoint) {
        this.endpoint = endpoint;
    }
    
    public <T> T makeJenkinsRestCallWithSuffix(String urlSuffix, Class<T> type) {
        return makeJenkinsRestCall(endpoint + ((urlSuffix.length() == 0) ? "" : ("/" + urlSuffix)), type);
    }
    
    public <T> T makeJenkinsRestCall(String url, Class<T> type) {
        final String reqUrl = url + (url.endsWith("/") ? "" : "/") + "api/json";
        T result = json.fromJson(restRequester.makeRequest(reqUrl), type);
        
        if (null == result) {
            LOG.warn("null result for json request: " + url);
            try {
                result = type.newInstance();
            }
            catch (Exception e) {
                LOG.error("Failed to instantiate " + type.getName());
            }
        }
        
        return result;
    }
    
    public String endpoint() {
        return endpoint;
    }
}

@@ -1017,16 +1017,25 @@
 /json%22;%0A
+        %0A
         
@@ -1049,63 +1049,321 @@
 t = 
-json.fromJson(restRequester.makeRequest(reqUrl), type);
+null;%0A        String content = %22%22;%0A        try %7B%0A            content = restRequester.makeRequest(reqUrl);%0A            result = json.fromJson(content, type);%0A        %7D%0A        catch (Exception e) %7B%0A            LOG.error(String.format(%22Failed to parse json from (%25s) of:%5Cn %25s%22, reqUrl, content));%0A        %7D%0A        
 %0A   
@@ -1454,17 +1454,20 @@
 st: %22 + 
-u
+reqU
 rl);%0A   

make the jenkins rest requests safe in the face of malformed json