Search in sources :

Example 6 with GeneralLockService

use of org.craftercms.studio.api.v1.service.GeneralLockService in project studio by craftercms.

the class GitContentRepository method publish.

@RetryingOperation
@Override
public void publish(String site, String sandboxBranch, List<DeploymentItemTO> deploymentItems, String environment, String author, String comment) throws DeploymentException {
    if (CollectionUtils.isEmpty(deploymentItems)) {
        return;
    }
    String commitId = EMPTY;
    String gitLockKey = SITE_PUBLISHED_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, site);
    generalLockService.lock(gitLockKey);
    try {
        GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
        Repository repo = helper.getRepository(site, PUBLISHED);
        boolean repoCreated = false;
        if (Objects.isNull(repo)) {
            helper.createPublishedRepository(site, sandboxBranch);
            repo = helper.getRepository(site, PUBLISHED);
            repoCreated = Objects.nonNull(repo);
        }
        String path = EMPTY;
        String sandboxBranchName = sandboxBranch;
        if (StringUtils.isEmpty(sandboxBranchName)) {
            sandboxBranchName = studioConfiguration.getProperty(REPO_SANDBOX_BRANCH);
        }
        synchronized (repo) {
            try (Git git = new Git(repo)) {
                String inProgressBranchName = environment + IN_PROGRESS_BRANCH_NAME_SUFFIX;
                // fetch "origin/master"
                logger.debug("Fetch from sandbox for site " + site);
                FetchCommand fetchCommand = git.fetch();
                retryingRepositoryOperationFacade.call(fetchCommand);
                // checkout master and pull from sandbox
                logger.debug("Checkout published/master branch for site " + site);
                try {
                    // First delete it in case it already exists (ignored if does not exist)
                    String currentBranch = repo.getBranch();
                    if (currentBranch.endsWith(IN_PROGRESS_BRANCH_NAME_SUFFIX)) {
                        ResetCommand resetCommand = git.reset().setMode(HARD);
                        retryingRepositoryOperationFacade.call(resetCommand);
                    }
                    Ref ref = repo.exactRef(R_HEADS + sandboxBranchName);
                    boolean createBranch = (ref == null);
                    CheckoutCommand checkoutCommand = git.checkout().setName(sandboxBranchName).setCreateBranch(createBranch);
                    retryingRepositoryOperationFacade.call(checkoutCommand);
                    logger.debug("Delete in-progress branch, in case it was not cleaned up for site " + site);
                    DeleteBranchCommand deleteBranchCommand = git.branchDelete().setBranchNames(inProgressBranchName).setForce(true);
                    retryingRepositoryOperationFacade.call(deleteBranchCommand);
                    PullCommand pullCommand = git.pull().setRemote(DEFAULT_REMOTE_NAME).setRemoteBranchName(sandboxBranchName).setStrategy(THEIRS);
                    retryingRepositoryOperationFacade.call(pullCommand);
                } catch (RefNotFoundException e) {
                    logger.error("Failed to checkout published master and to pull content from sandbox for site " + site, e);
                    throw new DeploymentException("Failed to checkout published master and to pull content from " + "sandbox for site " + site);
                }
                // checkout environment branch
                logger.debug("Checkout environment branch " + environment + " for site " + site);
                try {
                    CheckoutCommand checkoutCommand = git.checkout().setName(environment);
                    retryingRepositoryOperationFacade.call(checkoutCommand);
                } catch (RefNotFoundException e) {
                    logger.info("Not able to find branch " + environment + " for site " + site + ". Creating new branch");
                    // create new environment branch
                    // it will start as empty orphan branch
                    CheckoutCommand checkoutCommand = git.checkout().setOrphan(true).setForceRefUpdate(true).setStartPoint(sandboxBranchName).setUpstreamMode(TRACK).setName(environment);
                    retryingRepositoryOperationFacade.call(checkoutCommand);
                    // remove any content to create empty branch
                    RmCommand rmcmd = git.rm();
                    File[] toDelete = repo.getWorkTree().listFiles();
                    for (File toDel : toDelete) {
                        if (!repo.getDirectory().equals(toDel) && !StringUtils.equals(toDel.getName(), DOT_GIT_IGNORE)) {
                            rmcmd.addFilepattern(toDel.getName());
                        }
                    }
                    retryingRepositoryOperationFacade.call(rmcmd);
                    CommitCommand commitCommand = git.commit().setMessage(helper.getCommitMessage(REPO_INITIAL_COMMIT_COMMIT_MESSAGE)).setAllowEmpty(true);
                    retryingRepositoryOperationFacade.call(commitCommand);
                }
                // Create in progress branch
                try {
                    // Create in progress branch
                    logger.debug("Create in-progress branch for site " + site);
                    CheckoutCommand checkoutCommand = git.checkout().setCreateBranch(true).setForceRefUpdate(true).setStartPoint(environment).setUpstreamMode(TRACK).setName(inProgressBranchName);
                    retryingRepositoryOperationFacade.call(checkoutCommand);
                } catch (GitAPIException e) {
                    // TODO: DB: Error ?
                    logger.error("Failed to create in-progress published branch for site " + site);
                }
                Set<String> deployedCommits = new HashSet<String>();
                Set<String> deployedPackages = new HashSet<String>();
                logger.debug("Checkout deployed files started.");
                AddCommand addCommand = git.add();
                for (DeploymentItemTO deploymentItem : deploymentItems) {
                    commitId = deploymentItem.getCommitId();
                    path = helper.getGitPath(deploymentItem.getPath());
                    if (Objects.isNull(commitId) || !commitIdExists(site, PUBLISHED, commitId)) {
                        if (contentExists(site, path)) {
                            if (Objects.isNull(commitId)) {
                                logger.warn("Commit ID is NULL for content " + path + ". Was the git repo reset at some point?");
                            } else {
                                logger.warn("Commit ID " + commitId + " does not exist for content " + path + ". Was the git repo reset at some point?");
                            }
                            logger.info("Publishing content from HEAD for " + path);
                            commitId = getRepoLastCommitId(site);
                        } else {
                            logger.warn("Skipping file " + path + " because commit id is null");
                            continue;
                        }
                    }
                    logger.debug("Checking out file " + path + " from commit id " + commitId + " for site " + site);
                    CheckoutCommand checkout = git.checkout();
                    checkout.setStartPoint(commitId).addPath(path);
                    retryingRepositoryOperationFacade.call(checkout);
                    if (deploymentItem.isMove()) {
                        if (!StringUtils.equals(deploymentItem.getPath(), deploymentItem.getOldPath())) {
                            String oldPath = helper.getGitPath(deploymentItem.getOldPath());
                            RmCommand rmCommand = git.rm().addFilepattern(oldPath).setCached(false);
                            retryingRepositoryOperationFacade.call(rmCommand);
                            cleanUpMoveFolders(git, oldPath);
                        }
                    }
                    if (deploymentItem.isDelete()) {
                        String deletePath = helper.getGitPath(deploymentItem.getPath());
                        boolean isPage = deletePath.endsWith(FILE_SEPARATOR + INDEX_FILE);
                        RmCommand rmCommand = git.rm().addFilepattern(deletePath).setCached(false);
                        retryingRepositoryOperationFacade.call(rmCommand);
                        Path parentToDelete = Paths.get(path).getParent();
                        deleteParentFolder(git, parentToDelete, isPage);
                    }
                    deployedCommits.add(commitId);
                    String packageId = deploymentItem.getPackageId();
                    if (StringUtils.isNotEmpty(packageId)) {
                        deployedPackages.add(deploymentItem.getPackageId());
                    }
                    addCommand.addFilepattern(path);
                    objectMetadataManager.updateLastPublishedDate(site, deploymentItem.getPath(), ZonedDateTime.now(UTC));
                }
                logger.debug("Checkout deployed files completed.");
                // commit all deployed files
                String commitMessage = studioConfiguration.getProperty(REPO_PUBLISHED_COMMIT_MESSAGE);
                logger.debug("Get Author Ident started.");
                User user = userServiceInternal.getUserByIdOrUsername(-1, author);
                PersonIdent authorIdent = helper.getAuthorIdent(user);
                logger.debug("Get Author Ident completed.");
                logger.debug("Git add all published items started.");
                retryingRepositoryOperationFacade.call(addCommand);
                logger.debug("Git add all published items completed.");
                commitMessage = commitMessage.replace("{username}", author);
                commitMessage = commitMessage.replace("{datetime}", ZonedDateTime.now(UTC).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HHmmssSSSX")));
                commitMessage = commitMessage.replace("{source}", "UI");
                commitMessage = commitMessage.replace("{message}", comment);
                StringBuilder sb = new StringBuilder();
                for (String c : deployedCommits) {
                    sb.append(c).append(" ");
                }
                StringBuilder sbPackage = new StringBuilder();
                for (String p : deployedPackages) {
                    sbPackage.append(p).append(" ");
                }
                commitMessage = commitMessage.replace("{commit_id}", sb.toString().trim());
                commitMessage = commitMessage.replace("{package_id}", sbPackage.toString().trim());
                logger.debug("Git commit all published items started.");
                String prologue = studioConfiguration.getProperty(REPO_COMMIT_MESSAGE_PROLOGUE);
                String postscript = studioConfiguration.getProperty(REPO_COMMIT_MESSAGE_POSTSCRIPT);
                StringBuilder sbCommitMessage = new StringBuilder();
                if (StringUtils.isNotEmpty(prologue)) {
                    sbCommitMessage.append(prologue).append("\n\n");
                }
                sbCommitMessage.append(commitMessage);
                if (StringUtils.isNotEmpty(postscript)) {
                    sbCommitMessage.append("\n\n").append(postscript);
                }
                CommitCommand commitCommand = git.commit().setMessage(sbCommitMessage.toString()).setAuthor(authorIdent);
                RevCommit revCommit = retryingRepositoryOperationFacade.call(commitCommand);
                logger.debug("Git commit all published items completed.");
                int commitTime = revCommit.getCommitTime();
                // tag
                ZonedDateTime tagDate2 = Instant.ofEpochSecond(commitTime).atZone(UTC);
                ZonedDateTime publishDate = ZonedDateTime.now(UTC);
                String tagName2 = tagDate2.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HHmmssSSSX")) + "_published_on_" + publishDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HHmmssSSSX"));
                logger.debug("Get Author Ident started.");
                PersonIdent authorIdent2 = helper.getAuthorIdent(user);
                logger.debug("Get Author Ident completed.");
                logger.debug("Git tag started.");
                TagCommand tagCommand = git.tag().setTagger(authorIdent2).setName(tagName2).setMessage(commitMessage);
                retryingRepositoryOperationFacade.call(tagCommand);
                logger.debug("Git tag completed.");
                // checkout environment
                logger.debug("Checkout environment " + environment + " branch for site " + site);
                CheckoutCommand checkoutCommand = git.checkout().setName(environment);
                retryingRepositoryOperationFacade.call(checkoutCommand);
                Ref branchRef = repo.findRef(inProgressBranchName);
                // merge in-progress branch
                logger.debug("Merge in-progress branch into environment " + environment + " for site " + site);
                MergeCommand mergeCommand = git.merge().setCommit(true).include(branchRef);
                retryingRepositoryOperationFacade.call(mergeCommand);
                // clean up
                logger.debug("Delete in-progress branch (clean up) for site " + site);
                DeleteBranchCommand deleteBranchCommand = git.branchDelete().setBranchNames(inProgressBranchName).setForce(true);
                retryingRepositoryOperationFacade.call(deleteBranchCommand);
                git.close();
                if (repoCreated) {
                    siteService.setPublishedRepoCreated(site);
                }
            }
        }
    } catch (Exception e) {
        logger.error("Error when publishing site " + site + " to environment " + environment, e);
        throw new DeploymentException("Error when publishing site " + site + " to environment " + environment + " [commit ID = " + commitId + "]");
    } finally {
        generalLockService.unlock(gitLockKey);
    }
}
Also used : CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) User(org.craftercms.studio.api.v2.dal.User) MergeCommand(org.eclipse.jgit.api.MergeCommand) TagCommand(org.eclipse.jgit.api.TagCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RefNotFoundException(org.eclipse.jgit.api.errors.RefNotFoundException) ZonedDateTime(java.time.ZonedDateTime) ResetCommand(org.eclipse.jgit.api.ResetCommand) RmCommand(org.eclipse.jgit.api.RmCommand) CommitCommand(org.eclipse.jgit.api.CommitCommand) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) HashSet(java.util.HashSet) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Path(java.nio.file.Path) DeleteBranchCommand(org.eclipse.jgit.api.DeleteBranchCommand) PullCommand(org.eclipse.jgit.api.PullCommand) DeploymentItemTO(org.craftercms.studio.api.v1.to.DeploymentItemTO) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) IOException(java.io.IOException) RefNotFoundException(org.eclipse.jgit.api.errors.RefNotFoundException) RemoteRepositoryNotFoundException(org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotFoundException) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) DeploymentException(org.craftercms.studio.api.v1.service.deployment.DeploymentException) SiteNotFoundException(org.craftercms.studio.api.v1.exception.SiteNotFoundException) CryptoException(org.craftercms.commons.crypto.CryptoException) DuplicateKeyException(org.springframework.dao.DuplicateKeyException) InvalidRemoteRepositoryCredentialsException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryCredentialsException) InvalidRemoteRepositoryException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryException) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) ContentRepository(org.craftercms.studio.api.v2.repository.ContentRepository) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) FetchCommand(org.eclipse.jgit.api.FetchCommand) PersonIdent(org.eclipse.jgit.lib.PersonIdent) DeploymentException(org.craftercms.studio.api.v1.service.deployment.DeploymentException) File(java.io.File) AddCommand(org.eclipse.jgit.api.AddCommand) RetryingOperation(org.craftercms.studio.api.v2.annotation.RetryingOperation)

Example 7 with GeneralLockService

use of org.craftercms.studio.api.v1.service.GeneralLockService in project studio by craftercms.

the class GitContentRepository method contentExists.

@Override
public boolean contentExists(String site, String path) {
    boolean toReturn = false;
    try {
        GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
        Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX);
        if (repo != null) {
            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) {
                    toReturn = true;
                    tw.close();
                } else if (tw == null) {
                    String gitPath = helper.getGitPath(path);
                    if (StringUtils.isEmpty(gitPath) || gitPath.equals(".")) {
                        toReturn = true;
                    }
                }
            } catch (IOException e) {
                logger.info("Content not found for site: " + site + " path: " + path, e);
            }
        }
    } catch (Exception 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.v2.repository.ContentRepository) IOException(java.io.IOException) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevTree(org.eclipse.jgit.revwalk.RevTree) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) IOException(java.io.IOException) RefNotFoundException(org.eclipse.jgit.api.errors.RefNotFoundException) RemoteRepositoryNotFoundException(org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotFoundException) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) DeploymentException(org.craftercms.studio.api.v1.service.deployment.DeploymentException) SiteNotFoundException(org.craftercms.studio.api.v1.exception.SiteNotFoundException) CryptoException(org.craftercms.commons.crypto.CryptoException) DuplicateKeyException(org.springframework.dao.DuplicateKeyException) InvalidRemoteRepositoryCredentialsException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryCredentialsException) InvalidRemoteRepositoryException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryException)

Example 8 with GeneralLockService

use of org.craftercms.studio.api.v1.service.GeneralLockService in project studio by craftercms.

the class GitContentRepository method createSiteCloneRemote.

@Override
public boolean createSiteCloneRemote(String siteId, String sandboxBranch, String remoteName, String remoteUrl, String remoteBranch, boolean singleBranch, String authenticationType, String remoteUsername, String remotePassword, String remoteToken, String remotePrivateKey, Map<String, String> params, boolean createAsOrphan) throws InvalidRemoteRepositoryException, InvalidRemoteRepositoryCredentialsException, RemoteRepositoryNotFoundException, ServiceLayerException {
    boolean toReturn = false;
    // clone remote git repository for site content
    logger.debug("Creating site " + siteId + " as a clone of remote repository " + remoteName + " (" + remoteUrl + ").");
    String gitLockKey = SITE_SANDBOX_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, siteId);
    generalLockService.lock(gitLockKey);
    try {
        GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
        toReturn = helper.createSiteCloneRemoteGitRepo(siteId, sandboxBranch, remoteName, remoteUrl, remoteBranch, singleBranch, authenticationType, remoteUsername, remotePassword, remoteToken, remotePrivateKey, createAsOrphan);
        if (toReturn) {
            try {
                if (createAsOrphan) {
                    removeRemote(siteId, remoteName);
                } else {
                    insertRemoteToDb(siteId, remoteName, remoteUrl, authenticationType, remoteUsername, remotePassword, remoteToken, remotePrivateKey);
                }
            } catch (CryptoException e) {
                throw new ServiceLayerException(e);
            }
            // update site name variable inside config files
            logger.debug("Update site name configuration variables for site " + siteId);
            toReturn = helper.updateSiteNameConfigVar(siteId);
            if (toReturn) {
                toReturn = helper.replaceParameters(siteId, params);
            }
            if (toReturn) {
                // commit everything so it is visible
                logger.debug("Perform initial commit for site " + siteId);
                toReturn = helper.performInitialCommit(siteId, helper.getCommitMessage(REPO_INITIAL_COMMIT_COMMIT_MESSAGE), sandboxBranch);
            }
        } else {
            logger.error("Error while creating site " + siteId + " by cloning remote repository " + remoteName + " (" + remoteUrl + ").");
        }
    } catch (CryptoException e) {
        logger.error("Error while creating site " + siteId + " by cloning remote repository " + remoteName + " (" + remoteUrl + ").", e);
    } finally {
        generalLockService.unlock(gitLockKey);
    }
    return toReturn;
}
Also used : ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) CryptoException(org.craftercms.commons.crypto.CryptoException)

Example 9 with GeneralLockService

use of org.craftercms.studio.api.v1.service.GeneralLockService in project studio by craftercms.

the class GitContentRepository method getPublishingHistory.

@Override
public List<PublishingHistoryItem> getPublishingHistory(String siteId, String environment, String pathRegex, String publisher, ZonedDateTime fromDate, ZonedDateTime toDate, int limit) {
    List<PublishingHistoryItem> toRet = new ArrayList<PublishingHistoryItem>();
    try {
        GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
        Repository publishedRepo = helper.getRepository(siteId, PUBLISHED);
        if (publishedRepo != null) {
            int counter = 0;
            try (Git git = new Git(publishedRepo)) {
                // List all environments
                List<Ref> environments = git.branchList().call();
                for (int i = 0; i < environments.size() && counter < limit; i++) {
                    Ref env = environments.get(i);
                    String environmentGit = env.getName();
                    environmentGit = environmentGit.replace(R_HEADS, "");
                    if ((StringUtils.isBlank(environment) && !StringUtils.equals(MASTER, environmentGit)) || StringUtils.equals(environment, environmentGit)) {
                        List<RevFilter> filters = new ArrayList<RevFilter>();
                        if (fromDate != null) {
                            filters.add(CommitTimeRevFilter.after(fromDate.toInstant().toEpochMilli()));
                        }
                        if (toDate != null) {
                            filters.add(CommitTimeRevFilter.before(toDate.toInstant().toEpochMilli()));
                        } else {
                            filters.add(CommitTimeRevFilter.before(ZonedDateTime.now().toInstant().toEpochMilli()));
                        }
                        filters.add(NotRevFilter.create(MessageRevFilter.create("Initial commit.")));
                        if (StringUtils.isNotEmpty(publisher)) {
                            User user = userServiceInternal.getUserByIdOrUsername(-1, publisher);
                            filters.add(AuthorRevFilter.create(helper.getAuthorIdent(user).getName()));
                        }
                        Iterable<RevCommit> branchLog = git.log().add(env.getObjectId()).setRevFilter(AndRevFilter.create(filters)).call();
                        Iterator<RevCommit> iterator = branchLog.iterator();
                        while (iterator.hasNext() && counter < limit) {
                            RevCommit revCommit = iterator.next();
                            List<String> files = helper.getFilesInCommit(publishedRepo, revCommit);
                            for (int j = 0; j < files.size() && counter < limit; j++) {
                                String file = files.get(j);
                                Path path = Paths.get(file);
                                String fileName = path.getFileName().toString();
                                if (!ArrayUtils.contains(IGNORE_FILES, fileName)) {
                                    boolean addFile = false;
                                    if (StringUtils.isNotEmpty(pathRegex)) {
                                        Pattern pattern = Pattern.compile(pathRegex);
                                        Matcher matcher = pattern.matcher(file);
                                        addFile = matcher.matches();
                                    } else {
                                        addFile = true;
                                    }
                                    if (addFile) {
                                        PublishingHistoryItem phi = new PublishingHistoryItem();
                                        phi.setSiteId(siteId);
                                        phi.setPath(file);
                                        phi.setPublishedDate(Instant.ofEpochSecond(revCommit.getCommitTime()).atZone(UTC));
                                        phi.setPublisher(revCommit.getAuthorIdent().getName());
                                        phi.setEnvironment(environmentGit.replace(R_HEADS, ""));
                                        toRet.add(phi);
                                        counter++;
                                    }
                                }
                            }
                        }
                    }
                }
                git.close();
                toRet.sort((o1, o2) -> o2.getPublishedDate().compareTo(o1.getPublishedDate()));
            } catch (IOException | GitAPIException | UserNotFoundException | ServiceLayerException e1) {
                logger.error("Error while getting deployment history for site " + siteId, e1);
            }
        }
    } catch (CryptoException e) {
        e.printStackTrace();
    }
    return toRet;
}
Also used : UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) User(org.craftercms.studio.api.v2.dal.User) Matcher(java.util.regex.Matcher) PublishingHistoryItem(org.craftercms.studio.api.v2.dal.PublishingHistoryItem) ArrayList(java.util.ArrayList) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) CommitTimeRevFilter(org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter) MessageRevFilter(org.eclipse.jgit.revwalk.filter.MessageRevFilter) RevFilter(org.eclipse.jgit.revwalk.filter.RevFilter) AndRevFilter(org.eclipse.jgit.revwalk.filter.AndRevFilter) AuthorRevFilter(org.eclipse.jgit.revwalk.filter.AuthorRevFilter) NotRevFilter(org.eclipse.jgit.revwalk.filter.NotRevFilter) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Path(java.nio.file.Path) Pattern(java.util.regex.Pattern) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) IOException(java.io.IOException) RemoteRepository(org.craftercms.studio.api.v2.dal.RemoteRepository) Repository(org.eclipse.jgit.lib.Repository) ContentRepository(org.craftercms.studio.api.v2.repository.ContentRepository) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) CryptoException(org.craftercms.commons.crypto.CryptoException)

Example 10 with GeneralLockService

use of org.craftercms.studio.api.v1.service.GeneralLockService 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)

Aggregations

GitRepositoryHelper (org.craftercms.studio.api.v2.utils.GitRepositoryHelper)49 Repository (org.eclipse.jgit.lib.Repository)48 RemoteRepository (org.craftercms.studio.api.v2.dal.RemoteRepository)47 ContentRepository (org.craftercms.studio.api.v1.repository.ContentRepository)42 CryptoException (org.craftercms.commons.crypto.CryptoException)39 IOException (java.io.IOException)38 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)35 Git (org.eclipse.jgit.api.Git)33 ServiceLayerException (org.craftercms.studio.api.v1.exception.ServiceLayerException)30 Path (java.nio.file.Path)17 UserNotFoundException (org.craftercms.studio.api.v1.exception.security.UserNotFoundException)17 ArrayList (java.util.ArrayList)14 RevTree (org.eclipse.jgit.revwalk.RevTree)13 InvalidRemoteUrlException (org.craftercms.studio.api.v1.exception.repository.InvalidRemoteUrlException)11 ObjectId (org.eclipse.jgit.lib.ObjectId)11 RevCommit (org.eclipse.jgit.revwalk.RevCommit)11 File (java.io.File)10 InvalidRemoteException (org.eclipse.jgit.api.errors.InvalidRemoteException)10 TreeWalk (org.eclipse.jgit.treewalk.TreeWalk)10 HashMap (java.util.HashMap)8