Search in sources :

Example 16 with UserServiceInternal

use of org.craftercms.studio.api.v2.service.security.internal.UserServiceInternal in project studio by craftercms.

the class GitContentRepository method getContent.

@Override
public InputStream getContent(String site, String path) throws ContentNotFoundException, CryptoException {
    InputStream toReturn = null;
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
    Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX);
    if (repo == null) {
        throw new ContentNotFoundException("Repository not found for site " + site);
    }
    try {
        RevTree tree = helper.getTreeForLastCommit(repo);
        try (TreeWalk tw = TreeWalk.forPath(repo, helper.getGitPath(path), tree)) {
            // pick the first item in the list
            if (tw != null && tw.getObjectId(0) != null) {
                ObjectId id = tw.getObjectId(0);
                ObjectLoader objectLoader = repo.open(id);
                toReturn = objectLoader.openStream();
                tw.close();
            }
        } catch (IOException e) {
            logger.error("Error while getting content for file at site: " + site + " path: " + path, e);
        }
    } catch (IOException e) {
        logger.error("Failed to create RevTree for site: " + site + " path: " + path, e);
    }
    return toReturn;
}
Also used : RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) ContentRepository(org.craftercms.studio.api.v1.repository.ContentRepository) ContentNotFoundException(org.craftercms.studio.api.v1.exception.ContentNotFoundException) ObjectId(org.eclipse.jgit.lib.ObjectId) InputStream(java.io.InputStream) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) IOException(java.io.IOException) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevTree(org.eclipse.jgit.revwalk.RevTree)

Example 17 with UserServiceInternal

use of org.craftercms.studio.api.v2.service.security.internal.UserServiceInternal in project studio by craftercms.

the class GitContentRepository method copyContent.

@Override
public String copyContent(String site, String fromPath, String toPath) {
    String commitId = null;
    String gitLockKey = SITE_SANDBOX_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, site);
    generalLockService.lock(gitLockKey);
    try {
        GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
        synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX)) {
            Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX);
            String gitFromPath = helper.getGitPath(fromPath);
            String gitToPath = helper.getGitPath(toPath);
            try (Git git = new Git(repo)) {
                Path sourcePath = Paths.get(repo.getDirectory().getParent(), fromPath);
                File sourceFile = sourcePath.toFile();
                Path targetPath = Paths.get(repo.getDirectory().getParent(), toPath);
                File targetFile = targetPath.toFile();
                // Check if we're copying a single file or whole subtree
                FileUtils.copyDirectory(sourceFile, targetFile);
                // The operation is done on disk, now it's time to commit
                git.add().addFilepattern(gitToPath).call();
                CommitCommand commitCommand = git.commit().setOnly(gitFromPath).setOnly(gitToPath).setAuthor(helper.getCurrentUserIdent()).setCommitter(helper.getCurrentUserIdent()).setMessage(helper.getCommitMessage(REPO_COPY_CONTENT_COMMIT_MESSAGE).replaceAll(PATTERN_FROM_PATH, fromPath).replaceAll(PATTERN_TO_PATH, toPath));
                RevCommit commit = retryingRepositoryOperationFacade.call(commitCommand);
                commitId = commit.getName();
            }
        }
    } catch (IOException | GitAPIException | ServiceLayerException | UserNotFoundException | CryptoException e) {
        logger.error("Error while copying content for site: " + site + " fromPath: " + fromPath + " toPath: " + toPath + " newName: ");
    } finally {
        generalLockService.unlock(gitLockKey);
    }
    return commitId;
}
Also used : Path(java.nio.file.Path) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) IOException(java.io.IOException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) ContentRepository(org.craftercms.studio.api.v1.repository.ContentRepository) Git(org.eclipse.jgit.api.Git) CommitCommand(org.eclipse.jgit.api.CommitCommand) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) CryptoException(org.craftercms.commons.crypto.CryptoException) File(java.io.File) LockFile(org.eclipse.jgit.internal.storage.file.LockFile) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 18 with UserServiceInternal

use of org.craftercms.studio.api.v2.service.security.internal.UserServiceInternal in project studio by craftercms.

the class GitContentRepository method deleteParentFolder.

private String deleteParentFolder(Git git, Path parentFolder, boolean wasPage) throws GitAPIException, CryptoException, IOException {
    String parent = parentFolder.toString();
    String toRet = parent;
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
    String folderToDelete = helper.getGitPath(parent);
    Path toDelete = Paths.get(git.getRepository().getDirectory().getParent(), parent);
    if (toDelete.toFile().exists()) {
        List<String> dirs = Files.walk(toDelete).filter(x -> !x.equals(toDelete)).filter(Files::isDirectory).map(y -> y.getFileName().toString()).collect(Collectors.toList());
        List<String> files = Files.walk(toDelete, 1).filter(x -> !x.equals(toDelete)).filter(Files::isRegularFile).map(y -> y.getFileName().toString()).collect(Collectors.toList());
        if (wasPage || (CollectionUtils.isEmpty(dirs) && (CollectionUtils.isEmpty(files) || files.size() < 2 && files.get(0).equals(EMPTY_FILE)))) {
            if (CollectionUtils.isNotEmpty(dirs)) {
                for (String child : dirs) {
                    Path childToDelete = Paths.get(folderToDelete, child);
                    deleteParentFolder(git, childToDelete, false);
                    RmCommand rmCommand = git.rm().addFilepattern(folderToDelete + FILE_SEPARATOR + child + FILE_SEPARATOR + "*").setCached(false);
                    retryingRepositoryOperationFacade.call(rmCommand);
                }
            }
            if (CollectionUtils.isNotEmpty(files)) {
                for (String child : files) {
                    git.rm().addFilepattern(folderToDelete + FILE_SEPARATOR + child).setCached(false).call();
                }
            }
        }
    }
    return toRet;
}
Also used : Path(java.nio.file.Path) Arrays(java.util.Arrays) UserServiceInternal(org.craftercms.studio.api.v2.service.security.internal.UserServiceInternal) Status(org.eclipse.jgit.api.Status) TextEncryptor(org.craftercms.commons.crypto.TextEncryptor) ZonedDateTime(java.time.ZonedDateTime) MAX_VALUE(java.lang.Integer.MAX_VALUE) SITES_REPOS_PATH(org.craftercms.studio.api.v2.utils.StudioConfiguration.SITES_REPOS_PATH) RemoteConfig(org.eclipse.jgit.transport.RemoteConfig) OBJ_TREE(org.eclipse.jgit.lib.Constants.OBJ_TREE) StringUtils(org.apache.commons.lang3.StringUtils) SshTransport(org.eclipse.jgit.transport.SshTransport) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Config(org.eclipse.jgit.lib.Config) PathFilter(org.eclipse.jgit.treewalk.filter.PathFilter) REPO_DELETE_CONTENT_COMMIT_MESSAGE(org.craftercms.studio.api.v2.utils.StudioConfiguration.REPO_DELETE_CONTENT_COMMIT_MESSAGE) Map(java.util.Map) PullResult(org.eclipse.jgit.api.PullResult) URIish(org.eclipse.jgit.transport.URIish) ClusterDAO(org.craftercms.studio.api.v2.dal.ClusterDAO) RemoteAddCommand(org.eclipse.jgit.api.RemoteAddCommand) REJECTED_NODELETE(org.eclipse.jgit.transport.RemoteRefUpdate.Status.REJECTED_NODELETE) Path(java.nio.file.Path) EnumSet(java.util.EnumSet) TagCommand(org.eclipse.jgit.api.TagCommand) INDEX_FILE(org.craftercms.studio.api.v1.constant.StudioConstants.INDEX_FILE) GIT_COMMIT_ALL_ITEMS(org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryConstants.GIT_COMMIT_ALL_ITEMS) NONE(org.craftercms.studio.api.v2.dal.RemoteRepository.AuthenticationType.NONE) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) R_REMOTES(org.eclipse.jgit.lib.Constants.R_REMOTES) RefSpec(org.eclipse.jgit.transport.RefSpec) CommitCommand(org.eclipse.jgit.api.CommitCommand) Set(java.util.Set) OpenSshConfig(org.eclipse.jgit.transport.OpenSshConfig) HEAD(org.eclipse.jgit.lib.Constants.HEAD) Constants(org.eclipse.jgit.lib.Constants) RevTree(org.eclipse.jgit.revwalk.RevTree) PersonIdent(org.eclipse.jgit.lib.PersonIdent) FILE_SEPARATOR(org.craftercms.studio.api.v1.constant.StudioConstants.FILE_SEPARATOR) PATTERN_SITE(org.craftercms.studio.api.v1.constant.StudioConstants.PATTERN_SITE) Session(com.jcraft.jsch.Session) REPO_CREATE_FOLDER_COMMIT_MESSAGE(org.craftercms.studio.api.v2.utils.StudioConfiguration.REPO_CREATE_FOLDER_COMMIT_MESSAGE) PushResult(org.eclipse.jgit.transport.PushResult) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) RemoteRepositoryDAO(org.craftercms.studio.api.v2.dal.RemoteRepositoryDAO) FS(org.eclipse.jgit.util.FS) JSchException(com.jcraft.jsch.JSchException) SiteFeedMapper(org.craftercms.studio.api.v1.dal.SiteFeedMapper) REPO_COMMIT_MESSAGE_USERNAME_VAR(org.craftercms.studio.api.v1.constant.StudioConstants.REPO_COMMIT_MESSAGE_USERNAME_VAR) RetryingOperationFacade(org.craftercms.studio.api.v2.dal.RetryingOperationFacade) GLOBAL_REPOSITORY_GIT_LOCK(org.craftercms.studio.api.v1.constant.StudioConstants.GLOBAL_REPOSITORY_GIT_LOCK) RevCommit(org.eclipse.jgit.revwalk.RevCommit) REPO_SANDBOX_WRITE_COMMIT_MESSAGE(org.craftercms.studio.api.v2.utils.StudioConfiguration.REPO_SANDBOX_WRITE_COMMIT_MESSAGE) ClusterMember(org.craftercms.studio.api.v2.dal.ClusterMember) REPO_COMMIT_MESSAGE_PATH_VAR(org.craftercms.studio.api.v1.constant.StudioConstants.REPO_COMMIT_MESSAGE_PATH_VAR) Transport(org.eclipse.jgit.transport.Transport) SimpleDateFormat(java.text.SimpleDateFormat) CollectionUtils(org.apache.commons.collections4.CollectionUtils) ArrayList(java.util.ArrayList) EMPTY_FILE(org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryConstants.EMPTY_FILE) BLUE_PRINTS_PATH(org.craftercms.studio.api.v2.utils.StudioConfiguration.BLUE_PRINTS_PATH) VersionTO(org.craftercms.studio.api.v1.to.VersionTO) Calendar(java.util.Calendar) ImmutableNode(org.apache.commons.configuration2.tree.ImmutableNode) GitLogDAO(org.craftercms.studio.api.v2.dal.GitLogDAO) StatusCommand(org.eclipse.jgit.api.StatusCommand) IGNORE_FILES(org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryConstants.IGNORE_FILES) PushCommand(org.eclipse.jgit.api.PushCommand) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) REJECTED_NONFASTFORWARD(org.eclipse.jgit.transport.RemoteRefUpdate.Status.REJECTED_NONFASTFORWARD) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) Properties(java.util.Properties) Files(java.nio.file.Files) FOLLOW_LINKS(java.nio.file.FileVisitOption.FOLLOW_LINKS) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) RemoteRepositoryInfoTO(org.craftercms.studio.api.v1.to.RemoteRepositoryInfoTO) UnknownHostException(java.net.UnknownHostException) CLUSTERING_NODE_REGISTRATION(org.craftercms.studio.api.v2.utils.StudioConfiguration.CLUSTERING_NODE_REGISTRATION) File(java.io.File) RefNotFoundException(org.eclipse.jgit.api.errors.RefNotFoundException) RetryingOperation(org.craftercms.studio.api.v2.annotation.RetryingOperation) TreeMap(java.util.TreeMap) SecurityService(org.craftercms.studio.api.v1.service.security.SecurityService) REMOTE(org.eclipse.jgit.api.ListBranchCommand.ListMode.REMOTE) Paths(java.nio.file.Paths) RemoteRepositoryNotFoundException(org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotFoundException) RepositoryItem(org.craftercms.studio.api.v1.repository.RepositoryItem) TOKEN(org.craftercms.studio.api.v2.dal.RemoteRepository.AuthenticationType.TOKEN) REPO_BASE_PATH(org.craftercms.studio.api.v2.utils.StudioConfiguration.REPO_BASE_PATH) ServletContext(javax.servlet.ServletContext) Repository(org.eclipse.jgit.lib.Repository) PUBLISHED(org.craftercms.studio.api.v1.constant.GitRepositories.PUBLISHED) RetryingRepositoryOperationFacade(org.craftercms.studio.api.v2.repository.RetryingRepositoryOperationFacade) PullCommand(org.eclipse.jgit.api.PullCommand) ServletContextAware(org.springframework.web.context.ServletContextAware) RemoteRemoveCommand(org.eclipse.jgit.api.RemoteRemoveCommand) URISyntaxException(java.net.URISyntaxException) BOOTSTRAP_REPO(org.craftercms.studio.api.v2.utils.StudioConfiguration.BOOTSTRAP_REPO) GarbageCollectCommand(org.eclipse.jgit.api.GarbageCollectCommand) AddCommand(org.eclipse.jgit.api.AddCommand) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) InvalidRemoteUrlException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteUrlException) SITE_PUBLISHED_REPOSITORY_GIT_LOCK(org.craftercms.studio.api.v1.constant.StudioConstants.SITE_PUBLISHED_REPOSITORY_GIT_LOCK) GLOBAL(org.craftercms.studio.api.v1.constant.GitRepositories.GLOBAL) REJECTED_REMOTE_CHANGED(org.eclipse.jgit.transport.RemoteRefUpdate.Status.REJECTED_REMOTE_CHANGED) TRACK(org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode.TRACK) DateFormat(java.text.DateFormat) REPO_MOVE_CONTENT_COMMIT_MESSAGE(org.craftercms.studio.api.v2.utils.StudioConfiguration.REPO_MOVE_CONTENT_COMMIT_MESSAGE) HierarchicalConfiguration(org.apache.commons.configuration2.HierarchicalConfiguration) REJECTED_OTHER_REASON(org.eclipse.jgit.transport.RemoteRefUpdate.Status.REJECTED_OTHER_REASON) DeleteBranchCommand(org.eclipse.jgit.api.DeleteBranchCommand) Collection(java.util.Collection) REPO_COPY_CONTENT_COMMIT_MESSAGE(org.craftercms.studio.api.v2.utils.StudioConfiguration.REPO_COPY_CONTENT_COMMIT_MESSAGE) UUID(java.util.UUID) REPO_SANDBOX_BRANCH(org.craftercms.studio.api.v2.utils.StudioConfiguration.REPO_SANDBOX_BRANCH) Instant(java.time.Instant) SITE_SANDBOX_REPOSITORY_GIT_LOCK(org.craftercms.studio.api.v1.constant.StudioConstants.SITE_SANDBOX_REPOSITORY_GIT_LOCK) Collectors(java.util.stream.Collectors) REVERSE(org.eclipse.jgit.revwalk.RevSort.REVERSE) List(java.util.List) ServicesConfig(org.craftercms.studio.api.v1.service.configuration.ServicesConfig) StudioConfiguration(org.craftercms.studio.api.v2.utils.StudioConfiguration) BOOTSTRAP_REPO_PATH(org.craftercms.studio.api.v1.constant.StudioConstants.BOOTSTRAP_REPO_PATH) Ref(org.eclipse.jgit.lib.Ref) BASIC(org.craftercms.studio.api.v2.dal.RemoteRepository.AuthenticationType.BASIC) UTC(java.time.ZoneOffset.UTC) ListBranchCommand(org.eclipse.jgit.api.ListBranchCommand) RmCommand(org.eclipse.jgit.api.RmCommand) ContentNotFoundException(org.craftercms.studio.api.v1.exception.ContentNotFoundException) TransportConfigCallback(org.eclipse.jgit.api.TransportConfigCallback) RemoteAlreadyExistsException(org.craftercms.studio.api.v1.exception.repository.RemoteAlreadyExistsException) THEIRS(org.eclipse.jgit.merge.MergeStrategy.THEIRS) JSch(com.jcraft.jsch.JSch) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) PATTERN_FROM_PATH(org.craftercms.studio.api.v1.constant.StudioConstants.PATTERN_FROM_PATH) GitLog(org.craftercms.studio.api.v2.dal.GitLog) Logger(org.craftercms.studio.api.v1.log.Logger) HashMap(java.util.HashMap) ArrayUtils(org.apache.commons.lang3.ArrayUtils) REPO_INITIAL_COMMIT_COMMIT_MESSAGE(org.craftercms.studio.api.v2.utils.StudioConfiguration.REPO_INITIAL_COMMIT_COMMIT_MESSAGE) CLUSTER_MEMBER_LOCAL_ADDRESS(org.craftercms.studio.api.v1.constant.StudioConstants.CLUSTER_MEMBER_LOCAL_ADDRESS) PATTERN_PATH(org.craftercms.studio.api.v1.constant.StudioConstants.PATTERN_PATH) SshSessionFactory(org.eclipse.jgit.transport.SshSessionFactory) LoggerFactory(org.craftercms.studio.api.v1.log.LoggerFactory) EMPTY(org.apache.commons.lang3.StringUtils.EMPTY) BOOTSTRAP_REPO_GLOBAL_PATH(org.craftercms.studio.api.v1.constant.StudioConstants.BOOTSTRAP_REPO_GLOBAL_PATH) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) Iterator(java.util.Iterator) CreateBranchCommand(org.eclipse.jgit.api.CreateBranchCommand) PRIVATE_KEY(org.craftercms.studio.api.v2.dal.RemoteRepository.AuthenticationType.PRIVATE_KEY) StudioClusterUtils(org.craftercms.studio.impl.v2.service.cluster.StudioClusterUtils) DeploymentException(org.craftercms.studio.api.v1.service.deployment.DeploymentException) ContentRepository(org.craftercms.studio.api.v1.repository.ContentRepository) CryptoException(org.craftercms.commons.crypto.CryptoException) CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) ObjectId(org.eclipse.jgit.lib.ObjectId) TransportException(org.eclipse.jgit.api.errors.TransportException) DEFAULT_REMOTE_NAME(org.eclipse.jgit.lib.Constants.DEFAULT_REMOTE_NAME) SANDBOX(org.craftercms.studio.api.v1.constant.GitRepositories.SANDBOX) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) PATTERN_TO_PATH(org.craftercms.studio.api.v1.constant.StudioConstants.PATTERN_TO_PATH) FileVisitOption(java.nio.file.FileVisitOption) RemoteRepositoryNotBareException(org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotBareException) InvalidRemoteException(org.eclipse.jgit.api.errors.InvalidRemoteException) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) DateTimeFormatter(java.time.format.DateTimeFormatter) GeneralLockService(org.craftercms.studio.api.v1.service.GeneralLockService) LsRemoteCommand(org.eclipse.jgit.api.LsRemoteCommand) InvalidRemoteRepositoryCredentialsException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryCredentialsException) Git(org.eclipse.jgit.api.Git) LockFile(org.eclipse.jgit.internal.storage.file.LockFile) InvalidRemoteRepositoryException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryException) JschConfigSessionFactory(org.eclipse.jgit.transport.JschConfigSessionFactory) InputStream(java.io.InputStream) GitRepositories(org.craftercms.studio.api.v1.constant.GitRepositories) RmCommand(org.eclipse.jgit.api.RmCommand) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) Files(java.nio.file.Files)

Example 19 with UserServiceInternal

use of org.craftercms.studio.api.v2.service.security.internal.UserServiceInternal in project studio by craftercms.

the class GitContentRepository method getContentSize.

@Override
public long getContentSize(final String site, final String path) {
    try {
        GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
        Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX);
        RevTree tree = helper.getTreeForLastCommit(repo);
        try (TreeWalk tw = TreeWalk.forPath(repo, helper.getGitPath(path), tree)) {
            if (tw != null && tw.getObjectId(0) != null) {
                ObjectId id = tw.getObjectId(0);
                ObjectLoader objectLoader = repo.open(id);
                return objectLoader.getSize();
            }
        }
    } catch (IOException | CryptoException e) {
        logger.error("Error while getting content for file at site: " + site + " path: " + path, e);
    }
    return -1L;
}
Also used : RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) ContentRepository(org.craftercms.studio.api.v1.repository.ContentRepository) ObjectId(org.eclipse.jgit.lib.ObjectId) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) IOException(java.io.IOException) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) CryptoException(org.craftercms.commons.crypto.CryptoException) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevTree(org.eclipse.jgit.revwalk.RevTree)

Example 20 with UserServiceInternal

use of org.craftercms.studio.api.v2.service.security.internal.UserServiceInternal in project studio by craftercms.

the class GitContentRepository method pullFromRemote.

@Override
public boolean pullFromRemote(String siteId, String remoteName, String remoteBranch) throws ServiceLayerException, InvalidRemoteUrlException, CryptoException {
    logger.debug("Get remote data from database for remote " + remoteName + " and site " + siteId);
    Map<String, String> params = new HashMap<String, String>();
    params.put("siteId", siteId);
    params.put("remoteName", remoteName);
    RemoteRepository remoteRepository = remoteRepositoryDAO.getRemoteRepository(params);
    logger.debug("Prepare pull command");
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
    Repository repo = helper.getRepository(siteId, SANDBOX);
    String gitLockKey = SITE_SANDBOX_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, siteId);
    generalLockService.lock(gitLockKey);
    try (Git git = new Git(repo)) {
        PullResult pullResult = null;
        PullCommand pullCommand = git.pull();
        logger.debug("Set remote " + remoteName);
        pullCommand.setRemote(remoteRepository.getRemoteName());
        logger.debug("Set branch to be " + remoteBranch);
        pullCommand.setRemoteBranchName(remoteBranch);
        switch(remoteRepository.getAuthenticationType()) {
            case NONE:
                logger.debug("No authentication");
                pullResult = pullCommand.call();
                break;
            case BASIC:
                logger.debug("Basic authentication");
                String hashedPassword = remoteRepository.getRemotePassword();
                String password = encryptor.decrypt(hashedPassword);
                pullCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(remoteRepository.getRemoteUsername(), password));
                pullResult = pullCommand.call();
                break;
            case TOKEN:
                logger.debug("Token based authentication");
                String hashedToken = remoteRepository.getRemoteToken();
                String token = encryptor.decrypt(hashedToken);
                pullCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(token, EMPTY));
                pullResult = pullCommand.call();
                break;
            case PRIVATE_KEY:
                logger.debug("Private key authentication");
                final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
                String hashedPrivateKey = remoteRepository.getRemotePrivateKey();
                String privateKey = encryptor.decrypt(hashedPrivateKey);
                tempKey.toFile().deleteOnExit();
                pullCommand.setTransportConfigCallback(new TransportConfigCallback() {

                    @Override
                    public void configure(Transport transport) {
                        SshTransport sshTransport = (SshTransport) transport;
                        sshTransport.setSshSessionFactory(getSshSessionFactory(privateKey, tempKey));
                    }
                });
                pullResult = retryingRepositoryOperationFacade.call(pullCommand);
                Files.delete(tempKey);
                break;
            default:
                throw new ServiceLayerException("Unsupported authentication type " + remoteRepository.getAuthenticationType());
        }
        return pullResult != null ? pullResult.isSuccessful() : false;
    } catch (InvalidRemoteException e) {
        logger.error("Remote is invalid " + remoteName, e);
        throw new InvalidRemoteUrlException();
    } catch (GitAPIException e) {
        logger.error("Error while pulling from remote " + remoteName + " branch " + remoteBranch + " for site " + siteId, e);
        throw new ServiceLayerException("Error while pulling from remote " + remoteName + " branch " + remoteBranch + " for site " + siteId, e);
    } catch (CryptoException | IOException e) {
        throw new ServiceLayerException(e);
    } finally {
        generalLockService.unlock(gitLockKey);
    }
}
Also used : Path(java.nio.file.Path) PullCommand(org.eclipse.jgit.api.PullCommand) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) HashMap(java.util.HashMap) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) IOException(java.io.IOException) InvalidRemoteUrlException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteUrlException) PullResult(org.eclipse.jgit.api.PullResult) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) ContentRepository(org.craftercms.studio.api.v1.repository.ContentRepository) Git(org.eclipse.jgit.api.Git) TransportConfigCallback(org.eclipse.jgit.api.TransportConfigCallback) InvalidRemoteException(org.eclipse.jgit.api.errors.InvalidRemoteException) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) SshTransport(org.eclipse.jgit.transport.SshTransport) Transport(org.eclipse.jgit.transport.Transport) CryptoException(org.craftercms.commons.crypto.CryptoException) SshTransport(org.eclipse.jgit.transport.SshTransport)

Aggregations

GitRepositoryHelper (org.craftercms.studio.api.v2.utils.GitRepositoryHelper)65 Repository (org.eclipse.jgit.lib.Repository)59 RemoteRepository (org.craftercms.studio.api.v2.dal.RemoteRepository)58 CryptoException (org.craftercms.commons.crypto.CryptoException)53 IOException (java.io.IOException)48 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)43 ContentRepository (org.craftercms.studio.api.v1.repository.ContentRepository)42 Git (org.eclipse.jgit.api.Git)41 ServiceLayerException (org.craftercms.studio.api.v1.exception.ServiceLayerException)33 ArrayList (java.util.ArrayList)21 Path (java.nio.file.Path)20 UserNotFoundException (org.craftercms.studio.api.v1.exception.security.UserNotFoundException)20 ObjectId (org.eclipse.jgit.lib.ObjectId)19 RevCommit (org.eclipse.jgit.revwalk.RevCommit)17 RevTree (org.eclipse.jgit.revwalk.RevTree)17 ContentRepository (org.craftercms.studio.api.v2.repository.ContentRepository)15 TreeWalk (org.eclipse.jgit.treewalk.TreeWalk)13 File (java.io.File)12 HashMap (java.util.HashMap)11 InvalidRemoteUrlException (org.craftercms.studio.api.v1.exception.repository.InvalidRemoteUrlException)11