How to Import Java classes and Alloy-UI tag library in Dynamic Datalist (DDL) Freemarker/Velocity Display Template (Liferay 6.2) - liferay-6

Is there any way to Import Java classes and Alloy-UI tag library into a Liferay 6.2 Dynamic Data List (DDL) Freemarker/Velocity Display Template?
For example, when editing the Display Template of a Dynamic Data List portlet (DDL), is there any way to import a class such as WorkflowConstants.java and use it?
Also is there any way to use add dependencies for alloy-ui tags with Display templates?
Thank you!

You can access static fields,static methods and non-static methods from freemarker template. Here is sample Program.
Custom constant class but you have WorkflowConstants in life ray you can access same
public class WorkflowConstants {
public static int ACTION_SAVE_DRAFT = 1;
public static String CONTEXT_COMPANY_ID = "MTRX_78";
// static method
public static String test() {
return "executed Constant#test()";
}
}
//FooCallMethod class
public class FooCallMethod {
public static void main(String[] args) throws Exception {
Configuration config = new Configuration();
config.setClassForTemplateLoading(FooCallMethod.class, "");
config.setObjectWrapper(new DefaultObjectWrapper());
config.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
Map<String, Object> dataModel = new HashMap<String, Object>();
TemplateHashModel staticModels = BeansWrapper.getDefaultInstance().getStaticModels();
dataModel.put("statics", staticModels);
TemplateHashModel fileStatics = (TemplateHashModel) staticModels
.get("java.io.File");
Cal cal = new Cal();
dataModel.put("cal", cal);
dataModel.put("File", fileStatics);
Template template = config.getTemplate("/foo.ftl");
StringWriter out = new StringWriter();
template.process(dataModel, out);
System.out.println(out.getBuffer().toString());
}
}
Cal.java
public class Cal {
public int add(int a, int b) {
return a + b;
}
public int mul(int a, int b) {
return a * b;
}
}
Template
${statics["com.tset.WorkflowConstants"].test()}
${statics["com.tset.WorkflowConstants"].ACTION_SAVE_DRAFT}
${statics["com.tset.WorkflowConstants"].CONTEXT_COMPANY_ID}
2+3 = ${cal.add(2,3)}
10/2 = ${cal.mul(10,2)}
${statics["java.lang.System"].currentTimeMillis()}
Note:
You can easily use Dynamic Data Lists in freeMarker tempalte
see here it is mentioned in velocity but need to use freeMarker syntax.
Use freemaker language: more powerfull and full support of taglib, velocity, it's too poor to use taglib
https://www.liferay.com/it/web/mika.koivisto/blog/-/blogs/using-freemarker-in-your-theme-templates
Look also freemaker guide

Related

Add my own rules in SonarQube with RPG

I want to create my own SonarQube Plugin for the RPG language. I have the following problem.
I start by created the RpgLanguage class that extends to AbstractLanguage. In this class, I defined my new language "Rpg". You can see my class in the following code :
public class RpgLanguage extends AbstractLanguage{
public static final String KEY = "rpg";
private Settings settings;
public RpgLanguage(Settings settings) {
super(KEY, "Rpg");
this.settings = settings;
}
public String[] getFileSuffixes() {
String[] suffixes = settings.getStringArray("");
if (suffixes == null || suffixes.length == 0) {
suffixes = StringUtils.split(".RPG", ",");
}
return suffixes;
}
}
After, I have created my RpgRulesDefinition class that implements RulesDefinition. In this class, I create a new repository for the language RPG and I want to add a rule in this repository (empty rules). The code is like below :
public static final String REPOSITORY_KEY = "rpg_repository_mkoza";
public void define(Context context) {
NewRepository repo = context.createRepository(REPOSITORY_KEY, "rpg");
repo.setName("Mkoza Analyser rules RPG");
// We could use a XML or JSON file to load all rule metadata, but
// we prefer use annotations in order to have all information in a single place
RulesDefinitionAnnotationLoader annotationLoader = new RulesDefinitionAnnotationLoader();
annotationLoader.load(repo, RpgFileCheckRegistrar.checkClasses());
repo.done();
}
My class RpgFileCheckRegistrar that call my Rules :
/**
* Register the classes that will be used to instantiate checks during analysis.
*/
public void register(RegistrarContext registrarContext) {
// Call to registerClassesForRepository to associate the classes with the correct repository key
registrarContext.registerClassesForRepository(RpgRulesDefinition.REPOSITORY_KEY, Arrays.asList(checkClasses()), Arrays.asList(testCheckClasses()));
}
/**
* Lists all the checks provided by the plugin
*/
public static Class<? extends JavaCheck>[] checkClasses() {
return new Class[] {
RulesExampleCheck.class
};
}
/**
* Lists all the test checks provided by the plugin
*/
public static Class<? extends JavaCheck>[] testCheckClasses() {
return new Class[] {};
}
My Rule class (still empty):
#Rule(
key = "Rule1",
name = "Rule that make nothing",
priority = Priority.MAJOR,
tags = {"example"}
)
public class RulesExampleCheck extends BaseTreeVisitor{
/**
* Right in java code your rule
*/
}
And the class SonarPlugin that call all these extensions :
public final class RpgSonarPlugin extends SonarPlugin
{
// This is where you're going to declare all your Sonar extensions
public List getExtensions() {
return Arrays.asList(
RpgLanguage.class,
RpgRulesDefinition.class,
RpgFileCheckRegistrar.class
);
}
}
The problem when I want to start the server sonar, I obtain this error stack :
Exception sending context initialized event to listener instance of class org.sonar.server.platform.PlatformServletContextListener
java.lang.IllegalStateException: One of HTML description or Markdown description must be defined for rule [repository=rpg_repository_mkoza, key=Rule1]
I try different things but I don't understand why there are these error.
Of course I want that my repository "rpg_repository_mkoza" is display in the RPG's repository in SonarQube with the Rules : RulesExampleCheck.
My sonar-plugin-version is the 3.7.1
I find my problem. There are need to add the field 'description' in #Rule.
For example :
#Rule(
key = "Rule1",
name = "RuleExampleCheck",
description = "This rule do nothing",
priority = Priority.INFO,
tags = {"try"}
)

unit-testing Wicket input components

I just wrote my first Wicket component :) It contains a ListView with some Radio input fields. Now I want to unit test if a selected value makes its way to the model.
As WicketTester.newFormTester("myForm") expects a form, I try to create a form on the fly:
public void testDataBinding()
{
Model model = ...
MyRadioComponent myRadioComponent = new MyRadioComponent (...);
Form form = new Form("myForm", ...);
form.add(myRadioComponent);
WicketTester wicketTester = new WicketTester();
wicketTester.startComponentInPage(form);
// FormTester formTester = wicketTester.newFormTester("myForm");
// ...
}
Now wicketTester.startComponentInPage(form) results in:
Failed: Component [myForm] (path = [0:x]) must be applied to a tag of type [form],
not: '<span wicket:id="myForm" id="myForm3">'
Any idea how to fix this and/or how to test such an input component the right way?
OK, in detail the solution now looks like this:
public FormTester createFormTester(Component c) {
final WicketTester wicketTester = new WicketTester();
final FormPage page = new FormPage(c);
wicketTester.startPage(page);
return wicketTester.newFormTester(page.getPathToForm());
}
private static class FormPage extends WebPage implements IMarkupResourceStreamProvider {
private final Form<Void> form;
private final Component c;
private FormPage(final Component c) {
this.c = c;
add(form = new Form<>("form"));
form.add(c);
}
public String getPathToForm() {
return form.getPageRelativePath();
}
#Override
public IResourceStream getMarkupResourceStream(MarkupContainer container, Class<?> containerClass) {
return new StringResourceStream(
"<html><body>"
+ "<form wicket:id='" + form.getId() + "'><span wicket:id='" + c.getId() + "'/></form>"
+ "</body></html>");
}
}
I believe startComponentInPage uses a <span> for its component. Wicket checks that Forms are attached to <form> tags which is why you get this error.
You need to create your own test page with a <form> inside it. See org.apache.wicket.markup.html.form.NumberTextFieldTest for an example of inline markup. Otherwise, create a Form test page class with associated html markup file.

Get and Set attribute values of a class using aspectJ

I am using aspectj to add some field to a existing class and annotate it also.
I am using load time weaving .
Example :- I have a Class customer in which i am adding 3 string attributes. But my issues is that I have to set some values and get it also before my business call.
I am trying the below approach.
In my aj file i have added the below, my problem is in the Around pointcut , how do i get the attribute and set the attribute.
public String net.customers.PersonCustomer.getOfflineRiskCategory() {
return OfflineRiskCategory;
}
public void net.customers.PersonCustomer.setOfflineRiskCategory(String offlineRiskCategory) {
OfflineRiskCategory = offlineRiskCategory;
}
public String net.customers.PersonCustomer.getOnlineRiskCategory() {
return OnlineRiskCategory;
}
public void net.customers.PersonCustomer.setOnlineRiskCategory(String onlineRiskCategory) {
OnlineRiskCategory = onlineRiskCategory;
}
public String net.customers.PersonCustomer.getPersonCommercialStatus() {
return PersonCommercialStatus;
}
public void net.customers.PersonCustomer.setPersonCommercialStatus(String personCommercialStatus) {
PersonCommercialStatus = personCommercialStatus;
}
#Around("execution(* net.xxx.xxx.xxx.DataMigration.populateMap(..))")
public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
Object arguments[] = joinPoint.getArgs();
if (arguments != null) {
HashMap<String, String> hMap = (HashMap) arguments[0];
PersonCustomer cus = (PersonCustomer) arguments[1];
return joinPoint.proceed();
}
If anyone has ideas please let me know.
regards,
FT
First suggestion, I would avoid mixing code-style aspectj with annotation-style. Ie- instead of #Around, use around.
Second, instead of getting the arguments from the joinPoint, you should bind them in the pointcut:
Object around(Map map, PersonCustomer cust) :
execution(* net.xxx.xxx.xxx.DataMigration.populateMap(Map, PersonCustomer) && args(map, cust) {
...
return proceed(map, cust);
}
Now, to answer your question: you also need to use intertype declarations to add new fields to your class, so do something like this:
private String net.customers.PersonCustomer.OfflineRiskCategory;
private String net.customers.PersonCustomer.OnlineRiskCategory;
private String net.customers.PersonCustomer.PersonCommercialStatus;
Note that the private keyword here means private to the aspect, not to the class that you declare it on.

GWT JSNI call Java instance method from nested Javascript funcion

I have a simple wrapper around a WYSIWYG editor (TinyMCE). I'm using JSNI to call a Java instance method (onClick) from Javascript. However the Java onClick method always gets called on the same Java instance (the last one created), no matter the editor that originated it.
private SimplePanel panel;
private TextArea ta;
private String id;
public TinyMCE(AbstractTinyMCEConfiguration config) {
id = HTMLPanel.createUniqueId();
ta = new TextArea();
ta.getElement().setId(id);
panel = new SimplePanel();
panel.add(ta);
initWidget(panel);
init(config);
}
protected native void init(AbstractTinyMCEConfiguration conf) /*-{
var ins = this;
$wnd.tinyMCE.init({
// General options
mode : conf.#com.chip.tinymce.client.AbstractTinyMCEConfiguration::getMode()(),
setup : function(ed) {
ed.onClick.add(function(ed,e) {
alert(ed.id);
ins.#com.chip.tinymce.client.TinyMCE::onClick(Lcom/google/gwt/dom/client/NativeEvent;)(e);
});
}
});
}-*/;
private void onClick(NativeEvent e) {
GWT.log("onClick " + id);
ClickEvent.fireNativeEvent(e, this);
}
I'm not sure if I can call a Java method from a Javascript funcion that is inside another funcion. Maybe that explains my problem... or maybe I'm missing something. Thanks for your help.
I think TinyMCE has one shared configuration for all editors, and that is the problem here.
It probably does not make much sense to hand the configuration to the constructor if it is shared...
Why not add a static map that maps the id back to the Java instance, something like
// ....
private static Map<String, TinyMCE> idMap = new HashMap<String, TinyMCE>();
public TinyMCE() {
// ...
idMap.put(id, this);
}
// call this from Javascript with (ed.id, e)
private static void onClick(String id, NativeEvent e) {
idMap.get(id).onClick(e);
}

Satisfy Imports in custom ExportProvider

I'd like to know how I can have Imports in my custom ExportProvider. Here's an example of what I'm trying to do:
public class MyExportProvider : ExportProvider
{
private List<Export> _exports;
[Import()]
private IConfig _config;
public MyExportProvider()
base()
{
_exports = new List<Export>();
}
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition,
AtomicComposition composition)
{
if (!_exports.Any())
Initialize();
return _exports.Where(x => definition.IsConstraintSatisfiedBy(s.Definition);
}
private void Initialize()
{
var contractName = typeof(MyObject).FullName;
var exportDefinition = new ExportDefinition(contractName, null);
var export = new Export(exportDefinition, () => new MyObject(_config));
_exports.Add(export);
}
}
I am adding the provider when I create the CompositionContainer.
Unfortunately, the import is never satisfied. I can see this by setting AllowDefaults = true so my provider is created, but _config is always null.
How can I configure the container and/or provider so the Import will be satisfied?
When you are adding your export provider you are still creating your composition container. Thus I don't see how you can use the not yet created composition container to import parts of your custom export provider.
What I would do is first create a temporary CompositionContainer that will be used to create MyExportProvider.
Afterwards use the MyExportProvider to create your second final CompositionContainer that will be used by the rest of the application.
EDIT:
// this is your real container, only shown here for reference
CompositionContainer container;
public void BootstrapContainerMethod()
{
// Replace this part with the catalogs required to create your export provider.
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new DirectoryCatalog("./bin", "*.dll"));
// Your temporary container, declared here in local scope
// will be disposed because of using
using (var bootstrapContainer = new CompositionContainer(catalog))
{
var myExportProvider = bootstrapContainer.GetExportedValue<IMyExportProvider>();
// create your real container and optionnally add catalogs (not shown here)
container = new CompositionContainer(myExportProvider);
}
}
You might also consider the problem from another angle. Do you really need to have imports in your custom ExportProvider? I do not know your requirements, but maybe you can make do without having imports.
As an alternative to the dual CompositionContainer solution, you could wire this up in a single export provider, and have it compose itself using the same container. As an example, I've defined the following contract and it's export:
public interface ILogger
{
void Log(string message);
}
[Export(typeof(ILogger))]
public class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
And with my example ExportProvider, I expect to be able to import an instance of it:
public class TestExportProvider : ExportProvider
{
private readonly object _lock = new object();
private bool _initialised;
[Import]
public ILogger Logger { get; set; }
public void SetCompositionService(ICompositionService service)
{
if (service == null) throw new ArgumentNullException("service");
lock (_lock)
{
if (!_initialised)
{
InitialiseProvider(service);
}
}
}
private void InitialiseProvider(ICompositionService service)
{
service.SatisfyImportsOnce(this);
_initialised = true;
}
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
{
if (_initialised)
{
Logger.Log("Getting available exports for '" + definition.ContractName + "'");
// Do work here.);
return Enumerable.Empty<Export>();
}
return Enumerable.Empty<Export>();
}
}
I provide an instance of an ICompositionService, which CompositionContainer implements, and I perform a first-time initialisation when I call SetCompositionService. It checks to see if it has already been initialised, and if not, goes ahead and calls the SatisfyImportsOnce method on itself.
We would wire this up, something like this:
// Build our catalog.
var catalog = new AssemblyCatalog(typeof(Program).Assembly);
// Create our provider.
var provider = new TestExportProvider();
// Create our container.
var container = new CompositionContainer(catalog, provider);
// Register the composition service to satisfy it's own imports.
provider.SetCompositionService(container);
Obviously you wouldn't be able to use any imports and your ExportProvider will explicitly create for you, but for everything else, it should work.