Search in sources :

Example 21 with ExitException

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

the class RunContext method forResource.

public Code forResource(String resource) {
    Catalog catalog = getCatalog() != null ? Catalog.get(getCatalog().toPath()) : null;
    ResourceResolver resolver = ResourceResolver.forScripts(this::resolveDependency, catalog);
    ResourceRef resourceRef = resolver.resolve(resource);
    // just proceed if the script file is a regular file at this point
    if (resourceRef == null || !resourceRef.getFile().canRead()) {
        throw new ExitException(BaseCommand.EXIT_INVALID_INPUT, "Script or alias could not be found or read: '" + resource + "'");
    }
    if (resourceRef instanceof AliasResourceResolver.AliasedResourceRef) {
        // The resource we found was obtained from an alias which might
        // contain extra options that need to be taken into account
        // when running the code
        Alias alias = ((AliasResourceResolver.AliasedResourceRef) resourceRef).getAlias();
        if (getArguments() == null || getArguments().isEmpty()) {
            setArguments(alias.arguments);
        }
        if (getJavaOptions() == null || getJavaOptions().isEmpty()) {
            setJavaOptions(alias.javaOptions);
        }
        if (getAdditionalSources() == null || getAdditionalSources().isEmpty()) {
            setAdditionalSources(alias.sources);
        }
        if (getAdditionalDependencies() == null || getAdditionalDependencies().isEmpty()) {
            setAdditionalDependencies(alias.dependencies);
        }
        if (getAdditionalRepositories() == null || getAdditionalRepositories().isEmpty()) {
            setAdditionalRepositories(alias.repositories);
        }
        if (getAdditionalClasspaths() == null || getAdditionalClasspaths().isEmpty()) {
            setAdditionalClasspaths(alias.classpaths);
        }
        if (getProperties() == null || getProperties().isEmpty()) {
            setProperties(alias.properties);
        }
        if (getJavaVersion() == null) {
            setJavaVersion(alias.javaVersion);
        }
        if (getMainClass() == null) {
            setMainClass(alias.mainClass);
        }
        setAlias(alias);
    }
    // note script file must be not null at this point
    setOriginalRef(resource);
    return forResourceRef(resourceRef);
}
Also used : Alias(dev.jbang.catalog.Alias) AliasResourceResolver(dev.jbang.source.resolvers.AliasResourceResolver) ExitException(dev.jbang.cli.ExitException) Catalog(dev.jbang.catalog.Catalog)

Example 22 with ExitException

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

the class JarCmdGenerator method generateCommandLineList.

@Override
protected List<String> generateCommandLineList() throws IOException {
    List<String> fullArgs = new ArrayList<>();
    if (ctx.isNativeImage()) {
        String imagename = getImageName(code.getJarFile()).toString();
        if (new File(imagename).exists()) {
            fullArgs.add(imagename);
        } else {
            Util.warnMsg("native built image not found - running in java mode.");
        }
    }
    if (fullArgs.isEmpty()) {
        String classpath = ctx.resolveClassPath(code);
        List<String> optionalArgs = new ArrayList<>();
        String requestedJavaVersion = ctx.getJavaVersion() != null ? ctx.getJavaVersion() : code.getJavaVersion().orElse(null);
        String javacmd = JavaUtil.resolveInJavaHome("java", requestedJavaVersion);
        addPropertyFlags(ctx.getProperties(), "-D", optionalArgs);
        // optionalArgs.add("--source 11");
        if (ctx.isDebugEnabled()) {
            optionalArgs.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=" + ctx.getDebugString());
        }
        if (ctx.isEnableAssertions()) {
            optionalArgs.add("-ea");
        }
        if (ctx.isEnableSystemAssertions()) {
            optionalArgs.add("-esa");
        }
        if (ctx.isFlightRecordingEnabled()) {
            // TODO: find way to generate ~/.jbang/script.jfc to configure flightrecorder to
            // have 0 ms thresholds
            String jfropt = "-XX:StartFlightRecording=" + ctx.getFlightRecorderString().replace("{baseName}", Util.getBaseName(code.getResourceRef().getFile().toString()));
            optionalArgs.add(jfropt);
            Util.verboseMsg("Flight recording enabled with:" + jfropt);
        }
        if (code.getJarFile() != null) {
            if (Util.isBlankString(classpath)) {
                classpath = code.getJarFile().getAbsolutePath();
            } else {
                classpath = code.getJarFile().getAbsolutePath() + Settings.CP_SEPARATOR + classpath.trim();
            }
        }
        if (!Util.isBlankString(classpath)) {
            optionalArgs.add("-classpath");
            optionalArgs.add(classpath);
        }
        if (Optional.ofNullable(ctx.getClassDataSharing()).orElse(code.enableCDS())) {
            Path cdsJsa = code.getJarFile().toPath().toAbsolutePath();
            if (Files.exists(cdsJsa)) {
                Util.verboseMsg("CDS: Using shared archive classes from " + cdsJsa);
                optionalArgs.add("-XX:SharedArchiveFile=" + cdsJsa);
            } else {
                Util.verboseMsg("CDS: Archiving Classes At Exit at " + cdsJsa);
                optionalArgs.add("-XX:ArchiveClassesAtExit=" + cdsJsa);
            }
        }
        fullArgs.add(javacmd);
        addAgentsArgs(fullArgs);
        fullArgs.addAll(ctx.getRuntimeOptionsMerged(code));
        fullArgs.addAll(ctx.getAutoDetectedModuleArguments(code, requestedJavaVersion));
        fullArgs.addAll(optionalArgs);
        String mainClass = ctx.getMainClassOr(code);
        if (mainClass != null) {
            fullArgs.add(mainClass);
        } else {
            throw new ExitException(BaseCommand.EXIT_INVALID_INPUT, "no main class deduced, specified nor found in a manifest");
        }
    }
    fullArgs.addAll(ctx.getArguments());
    return fullArgs;
}
Also used : Path(java.nio.file.Path) ArrayList(java.util.ArrayList) File(java.io.File) ExitException(dev.jbang.cli.ExitException)

Example 23 with ExitException

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

the class DependencyUtil method resolveDependenciesViaAether.

public static List<ArtifactInfo> resolveDependenciesViaAether(List<String> depIds, List<MavenRepo> customRepos, boolean offline, boolean loggingEnabled, boolean transitively) {
    ConfigurableMavenResolverSystem resolver = Maven.configureResolver().withMavenCentralRepo(false).workOffline(offline);
    customRepos.forEach(mavenRepo -> mavenRepo.apply(resolver));
    System.setProperty("maven.repo.local", Settings.getLocalMavenRepo().toPath().toAbsolutePath().toString());
    Map<Boolean, List<MavenCoordinate>> coordList = depIds.stream().map(DependencyUtil::depIdToArtifact).collect(Collectors.partitioningBy(c -> c.getType().equals(PackagingType.POM)));
    List<MavenCoordinate> coords = coordList.get(false);
    List<MavenCoordinate> pomcoords = coordList.get(true);
    PomEquippedResolveStage pomResolve = null;
    if (!pomcoords.isEmpty()) {
        String beforeDepMgmt = "<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" + "         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + "         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n" + "    <modelVersion>4.0.0</modelVersion>\n" + "\n" + "    <groupId>dev.jbang.internal</groupId>\n" + "    <artifactId>dependency-pom</artifactId>\n" + "    <version>1.0-SNAPSHOT</version>\n" + "    <packaging>pom</packaging>\n" + "<dependencyManagement>\n" + "    <dependencies>\n";
        String afterDepMgmt = "</dependencies>\n" + "</dependencyManagement>\n" + "</project>";
        StringBuffer buf = new StringBuffer(beforeDepMgmt);
        for (MavenCoordinate pomcoord : pomcoords) {
            buf.append("<dependency>\n" + "      <groupId>" + pomcoord.getGroupId() + "</groupId>\n" + "      <artifactId>" + pomcoord.getArtifactId() + "</artifactId>\n" + "      <version>" + pomcoord.getVersion() + "</version>\n" + "             <type>pom</type>\n" + "      <scope>import</scope>\n" + "    </dependency>\n");
        }
        buf.append(afterDepMgmt);
        Path pompath = null;
        try {
            pompath = File.createTempFile("jbang", ".xml").toPath();
            Util.writeString(pompath, buf.toString());
        } catch (IOException e) {
            throw new ExitException(CommandLine.ExitCode.SOFTWARE, "Error trying to generate pom.xml for dependency management");
        }
        if (loggingEnabled) {
            infoMsg("Artifacts used for dependency management:");
            infoMsgFmt("         %s\n", String.join("\n         ", pomcoords.stream().map(Coordinate::toCanonicalForm).collect(Collectors.toList())));
        }
        pomResolve = resolver.loadPomFromFile(pompath.toFile());
    }
    Optional<MavenCoordinate> pom = coords.stream().filter(c -> c.getType().equals(PackagingType.POM)).findFirst();
    if (pom.isPresent()) {
        // when we support more than one BOM POM
        throw new ExitException(1, "POM imports as found in " + pom.get().toCanonicalForm() + " is only supported as the first import.");
    }
    List<String> canonicals = coords.stream().map(Coordinate::toCanonicalForm).collect(Collectors.toList());
    if (loggingEnabled) {
        infoHeader();
        infoMsgFmt("%s\n", String.join("\n         ", canonicals));
    }
    try {
        MavenStrategyStage resolve;
        if (pomResolve != null) {
            resolve = pomResolve.resolve(canonicals);
        } else {
            resolve = resolver.resolve(canonicals);
        }
        MavenFormatStage stage = transitively ? resolve.withTransitivity() : resolve.withoutTransitivity();
        // , RUNTIME);
        List<MavenResolvedArtifact> artifacts = stage.asList(MavenResolvedArtifact.class);
        if (loggingEnabled)
            infoMsgFmt("Done\n");
        return artifacts.stream().map(mra -> new ArtifactInfo(mra.getCoordinate(), mra.asFile())).collect(Collectors.toList());
    } catch (ResolutionException nrr) {
        Throwable cause = nrr.getCause();
        Set<Throwable> causes = new LinkedHashSet<Throwable>();
        StringBuffer buf = new StringBuffer();
        buf.append(nrr.getMessage());
        while (cause != null && !causes.contains(cause)) {
            causes.add(cause);
            buf.append("\n  " + cause.getMessage());
        }
        String repos = customRepos.stream().map(repo -> repo.toString()).collect(Collectors.joining(", "));
        throw new ExitException(1, String.format("Could not resolve dependencies from %s\n", repos) + buf.toString(), nrr);
    } catch (RuntimeException e) {
        throw new ExitException(1, "Unknown error occurred while trying to resolve dependencies", e);
    }
}
Also used : MavenFormatStage(org.jboss.shrinkwrap.resolver.api.maven.MavenFormatStage) Coordinate(org.jboss.shrinkwrap.resolver.api.Coordinate) HashMap(java.util.HashMap) PackagingType(org.jboss.shrinkwrap.resolver.api.maven.PackagingType) ArrayList(java.util.ArrayList) ExitException(dev.jbang.cli.ExitException) Util.errorMsg(dev.jbang.util.Util.errorMsg) Maven(org.jboss.shrinkwrap.resolver.api.maven.Maven) Matcher(java.util.regex.Matcher) CP_SEPARATOR(dev.jbang.Settings.CP_SEPARATOR) ResolutionException(org.jboss.shrinkwrap.resolver.api.ResolutionException) Map(java.util.Map) MavenCoordinates(org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinates) Path(java.nio.file.Path) LinkedHashSet(java.util.LinkedHashSet) CommandLine(picocli.CommandLine) Util(dev.jbang.util.Util) MavenStrategyStage(org.jboss.shrinkwrap.resolver.api.maven.MavenStrategyStage) Util.infoMsg(dev.jbang.util.Util.infoMsg) PomEquippedResolveStage(org.jboss.shrinkwrap.resolver.api.maven.PomEquippedResolveStage) Set(java.util.Set) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) File(java.io.File) List(java.util.List) ConfigurableMavenResolverSystem(org.jboss.shrinkwrap.resolver.api.maven.ConfigurableMavenResolverSystem) Util.infoMsgFmt(dev.jbang.util.Util.infoMsgFmt) MavenResolvedArtifact(org.jboss.shrinkwrap.resolver.api.maven.MavenResolvedArtifact) Optional(java.util.Optional) MavenCoordinate(org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinate) Settings(dev.jbang.Settings) Util.infoHeader(dev.jbang.util.Util.infoHeader) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) ArrayList(java.util.ArrayList) List(java.util.List) MavenStrategyStage(org.jboss.shrinkwrap.resolver.api.maven.MavenStrategyStage) ExitException(dev.jbang.cli.ExitException) ConfigurableMavenResolverSystem(org.jboss.shrinkwrap.resolver.api.maven.ConfigurableMavenResolverSystem) Path(java.nio.file.Path) MavenResolvedArtifact(org.jboss.shrinkwrap.resolver.api.maven.MavenResolvedArtifact) MavenFormatStage(org.jboss.shrinkwrap.resolver.api.maven.MavenFormatStage) IOException(java.io.IOException) PomEquippedResolveStage(org.jboss.shrinkwrap.resolver.api.maven.PomEquippedResolveStage) ResolutionException(org.jboss.shrinkwrap.resolver.api.ResolutionException) MavenCoordinate(org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinate)

Example 24 with ExitException

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

the class TrustedSources method createTrustedSources.

public static void createTrustedSources() {
    Path trustedSourcesFile = Settings.getTrustedSourcesFile();
    if (Files.notExists(trustedSourcesFile)) {
        String templateName = "trusted-sources.qute";
        Template template = TemplateEngine.instance().getTemplate(templateName);
        if (template == null)
            throw new ExitException(1, "Could not locate template named: '" + templateName + "'");
        String result = template.render();
        try {
            Util.writeString(trustedSourcesFile, result);
        } catch (IOException e) {
            Util.errorMsg("Could not create initial trusted-sources file at " + trustedSourcesFile, e);
        }
    }
}
Also used : Path(java.nio.file.Path) IOException(java.io.IOException) ExitException(dev.jbang.cli.ExitException) Template(io.quarkus.qute.Template)

Example 25 with ExitException

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

the class Catalog method getByRef.

/**
 * Load a Catalog's aliases given a file path or URL
 *
 * @param catalogRef File path or URL to a Catalog JSON file. If this does not
 *                   end in .json then jbang-catalog.json will be appended to
 *                   the end.
 * @return A Catalog object
 */
public static Catalog getByRef(String catalogRef) {
    if (!catalogRef.endsWith(".json")) {
        if (!catalogRef.endsWith("/")) {
            catalogRef += "/";
        }
        catalogRef += JBANG_CATALOG_JSON;
    }
    Path catalogPath = null;
    try {
        Catalog catalog = get(ResourceRef.forResource(catalogRef));
        if (catalog == null) {
            throw new ExitException(EXIT_UNEXPECTED_STATE, "Unable to download catalog: " + catalogRef);
        }
        Util.verboseMsg(String.format("Obtained catalog from %s", catalogRef));
        int p = catalogRef.lastIndexOf('/');
        if (p > 0) {
            String baseRef = catalog.baseRef;
            String catalogBaseRef = catalogRef.substring(0, p);
            if (baseRef != null) {
                if (!baseRef.startsWith("/") && !baseRef.contains(":")) {
                    baseRef = catalogBaseRef + "/" + baseRef;
                }
            } else {
                baseRef = catalogBaseRef;
            }
            catalog = new Catalog(baseRef, catalog.description, catalog.catalogRef, catalog.catalogs, catalog.aliases, catalog.templates);
        }
        return catalog;
    } catch (JsonParseException ex) {
        throw new ExitException(EXIT_UNEXPECTED_STATE, "Unable to download catalog: " + catalogRef + " via " + catalogPath, ex);
    }
}
Also used : Path(java.nio.file.Path) JsonParseException(com.google.gson.JsonParseException) 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