GitHub.java [src/m/utils/test/github] Revision: default  Date:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package m.utils.test.github;

import csip.api.server.ServiceException;
import java.io.InputStream;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.codehaus.jettison.json.JSONObject;

/**
 *
 * @author ktraff
 */
public class GitHub {
    
    protected static final Logger LOG = Logger.getLogger(GitHub.class.getSimpleName());
    
    public static Gist createGist(String gistName, String descr, String fileContents) throws ServiceException {
        try {
            JSONObject content = new JSONObject();
            content.put("description", descr);
            content.put("public", true);
            JSONObject files = new JSONObject();
            JSONObject file = new JSONObject();
            file.put("content", fileContents);
            files.put(gistName, file);
            content.put("files", files);
            JSONObject result = post("https://api.github.com/gists", content);
            Gist newGist = new Gist(result.getString("id"), result.getString("url"));
            return newGist;
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }
    
    /**
     * Needed to implement this method over using the core <code>Client</code> library
     * because POST requests wrap the JSON in a parameter, which is invalid for Github API.
     * @param githubRequest
     * @return 
     */
    public static JSONObject post(String url, JSONObject githubRequest) throws ServiceException {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost request = new HttpPost(url);
        
        try {
            StringEntity params =new StringEntity(githubRequest.toString(2));
            request.addHeader("Content-Type", "application/json");
            request.setEntity(params);
            HttpResponse response = httpClient.execute(request);
            InputStream responseStream = response.getEntity().getContent();
            JSONObject content = new JSONObject(IOUtils.toString(responseStream));
//            LOG.log(Level.INFO, "Response: " + content.toString(2));
            return content;
        }catch (Exception ex) {
            throw new ServiceException(ex);
        } finally {
            request.releaseConnection();
        }
    }
    
}