jetbrains.buildServer.util.StringUtil Java Examples

The following examples show how to use jetbrains.buildServer.util.StringUtil. 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 File: KubeDeleteImageDialogController.java    From teamcity-kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
protected ModelAndView doHandle(@NotNull HttpServletRequest httpServletRequest, @NotNull HttpServletResponse httpServletResponse) throws Exception {
    String projectId = httpServletRequest.getParameter("projectId");
    String profileId = httpServletRequest.getParameter("profileId");
    String imageId = httpServletRequest.getParameter("imageId");
    if(StringUtil.isEmpty(imageId)) return null;

    final CloudClientEx client = myCloudManager.getClientIfExistsByProjectExtId(projectId, profileId);
    CloudImage image = client.findImageById(imageId);

    if(isGet(httpServletRequest)){
        ModelAndView modelAndView = new ModelAndView(myPluginDescriptor.getPluginResourcesPath("deleteImageDialog.jsp"));
        modelAndView.getModelMap().put("instances", image == null ? Collections.emptyList() : image.getInstances());
        return modelAndView;
    } else if(isPost(httpServletRequest) && image != null){
        for (CloudInstance instance : image.getInstances()){
            client.terminateInstance(instance);
        }
    }
    return null;
}
 
Example #2
Source File: TelegramSettingsController.java    From teamcity-telegram-plugin with Apache License 2.0 6 votes vote down vote up
private ActionErrors validate(@NotNull TelegramSettingsBean settings) {
  ActionErrors errors = new ActionErrors();
  if (StringUtil.isEmptyOrSpaces(settings.getBotToken())) {
    errors.addError("emptyBotToken", "Bot token must not be empty");
  }
  if (settings.isUseProxy()) {
    if (StringUtils.isEmpty(settings.getProxyServer())) {
      errors.addError("emptyProxyServer", "Proxy server must not be empty");
    }
    if (StringUtils.isEmpty(settings.getProxyPort())) {
      errors.addError("emptyProxyPort", "Proxy port must not be empty");
    }
  }
  String port = settings.getProxyPort();
  if (!StringUtils.isEmpty(port) &&
      (!StringUtil.isNumber(port) || Integer.valueOf(port) < 1 || Integer.valueOf(port) > 65535)) {
    errors.addError("badProxyPort", "Proxy port must be integer between 1 and 65535");
  }
  return errors;
}
 
Example #3
Source File: AllureToolProvider.java    From allure-teamcity with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public GetPackageVersionResult tryGetPackageVersion(@NotNull File toolPackage) {
    final String packageName = FilenameUtils.removeExtension(toolPackage.getName());
    Pattern pattern = Pattern.compile("allure-commandline-(.+)");

    Matcher matcher = pattern.matcher(packageName);
    if (!matcher.matches()) {
        return GetPackageVersionResult.error("Not allure-commandline");
    }
    final String toolId = matcher.group(1);
    if (StringUtil.isEmpty(toolId)) {
        return GetPackageVersionResult.error(String.format("Failed to determine allure-commandline version based on its package file name %s. Checked package %s", toolPackage.getName(), toolPackage.getAbsolutePath()));
    }
    return GetPackageVersionResult.version(new AllureDownloadableToolVersion(toolId));
}
 
Example #4
Source File: CustomTemplatePodTemplateProvider.java    From teamcity-kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public PersistentVolumeClaim getPVC(@NotNull final String instanceName,
                                    @NotNull final KubeCloudImage kubeCloudImage) {
    String pvcTemplate = kubeCloudImage.getPVCTemplate();
    if (StringUtil.isEmpty(pvcTemplate)){
        return null;
    }
    pvcTemplate = pvcTemplate.replaceAll("%instance\\.id%", instanceName);
    final PersistentVolumeClaim pvc = Serialization.unmarshal(
      new ByteArrayInputStream(pvcTemplate.getBytes()),
      PersistentVolumeClaim.class
    );

    return pvc;
}
 
Example #5
Source File: CustomTemplatePodTemplateProvider.java    From teamcity-kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Used("tests")
/* package local for tests */ Pod getPodTemplateInternal(@NotNull final CloudInstanceUserData cloudInstanceUserData,
                                  @NotNull final String imageId,
                                  @NotNull final String namespace,
                                  final String instanceName,
                                  String spec) {
    spec = spec.replaceAll("%instance\\.id%", instanceName);

    if (StringUtil.isEmpty(spec)) {
        throw new KubeCloudException("Custom pod template spec is not specified for image " + imageId);
    }

    final PodTemplateSpec podTemplateSpec = Serialization.unmarshal(
      new ByteArrayInputStream(spec.getBytes()),
      PodTemplateSpec.class
    );

    return patchedPodTemplateSpec(podTemplateSpec,
                                  instanceName,
                                  namespace,
                                  myServerSettings.getServerUUID(),
                                  imageId,
                                  cloudInstanceUserData);
}
 
Example #6
Source File: BaseDeployerRunner.java    From teamcity-deployer-plugin with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public BuildProcess createBuildProcess(@NotNull final AgentRunningBuild runningBuild,
                                       @NotNull final BuildRunnerContext context) throws RunBuildException {

  final Map<String, String> runnerParameters = context.getRunnerParameters();
  final String username = StringUtil.emptyIfNull(runnerParameters.get(DeployerRunnerConstants.PARAM_USERNAME));
  final String password = StringUtil.emptyIfNull(runnerParameters.get(DeployerRunnerConstants.PARAM_PASSWORD));
  final String target = StringUtil.emptyIfNull(runnerParameters.get(DeployerRunnerConstants.PARAM_TARGET_URL));
  final String sourcePaths = runnerParameters.get(DeployerRunnerConstants.PARAM_SOURCE_PATH);

  final Collection<ArtifactsPreprocessor> preprocessors = myExtensionHolder.getExtensions(ArtifactsPreprocessor.class);

  final ArtifactsBuilder builder = new ArtifactsBuilder();
  builder.setPreprocessors(preprocessors);
  builder.setBaseDir(runningBuild.getCheckoutDirectory());
  builder.setArtifactsPaths(sourcePaths);

  final List<ArtifactsCollection> artifactsCollections = builder.build();

  return getDeployerProcess(context, username, password, target, artifactsCollections);
}
 
Example #7
Source File: AnsibleRunType.java    From tc-ansible-runner with MIT License 6 votes vote down vote up
@NotNull
@Override
public PropertiesProcessor getRunnerPropertiesProcessor() {
  return new PropertiesProcessor() {
    public Collection<InvalidProperty> process(final Map<String, String> properties) {
        List<InvalidProperty> errors = new ArrayList<InvalidProperty>();
        AnsibleRunConfig config = new AnsibleRunConfig(properties);
        if (AnsibleCommand.EXECUTABLE.equals(config.getCommandType())) {
            if (StringUtil.isEmptyOrSpaces(config.getExecutable())) {
                errors.add(new InvalidProperty(AnsibleRunnerConstants.EXECUTABLE_KEY, "Cannot be empty"));
            }
            if (StringUtil.isEmptyOrSpaces(config.getPlaybook())) {
                errors.add(new InvalidProperty(AnsibleRunnerConstants.PLAYBOOK_FILE_KEY, "Cannot be empty"));
            }
        } else if (AnsibleCommand.CUSTOM_SCRIPT.equals(config.getCommandType())) {
            if (StringUtil.isEmptyOrSpaces(config.getSourceCode())) {
                errors.add(new InvalidProperty(AnsibleRunnerConstants.SOURCE_CODE_KEY, "Cannot be empty"));
            }
        }
      return errors;
    }
  };
}
 
Example #8
Source File: TelegramBotManager.java    From teamcity-telegram-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Reload bot if settings changed
 * @param newSettings updated user settings
 */
public synchronized void reloadIfNeeded(@NotNull TelegramSettings newSettings) {
  if (Objects.equals(newSettings, settings)) {
    LOG.debug("Telegram bot token settings has not changed");
    return;
  }
  LOG.debug("New telegram bot token is received: " +
          StringUtil.truncateStringValueWithDotsAtEnd(newSettings.getBotToken(), 6));
  this.settings = newSettings;
  cleanupBot();
  if (settings.getBotToken() != null && !settings.isPaused()) {
    TelegramBot newBot = createBot(settings);
    addUpdatesListener(newBot);
    bot = newBot;
  }
}
 
Example #9
Source File: ArtifactPathHelper.java    From teamcity-symbol-server with Apache License 2.0 6 votes vote down vote up
@NotNull
String concatenateArtifactPath(@NotNull final String fileNamePrefix, @NotNull final String pdbFileName) {
  final String normalizedFileNamePrefix = fileNamePrefix.replace(ARCHIVE_PATH_SEPARATOR, ARCHIVE_PATH_SEPARATOR_FULL);
  if (StringUtil.isEmpty(normalizedFileNamePrefix)) {
    return pdbFileName;
  }

  final String archivePath = getArchivePath(normalizedFileNamePrefix);
  if (archivePath == null || normalizedFileNamePrefix.contains(ARCHIVE_PATH_SEPARATOR_FULL)) {
    return normalizedFileNamePrefix + FOLDER_SEPARATOR + pdbFileName;
  }

  return archivePath + ARCHIVE_PATH_SEPARATOR +
    StringUtil.trimStart(normalizedFileNamePrefix, archivePath) + FOLDER_SEPARATOR +
    pdbFileName;
}
 
Example #10
Source File: VMRunType.java    From TeamCity.Virtual with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public PropertiesProcessor getRunnerPropertiesProcessor() {
  return new PropertiesProcessor() {
    @NotNull
    public Collection<InvalidProperty> process(Map<String, String> properties) {
      List<InvalidProperty> result = new ArrayList<InvalidProperty>();
      if (StringUtil.isEmptyOrSpaces(properties.get(VMConstants.PARAMETER_SCRIPT))) {
        result.add(new InvalidProperty(VMConstants.PARAMETER_SCRIPT, "Script should not be empty"));
      }

      final String vm = properties.get(VMConstants.PARAMETER_VM);
      final VM w = VM.find(vm);
      if (w == null) {
        result.add(new InvalidProperty(VMConstants.PARAMETER_VM, "Unknown VM"));
      } else {
        result.addAll(w.validate(properties));
      }
      return result;
    }
  };
}
 
Example #11
Source File: VMWareApiConnectorImpl.java    From teamcity-vmware-plugin with Apache License 2.0 6 votes vote down vote up
private String getFullPath(@NotNull final String entityName,
                           @NotNull final ManagedObjectReference mor,
                           @Nullable final ManagedObjectReference firstParent,
                           @Nullable final Datacenter dc){
  final String uniqueName = String.format("%s (%s)", entityName, mor.getVal());
  if (firstParent == null) {
    return uniqueName;
  }
  try {
    final String morPath = getFullMORPath(createExactManagedEntity(firstParent), dc);
    if (StringUtil.isEmpty(morPath)) {
      return uniqueName;
    } else if (("Resources".equals(entityName) || "vm".equals(entityName)) && !mor.getType().equals(firstParent.getType())) {
      LOG.debug("The pool is a special pool. Skipping it...");
      return morPath;
    } else {
      return morPath + "/" + entityName;
    }
  } catch (Exception ex){
    LOG.warnAndDebugDetails("Can't calculate full path for " + uniqueName, ex);
    return uniqueName;
  }
}
 
Example #12
Source File: S3Util.java    From teamcity-s3-artifact-storage-plugin with Apache License 2.0 6 votes vote down vote up
@NotNull
public static Map<String, String> validateParameters(@NotNull final Map<String, String> params, final boolean acceptReferences) {
  final Map<String, String> commonErrors = AWSCommonParams.validate(params, acceptReferences);
  if (!commonErrors.isEmpty()) {
    return commonErrors;
  }
  final Map<String, String> invalids = new HashMap<>();
  if (StringUtil.isEmptyOrSpaces(getBucketName(params))) {
    invalids.put(beanPropertyNameForBucketName(), "S3 bucket name must not be empty");
  }
  final String pathPrefix = params.getOrDefault(S3_PATH_PREFIX_SETTING, "");
  if (TeamCityProperties.getBoolean("teamcity.internal.storage.s3.bucket.prefix.enable") && !StringUtil.isEmptyOrSpaces(pathPrefix)) {
    if (pathPrefix.length() > OUT_MAX_PREFIX_LENGTH) {
      invalids.put(S3_PATH_PREFIX_SETTING, "Should be less than " + OUT_MAX_PREFIX_LENGTH + " characters");
    }
    if (!OUR_OBJECT_KEY_PATTERN.matcher(pathPrefix).matches()) {
      invalids.put(S3_PATH_PREFIX_SETTING, "Should match the regexp [" + OUR_OBJECT_KEY_PATTERN.pattern() + "]");
    }
  }
  return invalids;
}
 
Example #13
Source File: KubeProfilePropertiesProcessor.java    From teamcity-kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<InvalidProperty> process(Map<String, String> map) {
    Collection<InvalidProperty> invalids = new ArrayList<>();
    if(StringUtil.isEmptyOrSpaces(map.get(API_SERVER_URL))) invalids.add(new InvalidProperty(API_SERVER_URL, "Kubernetes API server URL must not be empty"));
    final String authStrategy = map.get(AUTH_STRATEGY);
    if (StringUtil.isEmptyOrSpaces(authStrategy)) {
        invalids.add(new InvalidProperty(AUTH_STRATEGY, "Authentication strategy must be selected"));
        return invalids;
    }
    KubeAuthStrategy strategy = myKubeAuthStrategyProvider.find(authStrategy);
    if (strategy != null) {
        Collection<InvalidProperty> strategyCollection = strategy.process(map);
        if (strategyCollection != null && !strategyCollection.isEmpty()){
            invalids.addAll(strategyCollection);
        }
    }

    return invalids;
}
 
Example #14
Source File: VmwareCloudImageDetails.java    From teamcity-vmware-plugin with Apache License 2.0 6 votes vote down vote up
public VmwareCloudImageDetails(@NotNull final CloudImageParameters imageParameters){
  myCustomizationSpec = imageParameters.getParameter(VmwareConstants.CUSTOMIZATION_SPEC);
  myMaxInstances = StringUtil.parseInt(StringUtil.emptyIfNull(imageParameters.getParameter(VmwareConstants.MAX_INSTANCES)), 0);
  mySourceVmName = imageParameters.getParameter(VmwareConstants.SOURCE_VM_NAME);
  myFolderId = imageParameters.getParameter(VmwareConstants.FOLDER);
  myResourcePoolId = imageParameters.getParameter(VmwareConstants.RESOURCE_POOL);
  myCloneBehaviour = CloneBehaviour.valueOf(imageParameters.getParameter(VmwareConstants.BEHAVIOUR));
  mySnapshotName = StringUtil.emptyIfNull(imageParameters.getParameter(VmwareConstants.SNAPSHOT));
  myNickname = StringUtil.nullIfEmpty(imageParameters.getParameter(VmwareConstants.NICKNAME));
  myAgentPoolId = imageParameters.getAgentPoolId();
  if (myCloneBehaviour.isUseOriginal()){
    mySourceId = mySourceVmName;
  } else {
    mySourceId = myNickname == null ? mySourceVmName : myNickname;
  }
}
 
Example #15
Source File: S3Util.java    From teamcity-s3-artifact-storage-plugin with Apache License 2.0 6 votes vote down vote up
public static String getContentType(final File file) {
  String contentType = URLConnection.guessContentTypeFromName(file.getName());
  if (StringUtil.isNotEmpty(contentType)) {
    return contentType;
  }
  if (PROBE_CONTENT_TYPE_METHOD != null && FILE_TO_PATH_METHOD != null) {
    try {
      final Object result = PROBE_CONTENT_TYPE_METHOD.invoke(null, FILE_TO_PATH_METHOD.invoke(file));
      if (result instanceof String) {
        contentType = (String)result;
      }
    } catch (Exception ignored) {
    }
  }
  return StringUtil.notEmpty(contentType, DEFAULT_CONTENT_TYPE);
}
 
Example #16
Source File: KubePodNameGeneratorImpl.java    From teamcity-kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
private synchronized void loadIdxes(@NotNull final File idxStorage) {
  final File[] idxes = idxStorage.listFiles();
  if (idxes == null){

  }
  for (File idxFile : idxes) {
    if (!idxFile.getName().endsWith(".idx"))
      continue;
    String idxName = idxFile.getName().substring(0, idxFile.getName().length()-4);
    try {
      int val = StringUtil.parseInt(FileUtil.readText(idxFile), -1);
      if (val > 0){
        myCounters.putIfAbsent(idxName, new AtomicInteger(0));
        myCounters.get(idxName).set(val);
      }
    } catch (IOException e) {}
  }
}
 
Example #17
Source File: KubePodNameGeneratorImpl.java    From teamcity-kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@NotNull
public String generateNewVmName(@NotNull KubeCloudImage image) {
  try {
    myLock.readLock().lock();
    if (!myIsAvailable.get()){
      throw new CloudException("Unable to generate a name for image " + image.getId() + " - server is shutting down");
    }
    String newVmName;
    do {
      String prefix = image.getAgentNamePrefix();
      if (StringUtil.isEmptyOrSpaces(prefix)) {
        prefix = image.getDockerImage();
      }
      if (StringUtil.isEmptyOrSpaces(prefix)) {
        return UUID.randomUUID().toString();
      }
      prefix = StringUtil.replaceNonAlphaNumericChars(prefix.trim().toLowerCase(), '-');
      newVmName = String.format("%s-%d", prefix, getNextCounter(prefix));
      setTouched(prefix);

    } while (image.findInstanceById(newVmName) != null);
    return newVmName;
  } finally {
    myLock.readLock().unlock();
  }
}
 
Example #18
Source File: KubeApiConnectorImpl.java    From teamcity-kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
protected Config createConfig(@NotNull KubeApiConnection connectionSettings, @NotNull KubeAuthStrategy authStrategy){
    ConfigBuilder configBuilder = new ConfigBuilder()
      .withMasterUrl(connectionSettings.getApiServerUrl())
      .withNamespace(connectionSettings.getNamespace())
      .withRequestTimeout(DEFAULT_REQUEST_TIMEOUT_MS)
      .withHttp2Disable(true)
      .withConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT_MS);
    final String caCertData = connectionSettings.getCACertData();
    if(StringUtil.isEmptyOrSpaces(caCertData)){
        configBuilder.withTrustCerts(true);
    } else {
        configBuilder.withCaCertData(KubeUtils.encodeBase64IfNecessary(caCertData));
    }
    configBuilder = authStrategy.apply(configBuilder, connectionSettings);
    return configBuilder.build();
}
 
Example #19
Source File: KubeCloudInstanceImpl.java    From teamcity-kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public Date getStartedTime() {
    final PodStatus podStatus = myPod.getStatus();
    if(podStatus == null) return myCreationTime;
    try {
        final List<PodCondition> podConditions = podStatus.getConditions();
        if (podConditions != null && !podConditions.isEmpty()) {
            for (PodCondition podCondition : podConditions) {
                if (PodConditionType.valueOf(podCondition.getType()) == PodConditionType.Ready)
                    return myPodTransitionTimeFormat.parse(podCondition.getLastTransitionTime());
            }
        }
        String startTime = podStatus.getStartTime();
        return !StringUtil.isEmpty(startTime) ? myPodStartTimeFormat.parse(startTime) : myCreationTime;
    } catch (ParseException e) {
        throw new KubeCloudException("Failed to get instance start date", e);
    }
}
 
Example #20
Source File: VMWareApiConnectorImpl.java    From teamcity-vmware-plugin with Apache License 2.0 6 votes vote down vote up
private String getLatestSnapshot(final String snapshotNameMask, final Map<String, VirtualMachineSnapshotTree> snapshotList) {
  if (snapshotNameMask == null)
    return null;
  if (!snapshotNameMask.contains("*") && !snapshotNameMask.contains("?")) {
    return snapshotList.containsKey(snapshotNameMask) ? snapshotNameMask : null;
  }
  Date latestTime = new Date(0);
  String latestSnapshotName = null;
  for (Map.Entry<String, VirtualMachineSnapshotTree> entry : snapshotList.entrySet()) {
    final String snapshotNameMaskRegex = StringUtil.convertWildcardToRegexp(snapshotNameMask);
    final Pattern pattern = Pattern.compile(snapshotNameMaskRegex);
    if (pattern.matcher(entry.getKey()).matches()) {
      final Date snapshotTime = entry.getValue().getCreateTime().getTime();
      if (latestTime.before(snapshotTime)) {
        latestTime = snapshotTime;
        latestSnapshotName = entry.getKey();
      }
    }
  }
  return latestSnapshotName;
}
 
Example #21
Source File: ArtifactPathHelper.java    From teamcity-symbol-server with Apache License 2.0 5 votes vote down vote up
@Nullable
private String getArchivePath(@NotNull final String path) {
  for (ArchivePreprocessor preprocessor : myExtensions.getExtensions(ArchivePreprocessor.class)) {
    final String targetPath = preprocessor.getTargetKey(path);
    if (StringUtil.isEmpty(targetPath)) continue;
    return targetPath;
  }
  return null;
}
 
Example #22
Source File: SymbolsIndexerParametersPreprocessor.java    From teamcity-symbol-server with Apache License 2.0 5 votes vote down vote up
public void updateParameters(@NotNull BuildStartContext context) {
  final SBuildType buildType = context.getBuild().getBuildType();
  if(buildType == null) return;
  final Collection<SBuildFeatureDescriptor> buildFeatures = buildType.getResolvedSettings().getBuildFeatures();
  for(SBuildFeatureDescriptor buildFeature : buildFeatures){
    if(!buildFeature.getType().equals(SymbolsConstants.BUILD_FEATURE_TYPE)) continue;
    String serverOwnUrl = context.getSharedParameters().get(SymbolsConstants.SERVER_OWN_URL_PARAM_NAME);
    if(serverOwnUrl == null){
      serverOwnUrl = myRootUrlHolder.getRootUrl();
    }
    final String sourceServerUrl = String.format("%s%s", StringUtil.removeTailingSlash(serverOwnUrl), SymbolsConstants.APP_SOURCES);
    context.addSharedParameter(SymbolsConstants.SOURCES_SERVER_URL_PARAM_NAME, sourceServerUrl);
  }
}
 
Example #23
Source File: SlackNotificationListener.java    From tcSlackBuildNotifier with MIT License 5 votes vote down vote up
public void getFromConfig(SlackNotification slackNotification, SlackNotificationConfig slackNotificationConfig){
       slackNotification.setChannel(StringUtil.isEmpty(slackNotificationConfig.getChannel()) ? myMainSettings.getDefaultChannel() : slackNotificationConfig.getChannel());
       slackNotification.setTeamName(myMainSettings.getTeamName());
       slackNotification.setToken(StringUtil.isEmpty(slackNotificationConfig.getToken()) ? myMainSettings.getToken() : slackNotificationConfig.getToken());
       slackNotification.setIconUrl(myMainSettings.getIconUrl());
       slackNotification.setBotName(myMainSettings.getBotName());
	slackNotification.setEnabled(myMainSettings.getEnabled() && slackNotificationConfig.getEnabled());
	slackNotification.setBuildStates(slackNotificationConfig.getBuildStates());
	slackNotification.setProxy(myMainSettings.getProxyConfig());
       slackNotification.setShowBuildAgent(myMainSettings.getShowBuildAgent());
       slackNotification.setShowElapsedBuildTime(myMainSettings.getShowElapsedBuildTime());
       slackNotification.setShowCommits(myMainSettings.getShowCommits());
       slackNotification.setShowCommitters(myMainSettings.getShowCommitters());
       slackNotification.setFilterBranchName(slackNotificationConfig.getFilterBranchName());
       slackNotification.setShowTriggeredBy(myMainSettings.getShowTriggeredBy());
       slackNotification.setShowFailureReason(myMainSettings.getShowFailureReason() == null ? SlackNotificationContentConfig.DEFAULT_SHOW_FAILURE_REASON : myMainSettings.getShowFailureReason());
       slackNotification.setMaxCommitsToDisplay(myMainSettings.getMaxCommitsToDisplay());
       slackNotification.setMentionChannelEnabled(slackNotificationConfig.getMentionChannelEnabled());
	slackNotification.setMentionSlackUserEnabled(slackNotificationConfig.getMentionSlackUserEnabled());
	slackNotification.setMentionWhoTriggeredEnabled(slackNotificationConfig.isMentionWhoTriggeredEnabled());
	slackNotification.setMentionHereEnabled(slackNotificationConfig.getMentionHereEnabled());
       slackNotification.setShowElapsedBuildTime(myMainSettings.getShowElapsedBuildTime());
       if(slackNotificationConfig.getContent() != null && slackNotificationConfig.getContent().isEnabled()) {
           slackNotification.setBotName(slackNotificationConfig.getContent().getBotName());
           slackNotification.setIconUrl(slackNotificationConfig.getContent().getIconUrl());
           slackNotification.setMaxCommitsToDisplay(slackNotificationConfig.getContent().getMaxCommitsToDisplay());
           slackNotification.setShowBuildAgent(slackNotificationConfig.getContent().getShowBuildAgent());
           slackNotification.setShowElapsedBuildTime(slackNotificationConfig.getContent().getShowElapsedBuildTime());
           slackNotification.setShowCommits(slackNotificationConfig.getContent().getShowCommits());
           slackNotification.setShowCommitters(slackNotificationConfig.getContent().getShowCommitters());
           slackNotification.setShowTriggeredBy(slackNotificationConfig.getContent().getShowTriggeredBy());
           slackNotification.setShowFailureReason(slackNotificationConfig.getContent().getShowFailureReason() == null ? SlackNotificationContentConfig.DEFAULT_SHOW_FAILURE_REASON : slackNotificationConfig.getContent().getShowFailureReason());
       }
	Loggers.ACTIVITIES.debug("SlackNotificationListener :: SlackNotification proxy set to "
			+ slackNotification.getProxyHost() + " for " + slackNotificationConfig.getChannel());
}
 
Example #24
Source File: SmbDeployerRunner.java    From teamcity-deployer-plugin with Apache License 2.0 5 votes vote down vote up
private boolean shouldEnforceSMBv1(@NotNull final BuildRunnerContext context) {
  boolean shouldEnforceOnBuild =
          StringUtil.isTrue(context.getBuild().getSharedConfigParameters().get(SMBRunnerConstants.SHOULD_ENFORCE_SMB1));
  if (shouldEnforceOnBuild) {
    return true;
  }

  return TeamCityProperties.getBoolean(SMBRunnerConstants.SHOULD_ENFORCE_SMB1);
}
 
Example #25
Source File: CommandLineUtils.java    From TeamCity.Virtual with Apache License 2.0 5 votes vote down vote up
@NotNull
public static List<String> additionalCommands(@Nullable final String text) {
  if (StringUtil.isEmptyOrSpaces(text)) return Collections.emptyList();

  final List<String> result = new ArrayList<String>();
  for (String s : text.split("[\\r\\n]+")) {
    final String arg = s.trim();
    if (arg.length() == 0) continue;

    result.addAll(StringUtil.splitHonorQuotes(arg));
  }

  return result;
}
 
Example #26
Source File: SSHSessionProvider.java    From teamcity-deployer-plugin with Apache License 2.0 5 votes vote down vote up
private Session initSessionKeyFile(String username, String password, File keyFile, JSch jsch) throws JSchException {
  try {
    if (StringUtil.isNotEmpty(password)) {
      myLog.debug("Adding password");
      jsch.addIdentity(keyFile.getCanonicalPath(), password);
    } else {
      jsch.addIdentity(keyFile.getCanonicalPath());
    }
    final Session session = jsch.getSession(username, myHost, myPort);
    session.setConfig("PreferredAuthentications", "publickey");
    return session;
  } catch (IOException e) {
    throw new JSchException("Failed to use key file", e);
  }
}
 
Example #27
Source File: S3ArtifactContentProvider.java    From teamcity-s3-artifact-storage-plugin with Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public InputStream getContent(@NotNull StoredBuildArtifactInfo storedBuildArtifactInfo) throws IOException {
  final Map<String, String> params;
  final ArtifactData artifactData = storedBuildArtifactInfo.getArtifactData();
  if (artifactData == null) {
    throw new IOException("Invalid artifact data: S3 object path property is not set");
  }

  final String artifactPath = artifactData.getPath();
  try {
    params = S3Util.validateParameters(storedBuildArtifactInfo.getStorageSettings());
  } catch (IllegalArgumentException e) {
    throw new IOException("Failed to get artifact " + artifactPath + " content: Invalid storage settings " + e.getMessage(), e);
  }

  final String bucketName = S3Util.getBucketName(params);
  final String key = S3Util.getPathPrefix(storedBuildArtifactInfo.getCommonProperties()) + artifactPath;

  try {
    return S3Util.withS3Client(
      ParamUtil.putSslValues(myServerPaths, params),
      client -> client.getObject(bucketName, key).getObjectContent()
    );
  } catch (Throwable t) {
    final AWSException awsException = new AWSException(t);
    final String details = awsException.getDetails();
    if (StringUtil.isNotEmpty(details)) {
      final String message = awsException.getMessage() + details;
      LOG.warn(message);
    }
    throw new IOException(String.format(
      "Failed to get artifact '%s' content in bucket '%s': %s",
      artifactPath, bucketName, awsException.getMessage()
    ), awsException);
  }
}
 
Example #28
Source File: VMWarePropertiesReader.java    From teamcity-vmware-plugin with Apache License 2.0 5 votes vote down vote up
@Nullable
private static String getToolPath(@NotNull final BuildAgentConfiguration configuration) {
  final String rpctoolPath = TeamCityProperties.getProperty(RPC_TOOL_PARAMETER);
  if (StringUtil.isNotEmpty(rpctoolPath)){
    return rpctoolPath;
  }

  if (SystemInfo.isUnix) { // Linux, MacOSX, FreeBSD
    final Map<String, String> envs = configuration.getBuildParameters().getEnvironmentVariables();
    final String path = envs.get("PATH");
    if (path != null) for (String p : StringUtil.splitHonorQuotes(path, File.pathSeparatorChar)) {
      final File file = new File(p, VMWARE_RPCTOOL_NAME);
      if (file.exists()) {
        return file.getAbsolutePath();
      }
    }
  }
  if (SystemInfo.isLinux) {
    return getExistingCommandPath(LINUX_COMMANDS);
  } else if (SystemInfo.isWindows) {
    return getExistingCommandPath(WINDOWS_COMMANDS);
  } else if (SystemInfo.isMac) {
    return getExistingCommandPath(MAC_COMMANDS);
  } else {
    return getExistingCommandPath(LINUX_COMMANDS); //todo: update for other OS'es
  }
}
 
Example #29
Source File: VmwarePropertiesProcessor.java    From teamcity-vmware-plugin with Apache License 2.0 5 votes vote down vote up
private void notEmpty(@NotNull final Map<String, String> props,
                               @NotNull final String key,
                               @NotNull final Collection<InvalidProperty> col) {
  if (!props.containsKey(key) || StringUtil.isEmptyOrSpaces(props.get(key))) {
    col.add(new InvalidProperty(key, "Value should be set"));
  }
}
 
Example #30
Source File: FolderBean.java    From teamcity-vmware-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public int compareTo(@NotNull final FolderBean o) {
  if (myPath == null && o.myPath == null) {
    return StringUtil.compare(StringUtil.toLowerCase(myName), StringUtil.toLowerCase(o.myName));
  }
  return StringUtil.compare(StringUtil.toLowerCase(myPath), StringUtil.toLowerCase(o.myPath));
}