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

The following examples show how to use org.springframework.boot.loader.jar.JarFile. 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 File: BootJarLaucherUtils.java    From tac with 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 File: LancherTest.java    From tac with 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 File: ContainerApplication.java    From tac with 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
Source File: FunctionArchiveDeployer.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
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
Source File: BootApplicationConfigurationMetadataResolver.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
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 File: BootJarLaucherUtils.java    From tac with 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 File: BootJarLaucherUtils.java    From tac with 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 File: BootJarLaucherUtils.java    From tac with 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
Source File: BootApplicationConfigurationMetadataResolver.java    From spring-cloud-dashboard with Apache License 2.0 5 votes vote down vote up
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 File: GcfJarLauncher.java    From spring-cloud-function with 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 File: ConsoleApplication.java    From tac with 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 File: LancherTest.java    From tac with MIT License 4 votes vote down vote up
@Test
public void test3() throws Exception {

    BootJarLaucherUtils.unpackBootLibs(new JarFile(new File(file)));
}
 
Example #13
Source File: FatJarHandle.java    From JavaProbe with 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 File: FatJarHandle.java    From JavaProbe with 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;

}