Call GitHub API from Java Socket API part2

At the beginning

It is a continuation of Call Rest API of GitHub from Java Socket API Let's call the GitHub API that commits the file to the repository for GitHub from Java's Soceket API

Implementation notes

1. What to do before implementing Java logic

In order to make changes to the GitHub repository, you need to consider authentication when calling the GitHub API. This time we will authenticate with OAuth2 authentication, so we will issue a Personal access token on GitHub in advance (Detailed information on how to issue a Personal Access Token can be found on the reference site below.)

2. About Java logic

Points added from the previous implementation

The following processing has been added from Last implementation.

--Added logic to generate json to generate necessary parameters on GitHub --Added logic to convert files to commit to GitHub to Base64 format

Memo about the execution result

--If no authentication token is set, a 404 error will be returned --If you specify something other than PUT for the send method, a 404 error will be returned. --A 422 error is returned if the json parameter sent to GitHub is incorrect --Specify that the destination path must include files Specifying a directory returns a 422 error

Reference site

-I tried to summarize various things about Github API There is a description about basic authentication related to GitHub API. This is a site you should read when implementing the GitHub API.

Source

Test.java


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;


import com.fasterxml.jackson.databind.ObjectMapper;


public class Test {
	//Add files to your GitHub repository using GitHub's REST API v3
	//The format of REST API v3 is
	// /repos/:owner/:repo/contents/:path
	//Becomes
	private static final String ACCESS_KEY ="*********";
	private static final String GITHUB_RESTAPI_PATH = "https://api.github.com/repos/triple4649/images/contents/img/mypicture.png?access_token=%s";
	public static void main(String[] args) throws Exception {

		HttpsURLConnection con = createHttpsURLConnection(String.format(GITHUB_RESTAPI_PATH, ACCESS_KEY)
				,"PUT");

		//Commit the image file to GitHub with Rest API
		putContents(con,createJson());
		//Output header information of Rest API response
		printHeaderFields(con);
		//Output the result of Rest API response
		printBody(con);
		con.disconnect();
	}
	
	//Write JSON to Stream
	private static void putContents(HttpsURLConnection con,byte[] b) throws Exception{
		con.setDoOutput(true);
		OutputStream o = con.getOutputStream();
		o.write(b);
		o.flush();
	}
	
	//Converts a file with the specified path to Base64 format
	public static String converToBase64(String path)throws Exception{
		return Base64.getEncoder()
				.encodeToString(
						Files.readAllBytes(Paths.get(path)));
	}
	
	//Generate HttpsURLConnection by specifying HTTP send method
	private static HttpsURLConnection  createHttpsURLConnection (String path,String method) throws Exception{
		HttpsURLConnection con = createHttpsURLConnection (path);
		con.setRequestMethod(method);
		return con;
	}
	
	
	//Generate data to commit to GitHub
	private static byte[] createJson() throws Exception{
		Map <String,Object> map = new LinkedHashMap<String,Object>();
		Map <String,String> nestmap=new LinkedHashMap<String,String>();
		nestmap.put("name", "triple");
		nestmap.put("email", "[email protected]");
		map.put("committer",nestmap);
		map.put("message","GitHub API");
		map.put("content",converToBase64("./CA390046.JPG"));
		return new ObjectMapper()
		.writeValueAsBytes(map);
	}
	
	
	//Generate a URLConnection for a TLS connection(Unverified version of certification)
	//Request method is the default(Get)
	private static HttpsURLConnection  createHttpsURLConnection (String path) throws Exception{
		SSLSocketFactory factory = null;
		SSLContext ctx = SSLContext.getInstance("TLS");
		ctx.init(null, new NonAuthentication[] { new NonAuthentication() },
				null);
		factory = ctx.getSocketFactory();

		URL url = new URL(path);
		HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
		con.setSSLSocketFactory(factory);
		return con;
	}
	
	//Output header information
	private static void printHeaderFields(HttpsURLConnection con){
		con.getHeaderFields()
		.entrySet()
		.stream()
		.map(e->String.format("key:%s value:%s", e.getKey(),e.getValue()))
		.forEach(System.out::println);
	}
	
	//Output Body information
	private static void printBody(HttpsURLConnection con) throws Exception{
		new BufferedReader(new InputStreamReader(
				con.getInputStream()))
		.lines()
		.forEach(System.out::println);

	}
}

class NonAuthentication implements X509TrustManager {
	@Override
	public void checkClientTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
	}

	@Override
	public void checkServerTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
		return null;
	}
}

Recommended Posts

Call GitHub API from Java Socket API part2
Call TensorFlow Java API from Scala
Call GitHub's Rest API from Java's Socket API
Call Java from JRuby
Call Kotlin's sealed class from Java
Call API [Call]
Data processing using stream API from Java 8
Call Java library from C with JNI
API integration from Java with Jersey Client
Call Java method from JavaScript executed in Java
Call the Windows Notification API in Java
Hit the Salesforce REST API from Java
Getting Started with Java Starting from 0 Part 1
Call Java methods from Nim using jnim
Call the Microsoft Emotion API by sending image data directly from Java.
Call API [Preparation]
[Android] Call Kotlin's default argument method from Java
Java method call from RPG (method call in own class)
Call API [Handling]
Java Stream API
java practice part 1
Call Amazon Product Advertising API 5.0 (PA-API v5) in Java
Call a method with a Kotlin callback block from Java
Summary of Java communication API (1) How to use Socket
Call a program written in Swift from Processing (Java)
Quick learning Java "Introduction?" Part 3 Talking away from programming
Call API [Core Edition]
Pack API response (java)
[Java] Stream API / map
Eval Java source from Java
Docker-Client Java API Troubleshooting
Access API.AI from Java
Java8 Stream API practice
From Java to Ruby !!
Zabbix API in Java
Studying Java ~ Part 8 ~ Cast
JAVA constructor call processing
Cloud9 (Rails) from Github
Call this cat API of Metadata Co., Ltd. in Java.
JSON in Java and Jackson Part 1 Return JSON from the server
Implement Java Interface in JRuby class and call it from Java
How to call and use API in Java (Spring Boot)
[Kotlin] Get Java Constructor / Method from KFunction and call it