Thursday, February 8, 2018

Running CURL through Java: Windows and Linux Executions

Normally, the environment variables are set through envp and the command is broken up into separate strings.

However, when on Windows, all the envp and command strings should be concatenated and then processed through Git Bash.  Here is the implementation.


package com.mycompany.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

public class CurlHelperGeneric {
    
    /**
     *  USERNAME=sizu
        RSA_TOKEN=myRSAToken
        http_proxy=http://myproxy.com:8080/ https_proxy=http://myproxy.com:8080/ curl --proxy-header "Proxy-Authorization: Basic $(echo -n "USERNAME:$RSA_TOKEN" | openssl enc -base64 -e)" "https://myservice.com/registry/v1/service" -k 

        http_proxy=http://myproxy.com:8080/ https_proxy=http://myproxy.com:8080/ curl --proxy-header 'Proxy-Authorization: "+helper.getBasic()+"' 'https://myservice.com/registry/v1/service' -k
     * @param args
     * @throws Exception
     */
    public static void main (String[] args) throws Exception {
         
        CurlHelperGeneric helper = new CurlHelperGeneric();
        String[] cmdArray = new String[] {
                "curl"
                "--proxy-header"
                "Proxy-Authorization: Basic c2lXXXXXXzEyMjAwMjQyMTI2OA==",
                "https://myservice.com/v1/pools",
                "-k"
                };
        String[] envp = new String[]{
            "http_proxy=http://myproxy.com:8080/",
            "https_proxy=http://myproxy.com:8080/"
        };
        
        String output = helper.runCommand(cmdArray, envp);
        
        System.out.println("Output:"+output);
    }
    
    public String runCommand(String[] cmdArray, String[] envp) {
        String os = System.getProperty("os.name");
        if(os.toUpperCase().contains("WINDOWS")) {
//            String[] cmdArray = new String[] {
//                    "C:\\Users\\sizu\\AppData\\Local\\Programs\\Git\\bin\\sh.exe",
//                    "--login",
//                    "-i",
//                    "-c",
//                    "http_proxy=http://myproxy.com:8080/ https_proxy=http://myproxy.com:8080/ curl --proxy-header 'Proxy-Authorization: "+proxyAuthorization+"' '"+httpString+"' -k",
//            };
//            String[] envp = new String[]{};
            
            String curlCommandToRunThroughGit = "";
            for(int i=0; i<envp.length; i++) {
                curlCommandToRunThroughGit = curlCommandToRunThroughGit + envp[i] + " ";
            }
            for(int i=0; i<cmdArray.length; i++) {
                curlCommandToRunThroughGit = curlCommandToRunThroughGit + "'" + cmdArray[i] + "' "// Wrap Authorization and https String with single quotes
            }
            
            cmdArray = new String[] {
                "C:\\Users\\sizu\\AppData\\Local\\Programs\\Git\\bin\\sh.exe",
                "--login",
                "-i",
                "-c",
                curlCommandToRunThroughGit,
            };
            envp = new String[]{};
        }
        
        
        
        try {
            Process process = Runtime.getRuntime().exec(cmdArray, envp);
            StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream()); // Gobble Stream even if not used
            StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream());
            errorGobbler.start();
            outputGobbler.start();
            int processComplete = process.waitFor(); // Wait for process to finish    
            
//            System.out.println("ERR:"+errorGobbler.streamContent.toString());
//            System.out.println("OUT:"+outputGobbler.streamContent.toString());
            
            return outputGobbler.streamContent.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
    
    public static class StreamGobbler extends Thread {
        InputStream is;
        
        StreamGobbler(InputStream is) {
            this.is = is;
        }
        
        StringBuilder streamContent = new StringBuilder();
        
        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null) {
                    streamContent.append(line);
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();  
            }
        }
    }
}

No comments:

Post a Comment