public static File getClasspathForClass(Class<?> targetClass) { URI location; try { CodeSource codeSource = targetClass.getProtectionDomain().getCodeSource(); if (codeSource != null && codeSource.getLocation() != null) { location = codeSource.getLocation().toURI(); if (location.getScheme().equals("file")) { return new File(location); } } if (targetClass.getClassLoader() != null) { String resourceName = targetClass.getName().replace('.', '/') + ".class"; URL resource = targetClass.getClassLoader().getResource(resourceName); if (resource != null) { return getClasspathForResource(resource, resourceName); } } throw new GradleException(String.format("Cannot determine classpath for class %s.", targetClass.getName())); } catch (URISyntaxException e) { throw UncheckedException.throwAsUncheckedException(e); } }
@Override 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." + "\n Command line issued: " + execAction.getCommandLine() + "\n Generated Javadoc options file 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); }
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; }
@Override public void execute(Task task) { Set<? extends Task> taskDependencies = task.getTaskDependencies().getDependencies(task); if (taskDependencies.isEmpty()) { TreeFormatter formatter = new TreeFormatter(); formatter.node("No buildable binaries found"); formatter.startChildren(); for (BinarySpecInternal binary : notBuildable) { formatter.node(binary.getDisplayName()); formatter.startChildren(); binary.getBuildAbility().explain(formatter); formatter.endChildren(); } formatter.endChildren(); throw new GradleException(formatter.toString()); } }
@Override protected void publishArtifacts(Collection<Artifact> artifacts, RepositorySystem repositorySystem, RepositorySystemSession session) throws DeploymentException { RemoteRepository gradleRepo = remoteRepository; if (artifacts.iterator().next().isSnapshot() && remoteSnapshotRepository != null) { gradleRepo = remoteSnapshotRepository; } if (gradleRepo == null) { throw new GradleException("Must specify a repository for deployment"); } org.sonatype.aether.repository.RemoteRepository aetherRepo = createRepository(gradleRepo); DeployRequest request = new DeployRequest(); request.setRepository(aetherRepo); for (Artifact artifact : artifacts) { request.addArtifact(artifact); } LOGGER.info("Deploying to {}", gradleRepo.getUrl()); repositorySystem.deploy(session, request); }
@Override protected ExecutionFailure doRunWithFailure() { if (isForkRequired()) { return doStart().waitForFailure(); } StandardOutputListener outputListener = new OutputListenerImpl(); StandardOutputListener errorListener = new OutputListenerImpl(); BuildListenerImpl buildListener = new BuildListenerImpl(); try { doRun(outputListener, errorListener, buildListener).rethrowFailure(); throw new AssertionError("expected build to fail but it did not."); } catch (GradleException e) { return assertResult(new InProcessExecutionFailure(buildListener.executedTasks, buildListener.skippedTasks, new OutputScrapingExecutionFailure(outputListener.toString(), errorListener.toString()), e)); } }
@TaskAction public void setupProjectLayout() { final String type = getType(); BuildInitTestFramework testFramework = BuildInitTestFramework.fromName(getTestFramework()); final ProjectLayoutSetupRegistry projectLayoutRegistry = getProjectLayoutRegistry(); if (!projectLayoutRegistry.supports(type)) { String supportedTypes = Joiner.on(", ").join(Iterables.transform(projectLayoutRegistry.getSupportedTypes(), new Function<String, String>() { @Override public String apply(String input) { return "'" + input + "'"; } })); throw new GradleException("The requested build setup type '" + type + "' is not supported. Supported types: " + supportedTypes + "."); } ProjectInitDescriptor initDescriptor = projectLayoutRegistry.get(type); if (!testFramework.equals(BuildInitTestFramework.NONE) && !initDescriptor.supports(testFramework)) { throw new GradleException("The requested test framework '" + testFramework.getId() + "' is not supported in '" + type + "' setup type"); } initDescriptor.generate(testFramework); }
public Collection<MavenPackageDescriptor> runAudit() { try { List<MavenPackageDescriptor> results = new LinkedList<>(); Collection<PackageDescriptor> packages = request.run(); for (PackageDescriptor pkg : packages) { MavenPackageDescriptor mvnPkg = new MavenPackageDescriptor(pkg); if (parents.containsKey(pkg)) { PackageDescriptor parent = parents.get(pkg); if (parent != null) { mvnPkg.setParent(new MavenIdWrapper(parent)); } } if (mvnPkg.getVulnerabilityMatches() > 0) { results.add(mvnPkg); } } return results; } catch(IOException e) { throw new GradleException("Error trying to get audit results", e); } }
/** * Generate this file */ @TaskAction public void generate() throws IOException { dependencyDiff = getDependencyDiff(); //If it's patch, get the diff operation if (null == dependencyDiff) { return; } try { appVariantOutputContext.artifactBundleInfos = getArtifactBundleInfo(getDependencyDiff(), getManifestFile(), getApDir()); FileUtils.writeStringToFile(new File(getOutJsonFile(), "dependencyDiff.json"), JSON.toJSONString(dependencyDiff, true)); } catch (Exception e) { throw new GradleException(e.getMessage()); } }
private Result resolveToFoundResult(PluginResolver effectivePluginResolver, PluginRequest request) { Result result = new Result(request); try { effectivePluginResolver.resolve(request, result); } catch (Exception e) { throw new LocationAwareException( new GradleException(String.format("Error resolving plugin %s", request.getDisplayName()), e), request.getScriptDisplayName(), request.getLineNumber()); } if (!result.isFound()) { String message = buildNotFoundMessage(request, result); Exception exception = new UnknownPluginException(message); throw new LocationAwareException(exception, request.getScriptDisplayName(), request.getLineNumber()); } return result; }
private JavaVersion parseJavaVersionCommandOutput(String javaExecutable, BufferedReader reader) { try { String versionStr = reader.readLine(); while (versionStr != null) { Matcher matcher = Pattern.compile("(?:java|openjdk) version \"(.+?)\"").matcher(versionStr); if (matcher.matches()) { return JavaVersion.toVersion(matcher.group(1)); } versionStr = reader.readLine(); } } catch (IOException e) { throw new UncheckedIOException(e); } throw new GradleException(String.format("Could not determine Java version using executable %s.", javaExecutable)); }
@TaskAction public void executeSQLExecutor() { String taskName = this.getName(); if (sqlFiles==null) { throw new GradleException("sqlFiles is null"); } List<File> files = convertToFileList(sqlFiles); try { SqlExecutorStep step = new SqlExecutorStep(taskName); step.execute(database, files,sqlParameters); log.info("Task start"); } catch (Exception e) { log.error("Exception in creating / invoking SqlExecutorStep.", e); GradleException ge = TaskUtil.toGradleException(e); throw ge; } }
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")); } } // Tasks are ignored by providers if launchables is not null this.launchables = launchablesParams.isEmpty() ? null : launchablesParams; tasks = Lists.newArrayList(taskPaths); return this; }
private Map<String, String> getClassObfMap(GradleVariantConfiguration config) { Map<String, String> classMap = new HashMap<String, String>(); boolean isMinifyEnabled = config.isMinifyEnabled(); File proguardOut = new File(Joiner.on(File.separatorChar).join( String.valueOf(appVariantContext.getScope().getGlobalScope().getBuildDir()), FD_OUTPUTS, "mapping", appVariantContext.getScope().getVariantConfiguration().getDirName())); File mappingFile = new File(proguardOut, "mapping.txt"); // Parse the mapping file to generate the new mainDexListFile if (isMinifyEnabled && mappingFile.exists()) { MappingReader mappingReader = new MappingReader(mappingFile); MappingReaderProcess process = new MappingReaderProcess(); try { mappingReader.pump(process); } catch (IOException e) { throw new GradleException(e.getMessage(), e); } classMap = process.classMapping; } return classMap; }
@SuppressWarnings("UnusedDeclaration") @TaskAction void generate() { File inputFile = getInputFileIfExists(); if (inputFile != null) { try { domainObject = generator.read(inputFile); } catch (RuntimeException e) { throw new GradleException(String.format("Cannot parse file '%s'.\n" + " Perhaps this file was tinkered with? In that case try delete this file and then retry.", inputFile), e); } } else { domainObject = generator.defaultInstance(); } beforeConfigured.execute(domainObject); generator.configure(domainObject); afterConfigured.execute(domainObject); generator.write(domainObject, getOutputFile()); }
public void execute(TaskInternal task, TaskStateInternal state, TaskExecutionContext context) { listener.beforeActions(task); if (!task.getTaskActions().isEmpty()) { outputsGenerationListener.beforeTaskOutputsGenerated(); } state.setExecuting(true); try { GradleException failure = executeActions(task, state, context); if (failure != null) { state.setOutcome(failure); } else { state.setOutcome( state.getDidWork() ? TaskExecutionOutcome.EXECUTED : TaskExecutionOutcome.UP_TO_DATE ); } } finally { state.setExecuting(false); listener.afterActions(task); } }
public void execute(TaskInternal task, TaskStateInternal state, TaskExecutionContext context) { boolean skip; try { skip = !task.getOnlyIf().isSatisfiedBy(task); } catch (Throwable t) { state.setOutcome(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.setOutcome(TaskExecutionOutcome.SKIPPED); return; } executer.execute(task, state, context); }
private void doVisit(FileVisitor visitor, File file, LinkedList<String> relativePath, int segmentIndex, AtomicBoolean stopFlag) { if (stopFlag.get()) { return; } String segment = patternSegments.get(segmentIndex); if (segment.contains("**")) { PatternSet patternSet = new PatternSet(); patternSet.include(includePattern); patternSet.exclude(excludeSpec); DirectoryFileTree fileTree = new DirectoryFileTree(baseDir, patternSet); fileTree.visitFrom(visitor, file, new RelativePath(file.isFile(), relativePath.toArray(new String[relativePath.size()]))); } else if (segment.contains("*") || segment.contains("?")) { PatternStep step = PatternStepFactory.getStep(segment, false); File[] children = file.listFiles(); if (children == null) { if (!file.canRead()) { throw new GradleException(String.format("Could not list contents of directory '%s' as it is not readable.", file)); } // else, might be a link which points to nothing, or has been removed while we're visiting, or ... throw new GradleException(String.format("Could not list contents of '%s'.", file)); } for (File child : children) { if (stopFlag.get()) { break; } String childName = child.getName(); if (step.matches(childName)) { relativePath.addLast(childName); doVisitDirOrFile(visitor, child, relativePath, segmentIndex + 1, stopFlag); relativePath.removeLast(); } } } else { relativePath.addLast(segment); doVisitDirOrFile(visitor, new File(file, segment), relativePath, segmentIndex + 1, stopFlag); relativePath.removeLast(); } }
/** * Injects the interfaces into an arbitrary classloader via * {@link ClassLoader#defineClass(String, byte[], int, int)}. */ @Override public void injectEmptyInterfacesIntoClassLoader(ClassLoader classLoader) { try { java.lang.reflect.Method defineClassMethod = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class); defineClassMethod.setAccessible(true); for (String name : syntheticClasses) { byte[] bytes = generateSyntheticClass(name); defineClassMethod.invoke(classLoader, name, bytes, 0, bytes.length); } defineClassMethod.setAccessible(false); } catch (Exception e) { throw new GradleException("Could not inject synthetic classes.", e); } }
@Override public void compileToDir(ScriptSource source, ClassLoader classLoader, File classesDir, File metadataDir, CompileOperation<?> extractingTransformer, Class<? extends Script> scriptBaseClass, Action<? super ClassNode> verifier) { Timer clock = Timers.startTimer(); GFileUtils.deleteDirectory(classesDir); GFileUtils.mkdirs(classesDir); CompilerConfiguration configuration = createBaseCompilerConfiguration(scriptBaseClass); configuration.setTargetDirectory(classesDir); try { compileScript(source, classLoader, configuration, metadataDir, extractingTransformer, verifier); } catch (GradleException e) { GFileUtils.deleteDirectory(classesDir); GFileUtils.deleteDirectory(metadataDir); throw e; } logger.debug("Timing: Writing script to cache at {} took: {}", classesDir.getAbsolutePath(), clock.getElapsed()); }
protected LocallyAvailableResource saveIntoFileStore(final File source, final File destination, final boolean isMove) { String verb = isMove ? "move" : "copy"; if (!source.exists()) { throw new GradleException(String.format("Cannot %s '%s' into filestore @ '%s' as it does not exist", verb, source, destination)); } String error = String.format("Failed to %s file '%s' into filestore at '%s' ", verb, source, destination); return doAdd(destination, error, new Action<File>() { public void execute(File file) { if (isMove) { GFileUtils.moveFile(source, destination); } else { GFileUtils.copyFile(source, destination); } } }); }
private Collection<IncludedBuild> validateBuildNames(Collection<IncludedBuild> builds, SettingsInternal settings) { Set<String> names = Sets.newHashSet(); for (IncludedBuild build : builds) { String buildName = build.getName(); if (!names.add(buildName)) { throw new GradleException("Included build '" + buildName + "' is not unique in composite."); } if (settings.getRootProject().getName().equals(buildName)) { throw new GradleException("Included build '" + buildName + "' collides with root project name."); } if (settings.findProject(":" + buildName) != null) { throw new GradleException("Included build '" + buildName + "' collides with subproject of the same name."); } } return builds; }
private void serialize(T newValue) { try { if (!cacheFile.isFile()) { cacheFile.createNewFile(); } chmod.chmod(cacheFile.getParentFile(), 0700); // read-write-execute for user only chmod.chmod(cacheFile, 0600); // read-write for user only OutputStreamBackedEncoder encoder = new OutputStreamBackedEncoder(new BufferedOutputStream(new FileOutputStream(cacheFile))); try { serializer.write(encoder, newValue); } finally { encoder.close(); } } catch (Exception e) { throw new GradleException(String.format("Could not write cache value to '%s'.", cacheFile), e); } }
public void replaceAaptOutput(File aaptApk, File sourceOutputDir, File symbolOutputDir) { log(String.format("start replacement ... \naaptApkDir = %s, \nsourceOutputDir = %s, \nsymbolOutputDir = %s", aaptApk.getAbsolutePath(), sourceOutputDir.getAbsolutePath(), symbolOutputDir.getAbsolutePath())); if (aaptApk == null || !aaptApk.exists()) { throw new GradleException("resource apk NOT found!"); } if (sourceOutputDir == null || !sourceOutputDir.exists()) { throw new GradleException("source output NOT found!"); } if (symbolOutputDir == null || !symbolOutputDir.exists()) { throw new GradleException("symbol output NOT found!"); } replaceApkDir(aaptApk); replaceR(sourceOutputDir); replaceR(symbolOutputDir); }
private void handleTestFailures(Exception e) { String message = "There were failing tests"; String resultsUrl = new ConsoleRenderer().asClickableFileUrl(getOutputDir()); message = message.concat(". See the results at: " + resultsUrl); if (isIgnoreFailures()) { getLogger().warn(message); } else { throw new GradleException(message, e); } }
private EnumMap<SysProp, String> getMetadataInternal(File jdkPath) { JavaExecAction exec = factory.newJavaExecAction(); exec.executable(javaExe(jdkPath, "java")); File workingDir = Files.createTempDir(); exec.setWorkingDir(workingDir); exec.setClasspath(new SimpleFileCollection(workingDir)); try { writeProbe(workingDir); exec.setMain(JavaProbe.CLASSNAME); ByteArrayOutputStream baos = new ByteArrayOutputStream(); exec.setStandardOutput(baos); ByteArrayOutputStream errorOutput = new ByteArrayOutputStream(); exec.setErrorOutput(errorOutput); exec.setIgnoreExitValue(true); ExecResult result = exec.execute(); int exitValue = result.getExitValue(); if (exitValue == 0) { return parseExecOutput(baos.toString()); } return error("Command returned unexpected result code: " + exitValue + "\nError output:\n" + errorOutput); } catch (ExecException ex) { return error(ex.getMessage()); } finally { try { FileUtils.deleteDirectory(workingDir); } catch (IOException e) { throw new GradleException("Unable to delete temp directory", e); } } }
public boolean isFastMultiDexEnabled() { if (null == multiDexConfig) { return false; } boolean fastMultiDex = multiDexConfig.isFastMultiDex(); if (fastMultiDex) { if (appVariantContext.getVariantData().getVariantConfiguration().isMultiDexEnabled()) { throw new GradleException( "atlas fast multi dex must close android's default multi dex , please `multiDexEnabled false`"); } if (appVariantContext.getAtlasExtension().getTBuildConfig().isAtlasMultiDex()) { logger.error("atlasMultiDex is ignored"); } } return fastMultiDex; }
@VisibleForTesting void evaluateResult(FindBugsResult result) { if (result.getException() != null) { throw new GradleException("FindBugs encountered an error. Run with --debug to get more information.", result.getException()); } if (result.getErrorCount() > 0) { throw new GradleException("FindBugs encountered an error. Run with --debug to get more information."); } if (result.getBugCount() > 0) { String message = "FindBugs rule violations were found."; SingleFileReport report = reports.getFirstEnabled(); if (report != null) { String reportUrl = new ConsoleRenderer().asClickableFileUrl(report.getDestination()); message += " See the report at: " + reportUrl; } if (getIgnoreFailures()) { getLogger().warn(message); } else { throw new GradleException(message); } } }
private VersionNumber getFindbugsVersion(Iterable<String> classpath) { for (String f: classpath) { Matcher m = Pattern.compile("findbugs-(\\d+.*)\\.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); }
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!"); }
public void publish() { List<Artifact> artifacts = new ArrayList<Artifact>(); if (mainArtifact.getFile() != null) { artifacts.add(mainArtifact); } artifacts.add(pomArtifact); artifacts.addAll(attached); try { publishArtifacts(artifacts, newRepositorySystem(), session); } catch (RepositoryException e) { throw new GradleException(e.getMessage(), e); } }
public Object getSettings() { try { return mavenSettingsProvider.buildSettings(); } catch (SettingsBuildingException e) { throw new GradleException("Could not load Maven Settings", e); } }
public static File assertInWindowsPathLengthLimitation(File file) { if (file.getAbsolutePath().length() > WINDOWS_PATH_LIMIT) { throw new GradleException(String.format("Cannot create file. '%s' exceeds windows path limitation of %d character.", file.getAbsolutePath(), WINDOWS_PATH_LIMIT)); } return file; }
public void generate(ProjectDescriptor projectDescriptor, CustomData customData) { try { copyCssResources(); copyImgResources(); processIndexPageTemplate(projectDescriptor, customData); } catch (Exception e) { throw new GradleException("Unable to generate site", e); } }
public final AntlrResult process(AntlrSpec spec) { try { return doProcess(spec); } catch (ClassNotFoundException e) { //this shouldn't happen if you call check availability with #available first throw new GradleException("Cannot process antlr sources", e); } }
void visit(GeneratorAdapter mv, Set<String> strings, String className) { this.className = className; this.classData = AcesoProguardMap.instance().getClassData(className); if (classData == null) { throw new GradleException("can not find class: " + className + " , sure you aceso-mapping is right and this class not in blacklist."); } visitClassifier(mv, strings); }
public static void installAwoSo(AndroidBuilder androidBuilder, File maindexFile, Collection<File> awoSoFiles, String packageName, Logger logger) { try { if (maindexFile != null) { if (!maindexFile.exists()) { throw new IllegalArgumentException( "maindexFile file " + maindexFile.getAbsolutePath() + " does not exist."); } installPatchIfDeviceConnected(androidBuilder, maindexFile, packageName, logger, "libcom_taobao_maindex.so"); } if (awoSoFiles != null) { for (File awoSoFile : awoSoFiles) { if (!awoSoFile.exists()) { throw new IllegalArgumentException( "awoSoFile file " + awoSoFile.getAbsolutePath() + " does not exist."); } installPatchIfDeviceConnected(androidBuilder, awoSoFile, packageName, logger, awoSoFile.getName()); } } notifyApppatching(androidBuilder, packageName, logger); } catch (Throwable e) { throw new GradleException("install awo error", e); } }
private static int parseValue(String property, int defaultValue) { String expireAt = System.getProperty(property); if (expireAt == null) { return defaultValue; } try { return Integer.parseInt(expireAt); } catch (Exception e) { throw new GradleException(format( "System property '%s' has incorrect value: '%s'. The value needs to be an integer.", property, expireAt)); } }
public DaemonStartupInfo parseDaemonOutput(String output) { DaemonStartupCommunication startupCommunication = new DaemonStartupCommunication(); if (!startupCommunication.containsGreeting(output)) { throw new GradleException(prepareMessage(output)); } String[] lines = output.split("\n"); //Assuming that the diagnostics were printed out to the last line. It's not bullet-proof but seems to be doing fine. String lastLine = lines[lines.length-1]; return startupCommunication.readDiagnostics(lastLine); }
@Override protected ProcessInfoBuilder makePackageProcessBuilder(AaptPackageConfig config) throws AaptException { ProcessInfoBuilder processInfoBuilder = super.makePackageProcessBuilder(config); List<String> args = null; try { args = (List<String>) FieldUtils.readField(processInfoBuilder, "mArgs", true); } catch (IllegalAccessException e) { throw new GradleException("getargs exception", e); } //args.remove("--no-version-vectors"); // ////Does not generate manifest_keep.txt file //int indexD = args.indexOf("-D"); //if (indexD > 0){ // args.remove(indexD); // args.remove(indexD); //} //Join the outputs of the R.txt file String sybolOutputDir = config.getSymbolOutputDir().getAbsolutePath(); if (!args.contains("--output-text-symbols") && null != sybolOutputDir) { args.add("--output-text-symbols"); args.add(sybolOutputDir); } return processInfoBuilder; }