Example usage for org.springframework.boot.loader.tools Repackager setMainClass

List of usage examples for org.springframework.boot.loader.tools Repackager setMainClass

Introduction

In this page you can find the example usage for org.springframework.boot.loader.tools Repackager setMainClass.

Prototype

public void setMainClass(String mainClass) 

Source Link

Document

Sets the main class that should be run.

Usage

From source file:com.hurence.logisland.plugin.PluginManager.java

private static void installPlugin(String artifact, String logislandHome) {
    Optional<ModuleInfo> moduleInfo = findPluginMeta().entrySet().stream()
            .filter(e -> artifact.equals(e.getKey().getArtifact())).map(Map.Entry::getKey).findFirst();
    if (moduleInfo.isPresent()) {
        System.err//from w  ww .  j a v  a2  s.c  om
                .println("A component already matches the artifact " + artifact + ". Please remove it first.");
        System.exit(-1);
    }

    try {

        IvySettings settings = new IvySettings();
        settings.load(new File(logislandHome, "conf/ivy.xml"));

        Ivy ivy = Ivy.newInstance(settings);
        ivy.bind();

        System.out.println("\nDownloading dependencies. Please hold on...\n");

        String parts[] = Arrays.stream(artifact.split(":")).map(String::trim).toArray(a -> new String[a]);
        if (parts.length != 3) {
            throw new IllegalArgumentException(
                    "Unrecognized artifact format. It should be groupId:artifactId:version");
        }
        ModuleRevisionId revisionId = new ModuleRevisionId(new ModuleId(parts[0], parts[1]), parts[2]);
        Set<ArtifactDownloadReport> toBePackaged = downloadArtifacts(ivy, revisionId,
                new String[] { "default", "compile", "runtime" });

        ArtifactDownloadReport artifactJar = toBePackaged.stream()
                .filter(a -> a.getArtifact().getModuleRevisionId().equals(revisionId)).findFirst()
                .orElseThrow(() -> new IllegalStateException("Unable to find artifact " + artifact
                        + ". Please check the name is correct and the repositories on ivy.xml are correctly configured"));

        Manifest manifest = new JarFile(artifactJar.getLocalFile()).getManifest();
        File libDir = new File(logislandHome, "lib");

        if (manifest.getMainAttributes().containsKey(ManifestAttributes.MODULE_ARTIFACT)) {
            org.apache.commons.io.FileUtils.copyFileToDirectory(artifactJar.getLocalFile(), libDir);
            //we have a logisland plugin. Just copy it
            System.out.println(String.format("Found logisland plugin %s version %s\n" + "It will provide:",
                    manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_NAME),
                    manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_VERSION)));
            Arrays.stream(manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_EXPORTS).split(","))
                    .map(String::trim).forEach(s -> System.out.println("\t" + s));

        } else {
            System.out.println("Repackaging artifact and its dependencies");
            Set<ArtifactDownloadReport> environment = downloadArtifacts(ivy, revisionId,
                    new String[] { "provided" });
            Set<ArtifactDownloadReport> excluded = toBePackaged.stream()
                    .filter(adr -> excludeGroupIds.stream()
                            .anyMatch(s -> s.matches(adr.getArtifact().getModuleRevisionId().getOrganisation()))
                            || excludedArtifactsId.stream().anyMatch(
                                    s -> s.matches(adr.getArtifact().getModuleRevisionId().getName())))
                    .collect(Collectors.toSet());

            toBePackaged.removeAll(excluded);
            environment.addAll(excluded);

            Repackager rep = new Repackager(artifactJar.getLocalFile(), new LogislandPluginLayoutFactory());
            rep.setMainClass("");
            File destFile = new File(libDir, "logisland-component-" + artifactJar.getLocalFile().getName());
            rep.repackage(destFile, callback -> toBePackaged.stream().filter(adr -> adr.getLocalFile() != null)
                    .filter(adr -> !adr.getArtifact().getModuleRevisionId().equals(revisionId))
                    .map(adr -> new Library(adr.getLocalFile(), LibraryScope.COMPILE)).forEach(library -> {
                        try {
                            callback.library(library);
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    }));
            Thread.currentThread().setContextClassLoader(new URLClassLoader(
                    environment.stream().filter(adr -> adr.getLocalFile() != null).map(adr -> {
                        try {
                            return adr.getLocalFile().toURI().toURL();
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }).toArray(a -> new URL[a]), Thread.currentThread().getContextClassLoader()));
            //now clean up package and write the manifest
            String newArtifact = "com.hurence.logisland.repackaged:" + parts[1] + ":" + parts[2];
            LogislandRepackager.execute(destFile.getAbsolutePath(), "BOOT-INF/lib-provided", parts[2],
                    newArtifact, "Logisland Component for " + artifact, "Logisland Component for " + artifact,
                    new String[] { "org.apache.kafka.*" }, new String[0],
                    "org.apache.kafka.connect.connector.Connector");
        }
        System.out.println("Install done!");
    } catch (Exception e) {
        System.err.println("Unable to install artifact " + artifact);
        e.printStackTrace();
        System.exit(-1);
    }

}

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void specificMainClass() throws Exception {
    this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class);
    File file = this.testJarFile.getFile();
    Repackager repackager = new Repackager(file);
    repackager.setMainClass("a.b.C");
    repackager.repackage(NO_LIBRARIES);//from   w  w w  .  j av a 2s .c o m
    Manifest actualManifest = getManifest(file);
    assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
            .isEqualTo("org.springframework.boot.loader.JarLauncher");
    assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C");
    assertThat(hasLauncherClasses(file)).isTrue();
}

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void jarThatUsesCustomCompressionConfigurationCanBeRepackaged() throws IOException {
    File source = this.temporaryFolder.newFile("source.jar");
    ZipOutputStream output = new ZipOutputStream(new FileOutputStream(source)) {
        {/*  w  w w . ja v  a 2 s. c  om*/
            this.def = new Deflater(Deflater.NO_COMPRESSION, true);
        }
    };
    byte[] data = new byte[1024 * 1024];
    new Random().nextBytes(data);
    ZipEntry entry = new ZipEntry("entry.dat");
    output.putNextEntry(entry);
    output.write(data);
    output.closeEntry();
    output.close();
    File dest = this.temporaryFolder.newFile("dest.jar");
    Repackager repackager = new Repackager(source);
    repackager.setMainClass("com.example.Main");
    repackager.repackage(dest, NO_LIBRARIES);
}