use of org.apache.velocity.context.Context in project OpenOLAT by OpenOLAT.
the class UserBulkChangeManager method changeSelectedIdentities.
public void changeSelectedIdentities(List<Identity> selIdentities, Map<String, String> attributeChangeMap, Map<String, String> roleChangeMap, List<String> notUpdatedIdentities, boolean isAdministrativeUser, List<Long> ownGroups, List<Long> partGroups, Translator trans, Identity addingIdentity) {
Translator transWithFallback = userManager.getPropertyHandlerTranslator(trans);
String usageIdentifyer = UserBulkChangeStep00.class.getCanonicalName();
notUpdatedIdentities.clear();
List<Identity> changedIdentities = new ArrayList<>();
List<UserPropertyHandler> userPropertyHandlers = userManager.getUserPropertyHandlersFor(usageIdentifyer, isAdministrativeUser);
String[] securityGroups = { Constants.GROUP_USERMANAGERS, Constants.GROUP_GROUPMANAGERS, Constants.GROUP_AUTHORS, Constants.GROUP_ADMIN, Constants.GROUP_POOL_MANAGER, Constants.GROUP_INST_ORES_MANAGER };
// loop over users to be edited:
for (Identity identity : selIdentities) {
// reload identity from cache, to prevent stale object
identity = securityManager.loadIdentityByKey(identity.getKey());
User user = identity.getUser();
String oldEmail = user.getEmail();
String errorDesc = "";
boolean updateError = false;
// change pwd
if (attributeChangeMap.containsKey(PWD_IDENTIFYER)) {
String newPwd = attributeChangeMap.get(PWD_IDENTIFYER);
if (StringHelper.containsNonWhitespace(newPwd)) {
if (!userManager.syntaxCheckOlatPassword(newPwd)) {
errorDesc = transWithFallback.translate("error.password");
updateError = true;
}
} else {
newPwd = null;
}
olatAuthManager.changePasswordAsAdmin(identity, newPwd);
}
// set language
String userLanguage = user.getPreferences().getLanguage();
if (attributeChangeMap.containsKey(LANG_IDENTIFYER)) {
String inputLanguage = attributeChangeMap.get(LANG_IDENTIFYER);
if (!userLanguage.equals(inputLanguage)) {
Preferences preferences = user.getPreferences();
preferences.setLanguage(inputLanguage);
user.setPreferences(preferences);
}
}
Context vcContext = new VelocityContext();
// set all properties as context
setUserContext(identity, vcContext);
// org.olat.admin.user.bulkChange.UserBulkChangeStep00
for (int k = 0; k < userPropertyHandlers.size(); k++) {
UserPropertyHandler propHandler = userPropertyHandlers.get(k);
String propertyName = propHandler.getName();
String userValue = identity.getUser().getProperty(propertyName, null);
String inputFieldValue = "";
if (attributeChangeMap.containsKey(propertyName)) {
inputFieldValue = attributeChangeMap.get(propertyName);
inputFieldValue = inputFieldValue.replace("$", "$!");
String evaluatedInputFieldValue = evaluateValueWithUserContext(inputFieldValue, vcContext);
// validate evaluated property-value
ValidationError validationError = new ValidationError();
// do validation checks with users current locale!
Locale locale = transWithFallback.getLocale();
if (!propHandler.isValidValue(identity.getUser(), evaluatedInputFieldValue, validationError, locale)) {
errorDesc = transWithFallback.translate(validationError.getErrorKey(), validationError.getArgs()) + " (" + evaluatedInputFieldValue + ")";
updateError = true;
break;
}
if (!evaluatedInputFieldValue.equals(userValue)) {
String stringValue = propHandler.getStringValue(evaluatedInputFieldValue, locale);
propHandler.setUserProperty(user, stringValue);
}
}
}
// loop over securityGroups defined above
for (String securityGroup : securityGroups) {
SecurityGroup secGroup = securityManager.findSecurityGroupByName(securityGroup);
Boolean isInGroup = securityManager.isIdentityInSecurityGroup(identity, secGroup);
String thisRoleAction = "";
if (roleChangeMap.containsKey(securityGroup)) {
thisRoleAction = roleChangeMap.get(securityGroup);
// user not anymore in security group, remove him
if (isInGroup && thisRoleAction.equals("remove")) {
securityManager.removeIdentityFromSecurityGroup(identity, secGroup);
log.audit("User::" + addingIdentity.getName() + " removed system role::" + securityGroup + " from user::" + identity.getName(), null);
}
// user not yet in security group, add him
if (!isInGroup && thisRoleAction.equals("add")) {
securityManager.addIdentityToSecurityGroup(identity, secGroup);
log.audit("User::" + addingIdentity.getName() + " added system role::" + securityGroup + " to user::" + identity.getName(), null);
}
}
}
// set status
if (roleChangeMap.containsKey("Status")) {
Integer status = Integer.parseInt(roleChangeMap.get("Status"));
int oldStatus = identity.getStatus();
String oldStatusText = (oldStatus == Identity.STATUS_PERMANENT ? "permanent" : (oldStatus == Identity.STATUS_ACTIV ? "active" : (oldStatus == Identity.STATUS_LOGIN_DENIED ? "login_denied" : (oldStatus == Identity.STATUS_DELETED ? "deleted" : "unknown"))));
String newStatusText = (status == Identity.STATUS_PERMANENT ? "permanent" : (status == Identity.STATUS_ACTIV ? "active" : (status == Identity.STATUS_LOGIN_DENIED ? "login_denied" : (status == Identity.STATUS_DELETED ? "deleted" : "unknown"))));
if (oldStatus != status && status == Identity.STATUS_LOGIN_DENIED && Boolean.parseBoolean(roleChangeMap.get("sendLoginDeniedEmail"))) {
sendLoginDeniedEmail(identity);
}
identity = securityManager.saveIdentityStatus(identity, status);
log.audit("User::" + addingIdentity.getName() + " changed accout status for user::" + identity.getName() + " from::" + oldStatusText + " to::" + newStatusText, null);
}
// persist changes:
if (updateError) {
String errorOutput = identity.getName() + ": " + errorDesc;
log.debug("error during bulkChange of users, following user could not be updated: " + errorOutput);
notUpdatedIdentities.add(errorOutput);
} else {
userManager.updateUserFromIdentity(identity);
securityManager.deleteInvalidAuthenticationsByEmail(oldEmail);
changedIdentities.add(identity);
log.audit("User::" + addingIdentity.getName() + " successfully changed account data for user::" + identity.getName() + " in bulk change", null);
}
// commit changes for this user
dbInstance.commit();
}
// FXOLAT-101: add identity to new groups:
if (ownGroups.size() != 0 || partGroups.size() != 0) {
List<BusinessGroupMembershipChange> changes = new ArrayList<BusinessGroupMembershipChange>();
for (Identity selIdentity : selIdentities) {
if (ownGroups != null && !ownGroups.isEmpty()) {
for (Long tutorGroupKey : ownGroups) {
BusinessGroupMembershipChange change = new BusinessGroupMembershipChange(selIdentity, tutorGroupKey);
change.setTutor(Boolean.TRUE);
changes.add(change);
}
}
if (partGroups != null && !partGroups.isEmpty()) {
for (Long partGroupKey : partGroups) {
BusinessGroupMembershipChange change = new BusinessGroupMembershipChange(selIdentity, partGroupKey);
change.setParticipant(Boolean.TRUE);
changes.add(change);
}
}
}
MailPackage mailing = new MailPackage();
businessGroupService.updateMemberships(addingIdentity, changes, mailing);
dbInstance.commit();
}
}
use of org.apache.velocity.context.Context in project OpenOLAT by OpenOLAT.
the class UserBulkChangeManager method getDemoContext.
public Context getDemoContext(Translator propertyTrans) {
Context vcContext = new VelocityContext();
List<UserPropertyHandler> userPropertyHandlers2 = userManager.getAllUserPropertyHandlers();
for (UserPropertyHandler userPropertyHandler : userPropertyHandlers2) {
String propertyName = userPropertyHandler.getName();
String userValue = propertyTrans.translate("import.example." + userPropertyHandler.getName());
vcContext.put(propertyName, userValue);
}
return vcContext;
}
use of org.apache.velocity.context.Context in project maven-archetype by apache.
the class DefaultOldArchetype method createArchetype.
public void createArchetype(ArchetypeGenerationRequest request, File archetypeFile) throws ArchetypeDescriptorException, ArchetypeTemplateProcessingException {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("basedir", request.getOutputDirectory());
parameters.put(Constants.PACKAGE, request.getPackage());
parameters.put("packageName", request.getPackage());
parameters.put(Constants.GROUP_ID, request.getGroupId());
parameters.put(Constants.ARTIFACT_ID, request.getArtifactId());
parameters.put(Constants.VERSION, request.getVersion());
// ---------------------------------------------------------------------
if (getLogger().isInfoEnabled()) {
getLogger().info("----------------------------------------------------------------------------");
getLogger().info("Using following parameters for creating project from Old (1.x) Archetype: " + request.getArchetypeArtifactId() + ":" + request.getArchetypeVersion());
getLogger().info("----------------------------------------------------------------------------");
for (Map.Entry<String, String> entry : parameters.entrySet()) {
String parameterName = entry.getKey();
String parameterValue = entry.getValue();
getLogger().info("Parameter: " + parameterName + ", Value: " + parameterValue);
}
}
// ----------------------------------------------------------------------
// Load the descriptor
// ----------------------------------------------------------------------
ArchetypeDescriptorBuilder builder = new ArchetypeDescriptorBuilder();
ArchetypeDescriptor descriptor;
URLClassLoader archetypeJarLoader;
InputStream is = null;
try {
URL[] urls = new URL[1];
urls[0] = archetypeFile.toURL();
archetypeJarLoader = new URLClassLoader(urls);
is = getStream(ARCHETYPE_DESCRIPTOR, archetypeJarLoader);
if (is == null) {
is = getStream(ARCHETYPE_OLD_DESCRIPTOR, archetypeJarLoader);
}
if (is == null) {
throw new ArchetypeDescriptorException("The " + ARCHETYPE_DESCRIPTOR + " descriptor cannot be found.");
}
descriptor = builder.build(new XmlStreamReader(is));
} catch (IOException e) {
throw new ArchetypeDescriptorException("Error reading the " + ARCHETYPE_DESCRIPTOR + " descriptor.", e);
} catch (XmlPullParserException e) {
throw new ArchetypeDescriptorException("Error reading the " + ARCHETYPE_DESCRIPTOR + " descriptor.", e);
} finally {
IOUtil.close(is);
}
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
String artifactId = request.getArtifactId();
File parentPomFile = new File(request.getOutputDirectory(), ARCHETYPE_POM);
File outputDirectoryFile;
boolean creating;
File pomFile;
if (parentPomFile.exists() && descriptor.isAllowPartial() && artifactId == null) {
outputDirectoryFile = new File(request.getOutputDirectory());
creating = false;
pomFile = parentPomFile;
} else {
if (artifactId == null) {
throw new ArchetypeTemplateProcessingException("Artifact ID must be specified when creating a new project from an archetype.");
}
outputDirectoryFile = new File(request.getOutputDirectory(), artifactId);
creating = true;
if (outputDirectoryFile.exists()) {
if (descriptor.isAllowPartial()) {
creating = false;
} else {
throw new ArchetypeTemplateProcessingException("Directory " + outputDirectoryFile.getName() + " already exists - please run from a clean directory");
}
}
pomFile = new File(outputDirectoryFile, ARCHETYPE_POM);
}
if (creating) {
if (request.getGroupId() == null) {
throw new ArchetypeTemplateProcessingException("Group ID must be specified when creating a new project from an archetype.");
}
if (request.getVersion() == null) {
throw new ArchetypeTemplateProcessingException("Version must be specified when creating a new project from an archetype.");
}
}
String outputDirectory = outputDirectoryFile.getAbsolutePath();
String packageName = request.getPackage();
// ----------------------------------------------------------------------
// Set up the Velocity context
// ----------------------------------------------------------------------
Context context = new VelocityContext();
context.put(Constants.PACKAGE, packageName);
for (Map.Entry<String, String> entry : parameters.entrySet()) {
context.put(entry.getKey(), entry.getValue());
}
// ----------------------------------------------------------------------
// Process the templates
// ----------------------------------------------------------------------
ClassLoader old = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(archetypeJarLoader);
Model parentModel = null;
if (creating) {
if (parentPomFile.exists()) {
Reader fileReader = null;
try {
fileReader = ReaderFactory.newXmlReader(parentPomFile);
MavenXpp3Reader reader = new MavenXpp3Reader();
parentModel = reader.read(fileReader);
if (!"pom".equals(parentModel.getPackaging())) {
throw new ArchetypeTemplateProcessingException("Unable to add module to the current project as it is not of packaging type 'pom'");
}
} catch (IOException e) {
throw new ArchetypeTemplateProcessingException("Unable to read parent POM", e);
} catch (XmlPullParserException e) {
throw new ArchetypeTemplateProcessingException("Unable to read parent POM", e);
} finally {
IOUtil.close(fileReader);
}
parentModel.getModules().add(artifactId);
}
}
try {
processTemplates(pomFile, outputDirectory, context, descriptor, packageName, parentModel);
} finally {
Thread.currentThread().setContextClassLoader(old);
}
if (parentModel != null) {
/*
// TODO: would be nice to just write out with the xpp3 writer again, except that it loses a bunch of info and
// reformats, so the module is just baked in as a string instead.
FileWriter fileWriter = null;
try
{
fileWriter = new FileWriter( parentPomFile );
MavenXpp3Writer writer = new MavenXpp3Writer();
writer.write( fileWriter, parentModel );
}
catch ( IOException e )
{
throw new ArchetypeTemplateProcessingException( "Unable to rewrite parent POM", e );
}
finally
{
IOUtil.close( fileWriter );
}
*/
Reader fileReader = null;
boolean added;
StringWriter w = new StringWriter();
try {
fileReader = ReaderFactory.newXmlReader(parentPomFile);
added = addModuleToParentPom(artifactId, fileReader, w);
} catch (IOException e) {
throw new ArchetypeTemplateProcessingException("Unable to rewrite parent POM", e);
} catch (DocumentException e) {
throw new ArchetypeTemplateProcessingException("Unable to rewrite parent POM", e);
} finally {
IOUtil.close(fileReader);
}
if (added) {
Writer out = null;
try {
out = WriterFactory.newXmlWriter(parentPomFile);
IOUtil.copy(w.toString(), out);
} catch (IOException e) {
throw new ArchetypeTemplateProcessingException("Unable to rewrite parent POM", e);
} finally {
IOUtil.close(out);
}
}
}
// ----------------------------------------------------------------------
if (getLogger().isInfoEnabled()) {
getLogger().info("project created from Old (1.x) Archetype in dir: " + outputDirectory);
}
}
use of org.apache.velocity.context.Context in project maven-archetype by apache.
the class DefaultFilesetArchetypeGenerator method prepareVelocityContext.
private Context prepareVelocityContext(ArchetypeGenerationRequest request) {
Context context = new VelocityContext();
context.put(Constants.GROUP_ID, request.getGroupId());
context.put(Constants.ARTIFACT_ID, request.getArtifactId());
context.put(Constants.VERSION, request.getVersion());
context.put(Constants.PACKAGE, request.getPackage());
final String packageInPathFormat = getPackageInPathFormat(request.getPackage());
context.put(Constants.PACKAGE_IN_PATH_FORMAT, packageInPathFormat);
if (getLogger().isInfoEnabled()) {
getLogger().info("----------------------------------------------------------------------------");
getLogger().info("Using following parameters for creating project from Archetype: " + request.getArchetypeArtifactId() + ":" + request.getArchetypeVersion());
getLogger().info("----------------------------------------------------------------------------");
getLogger().info("Parameter: " + Constants.GROUP_ID + ", Value: " + request.getGroupId());
getLogger().info("Parameter: " + Constants.ARTIFACT_ID + ", Value: " + request.getArtifactId());
getLogger().info("Parameter: " + Constants.VERSION + ", Value: " + request.getVersion());
getLogger().info("Parameter: " + Constants.PACKAGE + ", Value: " + request.getPackage());
getLogger().info("Parameter: " + Constants.PACKAGE_IN_PATH_FORMAT + ", Value: " + packageInPathFormat);
}
for (Iterator<?> iterator = request.getProperties().keySet().iterator(); iterator.hasNext(); ) {
String key = (String) iterator.next();
String value = request.getProperties().getProperty(key);
if (maybeVelocityExpression(value)) {
value = evaluateExpression(context, key, value);
}
context.put(key, value);
if (getLogger().isInfoEnabled()) {
getLogger().info("Parameter: " + key + ", Value: " + value);
}
}
return context;
}
use of org.apache.velocity.context.Context in project maven-archetype by apache.
the class DefaultFilesetArchetypeGenerator method generateArchetype.
public void generateArchetype(ArchetypeGenerationRequest request, File archetypeFile) throws UnknownArchetype, ArchetypeNotConfigured, ProjectDirectoryExists, PomFileExists, OutputFileExists, ArchetypeGenerationFailure {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
ArchetypeDescriptor archetypeDescriptor = archetypeArtifactManager.getFileSetArchetypeDescriptor(archetypeFile);
if (!isArchetypeConfigured(archetypeDescriptor, request)) {
if (request.isInteractiveMode()) {
throw new ArchetypeNotConfigured("No archetype was chosen.", null);
}
StringBuffer exceptionMessage = new StringBuffer("Archetype " + request.getArchetypeGroupId() + ":" + request.getArchetypeArtifactId() + ":" + request.getArchetypeVersion() + " is not configured");
List<String> missingProperties = new ArrayList<String>(0);
for (RequiredProperty requiredProperty : archetypeDescriptor.getRequiredProperties()) {
if (StringUtils.isEmpty(request.getProperties().getProperty(requiredProperty.getKey()))) {
exceptionMessage.append("\n\tProperty " + requiredProperty.getKey() + " is missing.");
missingProperties.add(requiredProperty.getKey());
}
}
throw new ArchetypeNotConfigured(exceptionMessage.toString(), missingProperties);
}
Context context = prepareVelocityContext(request);
String packageName = request.getPackage();
String artifactId = request.getArtifactId();
File outputDirectoryFile = new File(request.getOutputDirectory(), artifactId);
File basedirPom = new File(request.getOutputDirectory(), Constants.ARCHETYPE_POM);
File pom = new File(outputDirectoryFile, Constants.ARCHETYPE_POM);
List<String> archetypeResources = archetypeArtifactManager.getFilesetArchetypeResources(archetypeFile);
ZipFile archetypeZipFile = archetypeArtifactManager.getArchetypeZipFile(archetypeFile);
ClassLoader archetypeJarLoader = archetypeArtifactManager.getArchetypeJarLoader(archetypeFile);
Thread.currentThread().setContextClassLoader(archetypeJarLoader);
if (archetypeDescriptor.isPartial()) {
getLogger().debug("Processing partial archetype " + archetypeDescriptor.getName());
if (outputDirectoryFile.exists()) {
if (!pom.exists()) {
throw new PomFileExists("This is a partial archetype and the pom.xml file doesn't exist.");
}
processPomWithMerge(context, pom, "");
processArchetypeTemplatesWithWarning(archetypeDescriptor, archetypeResources, archetypeZipFile, "", context, packageName, outputDirectoryFile);
} else {
if (basedirPom.exists()) {
processPomWithMerge(context, basedirPom, "");
processArchetypeTemplatesWithWarning(archetypeDescriptor, archetypeResources, archetypeZipFile, "", context, packageName, new File(request.getOutputDirectory()));
} else {
processPom(context, pom, "");
processArchetypeTemplates(archetypeDescriptor, archetypeResources, archetypeZipFile, "", context, packageName, outputDirectoryFile);
}
}
if (archetypeDescriptor.getModules().size() > 0) {
getLogger().info("Modules ignored in partial mode");
}
} else {
getLogger().debug("Processing complete archetype " + archetypeDescriptor.getName());
if (outputDirectoryFile.exists() && pom.exists()) {
throw new ProjectDirectoryExists("A Maven 2 project already exists in the directory " + outputDirectoryFile.getPath());
}
if (outputDirectoryFile.exists()) {
getLogger().warn("The directory " + outputDirectoryFile.getPath() + " already exists.");
}
context.put("rootArtifactId", artifactId);
processFilesetModule(artifactId, artifactId, archetypeResources, pom, archetypeZipFile, "", basedirPom, outputDirectoryFile, packageName, archetypeDescriptor, context);
}
String postGenerationScript = archetypeArtifactManager.getPostGenerationScript(archetypeFile);
if (postGenerationScript != null) {
getLogger().info("Executing " + Constants.ARCHETYPE_POST_GENERATION_SCRIPT + " post-generation script");
Binding binding = new Binding();
final Properties archetypeGeneratorProperties = new Properties();
archetypeGeneratorProperties.putAll(System.getProperties());
if (request.getProperties() != null) {
archetypeGeneratorProperties.putAll(request.getProperties());
}
for (Map.Entry<Object, Object> entry : archetypeGeneratorProperties.entrySet()) {
binding.setVariable(entry.getKey().toString(), entry.getValue());
}
binding.setVariable("request", request);
GroovyShell shell = new GroovyShell(binding);
shell.evaluate(postGenerationScript);
}
// ----------------------------------------------------------------------
if (getLogger().isInfoEnabled()) {
getLogger().info("Project created from Archetype in dir: " + outputDirectoryFile.getAbsolutePath());
}
} catch (FileNotFoundException ex) {
throw new ArchetypeGenerationFailure(ex);
} catch (IOException ex) {
throw new ArchetypeGenerationFailure(ex);
} catch (XmlPullParserException ex) {
throw new ArchetypeGenerationFailure(ex);
} catch (DocumentException ex) {
throw new ArchetypeGenerationFailure(ex);
} catch (ArchetypeGenerationFailure ex) {
throw new ArchetypeGenerationFailure(ex);
} catch (InvalidPackaging ex) {
throw new ArchetypeGenerationFailure(ex);
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
Aggregations