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);
}
}
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;
}
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);
}
}
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;
}
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);
}
}
Aggregations