Java Code Examples for org.gradle.api.GradleException

The following examples show how to use org.gradle.api.GradleException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: smallrye-graphql   Source File: GenerateSchemaTask.java    License: Apache License 2.0 6 votes vote down vote up
private void write(String schema) {
    try {
        if (destination == null || destination.isEmpty()) {
            // no destination file specified => print to stdout
            getLogger().quiet(schema);
        } else {
            Path path = new File(destination).toPath();
            path.toFile().getParentFile().mkdirs();
            Files.write(path, schema.getBytes(),
                    StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING);
            getLogger().info("Wrote the schema to " + path.toAbsolutePath().toString());
        }
    } catch (IOException e) {
        throw new GradleException("Can't write the result", e);
    }
}
 
Example 2
@TaskAction
public void action() {
    getProject().getLogger().info("ClientNativeLink action");

    boolean result;
    try {
        SubstrateDispatcher dispatcher = new ConfigBuild(project).createSubstrateDispatcher();
        result = dispatcher.nativeLink();
    } catch (Exception e) {
    	throw new GradleException("Failed to link", e);
    }

    if (!result) {
    	throw new GradleException("Linking failed");
    }
}
 
Example 3
Source Project: gradle-modules-plugin   Source File: ModularCreateStartScripts.java    License: MIT License 6 votes vote down vote up
private static void configure(ModularCreateStartScripts startScriptsTask, Project project) {
    var appConvention = project.getConvention().findPlugin(ApplicationPluginConvention.class);
    if (appConvention != null) {
        var distDir = project.file(project.getBuildDir() + "/install/" + appConvention.getApplicationName());
        startScriptsTask.setOutputDir(new File(distDir, appConvention.getExecutableDir()));
    }

    ModularJavaExec runTask = startScriptsTask.getRunTask();
    if (runTask == null) throw new GradleException("runTask not set for task " + startScriptsTask.getName());

    var runJvmArgs = runTask.getOwnJvmArgs();
    if (!runJvmArgs.isEmpty()) {
        var defaultJvmOpts = new ArrayList<>(runJvmArgs);
        startScriptsTask.getDefaultJvmOpts().forEach(defaultJvmOpts::add);
        startScriptsTask.setDefaultJvmOpts(defaultJvmOpts);
    }

    var mutator = new StartScriptsMutator(runTask, project);
    mutator.updateStartScriptsTask(startScriptsTask);
    mutator.movePatchedLibs();
}
 
Example 4
Source Project: swaggerhub-gradle-plugin   Source File: DownloadTask.java    License: Apache License 2.0 6 votes vote down vote up
@TaskAction
public void downloadDefinition() throws GradleException {
    SwaggerHubClient swaggerHubClient = new SwaggerHubClient(host, port, protocol, token);

    LOGGER.info("Downloading from " + host
            + ": api:" + api
            + ", owner:" + owner
            + ", version:" + version
            + ", format:" + format
            + ", outputFile:" + outputFile);

    SwaggerHubRequest swaggerHubRequest = new SwaggerHubRequest.Builder(api, owner, version)
            .format(format)
            .build();

    try {
        String swaggerJson = swaggerHubClient.getDefinition(swaggerHubRequest);
        File file = new File(outputFile);

        setUpOutputDir(file);
        Files.write(Paths.get(outputFile), swaggerJson.getBytes(Charset.forName("UTF-8")));
    } catch (IOException | GradleException e) {
        throw new GradleException(e.getMessage(), e);
    }
}
 
Example 5
public ExecAction getExecHandle() {
    try {
        options.write(optionsFile);
    } catch (IOException e) {
        throw new GradleException("Failed to store javadoc options.", e);
    }

    ExecAction execAction = execActionFactory.newExecAction();
    execAction.workingDir(execDirectory);
    execAction.executable(GUtil.elvis(executable, Jvm.current().getJavadocExecutable()));
    execAction.args("@" + optionsFile.getAbsolutePath());

    options.contributeCommandLineOptions(execAction);

    return execAction;
}
 
Example 6
Source Project: pushfish-android   Source File: Wrapper.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@TaskAction
void generate() {
    File jarFileDestination = getJarFile();
    File unixScript = getScriptFile();
    FileResolver resolver = getFileLookup().getFileResolver(unixScript.getParentFile());
    String jarFileRelativePath = resolver.resolveAsRelativePath(jarFileDestination);

    writeProperties(getPropertiesFile());

    URL jarFileSource = Wrapper.class.getResource("/gradle-wrapper.jar");
    if (jarFileSource == null) {
        throw new GradleException("Cannot locate wrapper JAR resource.");
    }
    GFileUtils.copyURLToFile(jarFileSource, jarFileDestination);

    StartScriptGenerator generator = new StartScriptGenerator();
    generator.setApplicationName("Gradle");
    generator.setMainClassName(GradleWrapperMain.class.getName());
    generator.setClasspath(WrapUtil.toList(jarFileRelativePath));
    generator.setOptsEnvironmentVar("GRADLE_OPTS");
    generator.setExitEnvironmentVar("GRADLE_EXIT_CONSOLE");
    generator.setAppNameSystemProperty("org.gradle.appname");
    generator.setScriptRelPath(unixScript.getName());
    generator.generateUnixScript(unixScript);
    generator.generateWindowsScript(getBatchScript());
}
 
Example 7
public Void methodMissing(String name, Object argsObj) {
    Object[] args = (Object[]) argsObj;

    if (!executingDsl.get()) {
        if (name.equals("$")) {
            throw new GradleException(ATTEMPTED_INPUT_SYNTAX_USED_MESSAGE);
        } else {
            throw new MissingMethodException(name, getClass(), args);
        }
    } else {
        if (args.length != 1 || !(args[0] instanceof Closure)) {
            throw new MissingMethodException(name, getClass(), args);
        } else {
            Closure closure = (Closure) args[0];
            getChildPath(name).registerConfigurationAction(closure);
            return null;
        }
    }
}
 
Example 8
public <T extends Script> Class<? extends T> loadFromDir(ScriptSource source, ClassLoader classLoader, File scriptCacheDir,
                                          Class<T> scriptBaseClass) {
    if (new File(scriptCacheDir, EMPTY_SCRIPT_MARKER_FILE_NAME).isFile()) {
        return emptyScriptGenerator.generate(scriptBaseClass);
    }
    
    try {
        URLClassLoader urlClassLoader = new URLClassLoader(WrapUtil.toArray(scriptCacheDir.toURI().toURL()),
                classLoader);
        return urlClassLoader.loadClass(source.getClassName()).asSubclass(scriptBaseClass);
    } catch (Exception e) {
        File expectedClassFile = new File(scriptCacheDir, source.getClassName()+".class");
        if(!expectedClassFile.exists()){
            throw new GradleException(String.format("Could not load compiled classes for %s from cache. Expected class file %s does not exist.", source.getDisplayName(), expectedClassFile.getAbsolutePath()), e);
        }
        throw new GradleException(String.format("Could not load compiled classes for %s from cache.", source.getDisplayName()), e);
    }
}
 
Example 9
private void applyConfigurationScript(File configScript, CompilerConfiguration configuration) {
    VersionNumber version = parseGroovyVersion();
    if (version.compareTo(VersionNumber.parse("2.1")) < 0) {
        throw new GradleException("Using a Groovy compiler configuration script requires Groovy 2.1+ but found Groovy " + version + "");
    }
    Binding binding = new Binding();
    binding.setVariable("configuration", configuration);

    CompilerConfiguration configuratorConfig = new CompilerConfiguration();
    ImportCustomizer customizer = new ImportCustomizer();
    customizer.addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
    configuratorConfig.addCompilationCustomizers(customizer);

    GroovyShell shell = new GroovyShell(binding, configuratorConfig);
    try {
        shell.evaluate(configScript);
    } catch (Exception e) {
        throw new GradleException("Could not execute Groovy compiler configuration script: " + configScript.getAbsolutePath(), e);
    }
}
 
Example 10
public Builder setLaunchables(Iterable<? extends Launchable> launchables) {
    Set<String> taskPaths = new LinkedHashSet<String>();
    List<InternalLaunchable> launchablesParams = Lists.newArrayList();
    for (Launchable launchable : launchables) {
        Object original = new ProtocolToModelAdapter().unpack(launchable);
        if (original instanceof InternalLaunchable) {
            // A launchable created by the provider - just hand it back
            launchablesParams.add((InternalLaunchable) original);
        } else if (original instanceof TaskListingLaunchable) {
            // A launchable synthesized by the consumer - unpack it into a set of task names
            taskPaths.addAll(((TaskListingLaunchable) original).getTaskNames());
        } else if (launchable instanceof Task) {
            // A task created by a provider that does not understand launchables
            taskPaths.add(((Task) launchable).getPath());
        } else {
            throw new GradleException("Only Task or TaskSelector instances are supported: "
                    + (launchable != null ? launchable.getClass() : "null"));
        }
    }
    this.launchables = launchablesParams;
    tasks = Lists.newArrayList(taskPaths);
    return this;
}
 
Example 11
public WorkResult execute(JavadocSpec spec) {
    JavadocExecHandleBuilder javadocExecHandleBuilder = new JavadocExecHandleBuilder(execActionFactory);
    javadocExecHandleBuilder.setExecutable(spec.getExecutable());
    javadocExecHandleBuilder.execDirectory(spec.getWorkingDir()).options(spec.getOptions()).optionsFile(spec.getOptionsFile());

    ExecAction execAction = javadocExecHandleBuilder.getExecHandle();
    if (spec.isIgnoreFailures()) {
        execAction.setIgnoreExitValue(true);
    }

    try {
        execAction.execute();
    } catch (ExecException e) {
        LOG.info("Problems generating Javadoc. The generated Javadoc options file used by Gradle has following contents:\n------\n{}------", GFileUtils.readFileQuietly(spec.getOptionsFile()));
        throw new GradleException(String.format("Javadoc generation failed. Generated Javadoc options file (useful for troubleshooting): '%s'", spec.getOptionsFile()), e);
    }

    return new SimpleWorkResult(true);
}
 
Example 12
public ExecAction getExecHandle() {
    try {
        options.write(optionsFile);
    } catch (IOException e) {
        throw new GradleException("Failed to store javadoc options.", e);
    }

    ExecAction execAction = execActionFactory.newExecAction();
    execAction.workingDir(execDirectory);
    execAction.executable(GUtil.elvis(executable, Jvm.current().getJavadocExecutable()));
    execAction.args("@" + optionsFile.getAbsolutePath());

    options.contributeCommandLineOptions(execAction);

    return execAction;
}
 
Example 13
Source Project: pushfish-android   Source File: Wrapper.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@TaskAction
void generate() {
    File jarFileDestination = getJarFile();
    File unixScript = getScriptFile();
    FileResolver resolver = getServices().get(FileLookup.class).getFileResolver(unixScript.getParentFile());
    String jarFileRelativePath = resolver.resolveAsRelativePath(jarFileDestination);

    writeProperties(getPropertiesFile());

    URL jarFileSource = Wrapper.class.getResource("/gradle-wrapper.jar");
    if (jarFileSource == null) {
        throw new GradleException("Cannot locate wrapper JAR resource.");
    }
    GFileUtils.copyURLToFile(jarFileSource, jarFileDestination);

    StartScriptGenerator generator = new StartScriptGenerator();
    generator.setApplicationName("Gradle");
    generator.setMainClassName(GradleWrapperMain.class.getName());
    generator.setClasspath(WrapUtil.toList(jarFileRelativePath));
    generator.setOptsEnvironmentVar("GRADLE_OPTS");
    generator.setExitEnvironmentVar("GRADLE_EXIT_CONSOLE");
    generator.setAppNameSystemProperty("org.gradle.appname");
    generator.setScriptRelPath(unixScript.getName());
    generator.generateUnixScript(unixScript);
    generator.generateWindowsScript(getBatchScript());
}
 
Example 14
public DefaultBuildInvocations buildAll(String modelName, Project project) {
    if (!canBuild(modelName)) {
        throw new GradleException("Unknown model name " + modelName);
    }
    List<LaunchableGradleTaskSelector> selectors = Lists.newArrayList();
    Set<String> aggregatedTasks = Sets.newLinkedHashSet();
    Set<String> visibleTasks = Sets.newLinkedHashSet();
    findTasks(project, aggregatedTasks, visibleTasks);
    for (String selectorName : aggregatedTasks) {
        selectors.add(new LaunchableGradleTaskSelector().
                setName(selectorName).
                setTaskName(selectorName).
                setProjectPath(project.getPath()).
                setDescription(project.getParent() != null
                        ? String.format("%s:%s task selector", project.getPath(), selectorName)
                        : String.format("%s task selector", selectorName)).
                setDisplayName(String.format("%s in %s and subprojects.", selectorName, project.toString())).
                setPublic(visibleTasks.contains(selectorName)));
    }
    return new DefaultBuildInvocations()
            .setSelectors(selectors)
            .setTasks(tasks(project));
}
 
Example 15
public void execute(TaskInternal task, TaskStateInternal state, TaskExecutionContext context) {
    boolean skip;
    try {
        skip = !task.getOnlyIf().isSatisfiedBy(task);
    } catch (Throwable t) {
        state.executed(new GradleException(String.format("Could not evaluate onlyIf predicate for %s.", task), t));
        return;
    }

    if (skip) {
        LOGGER.info("Skipping {} as task onlyIf is false.", task);
        state.skipped("SKIPPED");
        return;
    }

    executer.execute(task, state, context);
}
 
Example 16
public <T extends Script> Class<? extends T> loadFromDir(ScriptSource source, ClassLoader classLoader, File scriptCacheDir,
                                                         Class<T> scriptBaseClass) {
    if (new File(scriptCacheDir, EMPTY_SCRIPT_MARKER_FILE_NAME).isFile()) {
        return emptyScriptGenerator.generate(scriptBaseClass);
    }

    try {
        URLClassLoader urlClassLoader = new URLClassLoader(WrapUtil.toArray(scriptCacheDir.toURI().toURL()), classLoader);
        return urlClassLoader.loadClass(source.getClassName()).asSubclass(scriptBaseClass);
    } catch (Exception e) {
        File expectedClassFile = new File(scriptCacheDir, source.getClassName() + ".class");
        if (!expectedClassFile.exists()) {
            throw new GradleException(String.format("Could not load compiled classes for %s from cache. Expected class file %s does not exist.", source.getDisplayName(), expectedClassFile.getAbsolutePath()), e);
        }
        throw new GradleException(String.format("Could not load compiled classes for %s from cache.", source.getDisplayName()), e);
    }
}
 
Example 17
Source Project: swaggerhub-gradle-plugin   Source File: SwaggerHubClient.java    License: Apache License 2.0 6 votes vote down vote up
public void saveDefinition(SwaggerHubRequest swaggerHubRequest) throws GradleException {
    HttpUrl httpUrl = getUploadUrl(swaggerHubRequest);
    MediaType mediaType = MediaType.parse("application/" + swaggerHubRequest.getFormat());

    final Request httpRequest = buildPostRequest(httpUrl, mediaType, swaggerHubRequest.getSwagger());

    try {
        Response response = client.newCall(httpRequest).execute();
        if (!response.isSuccessful()) {
            throw new GradleException(
                    String.format("Failed to upload definition: %s", response.body().string())
            );
        }
    } catch (IOException e) {
        throw new GradleException("Failed to upload definition", e);
    }
    return;
}
 
Example 18
/**
 * Register to be released alongside another Firebase Library project.
 *
 * <p>This will force the released version of the current project to match the one it's released
 * with.
 */
public void releaseWith(Project releaseWithProject) {
  try {
    FirebaseLibraryExtension releaseWithLibrary =
        releaseWithProject.getExtensions().getByType(FirebaseLibraryExtension.class);
    releaseWithLibrary.librariesToCoRelease.add(this);
    this.project.setVersion(releaseWithProject.getVersion());

    String latestRelease = "latestReleasedVersion";
    if (releaseWithProject.getExtensions().getExtraProperties().has(latestRelease)) {
      this.project
          .getExtensions()
          .getExtraProperties()
          .set(latestRelease, releaseWithProject.getProperties().get(latestRelease));
    }

  } catch (UnknownDomainObjectException ex) {
    throw new GradleException(
        "Library cannot be released with a project that is not a Firebase Library itself");
  }
}
 
Example 19
public WorkResult execute(T spec) {
    ExecAction compiler = execActionFactory.newExecAction();
    compiler.executable(executable);
    if (workDir != null) {
        compiler.workingDir(workDir);
    }

    List<String> args = specToArgs.transform(specTransformer.transform(spec));
    compiler.args(args);

    if (!path.isEmpty()) {
        String pathVar = OperatingSystem.current().getPathVar();
        String compilerPath = Joiner.on(File.pathSeparator).join(path);
        compilerPath = compilerPath + File.pathSeparator + System.getenv(pathVar);
        compiler.environment(pathVar, compilerPath);
    }

    compiler.environment(environment);

    try {
        compiler.execute();
    } catch (ExecException e) {
        throw new GradleException(String.format("%s failed; see the error output for details.", action), e);
    }
    return new SimpleWorkResult(true);
}
 
Example 20
@Override
public void generateFile(File toBeGenerated, File original) throws IOException {
    try {
        super.generateFile(toBeGenerated, original);
    } catch (ResourcesNotSupportedException e) {
        // Add gradle-specific error message.
        throw new GradleException(
                String.format(
                        "Can't process attribute %1$s=\"%2$s\": "
                                + "references to other resources are not supported by "
                                + "build-time PNG generation. "
                                + "See http://developer.android.com/tools/help/vector-asset-studio.html "
                                + "for details.",
                        e.getName(), e.getValue()));
    }
}
 
Example 21
Source Project: skara   Source File: DownloadJDKTask.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static String checksum(Path file) throws IOException {
    try {
        var digest = MessageDigest.getInstance("SHA-256");
        var bytes = new byte[4096];
        try (var stream = Files.newInputStream(file)) {
            for (var read = stream.read(bytes); read != -1; read = stream.read(bytes)) {
                digest.update(bytes, 0, read);
            }
        }
        return new BigInteger(1, digest.digest()).toString(16);
    } catch (NoSuchAlgorithmException e) {
        throw new GradleException("this JRE does not support SHA-256");
    }
}
 
Example 22
public void build() {
	ProjectConfiguration clientConfig = createSubstrateConfiguration();

    boolean result;
    try {
        String mainClassName = clientConfig.getMainClassName();
        String name = clientConfig.getAppName();
        for (org.gradle.api.artifacts.Configuration configuration : project.getBuildscript().getConfigurations()) {
            project.getLogger().debug("Configuration = " + configuration);
            DependencySet deps = configuration.getAllDependencies();
            project.getLogger().debug("Dependencies = " + deps);
            deps.forEach(dep -> project.getLogger().debug("Dependency = " + dep));
        }
        project.getLogger().debug("mainClassName = " + mainClassName + " and app name = " + name);

        Path buildRootPath = project.getLayout().getBuildDirectory().dir("client").get().getAsFile().toPath();
        project.getLogger().debug("BuildRoot: " + buildRootPath);
        
        SubstrateDispatcher dispatcher = new SubstrateDispatcher(buildRootPath, clientConfig);
        result = dispatcher.nativeCompile();
    } catch (Exception e) {
        throw new GradleException("Failed to compile", e);
    }

    if (!result) {
        throw new IllegalStateException("Compilation failed");
    }
}
 
Example 23
private Path getGraalHome() {
    String graalvmHome = clientExtension.getGraalvmHome();
    if (graalvmHome == null) {
    	graalvmHome = System.getenv("GRAALVM_HOME");
    }
    if (graalvmHome == null) {
        throw new GradleException("GraalVM installation directory not found." +
                " Either set GRAALVM_HOME as an environment variable or" +
                " set graalvmHome in the client-plugin configuration");
    }
    return Path.of(graalvmHome);
}
 
Example 24
Source Project: swaggerhub-gradle-plugin   Source File: UploadTask.java    License: Apache License 2.0 5 votes vote down vote up
@TaskAction
public void uploadDefinition() throws GradleException {

    swaggerHubClient = new SwaggerHubClient(host, port, protocol, token);

    LOGGER.info("Uploading to " + host
            + ": api: " + api
            + ", owner: " + owner
            + ", version: " + version
            + ", inputFile: " + inputFile
            + ", format: " + format
            + ", isPrivate: " + isPrivate
            + ", oas: " + oas);

    try {
        String content = new String(Files.readAllBytes(Paths.get(inputFile)), Charset.forName("UTF-8"));

        SwaggerHubRequest swaggerHubRequest = new SwaggerHubRequest.Builder(api, owner, version)
                .swagger(content)
                .format(format)
                .isPrivate(isPrivate)
                .oas(oas)
                .build();

        swaggerHubClient.saveDefinition(swaggerHubRequest);
    } catch (IOException | GradleException e) {
        throw new GradleException(e.getMessage(), e);
    }
}
 
Example 25
public AttachServiceDefinition(String name) {
    this.name = name;

    try {
        this.service = AttachService.valueOf(name.replace('-', '_').toUpperCase(Locale.ROOT));
    } catch (IllegalArgumentException e) {
        String services = Stream.of(AttachService.values())
                .map(AttachService::getServiceName)
                .collect(Collectors.joining(", "));
        LOGGER.log(LogLevel.ERROR, "Could not determine Attach service for name '" + name + "'. The following services are available: " + services);
        throw new GradleException("Invalid name for Attach service: " + name, e);
    }
}
 
Example 26
Source Project: gradle-modules-plugin   Source File: TestTask.java    License: MIT License 5 votes vote down vote up
private static Stream<Path> buildRelativePathStream(Path dir) {
    try {
        return Files.walk(dir)
                .filter(Files::isRegularFile)
                .filter(path -> isValidClassFileReference(path.toString()))
                .map(path -> dir.relativize(path.getParent()));
    } catch (IOException e) {
        throw new GradleException("Failed to scan " + dir, e);
    }
}
 
Example 27
Source Project: gradle-modules-plugin   Source File: StartScriptsMutator.java    License: MIT License 5 votes vote down vote up
private static void replaceScriptContent(Path path, String regex, String replacement) {
    try {
        String updatedScriptContent = Files.readString(path).replaceAll(regex, replacement);

        Files.writeString(path, updatedScriptContent);
    } catch (IOException e) {
        throw new GradleException("Couldn't update run script in " + path);
    }
}
 
Example 28
private VersionNumber getFindbugsVersion(Iterable<String> classpath) {
    for (String f: classpath) {
        Matcher m = Pattern.compile("findbugs-(.*)\\.jar").matcher(f);
        if (m.matches()) {
            return VersionNumber.parse(m.group(1));
        }
    }
    throw new GradleException("Unable to infer the version of FindBugs from currently specified FindBugs classpath: " + classpath);
}
 
Example 29
private ModuleDependency findDependency(ModuleDependency dependency, Configuration configuration) {
    for (ModuleDependency configurationDependency : configuration.getDependencies().withType(ModuleDependency.class)) {
        if (dependency.equals(configurationDependency)) {
            return configurationDependency;
        }
    }
    throw new GradleException("Dependency could not be found. We should never get here!");
}
 
Example 30
private void attachDefaultProject(GradleInternal gradle) {
    ProjectSpec spec = ProjectSpecs.forStartParameter(gradle.getStartParameter());
    try {
        gradle.setDefaultProject(spec.selectProject(gradle.getRootProject().getProjectRegistry()));
    } catch (InvalidUserDataException e) {
        throw new GradleException(String.format("Could not select the default project for this build. %s",
                e.getMessage()), e);
    }
}