Search in sources :

Example 16 with ExitException

use of dev.jbang.cli.ExitException in project jbang by jbangdev.

the class Cache method clearCache.

public static void clearCache(CacheClass... classes) {
    for (CacheClass cc : classes) {
        Util.infoMsg("Clearing cache for " + cc.name());
        if (cc == CacheClass.jdks && Util.isWindows() && JdkManager.isCurrentJdkManaged()) {
            // entire folder!
            for (Integer v : JdkManager.listInstalledJdks()) {
                JdkManager.uninstallJdk(v);
            }
        }
        if (cc == CacheClass.deps) {
            try {
                if (Settings.getCacheDependencyFile().toFile().exists()) {
                    Util.verboseMsg("Deleting file " + Settings.getCacheDependencyFile());
                    Files.deleteIfExists(Settings.getCacheDependencyFile().toAbsolutePath());
                }
            } catch (IOException io) {
                throw new ExitException(-1, "Could not delete dependency cache " + Settings.getCacheDependencyFile().toString(), io);
            }
        } else {
            Util.deletePath(Settings.getCacheDir(cc), true);
        }
    }
}
Also used : IOException(java.io.IOException) ExitException(dev.jbang.cli.ExitException)

Example 17 with ExitException

use of dev.jbang.cli.ExitException in project jbang by jbangdev.

the class Util method createHardLink.

private static boolean createHardLink(Path src, Path target) {
    try {
        infoMsg("Now try creating a hard link instead of symbolic.");
        Files.createLink(src, target);
    } catch (IOException e) {
        infoMsg("Creation of hard link failed. Script must be on the same drive as $JBANG_CACHE_DIR (typically under $HOME) for hardlink creation to work. Or call the command with admin rights.");
        throw new ExitException(BaseCommand.EXIT_GENERIC_ERROR, e);
    }
    return true;
}
Also used : IOException(java.io.IOException) ExitException(dev.jbang.cli.ExitException)

Example 18 with ExitException

use of dev.jbang.cli.ExitException in project jbang by jbangdev.

the class Util method getStableID.

public static String getStableID(Stream<String> inputs) {
    final MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        throw new ExitException(-1, e);
    }
    inputs.forEach(input -> {
        digest.update(input.getBytes(StandardCharsets.UTF_8));
    });
    final byte[] hashbytes = digest.digest();
    StringBuilder sb = new StringBuilder();
    for (byte b : hashbytes) {
        sb.append(String.format("%02x", b));
    }
    return sb.toString();
}
Also used : NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest) ExitException(dev.jbang.cli.ExitException)

Example 19 with ExitException

use of dev.jbang.cli.ExitException in project jbang by jbangdev.

the class IntegrationManager method runIntegration.

/**
 * Discovers all integration points and runs them.
 * <p>
 * If an integration point created a native image it returns the resulting
 * image.
 *
 * @param repositories
 * @param artifacts
 * @param tmpJarDir
 * @param pomPath
 * @param source
 * @param nativeRequested
 * @return
 */
public static IntegrationResult runIntegration(List<MavenRepo> repositories, List<ArtifactInfo> artifacts, Path tmpJarDir, Path pomPath, Source source, boolean nativeRequested) {
    URL[] urls = artifacts.stream().map(s -> {
        try {
            return s.getFile().toURI().toURL();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }).toArray(URL[]::new);
    List<String> comments = source.getLines().stream().filter(s -> s.startsWith("//")).collect(Collectors.toList());
    URLClassLoader integrationCl = new URLClassLoader(urls);
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    Map<String, byte[]> data = new HashMap<>();
    List<Map.Entry<String, String>> repos = null;
    List<Map.Entry<String, Path>> deps = null;
    Path nativeImage = null;
    String mainClass = null;
    List<String> javaArgs = null;
    PrintStream oldout = System.out;
    try {
        // TODO: should we add new properties to the integration method?
        if (source.getResourceRef().getFile() != null) {
            System.setProperty("jbang.source", source.getResourceRef().getFile().getAbsolutePath());
        }
        Thread.currentThread().setContextClassLoader(integrationCl);
        Set<String> classNames = loadIntegrationClassNames(integrationCl);
        for (String className : classNames) {
            if (repos == null) {
                repos = repositories.stream().map(s -> new MapRepoEntry(s.getId(), s.getUrl())).collect(Collectors.toList());
            }
            if (deps == null) {
                deps = artifacts.stream().map(s -> new MapEntry(s.getCoordinate().toCanonicalForm(), s.getFile().toPath())).collect(Collectors.toList());
            }
            Class<?> clazz = Class.forName(className, true, integrationCl);
            Method method = clazz.getDeclaredMethod("postBuild", Path.class, Path.class, List.class, List.class, List.class, boolean.class);
            Util.infoMsg("Post build with " + className);
            if (Util.isVerbose()) {
                System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.err)));
            } else {
                System.setOut(new PrintStream(new OutputStream() {

                    public void write(int b) {
                    // DO NOTHING
                    // TODO: capture it for later print if error
                    }
                }));
            }
            @SuppressWarnings("unchecked") Map<String, Object> integrationResult = (Map<String, Object>) method.invoke(null, tmpJarDir, pomPath, repos, deps, comments, nativeRequested);
            @SuppressWarnings("unchecked") Map<String, byte[]> ret = (Map<String, byte[]>) integrationResult.get(FILES);
            if (ret != null) {
                data.putAll(ret);
            }
            Path image = (Path) integrationResult.get(NATIVE_IMAGE);
            if (image != null) {
                nativeImage = image;
            }
            String mc = (String) integrationResult.get(MAIN_CLASS);
            if (mc != null) {
                mainClass = mc;
            }
            @SuppressWarnings("unchecked") List<String> ja = (List<String>) integrationResult.get(JAVA_ARGS);
            if (ja != null) {
                javaArgs = ja;
            }
        }
        for (Map.Entry<String, byte[]> entry : data.entrySet()) {
            Path target = tmpJarDir.resolve(entry.getKey());
            Files.createDirectories(target.getParent());
            try (OutputStream out = Files.newOutputStream(target)) {
                out.write(entry.getValue());
            }
        }
    } catch (ClassNotFoundException e) {
        throw new ExitException(EXIT_UNEXPECTED_STATE, "Unable to load integration class", e);
    } catch (NoSuchMethodException e) {
        throw new ExitException(EXIT_UNEXPECTED_STATE, "Integration class missing method with signature public static Map<String, byte[]> postBuild(Path classesDir, Path pomFile, List<Map.Entry<String, Path>> dependencies)", e);
    } catch (Exception e) {
        throw new ExitException(EXIT_UNEXPECTED_STATE, "Issue running postBuild()", e);
    } finally {
        Thread.currentThread().setContextClassLoader(old);
        System.setOut(oldout);
    }
    return new IntegrationResult(nativeImage, mainClass, javaArgs);
}
Also used : Enumeration(java.util.Enumeration) URL(java.net.URL) HashMap(java.util.HashMap) MavenRepo(dev.jbang.dependencies.MavenRepo) Source(dev.jbang.source.Source) ExitException(dev.jbang.cli.ExitException) ArtifactInfo(dev.jbang.dependencies.ArtifactInfo) HashSet(java.util.HashSet) URLClassLoader(java.net.URLClassLoader) Map(java.util.Map) Method(java.lang.reflect.Method) Path(java.nio.file.Path) OutputStream(java.io.OutputStream) PrintStream(java.io.PrintStream) Util(dev.jbang.util.Util) MalformedURLException(java.net.MalformedURLException) Files(java.nio.file.Files) FileOutputStream(java.io.FileOutputStream) Set(java.util.Set) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) EXIT_UNEXPECTED_STATE(dev.jbang.cli.BaseCommand.EXIT_UNEXPECTED_STATE) FileDescriptor(java.io.FileDescriptor) BufferedReader(java.io.BufferedReader) InputStream(java.io.InputStream) MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) URL(java.net.URL) URLClassLoader(java.net.URLClassLoader) List(java.util.List) ExitException(dev.jbang.cli.ExitException) Path(java.nio.file.Path) PrintStream(java.io.PrintStream) Method(java.lang.reflect.Method) ExitException(dev.jbang.cli.ExitException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) URLClassLoader(java.net.URLClassLoader) FileOutputStream(java.io.FileOutputStream) HashMap(java.util.HashMap) Map(java.util.Map)

Example 20 with ExitException

use of dev.jbang.cli.ExitException in project jbang by jbangdev.

the class KotlinManager method downloadAndInstallKotlin.

public static Path downloadAndInstallKotlin(String version) {
    Util.infoMsg("Downloading Kotlin " + version + ". Be patient, this can take several minutes...");
    String url = String.format(KOTLIN_DOWNLOAD_URL, version, version);
    Util.verboseMsg("Downloading " + url);
    Path kotlinDir = getKotlinPath(version);
    Path kotlinTmpDir = kotlinDir.getParent().resolve(kotlinDir.getFileName().toString() + ".tmp");
    Path kotlinOldDir = kotlinDir.getParent().resolve(kotlinDir.getFileName().toString() + ".old");
    Util.deletePath(kotlinTmpDir, false);
    Util.deletePath(kotlinOldDir, false);
    try {
        Path kotlinPkg = Util.downloadAndCacheFile(url);
        Util.infoMsg("Installing Kotlin " + version + "...");
        Util.verboseMsg("Unpacking to " + kotlinDir);
        UnpackUtil.unpack(kotlinPkg, kotlinTmpDir);
        if (Files.isDirectory(kotlinDir)) {
            Files.move(kotlinDir, kotlinOldDir);
        }
        Files.move(kotlinTmpDir, kotlinDir);
        Util.deletePath(kotlinOldDir, false);
        return kotlinDir;
    } catch (Exception e) {
        Util.deletePath(kotlinTmpDir, true);
        if (!Files.isDirectory(kotlinDir) && Files.isDirectory(kotlinOldDir)) {
            try {
                Files.move(kotlinOldDir, kotlinDir);
            } catch (IOException ex) {
            // Ignore
            }
        }
        Util.errorMsg("Required Kotlin version not possible to download or install.");
        throw new ExitException(EXIT_UNEXPECTED_STATE, "Unable to download or install kotlinc version " + version, e);
    }
}
Also used : Path(java.nio.file.Path) IOException(java.io.IOException) ExitException(dev.jbang.cli.ExitException) IOException(java.io.IOException) ExitException(dev.jbang.cli.ExitException)

Aggregations

ExitException (dev.jbang.cli.ExitException)25 IOException (java.io.IOException)17 Path (java.nio.file.Path)16 File (java.io.File)4 ArrayList (java.util.ArrayList)4 ResourceRef (dev.jbang.source.ResourceRef)3 Util (dev.jbang.util.Util)3 Collectors (java.util.stream.Collectors)3 Template (io.quarkus.qute.Template)2 BufferedReader (java.io.BufferedReader)2 InputStream (java.io.InputStream)2 InputStreamReader (java.io.InputStreamReader)2 URISyntaxException (java.net.URISyntaxException)2 URL (java.net.URL)2 Files (java.nio.file.Files)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 Set (java.util.Set)2 JsonParseException (com.google.gson.JsonParseException)1