Java Code Examples for org.springframework.boot.loader.jar.JarFile

The following examples show how to use org.springframework.boot.loader.jar.JarFile. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: tac   Source File: BootJarLaucherUtils.java    License: MIT License 6 votes vote down vote up
/**
 *
 * @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();
    }
}
 
Example 2
Source Project: tac   Source File: LancherTest.java    License: MIT License 6 votes vote down vote up
@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);
    }
}
 
Example 3
Source Project: tac   Source File: ContainerApplication.java    License: MIT License 6 votes vote down vote up
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);
    }
 
Example 4
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);
}
 
Example 5
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);
	}
}
 
Example 6
Source Project: tac   Source File: BootJarLaucherUtils.java    License: MIT License 5 votes vote down vote up
/**
 *
 * 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;
}
 
Example 7
Source Project: tac   Source File: BootJarLaucherUtils.java    License: MIT License 5 votes vote down vote up
/**
 *
 * @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());
}
 
Example 8
Source Project: tac   Source File: BootJarLaucherUtils.java    License: MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 9
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);
	}
}
 
Example 10
Source Project: spring-cloud-function   Source File: GcfJarLauncher.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 11
Source Project: tac   Source File: ConsoleApplication.java    License: MIT License 4 votes vote down vote up
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);

}
 
Example 12
Source Project: tac   Source File: LancherTest.java    License: MIT License 4 votes vote down vote up
@Test
public void test3() throws Exception {

    BootJarLaucherUtils.unpackBootLibs(new JarFile(new File(file)));
}
 
Example 13
Source Project: JavaProbe   Source File: FatJarHandle.java    License: GNU General Public License v3.0 3 votes vote down vote up
/**
 * 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;
}
 
Example 14
Source Project: JavaProbe   Source File: FatJarHandle.java    License: GNU General Public License v3.0 3 votes vote down vote up
/**
 * 获取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;

}