Search in sources :

Example 1 with UnsupportedVersionException

use of org.gradle.tooling.UnsupportedVersionException in project intellij-community by JetBrains.

the class BaseProjectImportErrorHandler method getUserFriendlyError.

@NotNull
@Override
public ExternalSystemException getUserFriendlyError(@NotNull Throwable error, @NotNull String projectPath, @Nullable String buildFilePath) {
    if (error instanceof ExternalSystemException) {
        // This is already a user-friendly error.
        return (ExternalSystemException) error;
    }
    LOG.info(String.format("Failed to import Gradle project at '%1$s'", projectPath), error);
    if (error instanceof ProcessCanceledException) {
        return new ExternalSystemException("Project import was cancelled");
    }
    Pair<Throwable, String> rootCauseAndLocation = getRootCauseAndLocation(error);
    //noinspection ThrowableResultOfMethodCallIgnored
    Throwable rootCause = rootCauseAndLocation.getFirst();
    String location = rootCauseAndLocation.getSecond();
    if (location == null && !StringUtil.isEmpty(buildFilePath)) {
        location = String.format("Build file: '%1$s'", buildFilePath);
    }
    if (rootCause instanceof UnsupportedVersionException) {
        String msg = "You are using unsupported version of Gradle.";
        msg += ('\n' + FIX_GRADLE_VERSION);
        // Location of build.gradle is useless for this error. Omitting it.
        return createUserFriendlyError(msg, null);
    }
    final String rootCauseMessage = rootCause.getMessage();
    // CommandLineArgumentException class can be loaded by different classloaders
    if (rootCause.getClass().getName().equals(CommandLineArgumentException.class.getName())) {
        if (StringUtil.contains(rootCauseMessage, "Unknown command-line option '--include-build'")) {
            String msg = String.format("Gradle composite build support available for Gradle 3.1 or better version (<a href=\"%s\">Fix Gradle settings</a>)", OpenGradleSettingsCallback.ID);
            return createUserFriendlyError(msg, location, OpenGradleSettingsCallback.ID);
        }
    }
    final String rootCauseText = rootCause.toString();
    if (StringUtil.startsWith(rootCauseText, "org.gradle.api.internal.MissingMethodException")) {
        String method = parseMissingMethod(rootCauseText);
        String msg = "Build script error, unsupported Gradle DSL method found: '" + method + "'!";
        msg += (EMPTY_LINE + "Possible causes could be:  ");
        msg += String.format("%s  - you are using Gradle version where the method is absent (<a href=\"%s\">Fix Gradle settings</a>)", '\n', OpenGradleSettingsCallback.ID);
        msg += String.format("%s  - you didn't apply Gradle plugin which provides the method (<a href=\"%s\">Apply Gradle plugin</a>)", '\n', ApplyGradlePluginCallback.ID);
        msg += String.format("%s  - or there is a mistake in a build script (<a href=\"%s\">Goto source</a>)", '\n', GotoSourceNotificationCallback.ID);
        return createUserFriendlyError(msg, location, OpenGradleSettingsCallback.ID, ApplyGradlePluginCallback.ID, GotoSourceNotificationCallback.ID);
    }
    if (rootCause instanceof OutOfMemoryError) {
        // The OutOfMemoryError happens in the Gradle daemon process.
        String msg = "Out of memory";
        if (rootCauseMessage != null && !rootCauseMessage.isEmpty()) {
            msg = msg + ": " + rootCauseMessage;
        }
        if (msg.endsWith("Java heap space")) {
            msg += ". Configure Gradle memory settings using '-Xmx' JVM option (e.g. '-Xmx2048m'.)";
        } else if (!msg.endsWith(".")) {
            msg += ".";
        }
        msg += EMPTY_LINE + OPEN_GRADLE_SETTINGS;
        // Location of build.gradle is useless for this error. Omitting it.
        return createUserFriendlyError(msg, null);
    }
    if (rootCause instanceof ClassNotFoundException) {
        String msg = String.format("Unable to load class '%1$s'.", rootCauseMessage) + EMPTY_LINE + UNEXPECTED_ERROR_FILE_BUG;
        // Location of build.gradle is useless for this error. Omitting it.
        return createUserFriendlyError(msg, null);
    }
    if (rootCause instanceof UnknownHostException) {
        String msg = String.format("Unknown host '%1$s'.", rootCauseMessage) + EMPTY_LINE + "Please ensure the host name is correct. " + SET_UP_HTTP_PROXY;
        // Location of build.gradle is useless for this error. Omitting it.
        return createUserFriendlyError(msg, null);
    }
    if (rootCause instanceof ConnectException) {
        String msg = rootCauseMessage;
        if (msg != null && msg.contains("timed out")) {
            msg += msg.endsWith(".") ? " " : ". ";
            msg += SET_UP_HTTP_PROXY;
            return createUserFriendlyError(msg, null);
        }
    }
    if (rootCause instanceof RuntimeException) {
        String msg = rootCauseMessage;
        if (msg != null && UNSUPPORTED_GRADLE_VERSION_ERROR_PATTERN.matcher(msg).matches()) {
            if (!msg.endsWith(".")) {
                msg += ".";
            }
            msg += EMPTY_LINE + OPEN_GRADLE_SETTINGS;
            // Location of build.gradle is useless for this error. Omitting it.
            return createUserFriendlyError(msg, null);
        }
    }
    final String errMessage;
    if (rootCauseMessage == null) {
        StringWriter writer = new StringWriter();
        rootCause.printStackTrace(new PrintWriter(writer));
        errMessage = writer.toString();
    } else {
        errMessage = rootCauseMessage;
    }
    return createUserFriendlyError(errMessage, location);
}
Also used : UnknownHostException(java.net.UnknownHostException) StringWriter(java.io.StringWriter) ExternalSystemException(com.intellij.openapi.externalSystem.model.ExternalSystemException) CommandLineArgumentException(org.gradle.cli.CommandLineArgumentException) ProcessCanceledException(com.intellij.openapi.progress.ProcessCanceledException) UnsupportedVersionException(org.gradle.tooling.UnsupportedVersionException) ConnectException(java.net.ConnectException) PrintWriter(java.io.PrintWriter) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with UnsupportedVersionException

use of org.gradle.tooling.UnsupportedVersionException in project gradle by gradle.

the class DaemonBuildActionExecuter method execute.

public Object execute(BuildAction action, BuildRequestContext buildRequestContext, ProviderOperationParameters parameters, ServiceRegistry contextServices) {
    boolean continuous = action.getStartParameter() != null && action.getStartParameter().isContinuous() && isNotBuildingModel(action);
    if (continuous && !doesConsumerSupportCancellation(buildRequestContext)) {
        throw new UnsupportedVersionException("Continuous build requires Tooling API client version 2.1 or later.");
    }
    ClassPath classPath = DefaultClassPath.of(parameters.getInjectedPluginClasspath(Collections.<File>emptyList()));
    BuildActionParameters actionParameters = new DefaultBuildActionParameters(daemonParameters.getEffectiveSystemProperties(), daemonParameters.getEnvironmentVariables(), SystemProperties.getInstance().getCurrentDir(), parameters.getBuildLogLevel(), daemonParameters.isEnabled(), continuous, false, classPath);
    try {
        return executer.execute(action, buildRequestContext, actionParameters, contextServices);
    } catch (ReportedException e) {
        Throwable t = e.getCause();
        // Unpack tunnelled test request failure
        if (t instanceof InternalTestExecutionException) {
            throw (InternalTestExecutionException) t;
        }
        while (t != null) {
            if (t instanceof BuildCancelledException) {
                throw new InternalBuildCancelledException(e.getCause());
            }
            t = t.getCause();
        }
        throw new BuildExceptionVersion1(e.getCause());
    }
}
Also used : DefaultClassPath(org.gradle.internal.classpath.DefaultClassPath) ClassPath(org.gradle.internal.classpath.ClassPath) BuildExceptionVersion1(org.gradle.tooling.internal.protocol.BuildExceptionVersion1) DefaultBuildActionParameters(org.gradle.launcher.exec.DefaultBuildActionParameters) DefaultBuildActionParameters(org.gradle.launcher.exec.DefaultBuildActionParameters) BuildActionParameters(org.gradle.launcher.exec.BuildActionParameters) InternalTestExecutionException(org.gradle.tooling.internal.protocol.test.InternalTestExecutionException) File(java.io.File) InternalBuildCancelledException(org.gradle.tooling.internal.protocol.InternalBuildCancelledException) BuildCancelledException(org.gradle.api.BuildCancelledException) UnsupportedVersionException(org.gradle.tooling.UnsupportedVersionException) ReportedException(org.gradle.initialization.ReportedException) InternalBuildCancelledException(org.gradle.tooling.internal.protocol.InternalBuildCancelledException)

Example 3 with UnsupportedVersionException

use of org.gradle.tooling.UnsupportedVersionException in project gradle by gradle.

the class ToolingApiGradleExecutor method run.

@Override
public GradleExecutionResult run(GradleExecutionParameters parameters) {
    final StreamByteBuffer outputBuffer = new StreamByteBuffer();
    final OutputStream syncOutput = new SynchronizedOutputStream(outputBuffer.getOutputStream());
    final List<BuildTask> tasks = new ArrayList<BuildTask>();
    maybeRegisterCleanup();
    GradleConnector gradleConnector = buildConnector(parameters.getGradleUserHome(), parameters.getProjectDir(), parameters.isEmbedded(), parameters.getGradleProvider());
    ProjectConnection connection = null;
    GradleVersion targetGradleVersion = null;
    try {
        connection = gradleConnector.connect();
        targetGradleVersion = determineTargetGradleVersion(connection);
        if (targetGradleVersion.compareTo(TestKitFeature.RUN_BUILDS.getSince()) < 0) {
            throw new UnsupportedFeatureException(String.format("The version of Gradle you are using (%s) is not supported by TestKit. TestKit supports all Gradle versions 2.6 and later.", targetGradleVersion.getVersion()));
        }
        DefaultBuildLauncher launcher = (DefaultBuildLauncher) connection.newBuild();
        launcher.setStandardOutput(new NoCloseOutputStream(teeOutput(syncOutput, parameters.getStandardOutput())));
        launcher.setStandardError(new NoCloseOutputStream(teeOutput(syncOutput, parameters.getStandardError())));
        if (parameters.getStandardInput() != null) {
            launcher.setStandardInput(parameters.getStandardInput());
        }
        launcher.addProgressListener(new TaskExecutionProgressListener(tasks), OperationType.TASK);
        launcher.withArguments(parameters.getBuildArgs().toArray(new String[0]));
        launcher.setJvmArguments(parameters.getJvmArgs().toArray(new String[0]));
        launcher.setEnvironmentVariables(parameters.getEnvironment());
        if (!parameters.getInjectedClassPath().isEmpty()) {
            if (targetGradleVersion.compareTo(TestKitFeature.PLUGIN_CLASSPATH_INJECTION.getSince()) < 0) {
                throw new UnsupportedFeatureException("support plugin classpath injection", targetGradleVersion, TestKitFeature.PLUGIN_CLASSPATH_INJECTION.getSince());
            }
            launcher.withInjectedClassPath(parameters.getInjectedClassPath());
        }
        launcher.run();
    } catch (UnsupportedVersionException e) {
        throw new InvalidRunnerConfigurationException("The build could not be executed due to a feature not being supported by the target Gradle version", e);
    } catch (BuildException t) {
        return new GradleExecutionResult(new BuildOperationParameters(targetGradleVersion, parameters.isEmbedded()), outputBuffer.readAsString(), tasks, t);
    } catch (GradleConnectionException t) {
        StringBuilder message = new StringBuilder("An error occurred executing build with ");
        if (parameters.getBuildArgs().isEmpty()) {
            message.append("no args");
        } else {
            message.append("args '");
            message.append(CollectionUtils.join(" ", parameters.getBuildArgs()));
            message.append("'");
        }
        message.append(" in directory '").append(parameters.getProjectDir().getAbsolutePath()).append("'");
        String capturedOutput = outputBuffer.readAsString();
        if (!capturedOutput.isEmpty()) {
            message.append(". Output before error:").append(SystemProperties.getInstance().getLineSeparator()).append(capturedOutput);
        }
        throw new IllegalStateException(message.toString(), t);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
    return new GradleExecutionResult(new BuildOperationParameters(targetGradleVersion, parameters.isEmbedded()), outputBuffer.readAsString(), tasks);
}
Also used : BuildTask(org.gradle.testkit.runner.BuildTask) UnsupportedFeatureException(org.gradle.testkit.runner.UnsupportedFeatureException) GradleConnectionException(org.gradle.tooling.GradleConnectionException) SynchronizedOutputStream(org.gradle.testkit.runner.internal.io.SynchronizedOutputStream) TeeOutputStream(org.apache.commons.io.output.TeeOutputStream) NoCloseOutputStream(org.gradle.testkit.runner.internal.io.NoCloseOutputStream) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) ProjectConnection(org.gradle.tooling.ProjectConnection) StreamByteBuffer(org.gradle.internal.io.StreamByteBuffer) InvalidRunnerConfigurationException(org.gradle.testkit.runner.InvalidRunnerConfigurationException) DefaultBuildLauncher(org.gradle.tooling.internal.consumer.DefaultBuildLauncher) GradleConnector(org.gradle.tooling.GradleConnector) DefaultGradleConnector(org.gradle.tooling.internal.consumer.DefaultGradleConnector) SynchronizedOutputStream(org.gradle.testkit.runner.internal.io.SynchronizedOutputStream) BuildException(org.gradle.tooling.BuildException) GradleVersion(org.gradle.util.GradleVersion) NoCloseOutputStream(org.gradle.testkit.runner.internal.io.NoCloseOutputStream) UnsupportedVersionException(org.gradle.tooling.UnsupportedVersionException)

Example 4 with UnsupportedVersionException

use of org.gradle.tooling.UnsupportedVersionException in project gradle by gradle.

the class DefaultToolingImplementationLoader method create.

@Override
public ConsumerConnection create(Distribution distribution, ProgressLoggerFactory progressLoggerFactory, InternalBuildProgressListener progressListener, ConnectionParameters connectionParameters, BuildCancellationToken cancellationToken) {
    LOGGER.debug("Using tooling provider from {}", distribution.getDisplayName());
    ClassLoader serviceClassLoader = createImplementationClassLoader(distribution, progressLoggerFactory, progressListener, connectionParameters, cancellationToken);
    ServiceLocator serviceLocator = new DefaultServiceLocator(serviceClassLoader);
    try {
        Factory<ConnectionVersion4> factory = serviceLocator.findFactory(ConnectionVersion4.class);
        if (factory == null) {
            return new NoToolingApiConnection(distribution);
        }
        ConnectionVersion4 connection = factory.create();
        ProtocolToModelAdapter adapter = new ProtocolToModelAdapter(new ConsumerTargetTypeProvider());
        ModelMapping modelMapping = new ModelMapping();
        if (connection instanceof InternalStopWhenIdleConnection) {
            return createConnection(new StopWhenIdleConsumerConnection(connection, modelMapping, adapter), connectionParameters);
        } else if (connection instanceof InternalInvalidatableVirtualFileSystemConnection) {
            return createConnection(new NotifyDaemonsAboutChangedPathsConsumerConnection(connection, modelMapping, adapter), connectionParameters);
        } else if (connection instanceof InternalPhasedActionConnection) {
            return createConnection(new PhasedActionAwareConsumerConnection(connection, modelMapping, adapter), connectionParameters);
        } else if (connection instanceof InternalParameterAcceptingConnection) {
            return createConnection(new ParameterAcceptingConsumerConnection(connection, modelMapping, adapter), connectionParameters);
        } else if (connection instanceof InternalTestExecutionConnection) {
            return createConnection(new TestExecutionConsumerConnection(connection, modelMapping, adapter), connectionParameters);
        } else {
            return new UnsupportedOlderVersionConnection(connection, adapter);
        }
    } catch (UnsupportedVersionException e) {
        throw e;
    } catch (Throwable t) {
        throw new GradleConnectionException(String.format("Could not create an instance of Tooling API implementation using the specified %s.", distribution.getDisplayName()), t);
    }
}
Also used : NoToolingApiConnection(org.gradle.tooling.internal.consumer.connection.NoToolingApiConnection) InternalStopWhenIdleConnection(org.gradle.tooling.internal.protocol.InternalStopWhenIdleConnection) PhasedActionAwareConsumerConnection(org.gradle.tooling.internal.consumer.connection.PhasedActionAwareConsumerConnection) InternalTestExecutionConnection(org.gradle.tooling.internal.protocol.test.InternalTestExecutionConnection) UnsupportedOlderVersionConnection(org.gradle.tooling.internal.consumer.connection.UnsupportedOlderVersionConnection) TestExecutionConsumerConnection(org.gradle.tooling.internal.consumer.connection.TestExecutionConsumerConnection) ConsumerTargetTypeProvider(org.gradle.tooling.internal.consumer.converters.ConsumerTargetTypeProvider) GradleConnectionException(org.gradle.tooling.GradleConnectionException) DefaultServiceLocator(org.gradle.internal.service.DefaultServiceLocator) InternalParameterAcceptingConnection(org.gradle.tooling.internal.protocol.InternalParameterAcceptingConnection) ModelMapping(org.gradle.tooling.internal.consumer.versioning.ModelMapping) ParameterAcceptingConsumerConnection(org.gradle.tooling.internal.consumer.connection.ParameterAcceptingConsumerConnection) DefaultServiceLocator(org.gradle.internal.service.DefaultServiceLocator) ServiceLocator(org.gradle.internal.service.ServiceLocator) ConnectionVersion4(org.gradle.tooling.internal.protocol.ConnectionVersion4) StopWhenIdleConsumerConnection(org.gradle.tooling.internal.consumer.connection.StopWhenIdleConsumerConnection) ProtocolToModelAdapter(org.gradle.tooling.internal.adapter.ProtocolToModelAdapter) NotifyDaemonsAboutChangedPathsConsumerConnection(org.gradle.tooling.internal.consumer.connection.NotifyDaemonsAboutChangedPathsConsumerConnection) FilteringClassLoader(org.gradle.internal.classloader.FilteringClassLoader) VisitableURLClassLoader(org.gradle.internal.classloader.VisitableURLClassLoader) InternalInvalidatableVirtualFileSystemConnection(org.gradle.tooling.internal.protocol.InternalInvalidatableVirtualFileSystemConnection) InternalPhasedActionConnection(org.gradle.tooling.internal.protocol.InternalPhasedActionConnection) UnsupportedVersionException(org.gradle.tooling.UnsupportedVersionException)

Aggregations

UnsupportedVersionException (org.gradle.tooling.UnsupportedVersionException)4 GradleConnectionException (org.gradle.tooling.GradleConnectionException)2 ExternalSystemException (com.intellij.openapi.externalSystem.model.ExternalSystemException)1 ProcessCanceledException (com.intellij.openapi.progress.ProcessCanceledException)1 File (java.io.File)1 OutputStream (java.io.OutputStream)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 ConnectException (java.net.ConnectException)1 UnknownHostException (java.net.UnknownHostException)1 ArrayList (java.util.ArrayList)1 TeeOutputStream (org.apache.commons.io.output.TeeOutputStream)1 BuildCancelledException (org.gradle.api.BuildCancelledException)1 CommandLineArgumentException (org.gradle.cli.CommandLineArgumentException)1 ReportedException (org.gradle.initialization.ReportedException)1 FilteringClassLoader (org.gradle.internal.classloader.FilteringClassLoader)1 VisitableURLClassLoader (org.gradle.internal.classloader.VisitableURLClassLoader)1 ClassPath (org.gradle.internal.classpath.ClassPath)1 DefaultClassPath (org.gradle.internal.classpath.DefaultClassPath)1 StreamByteBuffer (org.gradle.internal.io.StreamByteBuffer)1