com.github.dirkraft.jash.ShExecutableJarBundler.java Source code

Java tutorial

Introduction

Here is the source code for com.github.dirkraft.jash.ShExecutableJarBundler.java

Source

/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Jason Dunkelberger (dirkraft)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.github.dirkraft.jash;

import com.google.common.base.Preconditions;
import com.google.common.io.ByteStreams;
import org.apache.commons.lang.ClassUtils;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.spi.FileOptionHandler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

/**
 * A single file houses the entire executable. Requires a single-jar (could be a "fat jar" or "jar jar") with
 * META-INF/MANIFEST.MF Main-Class defined.
 */
public class ShExecutableJarBundler extends AbstractBundler {

    @Argument(index = 1, metaVar = "executable jar file", handler = FileOptionHandler.class)
    public File jarFile;

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // internal build state

    protected File _targetBinary;

    @Override
    public List<String> validateAndInit() throws Exception {
        List<String> errors = super.validateAndInit();

        if (!jarFile.isFile()) {
            errors.add(jarFile + " is not a file.");
            return errors;
        }

        JarFile jar = new JarFile(jarFile);
        Manifest manifest = jar.getManifest();
        String mainClass = manifest.getMainAttributes().getValue(Attributes.Name.MAIN_CLASS);
        ClassLoader jarClassLoader = URLClassLoader.newInstance(new URL[] { jarFile.toURI().toURL() });
        try {
            ClassUtils.getClass(jarClassLoader, mainClass, false);
        } catch (ClassNotFoundException e) {
            errors.add("Could not find Main-Class: " + mainClass + " in jar " + jarFile.getAbsolutePath());
            return errors;
        }

        _targetBinary = outputDir.toPath().resolve(commandName).toFile();
        if (_targetBinary.exists()) {
            errors.add("Target binary path " + _targetBinary.getAbsolutePath()
                    + " is occupied. Will not overwrite, so aborting.");
        }

        return errors;
    }

    @Override
    public void run(Object cli) throws Exception {
        JasherDriver.validate(this).andThen(() -> {

            // Renders the jash script
            super.run(cli);

            // Concatenate jash script and jar contents together. java -jar can handle this :)
            concatJashAndJar();

        });
    }

    void concatJashAndJar() throws IOException {
        Preconditions.checkState(!_targetBinary.exists(), "Expected nothing to be here: %s",
                _targetBinary.getAbsolutePath());

        Files.copy(_renderedScriptFile.toPath(), _targetBinary.toPath());
        try (FileInputStream jarInputStream = new FileInputStream(jarFile);
                FileOutputStream appendJarStream = new FileOutputStream(_targetBinary, true)) {
            ByteStreams.copy(jarInputStream, appendJarStream);
            appendJarStream.flush();
        }

        JashIO.outf("Concatenated jash script and jar contents into %s%n", _targetBinary);
    }

    @Override
    public String toString() {
        return super.toString() + ", jarFile=" + jarFile;
    }
}