use of org.apache.velocity.app.VelocityEngine in project ngAndroid by davityle.
the class SourceCreator method createSourceFiles.
public void createSourceFiles() {
Properties props = new Properties();
props.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.SystemLogChute");
props.setProperty("resource.loader", "classpath");
props.setProperty("classpath.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
VelocityEngine ve = new VelocityEngine(props);
ve.init();
Template vtModel = ve.getTemplate("templates/ngmodel.vm");
Template vtScope = ve.getTemplate("templates/scope.vm");
Template vtLayout = ve.getTemplate("templates/layout.vm");
for (NgModelSourceLink ms : modelSourceLinks) {
try {
JavaFileObject jfo = filer.createSourceFile(ms.getSourceFileName(), ms.getElements());
Writer writer = jfo.openWriter();
vtModel.merge(ms.getVelocityContext(), writer);
writer.flush();
writer.close();
} catch (IOException e) {
messageUtils.error(Option.of(ms.getElements()[0]), e.getMessage());
}
}
for (ScopeSourceLink ss : scopeSourceLinks) {
try {
JavaFileObject jfo = filer.createSourceFile(ss.getSourceFileName(), ss.getElements());
Writer writer = jfo.openWriter();
vtScope.merge(ss.getVelocityContext(), writer);
writer.flush();
writer.close();
} catch (IOException e) {
messageUtils.error(Option.of(ss.getElements()[0]), e.getMessage());
}
}
for (LayoutSourceLink lsl : layoutSourceLinks) {
try {
JavaFileObject jfo = filer.createSourceFile(lsl.getSourceFileName(), lsl.getElements());
Writer writer = jfo.openWriter();
vtLayout.merge(lsl.getVelocityContext(), writer);
writer.flush();
writer.close();
} catch (IOException e) {
messageUtils.error(Option.<Element>absent(), e.getMessage());
}
}
}
use of org.apache.velocity.app.VelocityEngine in project camel by apache.
the class VelocityEndpoint method onExchange.
@Override
protected void onExchange(Exchange exchange) throws Exception {
String path = getResourceUri();
ObjectHelper.notNull(path, "resourceUri");
String newResourceUri = exchange.getIn().getHeader(VelocityConstants.VELOCITY_RESOURCE_URI, String.class);
if (newResourceUri != null) {
exchange.getIn().removeHeader(VelocityConstants.VELOCITY_RESOURCE_URI);
log.debug("{} set to {} creating new endpoint to handle exchange", VelocityConstants.VELOCITY_RESOURCE_URI, newResourceUri);
VelocityEndpoint newEndpoint = findOrCreateEndpoint(getEndpointUri(), newResourceUri);
newEndpoint.onExchange(exchange);
return;
}
Reader reader;
String content = exchange.getIn().getHeader(VelocityConstants.VELOCITY_TEMPLATE, String.class);
if (content != null) {
// use content from header
reader = new StringReader(content);
if (log.isDebugEnabled()) {
log.debug("Velocity content read from header {} for endpoint {}", VelocityConstants.VELOCITY_TEMPLATE, getEndpointUri());
}
// remove the header to avoid it being propagated in the routing
exchange.getIn().removeHeader(VelocityConstants.VELOCITY_TEMPLATE);
} else {
if (log.isDebugEnabled()) {
log.debug("Velocity content read from resource {} with resourceUri: {} for endpoint {}", new Object[] { getResourceUri(), path, getEndpointUri() });
}
reader = getEncoding() != null ? new InputStreamReader(getResourceAsInputStream(), getEncoding()) : new InputStreamReader(getResourceAsInputStream());
}
// getResourceAsInputStream also considers the content cache
StringWriter buffer = new StringWriter();
String logTag = getClass().getName();
Context velocityContext = exchange.getIn().getHeader(VelocityConstants.VELOCITY_CONTEXT, Context.class);
if (velocityContext == null) {
Map<String, Object> variableMap = ExchangeHelper.createVariableMap(exchange);
@SuppressWarnings("unchecked") Map<String, Object> supplementalMap = exchange.getIn().getHeader(VelocityConstants.VELOCITY_SUPPLEMENTAL_CONTEXT, Map.class);
if (supplementalMap != null) {
variableMap.putAll(supplementalMap);
}
velocityContext = new VelocityContext(variableMap);
}
// let velocity parse and generate the result in buffer
VelocityEngine engine = getVelocityEngine();
log.debug("Velocity is evaluating using velocity context: {}", velocityContext);
engine.evaluate(velocityContext, buffer, logTag, reader);
// now lets output the results to the exchange
Message out = exchange.getOut();
out.setBody(buffer.toString());
out.setHeaders(exchange.getIn().getHeaders());
out.setAttachments(exchange.getIn().getAttachments());
}
use of org.apache.velocity.app.VelocityEngine in project stashbot by palantir.
the class JenkinsJobXmlFormatter method generateJobXml.
public String generateJobXml(JobTemplate jobTemplate, Repository repo) throws SQLException {
final VelocityContext vc = velocityManager.getVelocityContext();
final RepositoryConfiguration rc = cpm.getRepositoryConfigurationForRepository(repo);
final JenkinsServerConfiguration jsc = cpm.getJenkinsServerConfiguration(rc.getJenkinsServerName());
RepositoryCloneLinksRequest rclr = new RepositoryCloneLinksRequest.Builder().repository(repo).protocol("http").user(null).build();
String repositoryUrl = rs.getCloneLinks(rclr).iterator().next().getHref();
String cleanRepositoryUrl = repositoryUrl;
// Handle the various Authentication modes
switch(jsc.getAuthenticationMode()) {
case USERNAME_AND_PASSWORD:
// manually insert the username and pw we are configured to use
repositoryUrl = repositoryUrl.replace("://", "://" + jsc.getStashUsername() + ":" + jsc.getStashPassword() + "@");
break;
case CREDENTIAL_MANUALLY_CONFIGURED:
vc.put("credentialUUID", jsc.getStashPassword());
break;
}
vc.put("repositoryUrl", repositoryUrl);
vc.put("cleanRepositoryUrl", cleanRepositoryUrl);
vc.put("prebuildCommand", prebuildCommand(rc.getPrebuildCommand()));
// TODO: figure out build command some other way?
switch(jobTemplate.getJobType()) {
case VERIFY_COMMIT:
vc.put("buildCommand", buildCommand(rc.getVerifyBuildCommand()));
break;
case VERIFY_PR:
vc.put("buildCommand", buildCommand(rc.getVerifyBuildCommand()));
break;
case PUBLISH:
vc.put("buildCommand", buildCommand(rc.getPublishBuildCommand()));
break;
case NOOP:
vc.put("buildCommand", buildCommand("/bin/true"));
break;
}
// Add email notification stuff for all build types
vc.put("isEmailNotificationsEnabled", rc.getEmailNotificationsEnabled());
vc.put("emailRecipients", rc.getEmailRecipients());
vc.put("isEmailForEveryUnstableBuild", rc.getEmailForEveryUnstableBuild());
vc.put("isEmailSendToIndividuals", rc.getEmailSendToIndividuals());
vc.put("isEmailPerModuleEmail", rc.getEmailPerModuleEmail());
vc.put("startedCommand", curlCommandBuilder(repo, jobTemplate, rc, repositoryUrl, "inprogress"));
vc.put("successCommand", curlCommandBuilder(repo, jobTemplate, rc, repositoryUrl, "successful"));
vc.put("failedCommand", curlCommandBuilder(repo, jobTemplate, rc, repositoryUrl, "failed"));
vc.put("repositoryLink", navBuilder.repo(repo).browse().buildAbsolute());
vc.put("repositoryName", repo.getProject().getName() + " " + repo.getName());
// Parameters are type-dependent for now
ImmutableList.Builder<Map<String, String>> paramBuilder = new ImmutableList.Builder<Map<String, String>>();
switch(jobTemplate.getJobType()) {
case VERIFY_COMMIT:
// repoId
paramBuilder.add(ImmutableMap.of("name", "repoId", "typeName", JenkinsBuildParamType.StringParameterDefinition.toString(), "description", "stash repository Id", "defaultValue", "unknown"));
// buildHead
paramBuilder.add(ImmutableMap.of("name", "buildHead", "typeName", JenkinsBuildParamType.StringParameterDefinition.toString(), "description", "the change to build", "defaultValue", "head"));
break;
case VERIFY_PR:
// repoId
paramBuilder.add(ImmutableMap.of("name", "repoId", "typeName", JenkinsBuildParamType.StringParameterDefinition.toString(), "description", "stash repository Id", "defaultValue", "unknown"));
// buildHead
paramBuilder.add(ImmutableMap.of("name", "buildHead", "typeName", JenkinsBuildParamType.StringParameterDefinition.toString(), "description", "the change to build", "defaultValue", "head"));
// pullRequestId
paramBuilder.add(ImmutableMap.of("name", "pullRequestId", "typeName", JenkinsBuildParamType.StringParameterDefinition.toString(), "description", "the pull request Id", "defaultValue", ""));
break;
case PUBLISH:
// repoId
paramBuilder.add(ImmutableMap.of("name", "repoId", "typeName", JenkinsBuildParamType.StringParameterDefinition.toString(), "description", "stash repository Id", "defaultValue", "unknown"));
// buildHead
paramBuilder.add(ImmutableMap.of("name", "buildHead", "typeName", JenkinsBuildParamType.StringParameterDefinition.toString(), "description", "the change to build", "defaultValue", "head"));
break;
case NOOP:
// no params
break;
}
vc.put("paramaterList", paramBuilder.build());
// Junit settings
vc.put("isJunit", rc.getJunitEnabled());
vc.put("junitPath", rc.getJunitPath());
// Artifact settings
vc.put("artifactsEnabled", rc.getArtifactsEnabled());
vc.put("artifactsPath", rc.getArtifactsPath());
// insert pinned data
switch(jobTemplate.getJobType()) {
case VERIFY_COMMIT:
case VERIFY_PR:
vc.put("isPinned", rc.getVerifyPinned());
vc.put("label", rc.getVerifyLabel());
break;
case PUBLISH:
vc.put("isPinned", rc.getPublishPinned());
vc.put("label", rc.getPublishLabel());
break;
case NOOP:
vc.put("isPinned", false);
break;
}
StringWriter xml = new StringWriter();
VelocityEngine ve = velocityManager.getVelocityEngine();
Template template = ve.getTemplate(jobTemplate.getTemplateFile());
template.merge(vc, xml);
return xml.toString();
}
use of org.apache.velocity.app.VelocityEngine in project qi4j-sdk by Qi4j.
the class RestServerAssembler method assemble.
@Override
public void assemble(ModuleAssembly module) throws AssemblyException {
Properties props = new Properties();
try {
props.load(getClass().getResourceAsStream("/velocity.properties"));
VelocityEngine velocity = new VelocityEngine(props);
module.importedServices(VelocityEngine.class).importedBy(INSTANCE).setMetaInfo(velocity);
} catch (Exception e) {
throw new AssemblyException("Could not load velocity properties", e);
}
freemarker.template.Configuration cfg = new freemarker.template.Configuration();
cfg.setClassForTemplateLoading(AbstractResponseWriter.class, "");
cfg.setObjectWrapper(new ValueCompositeObjectWrapper());
module.importedServices(freemarker.template.Configuration.class).setMetaInfo(cfg);
module.importedServices(MetadataService.class);
module.importedServices(ResponseWriterDelegator.class).identifiedBy("responsewriterdelegator").importedBy(NEW_OBJECT).visibleIn(Visibility.layer);
module.objects(ResponseWriterDelegator.class);
module.importedServices(RequestReaderDelegator.class).identifiedBy("requestreaderdelegator").importedBy(NEW_OBJECT).visibleIn(Visibility.layer);
module.objects(RequestReaderDelegator.class);
module.importedServices(InteractionConstraintsService.class).importedBy(NewObjectImporter.class).visibleIn(Visibility.application);
module.objects(InteractionConstraintsService.class);
// Standard response writers
Iterable<Class<?>> writers = ClassScanner.findClasses(DefaultResponseWriter.class);
Specification<Class<?>> responseWriterClass = isAssignableFrom(ResponseWriter.class);
Specification<Class<?>> isNotAnAbstract = not(hasModifier(Modifier.ABSTRACT));
Iterable<Class<?>> candidates = filter(and(isNotAnAbstract, responseWriterClass), writers);
for (Class<?> responseWriter : candidates) {
module.objects(responseWriter);
}
// Standard request readers
module.objects(DefaultRequestReader.class);
}
use of org.apache.velocity.app.VelocityEngine in project intellij-community by JetBrains.
the class VelocityHelper method evaluate.
public static String evaluate(PsiFile file, Project project, Module module, String template) {
VelocityEngine engine = getEngine();
VelocityContext vc = new VelocityContext();
vc.put("today", new DateInfo());
if (file != null)
vc.put("file", new FileInfo(file));
if (project != null)
vc.put("project", new ProjectInfo(project));
if (module != null)
vc.put("module", new ModuleInfo(module));
vc.put("username", System.getProperty("user.name"));
if (file != null) {
final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(file);
if (virtualFile != null) {
final CopyrightVariablesProvider variablesProvider = CopyrightVariablesProviders.INSTANCE.forFileType(virtualFile.getFileType());
if (variablesProvider != null) {
final Map<String, Object> context = new HashMap<>();
variablesProvider.collectVariables(context, project, module, file);
for (Map.Entry<String, Object> entry : context.entrySet()) {
vc.put(entry.getKey(), entry.getValue());
}
}
}
}
try {
StringWriter sw = new StringWriter();
boolean stripLineBreak = false;
if (template.endsWith("$")) {
template += getVelocitySuffix();
stripLineBreak = true;
}
engine.evaluate(vc, sw, CopyrightManager.class.getName(), template);
final String result = sw.getBuffer().toString();
return stripLineBreak ? StringUtil.trimEnd(result, getVelocitySuffix()) : result;
} catch (Exception e) {
return "";
}
}
Aggregations