Search in sources :

Example 1 with ServiceLayerException

use of org.craftercms.studio.api.v1.exception.ServiceLayerException in project studio by craftercms.

the class ConfigurationServiceImpl method validate.

@SuppressWarnings("unchecked")
protected InputStream validate(InputStream content, String filename) throws ServiceLayerException {
    // Check the filename to see if it needs to be validated
    String extension = getExtension(filename);
    if (isEmpty(extension)) {
        // without extension there is no way to know
        return content;
    }
    try {
        // Copy the contents of the stream
        byte[] bytes;
        bytes = IOUtils.toByteArray(content);
        // Perform the validation
        switch(extension.toLowerCase()) {
            case "xml":
                try {
                    DocumentHelper.parseText(new String(bytes));
                } catch (Exception e) {
                    throw new InvalidConfigurationException("Invalid XML file", e);
                }
                break;
            case "yaml":
            case "yml":
                try {
                    Yaml yaml = new Yaml(new DisableClassLoadingConstructor());
                    Map<String, Object> map = (Map<String, Object>) yaml.load(new ByteArrayInputStream(bytes));
                } catch (Exception e) {
                    throw new InvalidConfigurationException("Invalid YAML file", e);
                }
        }
        // Return a new stream
        return new ByteArrayInputStream(bytes);
    } catch (IOException e) {
        throw new ServiceLayerException("Error validating configuration", e);
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) IOException(java.io.IOException) DisableClassLoadingConstructor(org.craftercms.commons.config.DisableClassLoadingConstructor) Map(java.util.Map) HashMap(java.util.HashMap) SAXException(org.xml.sax.SAXException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) ContentNotFoundException(org.craftercms.studio.api.v1.exception.ContentNotFoundException) DocumentException(org.dom4j.DocumentException) ConfigurationException(org.craftercms.studio.api.v2.exception.configuration.ConfigurationException) IOException(java.io.IOException) SiteNotFoundException(org.craftercms.studio.api.v1.exception.SiteNotFoundException) InvalidConfigurationException(org.craftercms.studio.api.v2.exception.configuration.InvalidConfigurationException) Yaml(org.yaml.snakeyaml.Yaml) InvalidConfigurationException(org.craftercms.studio.api.v2.exception.configuration.InvalidConfigurationException)

Example 2 with ServiceLayerException

use of org.craftercms.studio.api.v1.exception.ServiceLayerException in project studio by craftercms.

the class RepositoryManagementServiceInternalImpl method listRemotes.

@Override
public List<RemoteRepositoryInfo> listRemotes(String siteId, String sandboxBranch) throws ServiceLayerException, CryptoException {
    List<RemoteRepositoryInfo> res = new ArrayList<RemoteRepositoryInfo>();
    Map<String, String> unreachableRemotes = new HashMap<String, String>();
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
    try (Repository repo = helper.getRepository(siteId, SANDBOX)) {
        try (Git git = new Git(repo)) {
            List<RemoteConfig> resultRemotes = git.remoteList().call();
            if (CollectionUtils.isNotEmpty(resultRemotes)) {
                for (RemoteConfig conf : resultRemotes) {
                    try {
                        fetchRemote(siteId, git, conf);
                    } catch (Exception e) {
                        logger.warn("Failed to fetch from remote repository " + conf.getName());
                        unreachableRemotes.put(conf.getName(), e.getMessage());
                    }
                }
                Map<String, List<String>> remoteBranches = getRemoteBranches(git);
                String sandboxBranchName = sandboxBranch;
                if (StringUtils.isEmpty(sandboxBranchName)) {
                    sandboxBranchName = studioConfiguration.getProperty(REPO_SANDBOX_BRANCH);
                }
                res = getRemoteRepositoryInfo(resultRemotes, remoteBranches, unreachableRemotes, sandboxBranchName);
            }
        } catch (GitAPIException e) {
            logger.error("Error getting remote repositories for site " + siteId, e);
        }
    }
    return res;
}
Also used : RemoteRepositoryInfo(org.craftercms.studio.api.v2.dal.RemoteRepositoryInfo) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) IOException(java.io.IOException) RemoteNotRemovableException(org.craftercms.studio.api.v1.exception.repository.RemoteNotRemovableException) URISyntaxException(java.net.URISyntaxException) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) InvalidRemoteUrlException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteUrlException) RemoteAlreadyExistsException(org.craftercms.studio.api.v1.exception.repository.RemoteAlreadyExistsException) CryptoException(org.craftercms.commons.crypto.CryptoException) InvalidRemoteException(org.eclipse.jgit.api.errors.InvalidRemoteException) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) 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) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) RemoteConfig(org.eclipse.jgit.transport.RemoteConfig)

Example 3 with ServiceLayerException

use of org.craftercms.studio.api.v1.exception.ServiceLayerException in project studio by craftercms.

the class RepositoryManagementServiceInternalImpl method pullFromRemote.

@Override
public boolean pullFromRemote(String siteId, String remoteName, String remoteBranch, String mergeStrategy) throws InvalidRemoteUrlException, ServiceLayerException, CryptoException {
    logger.debug("Get remote data from database for remote " + remoteName + " and site " + siteId);
    String gitLockKey = SITE_SANDBOX_REPOSITORY_GIT_LOCK.replaceAll(PATTERN_SITE, siteId);
    RemoteRepository remoteRepository = getRemoteRepository(siteId, remoteName);
    logger.debug("Prepare pull command");
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration, securityService, userServiceInternal, encryptor, generalLockService, retryingRepositoryOperationFacade);
    Repository repo = helper.getRepository(siteId, SANDBOX);
    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);
        Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
        pullCommand = helper.setAuthenticationForCommand(pullCommand, remoteRepository.getAuthenticationType(), remoteRepository.getRemoteUsername(), remoteRepository.getRemotePassword(), remoteRepository.getRemoteToken(), remoteRepository.getRemotePrivateKey(), tempKey, true);
        switch(mergeStrategy) {
            case THEIRS:
                pullCommand.setStrategy(MergeStrategy.THEIRS);
                break;
            case OURS:
                pullCommand.setStrategy(MergeStrategy.OURS);
                break;
            default:
                break;
        }
        pullCommand.setFastForward(MergeCommand.FastForwardMode.NO_FF);
        pullResult = retryingRepositoryOperationFacade.call(pullCommand);
        String pullResultMessage = pullResult.toString();
        if (StringUtils.isNotEmpty(pullResultMessage)) {
            logger.info(pullResultMessage);
        }
        Files.delete(tempKey);
        if (!pullResult.isSuccessful() && conflictNotificationEnabled()) {
            List<String> conflictFiles = new ArrayList<String>();
            if (pullResult.getMergeResult() != null) {
                pullResult.getMergeResult().getConflicts().forEach((m, v) -> {
                    conflictFiles.add(m);
                });
            }
            notificationService.notifyRepositoryMergeConflict(siteId, conflictFiles, Locale.ENGLISH);
        }
        if (pullResult.isSuccessful()) {
            String lastCommitId = contentRepository.getRepoLastCommitId(siteId);
            contentRepositoryV2.upsertGitLogList(siteId, Arrays.asList(lastCommitId), false, false);
            List<String> newMergedCommits = extractCommitIdsFromPullResult(siteId, repo, pullResult);
            List<String> commitIds = new ArrayList<String>();
            if (Objects.nonNull(newMergedCommits) && newMergedCommits.size() > 0) {
                logger.debug("Really pulled commits:");
                int cnt = 0;
                for (int i = 0; i < newMergedCommits.size(); i++) {
                    String commitId = newMergedCommits.get(i);
                    logger.debug(commitId);
                    if (!StringUtils.equals(lastCommitId, commitId)) {
                        commitIds.add(commitId);
                        if (cnt++ >= batchSizeGitLog) {
                            contentRepositoryV2.upsertGitLogList(siteId, commitIds, true, true);
                            cnt = 0;
                            commitIds.clear();
                        }
                    }
                }
                if (Objects.nonNull(commitIds) && commitIds.size() > 0) {
                    contentRepositoryV2.upsertGitLogList(siteId, commitIds, true, true);
                }
            }
            siteService.updateLastCommitId(siteId, lastCommitId);
        }
        return pullResult != null && pullResult.isSuccessful();
    } 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) ArrayList(java.util.ArrayList) 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) InvalidRemoteException(org.eclipse.jgit.api.errors.InvalidRemoteException) GitRepositoryHelper(org.craftercms.studio.api.v2.utils.GitRepositoryHelper) CryptoException(org.craftercms.commons.crypto.CryptoException)

Example 4 with ServiceLayerException

use of org.craftercms.studio.api.v1.exception.ServiceLayerException in project studio by craftercms.

the class UserServiceImpl method validateToken.

@Override
public boolean validateToken(String token) throws UserNotFoundException, UserExternallyManagedException, ServiceLayerException {
    boolean toRet = false;
    String decryptedToken = decryptToken(token);
    if (StringUtils.isNotEmpty(decryptedToken)) {
        StringTokenizer tokenElements = new StringTokenizer(decryptedToken, "|");
        if (tokenElements.countTokens() == 3) {
            String username = tokenElements.nextToken();
            User userProfile = userServiceInternal.getUserByIdOrUsername(-1, username);
            if (userProfile == null) {
                logger.info("User profile not found for " + username);
                throw new UserNotFoundException();
            } else {
                if (userProfile.isExternallyManaged()) {
                    throw new UserExternallyManagedException();
                } else {
                    String studioId = tokenElements.nextToken();
                    if (StringUtils.equals(studioId, instanceService.getInstanceId())) {
                        long tokenTimestamp = Long.parseLong(tokenElements.nextToken());
                        ZonedDateTime now = ZonedDateTime.now();
                        toRet = tokenTimestamp >= now.toInstant().toEpochMilli();
                    }
                }
            }
        }
    }
    return toRet;
}
Also used : UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) UserExternallyManagedException(org.craftercms.studio.api.v1.exception.security.UserExternallyManagedException) StringTokenizer(java.util.StringTokenizer) User(org.craftercms.studio.api.v2.dal.User) AuthenticatedUser(org.craftercms.studio.model.AuthenticatedUser) ZonedDateTime(java.time.ZonedDateTime)

Example 5 with ServiceLayerException

use of org.craftercms.studio.api.v1.exception.ServiceLayerException in project studio by craftercms.

the class UserServiceImpl method deleteUsers.

@Override
@HasPermission(type = DefaultPermission.class, action = "delete_users")
public void deleteUsers(List<Long> userIds, List<String> usernames) throws ServiceLayerException, AuthenticationException, UserNotFoundException {
    User currentUser = getCurrentUser();
    if (CollectionUtils.containsAny(userIds, Arrays.asList(currentUser.getId())) || CollectionUtils.containsAny(usernames, Arrays.asList(currentUser.getUsername()))) {
        throw new ServiceLayerException("Cannot delete self.");
    }
    generalLockService.lock(REMOVE_SYSTEM_ADMIN_MEMBER_LOCK);
    try {
        try {
            Group g = groupServiceInternal.getGroupByName(SYSTEM_ADMIN_GROUP);
            List<User> members = groupServiceInternal.getGroupMembers(g.getId(), 0, Integer.MAX_VALUE, StringUtils.EMPTY);
            if (CollectionUtils.isNotEmpty(members)) {
                List<User> membersAfterRemove = new ArrayList<User>();
                membersAfterRemove.addAll(members);
                members.forEach(m -> {
                    if (CollectionUtils.isNotEmpty(userIds)) {
                        if (userIds.contains(m.getId())) {
                            membersAfterRemove.remove(m);
                        }
                    }
                    if (CollectionUtils.isNotEmpty(usernames)) {
                        if (usernames.contains(m.getUsername())) {
                            membersAfterRemove.remove(m);
                        }
                    }
                });
                if (CollectionUtils.isEmpty(membersAfterRemove)) {
                    throw new ServiceLayerException("Removing all members of the System Admin group is not allowed." + " We must have at least one system administrator.");
                }
            }
        } catch (GroupNotFoundException e) {
            throw new ServiceLayerException("The System Admin group is not found.", e);
        }
        List<User> toDelete = userServiceInternal.getUsersByIdOrUsername(userIds, usernames);
        userServiceInternal.deleteUsers(userIds, usernames);
        SiteFeed siteFeed = siteService.getSite(studioConfiguration.getProperty(CONFIGURATION_GLOBAL_SYSTEM_SITE));
        AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
        auditLog.setOperation(OPERATION_DELETE);
        auditLog.setActorId(getCurrentUser().getUsername());
        auditLog.setPrimaryTargetId(siteFeed.getSiteId());
        auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
        auditLog.setPrimaryTargetValue(siteFeed.getName());
        List<AuditLogParameter> paramters = new ArrayList<AuditLogParameter>();
        for (User deletedUser : toDelete) {
            AuditLogParameter paramter = new AuditLogParameter();
            paramter.setTargetId(Long.toString(deletedUser.getId()));
            paramter.setTargetType(TARGET_TYPE_USER);
            paramter.setTargetValue(deletedUser.getUsername());
            paramters.add(paramter);
        }
        auditLog.setParameters(paramters);
        auditServiceInternal.insertAuditLog(auditLog);
    } finally {
        generalLockService.unlock(REMOVE_SYSTEM_ADMIN_MEMBER_LOCK);
    }
}
Also used : Group(org.craftercms.studio.api.v2.dal.Group) User(org.craftercms.studio.api.v2.dal.User) AuthenticatedUser(org.craftercms.studio.model.AuthenticatedUser) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) ArrayList(java.util.ArrayList) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) GroupNotFoundException(org.craftercms.studio.api.v1.exception.security.GroupNotFoundException) AuditLogParameter(org.craftercms.studio.api.v2.dal.AuditLogParameter) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog) HasPermission(org.craftercms.commons.security.permissions.annotations.HasPermission)

Aggregations

ServiceLayerException (org.craftercms.studio.api.v1.exception.ServiceLayerException)124 UserNotFoundException (org.craftercms.studio.api.v1.exception.security.UserNotFoundException)62 HashMap (java.util.HashMap)55 ArrayList (java.util.ArrayList)45 IOException (java.io.IOException)39 User (org.craftercms.studio.api.v2.dal.User)36 Repository (org.eclipse.jgit.lib.Repository)35 Git (org.eclipse.jgit.api.Git)33 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)33 ContentRepository (org.craftercms.studio.api.v1.repository.ContentRepository)32 RemoteRepository (org.craftercms.studio.api.v2.dal.RemoteRepository)30 SiteFeed (org.craftercms.studio.api.v1.dal.SiteFeed)29 SiteNotFoundException (org.craftercms.studio.api.v1.exception.SiteNotFoundException)29 CryptoException (org.craftercms.commons.crypto.CryptoException)28 ValidateParams (org.craftercms.commons.validation.annotations.param.ValidateParams)27 GitRepositoryHelper (org.craftercms.studio.api.v2.utils.GitRepositoryHelper)24 ContentItemTO (org.craftercms.studio.api.v1.to.ContentItemTO)23 Path (java.nio.file.Path)21 InvalidRemoteUrlException (org.craftercms.studio.api.v1.exception.repository.InvalidRemoteUrlException)21 AuditLog (org.craftercms.studio.api.v2.dal.AuditLog)20