use of org.apache.velocity.context.Context in project openolat by klemens.
the class CourseCreationConfiguration method getSinglePageText.
/**
* @param translator
* @return single page content
*/
public String getSinglePageText(Translator translator) {
VelocityContainer vc = new VelocityContainer("singlePageTemplate", CourseCreationHelper.class, "singlePageTemplate", translator, null);
vc.contextPut("coursetitle", courseTitle);
// prepare rendering of velocity page for the content of the single page node
GlobalSettings globalSettings = new GlobalSettings() {
public int getFontSize() {
return 100;
}
public AJAXFlags getAjaxFlags() {
return new EmptyAJAXFlags();
}
public boolean isIdDivsForced() {
return false;
}
};
Context context = vc.getContext();
Renderer fr = Renderer.getInstance(vc, translator, null, new RenderResult(), globalSettings);
StringOutput wOut = new StringOutput(10000);
VelocityRenderDecorator vrdec = new VelocityRenderDecorator(fr, vc, wOut);
context.put("r", vrdec);
VelocityHelper.getInstance().mergeContent(vc.getPage(), context, wOut, null);
// free the decorator
context.remove("r");
IOUtils.closeQuietly(vrdec);
return WysiwygFactory.createXHtmlFileContent(wOut.toString(), courseTitle);
}
use of org.apache.velocity.context.Context in project openolat by klemens.
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 maven-archetype by apache.
the class DefaultArchetypeGenerationConfigurator method configureArchetype.
public void configureArchetype(ArchetypeGenerationRequest request, Boolean interactiveMode, Properties executionProperties) throws ArchetypeNotDefined, UnknownArchetype, ArchetypeNotConfigured, IOException, PrompterException, ArchetypeGenerationConfigurationFailure {
ArtifactRepository localRepository = request.getLocalRepository();
ArtifactRepository archetypeRepository = null;
List<ArtifactRepository> repositories = new ArrayList<ArtifactRepository>();
Properties properties = new Properties(executionProperties);
ArchetypeDefinition ad = new ArchetypeDefinition(request);
if (!ad.isDefined()) {
if (!interactiveMode.booleanValue()) {
throw new ArchetypeNotDefined("No archetype was chosen");
} else {
throw new ArchetypeNotDefined("The archetype is not defined");
}
}
if (request.getArchetypeRepository() != null) {
archetypeRepository = createRepository(request.getArchetypeRepository(), ad.getArtifactId() + "-repo");
repositories.add(archetypeRepository);
}
if (request.getRemoteArtifactRepositories() != null) {
repositories.addAll(request.getRemoteArtifactRepositories());
}
if (!archetypeArtifactManager.exists(ad.getGroupId(), ad.getArtifactId(), ad.getVersion(), archetypeRepository, localRepository, repositories, request.getProjectBuildingRequest())) {
throw new UnknownArchetype("The desired archetype does not exist (" + ad.getGroupId() + ":" + ad.getArtifactId() + ":" + ad.getVersion() + ")");
}
request.setArchetypeVersion(ad.getVersion());
ArchetypeConfiguration archetypeConfiguration;
if (archetypeArtifactManager.isFileSetArchetype(ad.getGroupId(), ad.getArtifactId(), ad.getVersion(), archetypeRepository, localRepository, repositories, request.getProjectBuildingRequest())) {
org.apache.maven.archetype.metadata.ArchetypeDescriptor archetypeDescriptor = archetypeArtifactManager.getFileSetArchetypeDescriptor(ad.getGroupId(), ad.getArtifactId(), ad.getVersion(), archetypeRepository, localRepository, repositories, request.getProjectBuildingRequest());
archetypeConfiguration = archetypeFactory.createArchetypeConfiguration(archetypeDescriptor, properties);
} else if (archetypeArtifactManager.isOldArchetype(ad.getGroupId(), ad.getArtifactId(), ad.getVersion(), archetypeRepository, localRepository, repositories, request.getProjectBuildingRequest())) {
org.apache.maven.archetype.old.descriptor.ArchetypeDescriptor archetypeDescriptor = archetypeArtifactManager.getOldArchetypeDescriptor(ad.getGroupId(), ad.getArtifactId(), ad.getVersion(), archetypeRepository, localRepository, repositories, request.getProjectBuildingRequest());
archetypeConfiguration = archetypeFactory.createArchetypeConfiguration(archetypeDescriptor, properties);
} else {
throw new ArchetypeGenerationConfigurationFailure("The defined artifact is not an archetype");
}
Context context = new VelocityContext();
if (interactiveMode.booleanValue()) {
boolean confirmed = false;
context.put(Constants.GROUP_ID, ad.getGroupId());
context.put(Constants.ARTIFACT_ID, ad.getArtifactId());
context.put(Constants.VERSION, ad.getVersion());
while (!confirmed) {
List<String> propertiesRequired = archetypeConfiguration.getRequiredProperties();
getLogger().debug("Required properties before content sort: " + propertiesRequired);
Collections.sort(propertiesRequired, new RequiredPropertyComparator(archetypeConfiguration));
getLogger().debug("Required properties after content sort: " + propertiesRequired);
if (!archetypeConfiguration.isConfigured()) {
for (String requiredProperty : propertiesRequired) {
if (!archetypeConfiguration.isConfigured(requiredProperty)) {
if ("package".equals(requiredProperty)) {
// if the asked property is 'package', then
// use its default and if not defined,
// use the 'groupId' property value.
String packageDefault = archetypeConfiguration.getDefaultValue(requiredProperty);
packageDefault = (null == packageDefault || "".equals(packageDefault)) ? archetypeConfiguration.getProperty("groupId") : archetypeConfiguration.getDefaultValue(requiredProperty);
String value = getTransitiveDefaultValue(packageDefault, archetypeConfiguration, requiredProperty, context);
value = archetypeGenerationQueryer.getPropertyValue(requiredProperty, value, null);
archetypeConfiguration.setProperty(requiredProperty, value);
context.put(Constants.PACKAGE, value);
} else {
String value = archetypeConfiguration.getDefaultValue(requiredProperty);
value = getTransitiveDefaultValue(value, archetypeConfiguration, requiredProperty, context);
value = archetypeGenerationQueryer.getPropertyValue(requiredProperty, value, archetypeConfiguration.getPropertyValidationRegex(requiredProperty));
archetypeConfiguration.setProperty(requiredProperty, value);
context.put(requiredProperty, value);
}
} else {
getLogger().info("Using property: " + requiredProperty + " = " + archetypeConfiguration.getProperty(requiredProperty));
archetypeConfiguration.setProperty(requiredProperty, archetypeConfiguration.getProperty(requiredProperty));
}
}
} else {
for (String requiredProperty : propertiesRequired) {
getLogger().info("Using property: " + requiredProperty + " = " + archetypeConfiguration.getProperty(requiredProperty));
}
}
if (!archetypeConfiguration.isConfigured()) {
getLogger().warn("Archetype is not fully configured");
} else if (!archetypeGenerationQueryer.confirmConfiguration(archetypeConfiguration)) {
getLogger().debug("Archetype generation configuration not confirmed");
archetypeConfiguration.reset();
restoreCommandLineProperties(archetypeConfiguration, executionProperties);
} else {
getLogger().debug("Archetype generation configuration confirmed");
confirmed = true;
}
}
} else {
if (!archetypeConfiguration.isConfigured()) {
for (String requiredProperty : archetypeConfiguration.getRequiredProperties()) {
if (!archetypeConfiguration.isConfigured(requiredProperty) && (archetypeConfiguration.getDefaultValue(requiredProperty) != null)) {
String value = archetypeConfiguration.getDefaultValue(requiredProperty);
value = getTransitiveDefaultValue(value, archetypeConfiguration, requiredProperty, context);
archetypeConfiguration.setProperty(requiredProperty, value);
context.put(requiredProperty, value);
}
}
// in batch mode, we assume the defaults, and if still not configured fail
if (!archetypeConfiguration.isConfigured()) {
StringBuffer exceptionMessage = new StringBuffer();
exceptionMessage.append("Archetype ");
exceptionMessage.append(request.getArchetypeGroupId());
exceptionMessage.append(":");
exceptionMessage.append(request.getArchetypeArtifactId());
exceptionMessage.append(":");
exceptionMessage.append(request.getArchetypeVersion());
exceptionMessage.append(" is not configured");
List<String> missingProperties = new ArrayList<String>(0);
for (String requiredProperty : archetypeConfiguration.getRequiredProperties()) {
if (!archetypeConfiguration.isConfigured(requiredProperty)) {
exceptionMessage.append("\n\tProperty ");
exceptionMessage.append(requiredProperty);
missingProperties.add(requiredProperty);
exceptionMessage.append(" is missing.");
getLogger().warn("Property " + requiredProperty + " is missing. Add -D" + requiredProperty + "=someValue");
}
}
throw new ArchetypeNotConfigured(exceptionMessage.toString(), missingProperties);
}
}
}
request.setGroupId(archetypeConfiguration.getProperty(Constants.GROUP_ID));
request.setArtifactId(archetypeConfiguration.getProperty(Constants.ARTIFACT_ID));
request.setVersion(archetypeConfiguration.getProperty(Constants.VERSION));
request.setPackage(archetypeConfiguration.getProperty(Constants.PACKAGE));
properties = archetypeConfiguration.getProperties();
request.setProperties(properties);
}
use of org.apache.velocity.context.Context in project maven-archetype by apache.
the class ArchetypeTest method testArchetype.
public void testArchetype() throws Exception {
FileUtils.deleteDirectory(getTestFile("target/quickstart"));
// ----------------------------------------------------------------------
// This needs to be encapsulated in a maven test case.
// ----------------------------------------------------------------------
ArtifactRepositoryLayout layout = (ArtifactRepositoryLayout) getContainer().lookup(ArtifactRepositoryLayout.ROLE);
String mavenRepoLocal = getTestFile("target/local-repository").toURI().toURL().toString();
ArtifactRepository localRepository = new DefaultArtifactRepository("local", mavenRepoLocal, layout);
List<ArtifactRepository> remoteRepositories = new ArrayList<ArtifactRepository>();
String mavenRepoRemote = getTestFile("src/test/repository").toURI().toURL().toString();
ArtifactRepository remoteRepository = new DefaultArtifactRepository("remote", mavenRepoRemote, layout);
remoteRepositories.add(remoteRepository);
ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest();
buildingRequest.setRemoteRepositories(remoteRepositories);
MavenRepositorySystemSession repositorySession = new MavenRepositorySystemSession();
repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManager(localRepository.getBasedir()));
buildingRequest.setRepositorySession(repositorySession);
ArchetypeGenerationRequest request = new ArchetypeGenerationRequest().setProjectBuildingRequest(buildingRequest).setPackage("org.apache.maven.quickstart").setGroupId("maven").setArtifactId("quickstart").setVersion("1.0-alpha-1-SNAPSHOT").setArchetypeGroupId("org.apache.maven.archetypes").setArchetypeArtifactId("maven-archetype-quickstart").setArchetypeVersion("1.0-alpha-1-SNAPSHOT").setLocalRepository(localRepository).setRemoteArtifactRepositories(remoteRepositories).setOutputDirectory(getTestFile("target").getAbsolutePath());
// parameters.put( "name", "jason" );
archetype.createArchetype(request, remoteRepository);
// ----------------------------------------------------------------------
// Set up the Velocity context
// ----------------------------------------------------------------------
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("basedir", request.getOutputDirectory());
parameters.put("package", request.getPackage());
parameters.put("packageName", request.getPackage());
parameters.put("groupId", request.getGroupId());
parameters.put("artifactId", request.getArtifactId());
parameters.put("version", request.getVersion());
Context context = new VelocityContext();
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
context.put(entry.getKey(), entry.getValue());
}
// ----------------------------------------------------------------------
// Validate POM generation
// ----------------------------------------------------------------------
ArtifactFactory artifactFactory = (ArtifactFactory) lookup(ArtifactFactory.class.getName());
Artifact archetypeArtifact = artifactFactory.createArtifact(request.getArchetypeGroupId(), request.getArchetypeArtifactId(), request.getArchetypeVersion(), Artifact.SCOPE_RUNTIME, "jar");
StringWriter writer = new StringWriter();
ClassLoader old = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getContextClassloader(archetypeArtifact, localRepository, remoteRepositories));
try {
VelocityComponent velocity = (VelocityComponent) lookup(VelocityComponent.class.getName());
velocity.getEngine().mergeTemplate(OldArchetype.ARCHETYPE_RESOURCES + "/" + OldArchetype.ARCHETYPE_POM, context, writer);
} finally {
Thread.currentThread().setContextClassLoader(old);
}
Model generatedModel, templateModel;
try {
StringReader strReader = new StringReader(writer.toString());
MavenXpp3Reader reader = new MavenXpp3Reader();
templateModel = reader.read(strReader);
} catch (IOException e) {
throw new ArchetypeTemplateProcessingException("Error reading template POM", e);
}
File artifactDir = getTestFile("target", (String) parameters.get("artifactId"));
File pomFile = getTestFile(artifactDir.getAbsolutePath(), OldArchetype.ARCHETYPE_POM);
try {
FileReader pomReader = new FileReader(pomFile);
MavenXpp3Reader reader = new MavenXpp3Reader();
generatedModel = reader.read(pomReader);
} catch (IOException e) {
throw new ArchetypeTemplateProcessingException("Error reading generated POM", e);
} catch (XmlPullParserException e) {
throw new ArchetypeTemplateProcessingException("Error reading generated POM", e);
}
assertEquals("Generated POM ArtifactId is not equivalent to expected result.", generatedModel.getArtifactId(), templateModel.getArtifactId());
assertEquals("Generated POM GroupId is not equivalent to expected result.", generatedModel.getGroupId(), templateModel.getGroupId());
assertEquals("Generated POM Id is not equivalent to expected result.", generatedModel.getId(), templateModel.getId());
assertEquals("Generated POM Version is not equivalent to expected result.", generatedModel.getVersion(), templateModel.getVersion());
assertEquals("Generated POM Packaging is not equivalent to expected result.", generatedModel.getPackaging(), templateModel.getPackaging());
assertEquals("Generated POM Developers is not equivalent to expected result.", generatedModel.getDevelopers(), templateModel.getDevelopers());
assertEquals("Generated POM Scm is not equivalent to expected result.", generatedModel.getScm(), templateModel.getScm());
}
use of org.apache.velocity.context.Context in project openolat by klemens.
the class VelocityContainerRenderer method render.
/**
* @see org.olat.core.gui.render.ui.ComponentRenderer#render(org.olat.core.gui.render.Renderer,
* org.olat.core.gui.render.StringOutput, org.olat.core.gui.components.Component,
* org.olat.core.gui.render.URLBuilder, org.olat.core.gui.translator.Translator,
* org.olat.core.gui.render.RenderResult, java.lang.String[])
*/
@Override
public void render(Renderer renderer, StringOutput target, Component source, URLBuilder ubu, Translator translator, RenderResult renderResult, String[] args) {
VelocityContainer vc = (VelocityContainer) source;
String pagePath = vc.getPage();
Context ctx = vc.getContext();
// the component id of the urlbuilder will be overwritten by the recursive render call for
// subcomponents (see Renderer)
Renderer fr = Renderer.getInstance(vc, translator, ubu, renderResult, renderer.getGlobalSettings());
VelocityRenderDecorator vrdec = new VelocityRenderDecorator(fr, vc, target);
ctx.put("r", vrdec);
VelocityHelper vh = VelocityHelper.getInstance();
vh.mergeContent(pagePath, ctx, target, null);
// free the decorator
ctx.remove("r");
IOUtils.closeQuietly(vrdec);
// set all not rendered component as not dirty
for (Component cmp : vc.getComponents()) {
if (cmp.isDirty()) {
cmp.setDirty(false);
}
}
}
Aggregations