private File createBatchFile(MsBuildConfig msBuildConfig) { final String command = getCommand(msBuildConfig); final SecureTemporaryFiles.FileSpecBuilder fileSpecBuilder = SecureTemporaryFiles.builder() .setPrefix("epb") .setSuffix(".bat") .setExecutable(true); File batchFile; try { batchFile = SecureTemporaryFiles.create(fileSpecBuilder.build()); FileUtils.writeStringToFile(batchFile, command); } catch (IOException e) { throw new IllegalStateException(e); } batchFile.setReadOnly(); return batchFile; }
@VisibleForTesting static String determineHipChatApiBaseUrl() { final String apiBase = UrlUtils.stripTailingSlashes(System.getProperty(HIPCHAT_API_BASE_PROPERTY, HIPCHAT_API_BASE_DEFAULT)); log.info(apiBase + " will be used for HipChat integration (if enabled)."); return apiBase; } }
private void appendLongResults(String key, String results) { log.debug("Appending " + results + " to " + key); String existingResults = this.results.get(key); if (existingResults == null || existingResults.equals("")) existingResults = Long.toString(0); if (results == null || results.equals("")) results = Long.toString(0); Long newValue = NumberUtils.stringToLong(existingResults) + NumberUtils.stringToLong(results); NumberFormat defaultFormat = NumberFormat.getInstance(); this.results.put(key, defaultFormat.format(newValue)); }
@Override public List<ValidationProblem> validate(@NotNull TaskValidationContext taskValidationContext, @NotNull TaskProperties taskProperties) { List<ValidationProblem> result = new ArrayList<>(); final TestParserTaskProperties testParserTaskProperties = Narrow.downTo(taskProperties, TestParserTaskProperties.class); if (testParserTaskProperties != null) { if (StringUtils.isEmpty(getResultPath(testParserTaskProperties))) { result.add(new ValidationProblem(NUNIT_PARSER_CONTEXT, "Result path is mandatory")); } } return result; } }
/** * Generates the tool tip to show. * * @param xyDataset * @param series * @param item * @return the tool tip to show */ @Override public String generateToolTip(XYDataset xyDataset, int series, int item) { TimeTableXYDataset dataset = (TimeTableXYDataset) xyDataset; double percentageCovered = dataset.getYValue(series, item); String buildKey = (String) dataset.getSeriesKey(series); TimePeriod timePeriod = dataset.getTimePeriod(item); return "Tests in " +timePeriod+ " covered " + NumberUtils.round(percentageCovered, 1) + "% of code in build " + buildKey; } }
/** * Retrieves the branch rate from the <code>result</code>'s custom build * data, and adds it to the <code>coverage</code> instance variable. * @param result */ @Override public void addResult(ResultStatisticsProvider result) { log.debug("Inside addResult"); if (result instanceof BuildResultsSummary) { BuildResultsSummary summary = (BuildResultsSummary) result; Double nCoverLineRate = NumberUtils.createDoubleQuietly(summary.getCustomBuildData().get(NCoverBuildProcessor.NCOVER_LINE_RATE)); if (nCoverLineRate != null) { log.debug("Adding line rate: " + nCoverLineRate); coverage = coverage + nCoverLineRate; count++; } } }
private void appendDoubleResults(String key, String results) { log.debug("Appending " + results + " to " + key); boolean storeAverage = true; String existingResults = this.results.get(key); if (existingResults == null || existingResults.equals("")) { existingResults = Double.toString(0); storeAverage = false; } if (results == null || results.equals("")) results = Double.toString(0); Double newValue = NumberUtils.stringToDouble(existingResults) + NumberUtils.stringToDouble(results); if (storeAverage) newValue = newValue / 2; NumberFormat defaultFormat = NumberFormat.getInstance(); this.results.put(key, defaultFormat.format(newValue)); }
@Nullable protected ArtifactFileData getSingleDownloadableFile(@NotNull final Iterable<ArtifactFileData> urls) { final boolean isSingleFile = BambooIterables.hasSize(urls, 1); if (!isSingleFile) { return null; } final ArtifactFileData singleFile = Iterables.getOnlyElement(urls); final boolean isSingleDownloadableFile = singleFile.getFileType() == ArtifactFileData.FileType.REGULAR_FILE; return isSingleDownloadableFile ? singleFile : null; }
/** * Calculates the effective file pattern for {@link TestCollationService}. The result will include working * directory info from task configuration. * <p> * Note: it is necessary to transform the file pattern because methods like {@link * TestCollationService#collateTestResults(TaskContext, String)} visit files starting from the build root directory, * and not the task working directory. * <p> * Usage example: * <p> * <pre> * working directory: plugin/ * file pattern: *.css * ... * effective file pattern: plugin/*.css * </pre> * * @param taskContext task context, containing info about build root directory and task working directory. * @param filePattern an ant-style file pattern * @return A file pattern with task working directory included */ public static String calculateEffectiveFilePattern(@NotNull TaskContext taskContext, @NotNull String filePattern) { final String workingDirectoryPath = BambooFileUtils.calculateRelativePath( taskContext.getRootDirectory(), taskContext.getWorkingDirectory()); return workingDirectoryPath + filePattern; }
/** * Permission check for {@link Project} * * @param project the {@link Project} to check for * @return {@code true} is the current user is a system administrator, or can read a plan of the project */ private boolean canView(Project project) { if (SecurityContextHolder.getContext().getAuthentication().equals(BambooPermissionManager.SYSTEM_AUTHORITY)) { return true; } Iterable<Plan> plans = Narrow.iterableTo(planManager.getPlansByProject(project), Plan.class); return Iterables.isEmpty(plans) || Iterables.any(plans, canReadPlan); }
@NotNull @Override public String importNotificationRecipient(NotificationRecipientProperties recipient) { final HipChatRecipientProperties hipChatRecipient = Narrow.downTo(recipient, HipChatRecipientProperties.class); if (hipChatRecipient != null) { return hipChatRecipient.getApiToken() + '|' + String.valueOf(hipChatRecipient.isNotifyUsers()) + '|' + hipChatRecipient.getRoom(); } throw new IllegalStateException("Don't know how to import notification type class: " + recipient.getClass().getName()); }
double coverage = NumberUtils.round(parser.getLineRate() * 100, 4);
@Override public void execute(@NotNull final Chain chain, @NotNull final ChainResultsSummary chainResultsSummary, @NotNull final ChainExecution chainExecution) throws InterruptedException, Exception { if (!chainResultsSummary.isSuccessful()) { return; } double aggregatedLineRate = 0; int aggregatedLineRateCnt = 0; for (ChainStageResult stageResult : chainResultsSummary.getStageResults()) { for (BuildResultsSummary buildResult : stageResult.getBuildResults()) { final Double lineRate = NumberUtils.createDoubleQuietly(buildResult.getCustomBuildData().get(NCoverBuildProcessor.NCOVER_LINE_RATE)); if (lineRate != null) { aggregatedLineRate += lineRate; aggregatedLineRateCnt++; } } } if (aggregatedLineRateCnt > 0) { chainResultsSummary.getCustomBuildData().put(NCoverBuildProcessor.NCOVER_LINE_RATE, Double.toString(aggregatedLineRate / aggregatedLineRateCnt)); } } }
/** * @param results */ private void calculateDelta(Map<String, String> results) { try { ResultsSummary previousSummary = resultsSummaryManager.getLastSuccessfulResultSummary(buildContext.getPlanResultKey().getPlanKey()); if (previousSummary != null && previousSummary.getCustomBuildData() != null && previousSummary.getCustomBuildData().containsKey( NCoverBuildProcessor.NCOVER_LINE_RATE)) { String prevCoverStr = previousSummary .getCustomBuildData().get(NCoverBuildProcessor.NCOVER_LINE_RATE); String lineRate = results .get(NCoverBuildProcessor.NCOVER_LINE_RATE); if (!prevCoverStr.equals(lineRate)) { runCoverageChangeComparison(previousSummary, results); } double prevCoverDbl = NumberUtils.stringToDouble(prevCoverStr); double coverage = NumberUtils.stringToDouble(lineRate); results.put(NCoverBuildProcessor.NCOVER_COVERAGE_DELTA, Double .toString(coverage - prevCoverDbl)); } } catch (NumberFormatException e) { log.error(e); } }
@NotNull @Override public final Map<String, String> toTaskConfiguration(@NotNull TaskContainer taskContainer, @NotNull TaskProperties taskProperties) { final P typedTaskProperties = Narrow.downTo(taskProperties, propertiesClass); Preconditions.checkState(typedTaskProperties != null, "Don't know how to import task properties of type: " + taskProperties.getClass().getName()); final Map<String, String> config = new HashMap<>(); config.put(AbstractNodeRequiringTaskConfigurator.NODE_RUNTIME, typedTaskProperties.getNodeExecutable()); config.put(TaskConfigConstants.CFG_ENVIRONMENT_VARIABLES, typedTaskProperties.getEnvironmentVariables()); config.put(TaskConfigConstants.CFG_WORKING_SUBDIRECTORY, typedTaskProperties.getWorkingSubdirectory()); config.putAll(toTaskConfiguration(typedTaskProperties)); return config; }
@Override public Map<String, String> toTaskConfiguration(@NotNull TaskContainer taskContainer, final TaskProperties taskProperties) { final TestParserTaskProperties testParserTaskProperties = Narrow.downTo(taskProperties, TestParserTaskProperties.class); if (testParserTaskProperties != null) { final Map<String, String> cfg = new HashMap<>(); if (testParserTaskProperties.getResultDirectories() != null) { cfg.put(NUnitCollectorTaskType.TEST_DIRECTORY, getResultPath(testParserTaskProperties)); } cfg.put(TaskConfigConstants.CFG_TEST_OUTDATED_RESULTS_FILE, Boolean.toString(testParserTaskProperties.getPickUpTestResultsCreatedOutsideOfThisBuild())); return cfg; } throw new IllegalStateException("Don't know how to import task properties of type: " + taskProperties.getClass().getName()); }
@Override @NotNull public Map<String, String> toTaskConfiguration(@NotNull TaskContainer taskContainer, @NotNull final TaskProperties taskProperties) { final MsBuildTaskProperties msBuildTaskProperties = Narrow.downTo(taskProperties, MsBuildTaskProperties.class); if (msBuildTaskProperties == null) { throw new IllegalStateException("Unsupported import task of type: " + taskProperties.getClass().getName()); } final Map<String, String> cfg = new HashMap<>(); cfg.put(MsBuildConfig.LABEL, msBuildTaskProperties.getExecutable()); cfg.put(MsBuildConfig.SOLUTION, msBuildTaskProperties.getProjectFile()); cfg.put(MsBuildConfig.OPTIONS, msBuildTaskProperties.getOptions()); cfg.put(MsBuildConfig.ENVIRONMENT, msBuildTaskProperties.getEnvironmentVariables()); cfg.put(TaskConfigConstants.CFG_WORKING_SUBDIRECTORY, msBuildTaskProperties.getWorkingSubdirectory()); return cfg; }
@Override public List<ValidationProblem> validate(@NotNull TaskValidationContext taskValidationContext, @NotNull TaskProperties taskProperties) { final List<ValidationProblem> result = new ArrayList<>(); final MsBuildTaskProperties properties = Narrow.downTo(taskProperties, MsBuildTaskProperties.class); if (properties == null) { return result; } final String executableLabel = properties.getExecutable(); if (StringUtils.isEmpty(executableLabel)) { result.add(new ValidationProblem(CONTEXT, "Executable can't be empty")); } else { executableLabelValidator.validateExecutableLabelExists(CONTEXT, executableLabel, MsBuildConfig.MSBUILD_EXECUTABLE_LABEL) .ifPresent(result::add); } return result; } }
@Override public List<ValidationProblem> validate(@NotNull TaskValidationContext taskValidationContext, @NotNull TaskProperties taskProperties) { List<ValidationProblem> result = new ArrayList<>(); final NUnitRunnerTaskProperties properties = Narrow.downTo(taskProperties, NUnitRunnerTaskProperties.class); if (properties != null) { final String capabilityPrefix = getCapabilityShortKey(properties.getNUnitVersion()); final List<String> labels = uiConfigSupport.getExecutableLabels(capabilityPrefix); final String label = properties.getExecutable(); if (labels == null || !labels.contains(label)) { result.add(new ValidationProblem(NUNIT_PARSER_CONTEXT, String.format("Can't find executable by label: '%s'. Available values: %s", label, labels))); } } return result; }
@Override public final List<ValidationProblem> validate(@NotNull TaskValidationContext taskValidationContext, @NotNull TaskProperties taskProperties) { final List<ValidationProblem> validationProblems = new ArrayList<>(); final P typedTaskProperties = Narrow.downTo(taskProperties, propertiesClass); if (typedTaskProperties != null) { final String nodeExecutable = typedTaskProperties.getNodeExecutable(); if (StringUtils.isEmpty(nodeExecutable)) { validationProblems.add(new ValidationProblem(getValidationContext(), "Node.js executable can't be empty")); } else { final List<String> executableLabels = uiConfigSupport.getExecutableLabels(NodeCapabilityDefaultsHelper.NODE_CAPABILITY_KEY); if (executableLabels.stream().noneMatch(label -> label.equals(nodeExecutable))) { final String errorMessage = String.format("Can't find Node.js executable by label: '%s'. Available values: %s", nodeExecutable, executableLabels); validationProblems.add(new ValidationProblem(getValidationContext(), errorMessage)); } } validationProblems.addAll(validate(typedTaskProperties)); } return validationProblems; } }