Search in sources :

Example 1 with Source

use of dev.jbang.source.Source in project jbang by jbangdev.

the class JshCmdGenerator method generateCommandLineList.

@Override
protected List<String> generateCommandLineList() throws IOException {
    List<String> fullArgs = new ArrayList<>();
    String classpath = ctx.resolveClassPath(ss);
    List<String> optionalArgs = new ArrayList<>();
    String requestedJavaVersion = ctx.getJavaVersion() != null ? ctx.getJavaVersion() : ss.getJavaVersion().orElse(null);
    String javacmd;
    javacmd = JavaUtil.resolveInJavaHome("jshell", requestedJavaVersion);
    if (ss.getJarFile() != null && ss.getJarFile().exists()) {
        if (Util.isBlankString(classpath)) {
            classpath = ss.getJarFile().getAbsolutePath();
        } else {
            classpath = ss.getJarFile().getAbsolutePath() + Settings.CP_SEPARATOR + classpath.trim();
        }
    }
    // NB: See https://github.com/jbangdev/jbang/issues/992 for the reasons why we
    // use the -J flags below
    optionalArgs.add("--execution=local");
    optionalArgs.add("-J--add-modules=ALL-SYSTEM");
    if (!Util.isBlankString(classpath)) {
        optionalArgs.add("--class-path=" + classpath);
        optionalArgs.add("-J--class-path=" + classpath);
    }
    optionalArgs.add("--startup=DEFAULT");
    File tempFile = File.createTempFile("jbang_arguments_", ss.getResourceRef().getFile().getName());
    String defaultImports = "import java.lang.*;\n" + "import java.util.*;\n" + "import java.io.*;" + "import java.net.*;" + "import java.math.BigInteger;\n" + "import java.math.BigDecimal;\n";
    Util.writeString(tempFile.toPath(), defaultImports + generateArgs(ctx.getArguments(), ctx.getProperties()) + generateStdInputHelper() + generateMain(ctx.getMainClass()));
    if (ctx.getMainClass() != null) {
        if (!ctx.getMainClass().contains(".")) {
            Util.warnMsg("Main class `" + ctx.getMainClass() + "` is in the default package which JShell unfortunately does not support. You can still use JShell to explore the JDK and any dependencies available on the classpath.");
        } else {
            Util.infoMsg("You can run the main class `" + ctx.getMainClass() + "` using: userMain(args)");
        }
    }
    optionalArgs.add("--startup=" + tempFile.getAbsolutePath());
    if (ctx.isDebugEnabled()) {
        Util.warnMsg("debug not possible when running via jshell.");
    }
    if (ctx.isFlightRecordingEnabled()) {
        Util.warnMsg("Java Flight Recording not possible when running via jshell.");
    }
    fullArgs.add(javacmd);
    addAgentsArgs(fullArgs);
    fullArgs.addAll(jshellOpts(ctx.getRuntimeOptionsMerged(ss)));
    fullArgs.addAll(jshellOpts(ctx.getAutoDetectedModuleArguments(ss, requestedJavaVersion)));
    fullArgs.addAll(optionalArgs);
    if (ss.isJShell() || ctx.isForceJsh()) {
        ArrayList<Source> revSources = new ArrayList<>(ss.getSources());
        Collections.reverse(revSources);
        for (Source s : revSources) {
            fullArgs.add(s.getResourceRef().getFile().toString());
        }
    }
    if (!ctx.isInteractive()) {
        File exitFile = File.createTempFile("jbang_exit_", ss.getResourceRef().getFile().getName());
        Util.writeString(exitFile.toPath(), "/exit");
        fullArgs.add(exitFile.toString());
    }
    return fullArgs;
}
Also used : File(java.io.File) Source(dev.jbang.source.Source)

Example 2 with Source

use of dev.jbang.source.Source 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 3 with Source

use of dev.jbang.source.Source in project jbang by jbangdev.

the class TestGrape method testFindGrabs.

@Test
void testFindGrabs() throws FileNotFoundException {
    String grabBlock = "@Grapes({\n" + "\t\t@Grab(\"log4j:log4j:1.2.17\"),\n" + "\t\t@Grab(group = \"org.hibernate\", module = \"hibernate-core\", version = \"5.4.10.Final\"),\n" + "\t\t@Grab(group=\"net.sf.json-lib\", module=\"json-lib\", version=\"2.2.3\", classifier=\"jdk15\"), // classifier\n" + "\t\t@Grab(group=\"org.restlet\", version=\"1.1.6\", module=\"org.restlet\")  // different order\n" + "\t\t@Grab(group=\"org.restlet\", version=\"1.1.6\", module=\"org.restlet\", ext=\"wonka\")  // different order\n" + "\t//\t@Grab(group=\"blah\", version=\"1.0\", module=\"borked\", ext=\"wonka\")  // commented\n" + "})\n";
    Source src = new JavaSource(grabBlock, null);
    SourceSet ss = SourceSet.forSource(src);
    List<String> deps = ss.getDependencies();
    assertThat(deps, hasItem("org.hibernate:hibernate-core:5.4.10.Final"));
    assertThat(deps, hasItem("net.sf.json-lib:json-lib:2.2.3:jdk15"));
    assertThat(deps, hasItem("org.restlet:org.restlet:1.1.6"));
    assertThat(deps, hasItem("log4j:log4j:1.2.17"));
    assertThat(deps, not(hasItem("blah:borked:1.0@wonka")));
}
Also used : SourceSet(dev.jbang.source.SourceSet) JavaSource(dev.jbang.source.sources.JavaSource) JavaSource(dev.jbang.source.sources.JavaSource) Source(dev.jbang.source.Source) Test(org.junit.jupiter.api.Test) BaseTest(dev.jbang.BaseTest)

Aggregations

Source (dev.jbang.source.Source)3 BaseTest (dev.jbang.BaseTest)1 EXIT_UNEXPECTED_STATE (dev.jbang.cli.BaseCommand.EXIT_UNEXPECTED_STATE)1 ExitException (dev.jbang.cli.ExitException)1 ArtifactInfo (dev.jbang.dependencies.ArtifactInfo)1 MavenRepo (dev.jbang.dependencies.MavenRepo)1 SourceSet (dev.jbang.source.SourceSet)1 JavaSource (dev.jbang.source.sources.JavaSource)1 Util (dev.jbang.util.Util)1 BufferedReader (java.io.BufferedReader)1 File (java.io.File)1 FileDescriptor (java.io.FileDescriptor)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1 OutputStream (java.io.OutputStream)1 PrintStream (java.io.PrintStream)1 Method (java.lang.reflect.Method)1 MalformedURLException (java.net.MalformedURLException)1