类org.springframework.boot.loader.jar.JarFile源码实例Demo

下面列出了怎么用org.springframework.boot.loader.jar.JarFile的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: tac   文件: BootJarLaucherUtils.java
/**
 *
 * @param jarFile
 * @param entry
 * @param file
 * @throws IOException
 */
private static void unpack(JarFile jarFile, JarEntry entry, File file) throws IOException {
    InputStream inputStream = jarFile.getInputStream(entry, RandomAccessData.ResourceAccess.ONCE);
    try {
        OutputStream outputStream = new FileOutputStream(file);
        try {
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
        } finally {
            outputStream.close();
        }
    } finally {
        inputStream.close();
    }
}
 
源代码2 项目: tac   文件: LancherTest.java
@Test
public void test1() throws IOException {



    this.jarFile=new JarFile(new File(file));

    Enumeration<JarEntry> entries = this.jarFile.entries();
    while (entries.hasMoreElements()){

        JarEntry jarEntry = entries.nextElement();
        if (jarEntry.getName().contains(".jar")){
            getUnpackedNestedArchive(jarEntry);
        }
        System.out.println(jarEntry);
    }
}
 
源代码3 项目: tac   文件: ContainerApplication.java
public static void main(String[] args) throws Exception {

        // the code must execute before spring start
        JarFile bootJarFile = BootJarLaucherUtils.getBootJarFile();
        if (bootJarFile != null) {
            BootJarLaucherUtils.unpackBootLibs(bootJarFile);
            log.debug("the temp tac lib folder:{}", BootJarLaucherUtils.getTempUnpackFolder());
        }
        SpringApplication springApplication = new SpringApplication(ContainerApplication.class);

        springApplication.setWebEnvironment(true);
        springApplication.setBannerMode(Banner.Mode.OFF);

        springApplication.addListeners(new ApplicationListener<ApplicationEnvironmentPreparedEvent>() {
            @Override
            public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
                CodeLoadService.changeClassLoader(event.getEnvironment());
            }
        });
        springApplication.run(args);
    }
 
private void launchFunctionArchive(String[] args) throws Exception {
	JarFile.registerUrlProtocolHandler();

	String mainClassName = getMainClass();
	Class<?> mainClass = Thread.currentThread().getContextClassLoader().loadClass(mainClassName);

	Class<?> bootAppClass = Thread.currentThread().getContextClassLoader()
			.loadClass(SpringApplication.class.getName());
	Method runMethod = bootAppClass.getDeclaredMethod("run", Class.class, String[].class);
	Object applicationContext = runMethod.invoke(null, mainClass, args);
	if (logger.isInfoEnabled()) {
		logger.info("Application context for archive '" + this.getArchive().getUrl() + "' is created.");
	}
	evalContext.setVariable("context", applicationContext);
	setBeanFactory(applicationContext);
}
 
public BootApplicationConfigurationMetadataResolver(ClassLoader parent,
		ContainerImageMetadataResolver containerImageMetadataResolver) {
	this.parent = parent;
	this.containerImageMetadataResolver = containerImageMetadataResolver;
	JarFile.registerUrlProtocolHandler();
	try {
		// read both formats and concat
		Resource[] globalLegacyResources = new PathMatchingResourcePatternResolver(
				ApplicationConfigurationMetadataResolver.class.getClassLoader())
				.getResources(WHITELIST_LEGACY_PROPERTIES);
		Resource[] globalResources = new PathMatchingResourcePatternResolver(
				ApplicationConfigurationMetadataResolver.class.getClassLoader())
				.getResources(WHITELIST_PROPERTIES);
		loadWhiteLists(concatArrays(globalLegacyResources, globalResources), globalWhiteListedClasses,
				globalWhiteListedProperties);
	}
	catch (IOException e) {
		throw new RuntimeException("Error reading global white list of configuration properties", e);
	}
}
 
源代码6 项目: tac   文件: BootJarLaucherUtils.java
/**
 *
 * unpack jar to temp folder
 * @param jarFile
 * @return
 */
public static Integer unpackBootLibs(JarFile jarFile) throws IOException {

    Enumeration<JarEntry> entries = jarFile.entries();
    int count = 0;
    while (entries.hasMoreElements()) {

        JarEntry jarEntry = entries.nextElement();
        if (jarEntry.getName().startsWith(BOOT_INF_LIB) && jarEntry.getName().endsWith(".jar")) {
            getUnpackedNestedArchive(jarFile, jarEntry);
            count++;
        }
    }
    return count;
}
 
源代码7 项目: tac   文件: BootJarLaucherUtils.java
/**
 *
 * @param jarFile
 * @param jarEntry
 * @return
 * @throws IOException
 */
private static Archive getUnpackedNestedArchive(JarFile jarFile, JarEntry jarEntry) throws IOException {
    String name = jarEntry.getName();
    if (name.lastIndexOf("/") != -1) {
        name = name.substring(name.lastIndexOf("/") + 1);
    }
    File file = new File(getTempUnpackFolder(), name);
    if (!file.exists() || file.length() != jarEntry.getSize()) {
        unpack(jarFile, jarEntry, file);
    }
    return new JarFileArchive(file, file.toURI().toURL());
}
 
源代码8 项目: tac   文件: BootJarLaucherUtils.java
/**
 * get the boot jar file
 *
 * @return  the boot jar file; null is run through folder
 * @throws Exception
 */
public final static JarFile getBootJarFile() throws Exception {
    ProtectionDomain protectionDomain = BootJarLaucherUtils.class.getProtectionDomain();
    CodeSource codeSource = protectionDomain.getCodeSource();
    URI location = (codeSource == null ? null : codeSource.getLocation().toURI());

    String path = (location == null ? null : location.toURL().getPath());
    if (path == null) {
        throw new IllegalStateException("Unable to determine code source archive");
    }

    if (path.lastIndexOf("!/BOOT-INF") <= 0) {
        return null;
    }
    path = path.substring(0, path.lastIndexOf("!/BOOT-INF"));

    path = StringUtils.replace(path, "file:", "");

    File root = new File(path);

    if (root.isDirectory()) {
        return null;
    }
    if (!root.exists()) {
        throw new IllegalStateException(
            "Unable to determine code source archive from " + root);
    }
    return new JarFile(root);
}
 
public BootApplicationConfigurationMetadataResolver(ClassLoader parent) {
	this.parent = parent;
	JarFile.registerUrlProtocolHandler();
	try {
		Resource[] globalResources = new PathMatchingResourcePatternResolver(ApplicationConfigurationMetadataResolver.class.getClassLoader()).getResources(WHITELIST_PROPERTIES);
		loadWhiteLists(globalResources, globalWhiteListedClasses, globalWhiteListedProperties);
	}
	catch (IOException e) {
		throw new RuntimeException("Error reading global white list of configuration properties", e);
	}
}
 
源代码10 项目: spring-cloud-function   文件: GcfJarLauncher.java
public GcfJarLauncher() throws Exception {
	JarFile.registerUrlProtocolHandler();

	this.loader = createClassLoader(getClassPathArchivesIterator());

	Class<?> clazz = this.loader
		.loadClass("org.springframework.cloud.function.adapter.gcp.FunctionInvoker");
	this.delegate = clazz.getConstructor().newInstance();
}
 
源代码11 项目: tac   文件: ConsoleApplication.java
public static void main(String[] args)
    throws Exception {

    // parse the args
    ApplicationArguments arguments = new DefaultApplicationArguments(args);
    boolean help = arguments.containsOption(ConsoleConstants.MENU_HELP);
    if (help) {
        MenuOptionHandler.printUsage();
        return;
    }

    // the code must execute before spring start
    JarFile bootJarFile = BootJarLaucherUtils.getBootJarFile();
    if (bootJarFile != null) {
        BootJarLaucherUtils.unpackBootLibs(bootJarFile);
        log.debug("the temp tac lib folder:{}", BootJarLaucherUtils.getTempUnpackFolder());
    }


    // get command args and start spring boot
    Boolean webEnv = false;
    String additionProfile = ConsoleConstants.ADDDITION_PROFILE_SIMPLE;
    if (arguments.containsOption(ConsoleConstants.OPTION_ADMIN)) {
        webEnv = true;
        additionProfile = ConsoleConstants.ADDDITION_PROFILE_ADMIN;
    }

    SpringApplication springApplication = new SpringApplication(ConsoleApplication.class);
    springApplication.setWebEnvironment(webEnv);
    springApplication.setBannerMode(Banner.Mode.OFF);

    if (!webEnv) {
        // command model
        springApplication.setAdditionalProfiles(additionProfile);
    } else {
        // web model
        springApplication.setAdditionalProfiles(additionProfile);
    }

    springApplication.addListeners(new ApplicationListener<ApplicationEnvironmentPreparedEvent>() {
        @Override
        public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {

            CodeLoadService.changeClassLoader(event.getEnvironment());
        }
    });

    springApplication.run(args);

}
 
源代码12 项目: tac   文件: LancherTest.java
@Test
public void test3() throws Exception {

    BootJarLaucherUtils.unpackBootLibs(new JarFile(new File(file)));
}
 
源代码13 项目: JavaProbe   文件: FatJarHandle.java
/**
 * fat jar 依赖文件的获取,多用于处理springboot打包的jar 传入的path是这样的 jar:file:/home/q/system/java/live/build/libs/live-33541.a12ed7cc.jar!/BOOT-INF/classes!/
 * @param jarpath
 * @param dependencyInfoList
 * @return
 */
public static List<DependencyInfo> getDependencyInfo(String jarpath, List<DependencyInfo> dependencyInfoList) {

    try {

        JarFile jarFile = new JarFile(new File(getROOTJar(jarpath)));

        Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();

        while (jarEntryEnumeration.hasMoreElements()) {

            JarEntry jarEntry = jarEntryEnumeration.nextElement();

            if (jarEntry.getName().endsWith(".jar")) { // 这里就暂时不匹配BOOT-INF/lib,考虑通用性

                JarFile inJarFile = jarFile.getNestedJarFile(jarEntry);
                DependencyInfo dependencyInfo = getJarInJardependcyInfo(inJarFile); // 获取资源

                if (dependencyInfo != null) dependencyInfoList.add(dependencyInfo);

            }
        }

    }
    catch (Exception e) {

        CommonUtil.writeStr("/tmp/jvm_error.txt","getDependencyInfo:\t" + e.getMessage());
    }

    return dependencyInfoList;
}
 
源代码14 项目: JavaProbe   文件: FatJarHandle.java
/**
 * 获取Jarinjar中的资源
 * @param jarFile
 * @return
 */
public static DependencyInfo getJarInJardependcyInfo(JarFile jarFile) {

    try {

        Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();

        while (jarEntryEnumeration.hasMoreElements()) {

            JarEntry jarEntry= jarEntryEnumeration.nextElement();

            if (jarEntry.getName().endsWith("/pom.properties")) {

                Properties prop = new Properties();
                prop.load(jarFile.getInputStream(jarEntry));

                DependencyInfo dependencyInfo = new DependencyInfo(); // 存放依赖信息
                dependencyInfo.setArtifactId(prop.getProperty("artifactId"));
                dependencyInfo.setGroupId(prop.getProperty("groupId"));
                dependencyInfo.setVersion(prop.getProperty("version"));

                return dependencyInfo;
            }
        }

    }
    catch (Exception e) {

        CommonUtil.writeStr("/tmp/jvm_error.txt","getJarInJardependcyInfo:\t" + e.getMessage());
    }

    return null;

}
 
 类所在包
 类方法
 同包方法