use of jetbrains.buildServer.serverSide.SProject in project teamcity-git by JetBrains.
the class SpaceExternalChangeViewerExtensionTest method jetbrainsTeamVcsRoot_connectionNotFound.
@Test
void jetbrainsTeamVcsRoot_connectionNotFound() {
// given
final VcsRootInstanceImpl vcsRoot = Mockito.mock(VcsRootInstanceImpl.class);
Mockito.doReturn(Constants.VCS_NAME).when(vcsRoot).getVcsName();
Mockito.doReturn(selfHosted).when(vcsRoot).getProperty(Constants.FETCH_URL);
final SProject project = Mockito.mock(SProject.class);
final SVcsRoot sVcsRoot = Mockito.mock(SVcsRoot.class);
Mockito.doReturn(sVcsRoot).when(vcsRoot).getParent();
Mockito.doReturn(project).when(sVcsRoot).getProject();
// test
SpaceExternalChangeViewerExtension extension = mySpaceExternalChangeViewerExtension();
final Map<String, String> availableProperties = extension.getAvailableProperties(vcsRoot);
assertNull(availableProperties);
}
use of jetbrains.buildServer.serverSide.SProject in project teamcity-git by JetBrains.
the class SpaceExternalChangeViewerExtensionTest method jetbrainsTeamVcsRoot_twoConnections.
@Test
void jetbrainsTeamVcsRoot_twoConnections() {
// given
final VcsRootInstanceImpl vcsRoot = Mockito.mock(VcsRootInstanceImpl.class);
Mockito.doReturn(Constants.VCS_NAME).when(vcsRoot).getVcsName();
Mockito.doReturn(selfHosted).when(vcsRoot).getProperty(Constants.FETCH_URL);
final SProject project = Mockito.mock(SProject.class);
final SVcsRoot sVcsRoot = Mockito.mock(SVcsRoot.class);
Mockito.doReturn(sVcsRoot).when(vcsRoot).getParent();
Mockito.doReturn(project).when(sVcsRoot).getProject();
final OAuthConnectionDescriptor connection1 = Mockito.mock(OAuthConnectionDescriptor.class);
final OAuthConnectionDescriptor connection2 = Mockito.mock(OAuthConnectionDescriptor.class);
Mockito.doReturn(ImmutableList.of(connection1, connection2)).when(myOAuthConnectionsManager).getAvailableConnectionsOfType(project, SpaceOAuthProvider.TYPE);
Mockito.doReturn(ImmutableMap.of(SPACE_SERVER_URL, hostedOnJetBrainsSideServerUrl, SPACE_CLIENT_ID, "ignore", SPACE_CLIENT_SECRET, "ignore")).when(connection1).getParameters();
Mockito.doReturn(ImmutableMap.of(SPACE_SERVER_URL, selfHostedServerUrl, SPACE_CLIENT_ID, "ignore", SPACE_CLIENT_SECRET, "ignore")).when(connection2).getParameters();
// test
SpaceExternalChangeViewerExtension extension = mySpaceExternalChangeViewerExtension();
final Map<String, String> availableProperties = extension.getAvailableProperties(vcsRoot);
assertEquals(availableProperties, ImmutableMap.of(PropertyType.CHANGE_SET_TYPE, "https://jetbrains.team/p/tc/repositories/TeamCity/revision/${changeSetId}", PropertyType.LINK_TEXT, "Open in Space", PropertyType.LINK_ICON_CLASS, "tc-icon_space"));
}
use of jetbrains.buildServer.serverSide.SProject in project teamcity-git by JetBrains.
the class GitSupportBuilder method build.
@NotNull
public GitVcsSupport build() {
if (myPluginConfigBuilder == null && myServerPaths == null && myPluginConfig == null)
throw new IllegalStateException("Plugin config or server paths should be set");
if (myPluginConfig == null)
myPluginConfig = myPluginConfigBuilder != null ? myPluginConfigBuilder.build() : new PluginConfigImpl(myServerPaths);
if (myTransportFactory == null)
myTransportFactory = new TransportFactoryImpl(myPluginConfig, myVcsRootSSHKeyManager);
Mockery context = new Mockery();
if (myFetchCommand == null) {
if (myBeforeFetchHook == null) {
myFetchCommand = new FetchCommandImpl(myPluginConfig, myTransportFactory, new FetcherProperties(myPluginConfig), myVcsRootSSHKeyManager);
} else {
final FetchCommand originalCommand = new FetchCommandImpl(myPluginConfig, myTransportFactory, new FetcherProperties(myPluginConfig), myVcsRootSSHKeyManager);
myFetchCommand = (db, fetchURI, settings) -> {
myBeforeFetchHook.run();
originalCommand.fetch(db, fetchURI, settings);
};
}
}
MirrorManager mirrorManager = new MirrorManagerImpl(myPluginConfig, new HashCalculatorImpl(), new RemoteRepositoryUrlInvestigatorImpl());
myRepositoryManager = new RepositoryManagerImpl(myPluginConfig, mirrorManager);
final ResetCacheRegister resetCacheManager;
if (myResetCacheManager == null) {
context.setImposteriser(ClassImposteriser.INSTANCE);
resetCacheManager = context.mock(ResetCacheRegister.class);
context.checking(new Expectations() {
{
allowing(resetCacheManager).registerHandler(with(any(ResetCacheHandler.class)));
}
});
} else {
resetCacheManager = myResetCacheManager;
}
RevisionsCache revisionsCache = new RevisionsCache(myPluginConfig);
myMapFullPath = new GitMapFullPath(myPluginConfig, revisionsCache);
final GitRepoOperationsImpl gitRepoOperations = new GitRepoOperationsImpl(myPluginConfig, myTransportFactory, myVcsRootSSHKeyManager, myFetchCommand);
myCommitLoader = new CommitLoaderImpl(myRepositoryManager, gitRepoOperations, myMapFullPath, myPluginConfig);
GitResetCacheHandler resetCacheHandler = new GitResetCacheHandler(myRepositoryManager, new GcErrors());
ResetRevisionsCacheHandler resetRevisionsCacheHandler = new ResetRevisionsCacheHandler(revisionsCache);
TokenRefresher tokenRefresher = new TokenRefresher() {
@Nullable
@Override
public OAuthToken getRefreshableToken(@NotNull String vcsRootExtId, @NotNull String tokenFullId) {
return null;
}
@Nullable
@Override
public OAuthToken getRefreshableToken(@NotNull SProject project, @NotNull String tokenFullId) {
return null;
}
};
GitVcsSupport git = new GitVcsSupport(gitRepoOperations, myPluginConfig, resetCacheManager, myTransportFactory, myRepositoryManager, myMapFullPath, myCommitLoader, myVcsRootSSHKeyManager, new MockVcsOperationProgressProvider(), resetCacheHandler, resetRevisionsCacheHandler, tokenRefresher, myTestConnectionSupport);
git.addExtensions(myExtensions);
git.setExtensionHolder(myExtensionHolder);
return git;
}
use of jetbrains.buildServer.serverSide.SProject in project teamcity-s3-artifact-storage-plugin by JetBrains.
the class S3CloudFrontDistributionCreationController method doPost.
@Override
protected void doPost(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Element xmlResponse) {
final BasePropertiesBean bean = new BasePropertiesBean(null);
PluginPropertiesUtil.bindPropertiesFromRequest(request, bean);
Map<String, String> params = bean.getProperties();
String projectId = request.getParameter("projectId");
final ActionErrors errors = new ActionErrors();
SProject project = myProjectManager.findProjectByExternalId(projectId);
if (project == null) {
errors.addError(S3_CLOUDFRONT_CREATE_DISTRIBUTION, String.format("Project %s not found", projectId));
} else {
myAccessChecker.checkCanEditProject(project);
String projectName = project.getName();
IOGuard.allowNetworkCall(() -> {
try {
KeyPair keyPair = generateKeyPair();
String bucketName = S3Util.getBucketName(params);
if (keyPair.getPrivate() != null && keyPair.getPublic() != null && bucketName != null) {
String privateKey = toPemString("PRIVATE KEY", keyPair.getPrivate().getEncoded());
String publicKey = toPemString("PUBLIC KEY", keyPair.getPublic().getEncoded());
DistributionDTO distributionDTO = AWSCommonParams.withAWSClients(params, clients -> {
AmazonCloudFront cloudFrontClient = clients.createCloudFrontClient();
AmazonS3 s3Client = clients.createS3Client();
String comment;
long distrCount = cloudFrontClient.listDistributions(new ListDistributionsRequest()).getDistributionList().getItems().stream().filter(d -> d.getComment().startsWith(String.format(COMMENT, projectName))).count();
if (distrCount > 0) {
comment = String.format(NUMBERED_COMMENT, projectName, distrCount);
} else {
comment = String.format(COMMENT, projectName);
}
String name = "generated_" + UUID.randomUUID().toString().substring(0, 8);
String publicKeyId = null;
String keyGroupId = null;
try {
publicKeyId = uploadPublicKey(publicKey, name, comment, cloudFrontClient);
keyGroupId = createKeyGroup(publicKeyId, name, comment, cloudFrontClient);
Distribution distribution = createDistribution(keyGroupId, comment, bucketName, cloudFrontClient, s3Client);
return new DistributionDTO(distribution.getId(), comment, publicKeyId, name, privateKey);
} catch (SdkClientException e) {
errors.addException(S3_CLOUDFRONT_CREATE_DISTRIBUTION, e);
if (keyGroupId != null) {
try {
cloudFrontClient.deleteKeyGroup(new DeleteKeyGroupRequest().withId(keyGroupId));
} catch (SdkClientException clientException) {
LOG.warnAndDebugDetails("Encountered exception while trying to delete CloudFront key group", clientException);
}
}
if (publicKeyId != null) {
try {
cloudFrontClient.deletePublicKey(new DeletePublicKeyRequest().withId(publicKeyId));
} catch (SdkClientException clientException) {
LOG.warnAndDebugDetails("Encountered exception while trying to delete CloudFront public key", clientException);
}
}
}
return null;
});
if (distributionDTO != null) {
Element element = S3XmlSerializerFactory.getInstance().serializeAsElement(distributionDTO);
xmlResponse.addContent(element);
}
}
} catch (IllegalArgumentException | SdkClientException | IOException | NoSuchAlgorithmException e) {
errors.addException(S3_CLOUDFRONT_CREATE_DISTRIBUTION, e);
}
});
}
errors.serialize(xmlResponse);
}
use of jetbrains.buildServer.serverSide.SProject in project teamcity-git by JetBrains.
the class GitUrlSupport method convertToVcsRootProperties.
@Nullable
public Map<String, String> convertToVcsRootProperties(@NotNull VcsUrl url, @NotNull VcsOperationContext operationContext) throws VcsException {
String scmName = getMavenScmName(url);
if (// some other scm provider
scmName != null && !"git".equals(scmName) && !"ssh".equals(scmName))
return null;
String fetchUrl = getFetchUrl(url);
URIish uri = parseURIish(fetchUrl);
if (fetchUrl.startsWith("https://") && !fetchUrl.endsWith(".git")) {
VcsHostingRepo gitlabRepo = WellKnownHostingsUtil.getGitlabRepo(uri);
if (gitlabRepo != null) {
// for GitLab we need to add .git suffix to the fetch URL, otherwise, for some reason JGit can't work with this repository (although regular git command works)
fetchUrl = fetchUrl + ".git";
uri = parseURIish(fetchUrl);
}
}
Map<String, String> props = new HashMap<>(myGitSupport.getDefaultVcsProperties());
props.put(Constants.FETCH_URL, fetchUrl);
props.putAll(getAuthSettings(url, uri));
VcsHostingRepo ghRepo = WellKnownHostingsUtil.getGitHubRepo(uri);
if (ghRepo != null)
refineGithubSettings(ghRepo, props);
int numSshKeysTried = 0;
final SProject curProject = myProjectManager == null ? null : myProjectManager.findProjectById(operationContext.getCurrentProjectId());
if (AuthenticationMethod.PRIVATE_KEY_DEFAULT.toString().equals(props.get(Constants.AUTH_METHOD)) && fetchUrl.endsWith(".git") && curProject != null) {
// SSH access, before using the default private key which may not be accessible on the agent,
// let's iterate over all SSH keys of the current project, maybe we'll find a working one
ServerSshKeyManager serverSshKeyManager = getSshKeyManager();
if (serverSshKeyManager != null) {
for (TeamCitySshKey key : serverSshKeyManager.getKeys(curProject)) {
// don't know password, so can't use it
if (key.isEncrypted())
continue;
Map<String, String> propsCopy = new HashMap<>(props);
propsCopy.put(Constants.AUTH_METHOD, AuthenticationMethod.TEAMCITY_SSH_KEY.toString());
propsCopy.put(VcsRootSshKeyManager.VCS_ROOT_TEAMCITY_SSH_KEY_NAME, key.getName());
try {
numSshKeysTried++;
return testConnection(propsCopy, curProject);
} catch (VcsException e) {
if (isBranchRelatedError(e))
throw e;
}
}
}
// could not find any valid keys, proceed with default SSH key
try {
return testConnection(props, curProject);
} catch (VcsException e) {
if (isBranchRelatedError(e))
throw e;
String message = "Could not connect to the Git repository by SSH protocol.";
if (numSshKeysTried > 0) {
message += " Tried " + numSshKeysTried + " SSH " + StringUtil.pluralize("key", numSshKeysTried) + " accessible from the current project.";
} else {
message += " Could not find an SSH key in the current project which would work with this Git repository.";
}
throw new VcsException(message + " Error message: " + e.getMessage(), e);
}
}
final boolean defaultBranchKnown = props.get(Constants.BRANCH_NAME) != null;
if (defaultBranchKnown) {
// git protocol, or git scm provider
if ("git".equals(scmName) || "git".equals(uri.getScheme()) || fetchUrl.endsWith(".git"))
return props;
}
// not SSH or URL does not end with .git, still try to connect just for the case
try {
return testConnection(props, curProject);
} catch (VcsException e) {
if (isBranchRelatedError(e) || GitServerUtil.isAuthError(e) || fetchUrl.toLowerCase().contains("git"))
throw e;
// probably not git
Loggers.VCS.infoAndDebugDetails("Failed to recognize " + url.getUrl() + " as a git repository", e);
return null;
}
}
Aggregations