com.atlassian.bitbucket.setting.Settings Java Examples

The following examples show how to use com.atlassian.bitbucket.setting.Settings. 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: FileSizeHook.java    From stash-filehooks-plugin with Apache License 2.0 6 votes vote down vote up
private List<FileSizeHookSetting> getSettings(Settings settings) {
    List<FileSizeHookSetting> configurations = new ArrayList<>();
    String includeRegex;
    Long size;
    String excludeRegex;
    String branchesRegex;

    for (int i = 1; i <= MAX_SETTINGS; i++) {
        includeRegex = settings.getString(SETTINGS_INCLUDE_PATTERN_PREFIX + i);
        if (includeRegex != null) {
            excludeRegex = settings.getString(SETTINGS_EXCLUDE_PATTERN_PREFIX + i);
            size = settings.getLong(SETTINGS_SIZE_PREFIX + i);
            branchesRegex = settings.getString(SETTINGS_BRANCHES_PATTERN_PREFIX + i);
            configurations.add(new FileSizeHookSetting(size, includeRegex, excludeRegex, branchesRegex));
        }
    }

    return configurations;
}
 
Example #2
Source File: MirrorRepositoryHookTest.java    From stash-hook-mirror with MIT License 6 votes vote down vote up
private Settings defaultSettings() {
    Map<String, Object> map = new HashMap<>();
    map.put(MirrorRepositoryHook.SETTING_MIRROR_REPO_URL, "");

    Settings settings = mock(Settings.class);
    when(settings.asMap()).thenReturn(map);
    when(settings.getString(eq(MirrorRepositoryHook.SETTING_MIRROR_REPO_URL), eq(""))).thenReturn(mirrorRepoUrlHttp);
    when(settings.getString(eq(MirrorRepositoryHook.SETTING_USERNAME), eq(""))).thenReturn(username);
    when(settings.getString(eq(MirrorRepositoryHook.SETTING_PASSWORD), eq(""))).thenReturn(password);
    when(settings.getString(eq(MirrorRepositoryHook.SETTING_REFSPEC), eq(""))).thenReturn(refspec);
    when(settings.getBoolean(eq(MirrorRepositoryHook.SETTING_TAGS), eq(true))).thenReturn(true);
    when(settings.getBoolean(eq(MirrorRepositoryHook.SETTING_NOTES), eq(true))).thenReturn(true);
    when(settings.getBoolean(eq(MirrorRepositoryHook.SETTING_ATOMIC), eq(true))).thenReturn(true);

    return settings;
}
 
Example #3
Source File: MirrorRepositoryHook.java    From stash-hook-mirror with MIT License 6 votes vote down vote up
private List<MirrorSettings> getMirrorSettings(Settings settings, boolean defTags, boolean defNotes, boolean defAtomic) {
    Map<String, Object> allSettings = settings.asMap();
    int count = 0;

    List<MirrorSettings> results = new ArrayList<>();
    for (String key : allSettings.keySet()) {
        if (key.startsWith(SETTING_MIRROR_REPO_URL)) {
            String suffix = key.substring(SETTING_MIRROR_REPO_URL.length());

            MirrorSettings ms = new MirrorSettings();
            ms.mirrorRepoUrl = settings.getString(SETTING_MIRROR_REPO_URL + suffix, "");
            ms.username = settings.getString(SETTING_USERNAME + suffix, "");
            ms.password = settings.getString(SETTING_PASSWORD + suffix, "");
            ms.refspec = (settings.getString(SETTING_REFSPEC + suffix, ""));
            ms.tags = (settings.getBoolean(SETTING_TAGS + suffix, defTags));
            ms.notes = (settings.getBoolean(SETTING_NOTES + suffix, defNotes));
            ms.atomic = (settings.getBoolean(SETTING_ATOMIC + suffix, defAtomic));
            ms.suffix = String.valueOf(count++);

            results.add(ms);
        }
    }

    return results;
}
 
Example #4
Source File: RepositoryHookSettingsValidator.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Validates form data in repository triggers tab
 *
 * @param settings - to be validated.
 * @param errors - callback for reporting validation errors.
 * @throws IOException if JSON parsing error occurs
 */
private void validaterepositoryTriggersTab(final Settings settings, final SettingsValidationErrors errors) throws IOException {
    final String repositoryTriggersJson = settings.getString(Field.REPOSITORY_TRIGGERS_JSON, StringUtils.EMPTY);
    final ObjectMapper mapper = new ObjectMapper();
    final Map<String, Trigger> triggerMap = mapper.readValue(repositoryTriggersJson, mapper.getTypeFactory().constructParametricType(HashMap.class, String.class, Trigger.class));
    for (final Map.Entry<String, Trigger> triggerEntry : triggerMap.entrySet()) {
        final Trigger trigger = triggerEntry.getValue();
        if (StringUtils.isBlank(trigger.getTarget())) {
            errors.addFieldError(triggerEntry.getKey(), this.i18n.getText("error.string.empty"));
        } else if (StringUtils.containsWhitespace(trigger.getTarget())) {
            errors.addFieldError(triggerEntry.getKey(), this.i18n.getText("error.string.contains.whitespace"));
        }
        try {
            final Pattern pattern = Pattern.compile(triggerEntry.getValue().getRegex(), Pattern.CASE_INSENSITIVE);
            final Matcher matcher = pattern.matcher(BRANCH_TEST_STRING);
            if (matcher.groupCount() != 1) {
                errors.addFieldError(triggerEntry.getKey(), this.i18n.getText("error.regex.needs.capturing"));
            }
        } catch (final PatternSyntaxException e) {
            errors.addFieldError(triggerEntry.getKey(), e.getLocalizedMessage());
        }
    }
}
 
Example #5
Source File: TeamcityConnector.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 6 votes vote down vote up
public Boolean IsInQueue(TeamcityConfiguration conf, String buildConfig, String branch, Settings settings) throws IOException, JSONException {
    String queueData = this.GetQueueDataForConfiguration(conf, buildConfig, settings);
    JSONObject jsonObj = new JSONObject(queueData);
    
    Integer numberOfQueuedBuilds = jsonObj.getInt("count");
    
    if(numberOfQueuedBuilds == 0) {
      return false;
    }
    
    JSONArray builds = jsonObj.getJSONArray("build");
    for (int i = 0; i < builds.length(); i++) {
        try
        {                           
            JSONObject queued = builds.getJSONObject(i);
            String branchName = queued.getString("branchName");

            if (branchName.equals(branch)) {
                return true;
            }                            
        } catch (JSONException e) {
        }                                                   
    }
    
    return false;
}
 
Example #6
Source File: HttpConnector.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 6 votes vote down vote up
public String Get(String url, Settings settings) throws MalformedURLException, IOException {
  String urlstr = url;
  URL urldata = new URL(urlstr);
  TeamcityLogger.logMessage(settings, "[HttpConnector][Get]  Hook Request with timeout 5 seconds for connect: "  + urlstr);
  HttpURLConnection connection = (HttpURLConnection) urldata.openConnection();
  connection.setConnectTimeout(5000);
  connection.setRequestMethod("GET");
  connection.setDoOutput(true);
  connection.setRequestProperty("Accept", "application/json");
  InputStream content = (InputStream)connection.getInputStream();
  BufferedReader in   = 
      new BufferedReader (new InputStreamReader (content));

  StringBuilder dataout = new StringBuilder();
  String line;
  while ((line = in.readLine()) != null) {
      dataout.append(line);
  }

  TeamcityLogger.logMessage(settings, "[HttpConnector][Get] Hook Reply: "  + line);
  return dataout.toString();
}
 
Example #7
Source File: TeamctiyRest.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Trigger a build on the Teamcity instance using vcs root
 *
 * @param repository The repository to trigger
 * @return The response. Ok if it worked. Otherwise, an error.
 */
@GET
@Path(value = "triggerexternalurl")
public String triggerexternalurl(@Context final Repository repository, @QueryParam("url") final String url, @QueryParam("method") final String method) {

  final HttpConnector dummyConnector = new HttpConnector();
  String returnData;
  try {
    final Optional<Settings> settings = this.settingsService.getSettings(repository);

    if (!settings.isPresent()) {
      return "{\"status\": \"error\", \"message\": \"hook not configured\"}";
    }
  
    returnData = dummyConnector.Get(url, settings.get());
    return "{\"status\": \"ok\", \"message\": \" " + returnData + "\" }";
  } catch (final IOException ex) {
    return "{\"status\": \"failed\", \"message\": \" " + ex.getMessage() + "\" }";
  }
}
 
Example #8
Source File: TeamcityPullrequestEventListener.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 6 votes vote down vote up
@EventListener
public void onPullRequestRescoped(final PullRequestRescopedEvent event) throws IOException, JSONException {
  final String previousFromHash = event.getPreviousFromHash();
  final String currentFromHash = event.getPullRequest().getFromRef().getLatestCommit();

  if (currentFromHash.equals(previousFromHash)) {
    return;
  }

  final PullRequest pr = event.getPullRequest();
  final Repository repo = pr.getFromRef().getRepository();
  final Optional<Settings> settings = this.settingsService.getSettings(repo);
  if(!settings.isPresent()) {
    return;
  }

  try {
    TeamcityLogger.logMessage(settings.get(), "Run PullRequest Rescoped Event : " + pr.getFromRef().getDisplayId());
    TriggerBuildFromPullRequest(pr, false);
  } catch (final IOException | JSONException ex) {
    TeamcityLogger.logMessage(settings.get(), "PullRequest Rescoped Event Failed: " + ex.getMessage() + " " + pr.getFromRef().getDisplayId());
  }
}
 
Example #9
Source File: TeamcityPullrequestEventListener.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 6 votes vote down vote up
@EventListener
public void onPullRequestParticipantsUpdatedEvent(final PullRequestParticipantsUpdatedEvent event) throws IOException, JSONException {
  final PullRequest pr = event.getPullRequest();
  final Set<PullRequestParticipant> reviewers = pr.getReviewers();
  final Repository repo = pr.getFromRef().getRepository();
  final Optional<Settings> settings = this.settingsService.getSettings(repo);
  
  if(!settings.isPresent()) {
    return;
  }
  
  if (event.getAddedParticipants().size() > 0 && reviewers.size() > 0) {
    // trigger only when number of participations is 2 or higher (author + reviewer)
    try {
      TriggerBuildFromPullRequest(event.getPullRequest(), true);
    } catch (final IOException | JSONException ex) {
      TeamcityLogger.logMessage(settings.get(), "PullRequest Reviwer update event failed: " + ex.getMessage());
    }
  }
}
 
Example #10
Source File: TeamcityPullrequestEventListener.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 6 votes vote down vote up
@EventListener
public void onPullRequestOpenedEvent(final PullRequestOpenedEvent event) throws IOException, JSONException {
  final PullRequest pr = event.getPullRequest();
  final Repository repo = pr.getFromRef().getRepository();
  final Optional<Settings> settings = this.settingsService.getSettings(repo);
  
  if(!settings.isPresent()) {
    return;
  }
  
  try {
    TriggerBuildFromPullRequest(pr, false);
  } catch (final IOException | JSONException ex) {
    TeamcityLogger.logMessage(settings.get(), "PullRequest Opened Event Failed: " + ex.getMessage());
  }
}
 
Example #11
Source File: MirrorRepositoryHookTest.java    From stash-hook-mirror with MIT License 5 votes vote down vote up
@Test
public void testValidateForProject() {
    SettingsValidationErrors errors = mock(SettingsValidationErrors.class);
    Project project = mock(Project.class);
    Settings settings = mock(Settings.class);

    hook.validate(settings, errors, Scopes.project(project));

    verifyZeroInteractions(bucketedExecutor, errors, settings);
}
 
Example #12
Source File: TeamcityTriggerHook.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void TriggerCheckForChanges(final RepositoryHookContext context, final String vcsRoot, final TeamcityConfiguration conf, final Settings settings) {
  try {
    TeamcityLogger.logMessage(context, "Trigger Check for Changes in: " + vcsRoot);
    this.connector.TriggerCheckForChanges(conf, vcsRoot, settings);
  } catch (final Exception e) {
    TeamcityLogger.logMessage(context, "Trigger Check for Changes in: " + vcsRoot + " Failed : " + e.getMessage());
  }
}
 
Example #13
Source File: MirrorRepositoryHook.java    From stash-hook-mirror with MIT License 5 votes vote down vote up
private void updateSettings(List<MirrorSettings> mirrorSettings, Settings settings) {
    Map<String, Object> values = new HashMap<>();
    for (MirrorSettings ms : mirrorSettings) {
        values.put(SETTING_MIRROR_REPO_URL + ms.suffix, ms.mirrorRepoUrl);
        values.put(SETTING_USERNAME + ms.suffix, ms.username);
        values.put(SETTING_PASSWORD + ms.suffix, (ms.password.isEmpty() ? ms.password : passwordEncryptor.encrypt(ms.password)));
        values.put(SETTING_REFSPEC + ms.suffix, ms.refspec);
        values.put(SETTING_TAGS + ms.suffix, ms.tags);
        values.put(SETTING_NOTES + ms.suffix, ms.notes);
        values.put(SETTING_ATOMIC + ms.suffix, ms.atomic);
    }

    // Unfortunately the settings are stored in an immutable map, so need to cheat with reflection
    settingsReflectionHelper.set(values, settings);
}
 
Example #14
Source File: RepositoryHookSettingsValidator.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Validates form fields in connections tab
 *
 * @param settings - to be validated.
 * @param errors - callback for reporting validation errors.
 */
private void validateConnectionTab(final Settings settings, final SettingsValidationErrors errors) {
    
    final Boolean isDebugOn = settings.getBoolean(Field.DEBUG);
            
    final String bitbucketUrl = settings.getString(Field.BITBUCKET_URL, StringUtils.EMPTY);
    if (!URL_VALIDATION_PATTERN.matcher(bitbucketUrl).matches()) {
        errors.addFieldError(Field.BITBUCKET_URL, this.i18n.getText("error.invalid.url"));
    }

    final String teamCityUrl = settings.getString(Field.TEAMCITY_URL, StringUtils.EMPTY);
    if (!URL_VALIDATION_PATTERN.matcher(teamCityUrl).matches()) {
        errors.addFieldError(Field.TEAMCITY_URL, this.i18n.getText("error.invalid.url"));
    }

    final String teamCityUserName = settings.getString(Field.TEAMCITY_USERNAME, StringUtils.EMPTY);
    if (StringUtils.EMPTY.equals(teamCityUserName)) {
        errors.addFieldError(Field.TEAMCITY_USERNAME, this.i18n.getText("error.required.field"));
    }

    final String teamCityPassword = settings.getString(Field.TEAMCITY_PASSWORD, StringUtils.EMPTY);
    if (StringUtils.EMPTY.equals(teamCityPassword)) {
        errors.addFieldError(Field.TEAMCITY_PASSWORD, this.i18n.getText("error.required.field"));
    }

    if (!Constant.TEAMCITY_PASSWORD_SAVED_VALUE.equals(teamCityPassword)) {
        errors.addFieldError(Field.TEAMCITY_PASSWORD, this.i18n.getText("error.require.validation", this.i18n.getText("connetion.test.button")));
    }
}
 
Example #15
Source File: RepositoryHookSettingsValidator.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void validate(Settings stngs, SettingsValidationErrors sve, Scope scope) {
    try {
        validateConnectionTab(stngs, sve);
        validaterepositoryTriggersTab(stngs, sve);
    } catch (final IOException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #16
Source File: MirrorRepositoryHookTest.java    From stash-hook-mirror with MIT License 5 votes vote down vote up
@Test
public void testPostUpdateUnconfigured() {
    Repository repo = mock(Repository.class);
    when(repo.getScmId()).thenReturn(GitScm.ID);

    Settings settings = mock(Settings.class);
    when(settings.asMap()).thenReturn(Collections.emptyMap());

    PostRepositoryHookContext context = mock(PostRepositoryHookContext.class);
    when(context.getSettings()).thenReturn(settings);

    hook.postUpdate(context, new RepositoryPushHookRequest.Builder(repo).build());

    verifyZeroInteractions(bucketedExecutor);
}
 
Example #17
Source File: SettingsService.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Optional<Settings> getSettings(final Repository repository) {
  try {
    final RepositoryHookSettings settings =
        this.securityService
            .withPermission(Permission.REPO_ADMIN, "Retrieving settings")
            .call(
                new Operation<RepositoryHookSettings, Exception>() {
                  @Override
                  public RepositoryHookSettings perform() throws Exception {

                    final RepositoryHook hook =
                        SettingsService.this.hookService.getByKey(
                            new RepositoryScope(repository), SettingsService.KEY);
                    if (!hook.isEnabled() || !hook.isEnabled()) {
                      return null;
                    }
                    final GetRepositoryHookSettingsRequest req =
                        new GetRepositoryHookSettingsRequest.Builder(
                                new RepositoryScope(repository), SettingsService.KEY)
                            .build();
                    return SettingsService.this.hookService.getSettings(req);
                  }
                });
    if (settings == null) {
      return empty();
    }

    LOGGER.info("Using settings:\n" + settings);
    return Optional.of(settings.getSettings());
  } catch (final Exception e) {
    LOGGER.error("Unexpected exception trying to get repository settings", e);
    return empty();
  }
}
 
Example #18
Source File: TeamcityConnector.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void ReQueueBuild(TeamcityConfiguration conf, String id, Settings settings, Boolean readIntoQueue) {
  String url = "/app/rest/builds/id:" + id;
  if (readIntoQueue) {
    this.connector.PostPayload(conf, url, this.GetCancelAndRequeuePayload("true"), settings);
  } else {
    this.connector.PostPayload(conf, url, this.GetCancelAndRequeuePayload("false"), settings);
  }
  
}
 
Example #19
Source File: TeamcityConnector.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String QueueBuild(
        TeamcityConfiguration conf,
        String branch,
        String buildid,
        String comment,
        Boolean isDefault, Settings settings) {
    String url = "/app/rest/buildQueue";
    return this.connector.PostPayload(conf, url, GetPayload(branch, buildid, comment, isDefault), settings);        
}
 
Example #20
Source File: MirrorRepositoryHookTest.java    From stash-hook-mirror with MIT License 5 votes vote down vote up
@Test
public void testValidateForGlobal() {
    SettingsValidationErrors errors = mock(SettingsValidationErrors.class);
    Settings settings = mock(Settings.class);

    hook.validate(settings, errors, Scopes.global());

    verifyZeroInteractions(bucketedExecutor, errors, settings);
}
 
Example #21
Source File: TeamcityConnector.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String TestTeamcityConnection(TeamcityConfiguration conf, Settings settings) {
  String restpoint = "/app/rest/builds";
  
  try
  {
    String data = this.connector.Get(conf, restpoint, settings);
    TeamcityLogger.logMessage(settings, "teamcity returned: "  + data);
    return "Ok";
  } catch (Exception e) {
    TeamcityLogger.logMessage(settings, "Hook Exception: "  + e.getMessage());
    return "Not able to Connect to Teamcity Server : " + e.getMessage();
  }        
}
 
Example #22
Source File: TeamcityConnector.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
public List<TeamcityQueuedElement> GetQueuedAndRunningBuilds(TeamcityConfiguration conf, Settings settings, String branch) throws IOException, JSONException {
    String queueData = this.GetQueueAndRunningData(conf, settings, branch);
    List<TeamcityQueuedElement> queuedElements = new ArrayList<>();
    if(queueData == ""){
      return queuedElements;
    }
    JSONObject jsonObj = new JSONObject(queueData);        
    Integer numberOfQueuedBuilds = jsonObj.getInt("count");        
    if(numberOfQueuedBuilds == 0) {
      return new ArrayList<>();
    }
    
    JSONArray builds = jsonObj.getJSONArray("build");
    for (int i = 0; i < builds.length(); i++) {
        try
        {                           
            JSONObject queued = builds.getJSONObject(i);
            String branchName = "";
            if(queued.has("branchName")){
              branchName = queued.getString("branchName");
            }

            String buildType = queued.getString("buildTypeId");
            String id = queued.getString("id");
            String webUrl = queued.getString("webUrl");
            TeamcityQueuedElement queuedElement = new TeamcityQueuedElement();
            queuedElement.setBranch(branchName);
            queuedElement.setBuildType(buildType);
            queuedElement.setId(id);
            queuedElement.setWebUrl(webUrl);
            
            queuedElements.add(queuedElement);
            
        } catch (JSONException e) {
        }                                                   
    }
    
    return queuedElements;
}
 
Example #23
Source File: MirrorRepositoryHookTest.java    From stash-hook-mirror with MIT License 5 votes vote down vote up
private PostRepositoryHookContext buildContext() {
    Settings settings = defaultSettings();

    PostRepositoryHookContext context = mock(PostRepositoryHookContext.class);
    when(context.getSettings()).thenReturn(settings);

    return context;
}
 
Example #24
Source File: TeamcityConnector.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String GetQueueAndRunningData(TeamcityConfiguration conf, Settings settings, String branch) throws IOException {
  String restpoint = "/app/rest/builds?locator=state:(queued:true,running:true),branch:" + branch;
  if(!this.connector.isReachable(conf, settings)) {
    TeamcityLogger.logMessage(settings, "[HttpConnector][GetQueueData] Server Not reachable: " + conf.getUrl());
    return "";
  }
  
  String returnData = this.connector.Get(conf, restpoint, settings);
  TeamcityLogger.logMessage(settings, "[HttpConnector][GetQueueData] return data: " + returnData);      
  return returnData;
}
 
Example #25
Source File: TeamcityLogger.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void logMessage(Settings settings, String message) {
  if (settings == null) {
    LOG.error("[TeamcityTriggerHook] : Context is null, cant get debug flag");
    return;
  }

  Boolean isDebugEnabled = settings.getBoolean(Field.DEBUG, false);
  if(isDebugEnabled) {
    LOG.info("[TeamcityTriggerHook ->] : " + message);
  }
}
 
Example #26
Source File: HttpConnector.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String PostPayload(TeamcityConfiguration conf, String url, String payload, Settings settings) {
  try {                  
    String urlstr = conf.getUrl() + url;
    URL urldata = new URL(urlstr);
    TeamcityLogger.logMessage(settings, "[HttpConnector][PostPayload] Hook Request: "  + urlstr);
    String authStr = conf.getUserName() + ":" + conf.getPassWord();
    String authEncoded = Base64.encodeBase64String(authStr.getBytes());
    HttpURLConnection connection = (HttpURLConnection) urldata.openConnection();
    connection.setRequestMethod("POST");
    connection.setConnectTimeout(5000);
    connection.setDoOutput(true);
    connection.setRequestProperty("Authorization", "Basic " + authEncoded);
    if (payload != null) {
      connection.setRequestProperty("Content-Type", "application/xml; charset=utf-8");
      connection.setRequestProperty("Content-Length", Integer.toString(payload.length()));
      connection.getOutputStream().write(payload.getBytes("UTF8"));
    }

    InputStream content = (InputStream)connection.getInputStream();
    BufferedReader in   =  new BufferedReader (new InputStreamReader (content));

    StringBuilder dataout = new StringBuilder();
    String line;
    while ((line = in.readLine()) != null) {
      dataout.append(line);
    }

    TeamcityLogger.logMessage(settings, "[HttpConnector][PostPayload] Hook Reply: "  + line);
    return line;
  } catch (Exception e) {
    TeamcityLogger.logMessage(settings, "[HttpConnector][PostPayload] Hook Exception: "  + e.getMessage());
    e.printStackTrace();
    return e.getMessage();
  }         
}
 
Example #27
Source File: HttpConnector.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String Get(TeamcityConfiguration conf, String url, Settings settings) throws MalformedURLException, IOException {
    
  String urlstr = conf.getUrl() + url;

  URL urldata = new URL(urlstr);
  TeamcityLogger.logMessage(settings, "[HttpConnector][Get] Hook Request with timeout 5 seconds for connect: "  + urlstr + "-");

  String authStr = conf.getUserName() + ":" + conf.getPassWord();
  String authEncoded = Base64.encodeBase64String(authStr.getBytes());

  HttpURLConnection connection = (HttpURLConnection) urldata.openConnection();

  connection.setRequestMethod("GET");
  connection.setDoOutput(true);
  connection.setConnectTimeout(5000);
  connection.setRequestProperty("Accept", "application/json");
  connection.setRequestProperty("Authorization", "Basic " + authEncoded);

  InputStream content = (InputStream)connection.getInputStream();
  BufferedReader in = new BufferedReader (new InputStreamReader (content));

  StringBuilder dataout = new StringBuilder();
  String line;
  while ((line = in.readLine()) != null) {
      dataout.append(line);
  }

  TeamcityLogger.logMessage(settings, "[HttpConnector][Get] Hook Reply: "  + line);

  return dataout.toString();       
}
 
Example #28
Source File: HttpConnector.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
public boolean isReachable(TeamcityConfiguration conf, Settings settings) {
    try {       
        InetAddress address = InetAddress.getByName(conf.getUrl().replace("http://", "").replace("https://", ""));
        address.isReachable(500);
        return true;
    } catch (IOException e) {
        TeamcityLogger.logMessage(settings, "[HttpConnector][isReachable] Failed to reach server, skip queue checker thread to avoid deadlocks: " + e.getMessage());
        return false;
    }
}
 
Example #29
Source File: HttpConnector.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void Post(TeamcityConfiguration conf, String url, Map<String, String> parameters, Settings settings) {
    
    try {                  
        
        String urlstr = conf.getUrl() + url;

        URL urldata = new URL(urlstr);
        TeamcityLogger.logMessage(settings, "[HttpConnector][Post] Hook Request: "  + urlstr);
        
        String authStr = conf.getUserName() + ":" + conf.getPassWord();
        String authEncoded = Base64.encodeBase64String(authStr.getBytes());
        
        HttpURLConnection connection = (HttpURLConnection) urldata.openConnection();

        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setConnectTimeout(5000);
        connection.setRequestProperty("Authorization", "Basic " + authEncoded);
        connection.setRequestProperty("Content-Length", "0");
        
        InputStream content = (InputStream)connection.getInputStream();
        BufferedReader in   = 
            new BufferedReader (new InputStreamReader (content));
        
        StringBuilder dataout = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            dataout.append(line);
        }
        
        TeamcityLogger.logMessage(settings, "[HttpConnector][Post] Hook Reply: "  + line);
        
    } catch (Exception e) {
        TeamcityLogger.logMessage(settings, "[HttpConnector][Post] Hook Exception: "  + e.getMessage());
        e.printStackTrace();
    }         
}
 
Example #30
Source File: AreBuildsInQueueOrRunningCheck.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Boolean AreBuildsInQueueForBranch(String branch,
        final TeamcityConfiguration conf,
        final Settings settings) {    
  List<TeamcityQueuedElement> queue;    
  try {
    queue = this.connector.GetQueuedAndRunningBuilds(conf, settings, branch);
    TeamcityLogger.logMessage(settings, "[AreBuildsInQueueOrRunningCheck] Detected: " + queue.size() + " in queue.");
    return !queue.isEmpty();
  } catch (IOException | JSONException ex) {
    TeamcityLogger.logMessage(settings, "[AreBuildsInQueueOrRunningCheck] Exception " + ex.getMessage());
  }
  
  return false;    
}