在Windows平台上搭建无互联网的Java开发环境

由于公司规定,不可以使用互联网进行开发,我们曾多次上陈民情,还在期待中。决定自己先弄一个相对完整的离线开发环境。虽然有点陋,聊胜于无。

MAVEN私服

在网上瞧来瞧去,还是nexus最方便,下载了最新版的nexus-3.13.0-01-win64.zip。解压缩到D:\server\nexus目录下,有两个子目录:nexus-3.13.0-01和sonatype-work。

运行命令(CMD或PS均可,Linux下也可以)启动服务:
D:\server\nexus\nexus-3.13.0-01\bin> .\nexus.exe /run

打开http://localhost:8081,即可进入NXRM的界面。管理账号缺省用户名和密码:admin和admin123。

太简单了,只需要解压并运行起来就OK,如果需要安装成服务也没问题。太贴心了,我们的码的软件什么时候也是这个样子?

以服务方式运行:
D:\server\nexus\nexus-3.13.0-01\bin> .\nexus.exe /install
D:\server\nexus\nexus-3.13.0-01\bin> .\nexus.exe /start
D:\server\nexus\nexus-3.13.0-01\bin> .\nexus.exe /stop
D:\server\nexus\nexus-3.13.0-01\bin> .\nexus.exe /uninstall

察看状态:
D:\server\nexus\nexus-3.13.0-01\bin> .\nexus.exe /status

在Windows平台上参数restart和console似乎无效。Linux未测。当然,也可以使用net命令启动或停止服务:
D:\server\nexus\nexus-3.13.0-01\bin> net start nexus
D:\server\nexus\nexus-3.13.0-01\bin> net stop nexus

Maven上传第三方的jar包

当然,我们需要先创建仓库:Name=thirdparty, Format=maven2, Type=hosted, Version policy=Mixed,Layout policy=Strict, Deployment policy=Allow redeploy

提交后,察看仓库的信息,URL=http://localhost:8081/repository/thirdpart/

这时需要准备本地Maven的配置,编辑settings.xml文件,指定仓库:
      <repositories>
        <repository>
          <id>thirdpart</id>
          <name>third part</name>
          <url>http://localhost:8081/repository/thirdpart/</url>
          <releases>
            <enabled>true</enabled>
          </releases>
          <snapshots>
            <enabled>true</enabled>
          </snapshots>
        </repository>
      </repositories>

指定服务器用户,为了简便,直接使用了管理员账号:
    <server>
      <id>thirdpart</id>
      <username>admin</username>
      <password>admin123</password>
    </server>

使用mvn命令即可上传,例如:
mvn -s D:\tools\apache-maven-3.5.4\conf\settings.xml deploy:deploy-file -Durl=http://localhost:8081/repository/thirdpart -DrepositoryId=thirdpart -DgeneratePom=false -DpomFile=E:\tmp\repository\ant\ant\1.5\ant-1.5.pom -Dpackaging=jar -Dfile=E:\tmp\repository\ant\ant\1.5\ant-1.5.jar

注意了,pomFile和file必须指定路径,否则为当前路径。另为这里的路径不能在maven的localRepository下。

太多文件需要上传,编写批处理也是方便的,但这里是Java,顺道学习一下。参考网文《批量上传 Jar 包到 Maven 私服的工具》,原文地址:https://blog.csdn.net/isea533/article/details/77197017。按原文执行时有几个错误,可能是JDK的版本问题,没有确认,个人的是JDK1.8。修改后的代码如下:


import java.io.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

/**
 * 上传依赖到Maven私服。
 */
public class Main {

    /**
     * mvn -s E:\\tools\\apache-maven-3.5.4\\conf\\settings.xml
     * org.apache.maven.plugins:maven-deploy-plugin:2.8.2:deploy-file
     * -Durl=http://IP:PORT/repository/thirdpart
     * -DrepositoryId=thirdpart -Dfile=antlr-2.7.2.jar -DpomFile=antlr-2.7.2.pom
     * -Dpackaging=jar -DgeneratePom=false
     * -Dsources=./path/to/artifact-name-1.0-sources.jar
     * -Djavadoc=./path/to/artifact-name-1.0-javadoc.jar
     */
    public static final String BASE_CMD = "cmd /c mvn "
            + "-s E:\\tools\\apache-maven-3.5.4\\conf\\settings.xml "
            + "deploy:deploy-file "
            + "-Durl=http://10.2.1.201:8081/repository/thirdpart "
            + "-DrepositoryId=thirdpart "
            + "-DgeneratePom=false";

    public static final Pattern DATE_PATTERN = Pattern.compile("-[\\d]{8}\\.[\\d]{6}-");
    public static final Runtime CMD = Runtime.getRuntime();
    public static final Writer ERROR;
    public static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(10);

    static {
        Writer err = null;
        try {
            err = new OutputStreamWriter(new FileOutputStream("deploy-error.log"), "utf-8");
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            e.printStackTrace();
            System.exit(0);
        }
        ERROR = err;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        // 要注意的是如果你要安装的jar和pom是位于本地repository的目录下,这个命令就会出错 (Cannot deploy artifact from the local repository…)
        // so that 解决方法:将要安装的jar和pom copy到其它目录再安装,只要不在本地仓库目录都应该可以
        deploy(new File("E:\\tmp\\repository").listFiles());
//        if(checkArgs(args)){
//            File file = new File(args[0]);
//            deploy(file.listFiles());
//        }
        EXECUTOR_SERVICE.shutdown();
        try {
            ERROR.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void error(String error) {
        try {
            System.err.println(error);
            ERROR.write(error + "\n");
            ERROR.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean checkArgs(String[] args) {
        if (args.length != 1) {
            System.out.println("用法如: java -jar Deploy D:\\some\\path\\");
            return false;
        }
        File file = new File(args[0]);
        if (!file.exists()) {
            System.out.println(args[0] + " 目录不存在!");
            return false;
        }
        if (!file.isDirectory()) {
            System.out.println("必须指定为目录!");
            return false;
        }
        return true;
    }

    public static void deploy(File[] files) {
        if (files.length == 0) {
            //ignore
        } else if (files[0].isDirectory()) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deploy(file.listFiles());
                }
            }
        } else if (files[0].isFile()) {
            File pom = null;
            File jar = null;
            File source = null;
            File javadoc = null;
            //忽略日期快照版本,如 xxx-mySql-2.2.6-20170714.095105-1.jar
            for (File file : files) {
                String name = file.getName();
                if (DATE_PATTERN.matcher(name).find()) {
                    //skip
                } else if (name.endsWith(".pom")) {
                    pom = file;
                } else if (name.endsWith("-javadoc.jar")) {
                    javadoc = file;
                } else if (name.endsWith("-sources.jar")) {
                    source = file;
                } else if (name.endsWith(".jar")) {
                    jar = file;
                }
            }
            if (pom != null) {
                if (jar != null) {
                    deploy(pom, jar, source, javadoc);
                } else if (packingIsPom(pom)) {
                    deployPom(pom);
                }
            }
        }
    }

    public static boolean packingIsPom(File pom) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(pom)));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.trim().contains("<packaging>pom</packaging>")) {
                    return true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
            }
        }
        return false;
    }

    public static void deployPom(final File pom) {
        EXECUTOR_SERVICE.execute(() -> {
            @SuppressWarnings("StringBufferMayBeStringBuilder")
            StringBuffer cmd = new StringBuffer(BASE_CMD);
            //cmd.append(" -DpomFile=").append(pom.getName());
            //cmd.append(" -Dfile=").append(pom.getName());
            // 2018-08-25 需要完整路径
            cmd.append(" -DpomFile=").append(pom.getPath());
            cmd.append(" -Dfile=").append(pom.getPath());
            try {
                System.out.println(cmd);
                final Process proc = CMD.exec(cmd.toString(), null, pom.getParentFile());
                InputStream inputStream = proc.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(inputStreamReader);
                String line;
                StringBuffer logBuffer = new StringBuffer();
                logBuffer.append("\n\n\n==================================\n");
                while ((line = reader.readLine()) != null) {
                    if (line.startsWith("[INFO]") || line.startsWith("Upload")) {
                        logBuffer.append(Thread.currentThread().getName()).append(" : ").append(line).append("\n");
                    }
                }
                System.out.println(logBuffer);
                int result = proc.waitFor();
                if (result != 0) {
                    error("上传失败:" + pom.getAbsolutePath());
                }
            } catch (IOException | InterruptedException e) {
                error("上传失败:" + pom.getAbsolutePath());
                e.printStackTrace();
            }
        });
    }

    public static void deploy(final File pom, final File jar, final File source, final File javadoc) {
        EXECUTOR_SERVICE.execute(() -> {
            StringBuffer cmd = new StringBuffer(BASE_CMD);
            // 2018-08-25 需要完整路径
            //cmd.append(" -DpomFile=").append(pom.getName());
            cmd.append(" -DpomFile=").append(pom.getPath());
            if (jar != null) {
                //当有bundle类型时,下面的配置可以保证上传的jar包后缀为.jar
            // 2018-08-25 需要完整路径
                //cmd.append(" -Dpackaging=jar -Dfile=").append(jar.getName());
                cmd.append(" -Dpackaging=jar -Dfile=").append(jar.getPath());
            } else {
            // 2018-08-25 需要完整路径
                //cmd.append(" -Dfile=").append(pom.getName());
                cmd.append(" -Dfile=").append(pom.getPath());
            }
            if (source != null) {
                cmd.append(" -Dsources=").append(source.getName());
            }
            if (javadoc != null) {
                cmd.append(" -Djavadoc=").append(javadoc.getName());
            }

            try {
                System.out.println(cmd);
                final Process proc = CMD.exec(cmd.toString(), null, pom.getParentFile());
                InputStream inputStream = proc.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(inputStreamReader);
                String line;
                StringBuffer logBuffer = new StringBuffer();
                logBuffer.append("\n\n\n=======================================\n");
                while ((line = reader.readLine()) != null) {
                    if (line.startsWith("[INFO]") || line.startsWith("Upload")) {
                        logBuffer.append(Thread.currentThread().getName()).append(" : ").append(line).append("\n");
                    }
                }
                System.out.println(logBuffer);
                int result = proc.waitFor();
                if (result != 0) {
                    error("上传失败:" + pom.getAbsolutePath());
                }
            } catch (IOException | InterruptedException e) {
                error("上传失败:" + pom.getAbsolutePath());
                e.printStackTrace();
            }
        });
    }
}
创建的工程是基于MAVEN的,POM文件里添加了:
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.pounet.tool.imp3rdparty.Main</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.4.3</version>
        </dependency>
    </dependencies>

注意:没有完整地处理路径问题。请自行处理。

哥几个都觉得使用Spring Boot 2进行开发是一个好的选择,就简易说一下Spring Initializr的部署。下载源码,编译,运行。请参考在阿里云上搭建Spring Initializr服务器(http://www.cnblogs.com/JasonChen92/p/9297455.html),很简单地。

其他的都略过。

 

 

 

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值