Nexus3批量導(dǎo)入本地倉(cāng)庫(kù)

先看效果(源碼Github地址:https://github.com/qudengr/minitool)

上傳后效果

沒(méi)有任何的第三方依賴(lài)扮休,直接通過(guò)java命令編譯運(yùn)行即可刨疼。

javac NexusComponentsUpload.java
java NexusComponentsUpload

curl命令調(diào)用API上傳

curl -v -u admin:admin123 -X POST 'http://192.168.0.8:8081/service/rest/v1/components?repository=appname-hosted'  -F maven2.generate-pom=true -F maven2.groupId=com.xxx.xxx.thirdlib -F maven2.artifactId=ojdbc8 -F maven2.version=12.2.0.1 -F maven2.asset1=@/home/appname/repo/thirdlib/ojdbc8/12.2.0.1/ojdbc8-12.2.0.1.jar -F maven2.asset1.extension=jar

沒(méi)有任何三方依賴(lài),需要在linux借助curl命令上傳。

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;

public class NexusComponentsUpload {

    public static final String USAGE =
            "Expected Parameters: [options] -U username -P password -h host -p port -r repositoryName -d repositoryDirectory\n" +
                    "\t-U - nexus username\n" +
                    "\t-P - nexus password\n" +
                    "\t-h - nexus host\n" +
                    "\t-p - nexus port\n" +
                    "\t-r - nexus repository name\n" +
                    "\t-d - local repository directory\n";

    public static void main(String[] args) {
        NexusComponentsUpload nexusComponentsUpload = new NexusComponentsUpload();

        String repositoryHost = "localhost";
        String repositoryPort = "8081";
        String repositoryName = "maven-hosted";
        String repositoryDirectory = "~/repo/";
        String username = "admin";
        String password = "admin123";

        int base = 0;
        for (base = 0; base < args.length; base++) {
            if (args[base].equals("-h")) {
                repositoryHost = args[++base];
            } else if (args[base].equals("-p")) {
                repositoryPort = args[++base];
            } else if (args[base].equals("-r")) {
                repositoryName = args[++base];
            } else if (args[base].equals("-d")) {
                repositoryDirectory = args[++base];
            } else if (args[base].equals("-U")) {
                username = args[++base];
            } else if (args[base].equals("-P")) {
                password = args[++base];
            } else {
                break;
            }
        }

        int minParams = 1;
        int remain = args.length;
        if (remain < minParams) {
            if (args.length > 0) {
                System.err.println("Actual Parameters: " + Arrays.toString(args));
            }
            System.err.println(USAGE);
            System.exit(1);
        }

        System.out.println("Repository:" + repositoryName);
        System.out.println("Repository:" + repositoryName);

        // 獲取所有的pom文件
        ArrayList<String> files = getFileLists(repositoryDirectory, ".pom");

        // 一個(gè)個(gè)的解析并處理POM文件及對(duì)應(yīng)的jar包
        for (String file : files) {
            try {

                String fileNameWithoutExtension = file.substring(0, file.lastIndexOf("."));

                // 解析POM文件
                GAVP gavp = nexusComponentsUpload.parsePom(file);
                //如果是POM組件,直接上傳
                if (gavp.packaging.equals("pom")) {
                    String cmd = getApiCmd(repositoryHost, repositoryPort, username, password, repositoryName, gavp.groupId, gavp.artifactId, gavp.version, "pom", file);
                    exec(cmd);
                } else {
                    //如果是jar包組件,判斷一下jar包是存在
                    String jarFilePath = fileNameWithoutExtension + ".jar";
                    File jarFile = new File(jarFilePath);
                    if (jarFile.exists()) {
                        String cmd = getApiCmd(repositoryHost, repositoryPort, username, password, repositoryName, gavp.groupId, gavp.artifactId, gavp.version, "jar", jarFilePath);
                        exec(cmd);
                    }
                }

            } catch (Exception e) {
                System.err.println("Error:"+e);
            }

        }

    }

    /**
     * 獲取待執(zhí)行的命令字符串
     * @param file
     * @return
     */
    public static String getApiCmd(String host, String port, String username, String password, String repository, String groupId, String artifactId, String version, String extension, String file) {
        String apiUri = "/service/rest/v1/components?repository=";
        String cmd = "curl -v -u " + username + ":" + password
                + " -X POST \'http://" + host + ":" + port + apiUri + repository + "\'"
                + " -F maven2.generate-pom=true -F maven2.groupId=" + groupId + " -F maven2.artifactId=" + artifactId + " -F maven2.version=" + version
                + " -F maven2.asset1=@" + file + " -F maven2.asset1.extension=" + extension;
        return cmd;
    }

    /**
     * 解析POM文件
     * @param file
     * @return
     */
    public GAVP parsePom(String file) {
        String fileContent = readFileString(file);
        //groupId
        String groupId = fileContent.substring(fileContent.indexOf("<groupId>")+9, fileContent.indexOf("</groupId>"));
        //artifactId
        String artifactId = fileContent.substring(fileContent.indexOf("<artifactId>")+12, fileContent.indexOf("</artifactId>"));
        //version
        String version = fileContent.substring(fileContent.indexOf("<version>")+9, fileContent.indexOf("</version>"));
        //packaging
        String packaging = "jar";
        if (fileContent.indexOf("<packaging>")>0) {
            packaging = fileContent.substring(fileContent.indexOf("<packaging>")+11, fileContent.indexOf("</packaging>"));
        }
        return new GAVP(groupId, artifactId, version, packaging);
    }

    /**
     * 執(zhí)行命令
     * @param cmd
     */
    public static void exec(String cmd) {

        Process process = null;
        try {
            System.out.println("============exec cmd============");
            System.out.println(cmd);

            process = Runtime.getRuntime().exec("/bin/sh");
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));

            bw.write(cmd, 0, cmd.length());
            bw.newLine();
            bw.write("exit", 0, 4);
            bw.newLine();
            bw.flush();

            try {
                process.waitFor();
            } catch (InterruptedException e) {
                System.err.println(cmd+"\n"+e);
            }

            InputStream errIs = process.getErrorStream();
            InputStream stdIs = process.getInputStream();

            int len = errIs.available();
            byte[] buf = null;
            if (len != 0) {
                buf = new byte[len];
                System.err.println("============stderr msg============");
                errIs.read(buf);
                System.err.println(new String(buf, 0, len));
            }

            len = stdIs.available();
            if (len != 0) {
                buf = new byte[len];
                System.out.println("============stdout msg===========");
                stdIs.read(buf);
                System.out.println(new String(buf, 0, len));
            }
        } catch (IOException e) {
            System.err.println(e);
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
    }

    /**
     * 判斷目錄不存在
     * @param filePath
     * @return
     */
    public static boolean directoryExists(String filePath) {
        File file = new File(filePath);
        return file.isDirectory() && file.exists();
    }

    /**
     * 判斷目錄存在
     * @param filePath
     * @return
     */
    public static boolean directoryNotExists(String filePath) {
        return !directoryExists(filePath);
    }

    /**
     * 判斷文件存在
     * @param filePath
     * @return
     */
    public static boolean fileExists(String filePath) {
        File file = new File(filePath);
        return file.isFile() && file.exists();
    }

    /**
     * 判斷文件不存在
     * @param filePath
     * @return
     */
    public static boolean fileNotExists(String filePath) {
        return !fileExists(filePath);
    }

    /**
     * 列出目錄下所有的文件  */
    public static ArrayList<String> getFileLists(String directory, String extension) {
        ArrayList<String> fileLists = new ArrayList<>();

        if (directoryNotExists(directory)) {
            return fileLists;
        }

        File rootDirectory = new File(directory);
        File[] files = rootDirectory.listFiles();

        for (File file : files) {
            if (file.isFile()) {
                // 文件
                if (file.getAbsolutePath().endsWith(extension) || extension == null || extension.length() == 0) {
                    fileLists.add(file.getAbsolutePath());
                }
            } else {
                // 子目錄
                fileLists.addAll(getFileLists(file.getAbsolutePath(), extension));
            }
        }
        return fileLists;
    }

    public static String readFileString(String filePath) {
        StringBuffer fileString = new StringBuffer("");
        if (fileNotExists(filePath)) {
            return fileString.toString();
        }

        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        try {
            fileReader = new FileReader(filePath);
            bufferedReader = new BufferedReader(fileReader);
            String str;
            // read by line
            while ((str = bufferedReader.readLine()) != null) {
                fileString.append(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                }
            }
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                }
            }
        }
        return fileString.toString();
    }

    /**
     * 存放POM信息
     */
    public class GAVP {
        public String groupId;
        public String artifactId;
        public String version;
        public String packaging;

        GAVP(String groupId,
             String artifactId,
             String version,
             String packaging) {
            this.groupId = groupId;
            this.artifactId = artifactId;
            this.version = version;
            this.packaging = packaging;
        }

        @Override
        public String toString() {
            return "GAVP{" +
                    "groupId='" + groupId + '\'' +
                    ", artifactId='" + artifactId + '\'' +
                    ", version='" + version + '\'' +
                    ", packaging='" + packaging + '\'' +
                    '}';
        }
    }

}

參考:
https://help.sonatype.com/repomanager3/rest-and-integration-api/components-api#ComponentsAPI-UploadComponent

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末融虽,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖往衷,帶你破解...
    沈念sama閱讀 219,039評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異严卖,居然都是意外死亡席舍,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)哮笆,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)来颤,“玉大人,你說(shuō)我怎么就攤上這事稠肘「GΓ” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,417評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵启具,是天一觀的道長(zhǎng)本讥。 經(jīng)常有香客問(wèn)我珊泳,道長(zhǎng)鲁冯,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,868評(píng)論 1 295
  • 正文 為了忘掉前任色查,我火速辦了婚禮薯演,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘秧了。我一直安慰自己跨扮,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,892評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著衡创,像睡著了一般帝嗡。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上璃氢,一...
    開(kāi)封第一講書(shū)人閱讀 51,692評(píng)論 1 305
  • 那天哟玷,我揣著相機(jī)與錄音,去河邊找鬼一也。 笑死巢寡,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的椰苟。 我是一名探鬼主播抑月,決...
    沈念sama閱讀 40,416評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼舆蝴!你這毒婦竟也來(lái)了谦絮?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,326評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤须误,失蹤者是張志新(化名)和其女友劉穎挨稿,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體京痢,經(jīng)...
    沈念sama閱讀 45,782評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡奶甘,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,957評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了祭椰。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片臭家。...
    茶點(diǎn)故事閱讀 40,102評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖方淤,靈堂內(nèi)的尸體忽然破棺而出钉赁,到底是詐尸還是另有隱情,我是刑警寧澤携茂,帶...
    沈念sama閱讀 35,790評(píng)論 5 346
  • 正文 年R本政府宣布你踩,位于F島的核電站,受9級(jí)特大地震影響讳苦,放射性物質(zhì)發(fā)生泄漏带膜。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,442評(píng)論 3 331
  • 文/蒙蒙 一鸳谜、第九天 我趴在偏房一處隱蔽的房頂上張望膝藕。 院中可真熱鬧,春花似錦咐扭、人聲如沸芭挽。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,996評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)袜爪。三九已至蠕趁,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間辛馆,已是汗流浹背妻导。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,113評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留怀各,地道東北人倔韭。 一個(gè)月前我還...
    沈念sama閱讀 48,332評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像瓢对,于是被迫代替她去往敵國(guó)和親寿酌。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,044評(píng)論 2 355