I started working on a Micronaut 2.57 application with Thymeleaf 3.0.12 and micronaut-views-thymeleaf 2.21 that can present some views. According to the Thymeleaf docs, I should have the #request object but I think I always get null.
The thymeleaf template looks like:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home</title>
</head>
<body>
<h3>#request.contextPath</h3>
<span th:utext="${#request.contextPath}"></span>
<h3>#request.requestURI</h3>
<span th:utext="${#request.requestURI}"></span>
<h3>#request.requestURL</h3>
<span th:utext="${#request.requestURL}"></span>
</body>
</html>
The controller to present the view:
import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.views.View;
#Controller
public class HomeController {
#View("home2")
#Get("/")
public HttpResponse<Object> showHome() {
return HttpResponse.ok();
}
}
After starting the application and browsing to localhost:8080, I receive the following stacktrace which indicates that the #request does not exist
17:52:57.326 [main] INFO io.micronaut.runtime.Micronaut - Startup completed in 2231ms. Server Running: http://localhost:8080
17:53:06.644 [io-executor-thread-1] ERROR org.thymeleaf.TemplateEngine - [THYMELEAF][io-executor-thread-1] Exception processing template "home2": Exception evaluating OGNL expression: "#request.contextPath" (template: "home2" - line 8, col 7)
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating OGNL expression: "#request.contextPath" (template: "home2" - line 8, col 7)
at org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator.evaluate(OGNLVariableExpressionEvaluator.java:191)
at org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator.evaluate(OGNLVariableExpressionEvaluator.java:95)
at org.thymeleaf.standard.expression.VariableExpression.executeVariableExpression(VariableExpression.java:166)
at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:66)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:109)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:138)
at org.thymeleaf.standard.processor.StandardUtextTagProcessor.doProcess(StandardUtextTagProcessor.java:87)
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74)
at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95)
at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633)
at org.thymeleaf.engine.ProcessorTemplateHandler.handleOpenElement(ProcessorTemplateHandler.java:1314)
at org.thymeleaf.engine.OpenElementTag.beHandled(OpenElementTag.java:205)
at org.thymeleaf.engine.TemplateModel.process(TemplateModel.java:136)
at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:661)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1067)
at io.micronaut.views.thymeleaf.ThymeleafViewsRenderer.render(ThymeleafViewsRenderer.java:109)
at io.micronaut.views.thymeleaf.ThymeleafViewsRenderer.lambda$render$1(ThymeleafViewsRenderer.java:96)
at io.micronaut.core.io.Writable.writeTo(Writable.java:77)
at io.micronaut.http.server.netty.RoutingInBoundHandler.lambda$encodeHttpResponse$7(RoutingInBoundHandler.java:1683)
at io.micronaut.scheduling.instrument.InvocationInstrumenterWrappedRunnable.run(InvocationInstrumenterWrappedRunnable.java:47)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: ognl.OgnlException: source is null for getProperty(null, "contextPath")
at ognl.OgnlRuntime.getProperty(OgnlRuntime.java:3229)
at ognl.ASTProperty.getValueBody(ASTProperty.java:114)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.ASTChain.getValueBody(ASTChain.java:141)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.Ognl.getValue(Ognl.java:537)
at ognl.Ognl.getValue(Ognl.java:501)
at org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator.executeExpression(OGNLVariableExpressionEvaluator.java:328)
at org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator.evaluate(OGNLVariableExpressionEvaluator.java:170)
... 23 common frames omitted
Does anyone know why this variable might not be passed to the template?
Other variables that I've tested:
#locale - works
#ctx - works
#request - always null
#response - always null
#session - always null
#servletContext - always null
The io.micronaut.views.thymeleaf.ThymeleafViewsRenderer passes a WebContext to the engine it's rendering, so I'm clueless why these objects are not accessible.
Any pointers are appreciated.
EDIT: I've debugged somewhat further and this is the list of keys that the contextVariableMap contains: [ctx, root, vars, object, locale, request, response, session, servletContext, conversions, uris, calendars, dates, bools, numbers, objects, strings, arrays, lists, sets, maps, aggregates, messages, ids, execInfo, httpServletRequest, httpSession] but the servletContext,httpServletRequest, request are all null.
Second edit: looking even deeper I stumbled across
if (REQUEST_EXPRESSION_OBJECT_NAME.equals(expressionObjectName)) {
if (context instanceof IWebContext) {
return ((IWebContext) context).getRequest();
}
return null;
}
in the org.thymeleaf.standard.expression.StandardExpressionObjectFactory. The passed context is of type WebEngineContext, which should implement IWebContext but the instanceof evaluation is false...
Diving even deeper now.
Looking into the creation of the WebEngineContext I stumble on this class: o.micronaut.views.thymeleaf.WebEngineContext which is defined as public class WebEngineContext extends EngineContext. This is different from the org.thymeleaf.context.WebEngineContext that implements the interface to resolve #request.
It turns out that there is a incompatibility with Micronaut and the Thymeleaf Servlet objects. I've reported the issue https://github.com/micronaut-projects/micronaut-views/issues/241 and we'll see from there.
At the moment you can use #ctx.getRequest() to get the instance of the io.micronaut.http.server.netty.NettyHttpRequest.
The other objects are still a mystery for me too.
Related
I'm trying to use the following template (TestTemplate) in a console application using .NET Core 2.1 and Handlebars.Net 1.9.5
<html>
<head>
<title>A title</title>
</head>
<body>
{{ > (lookup TemplateName)}}
</body>
</html>
So the line with {{ > (lookup TemplateName)}} is causing me problems.
The idea is to use a partial, where the partial name will be resolved later by passing the TemplateName variable.
However, when I try to compile the template by using
var foo = Resource1.TestTemplate;
Handlebars.Compile(Encoding.UTF8.GetString(foo));
I get the following exception :
System.ArgumentException: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
at System.Reflection.RuntimeMethodInfo.CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags)
at HandlebarsDotNet.Compiler.SubExpressionVisitor.GetHelperDelegateFromMethodCallExpression(MethodCallExpression helperCall)
at HandlebarsDotNet.Compiler.SubExpressionVisitor.VisitSubExpression(SubExpressionExpression subex)
at System.Linq.Expressions.ExpressionVisitor.VisitUnary(UnaryExpression node)
at System.Linq.Expressions.UnaryExpression.Accept(ExpressionVisitor visitor)
at System.Dynamic.Utils.ExpressionVisitorUtils.VisitArguments(ExpressionVisitor visitor, IArgumentProvider nodes)
at System.Linq.Expressions.ExpressionVisitor.VisitMethodCall(MethodCallExpression node)
at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.VisitUnary(UnaryExpression node)
at System.Linq.Expressions.UnaryExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.VisitConditional(ConditionalExpression node)
at System.Linq.Expressions.ConditionalExpression.Accept(ExpressionVisitor visitor)
at System.Dynamic.Utils.ExpressionVisitorUtils.VisitBlockExpressions(ExpressionVisitor visitor, BlockExpression block)
at System.Linq.Expressions.ExpressionVisitor.VisitBlock(BlockExpression node)
at System.Linq.Expressions.BlockExpression.Accept(ExpressionVisitor visitor)
at HandlebarsDotNet.Compiler.FunctionBuilder.Compile(IEnumerable1 expressions, Expression parentContext, String templatePath) --- End of inner exception stack trace --- at HandlebarsDotNet.Compiler.FunctionBuilder.Compile(IEnumerable1 expressions, Expression parentContext, String templatePath)
at HandlebarsDotNet.Compiler.FunctionBuilder.Compile(IEnumerable1 expressions, String templatePath) --- End of inner exception stack trace --- at HandlebarsDotNet.Compiler.FunctionBuilder.Compile(IEnumerable1 expressions, String templatePath)
at HandlebarsDotNet.Handlebars.HandlebarsEnvironment.Compile(String template)
I hope someone has an idea, because I've already been searching quite some time.
Ok I totally missed that I was looking at the HandleBars.js documentation.
In HandleBars.js the lookup helper is built-in, but so far, it isn't in the .net version.
So you have to declare the lookup helper yourself, which in my case goes something like this:
Handlebars.RegisterHelper("lookup", (output, context, arguments) => { output.WriteSafeString(arguments[0]); });
Hope it can help someone else.
Using JSF 2 on JBoss AS 7
Getting the following error:
07:36:39,579 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (http-/172.20.91.126:12580-16)
Error Rendering View[/views/afgarendesok.xhtml]:
com.sun.faces.mgbean.ManagedBeanCreationException:
Unable to set property searchManager for managed bean afgArendeBacking
at com.sun.faces.mgbean.ManagedBeanBuilder$BakedBeanProperty.set(ManagedBeanBuilder.java:615)
The searchManager property is defined in the AfgArendeBacking class as:
#ManagedProperty(value="#{afgArendeSokManager}")
private AfgArendeSokManager searchManager;
#Override
public AfgArendeSokManager getSearchManager() {
return searchManager;
}
public void setSearchManager(AfgArendeSokManager searchManager) {
this.searchManager = searchManager;
}
The AfgArendeSokManager is a #ManagedBean that is #SessionScoped.
Two things I don't get. One is why the error shuts down all usage of JSF not just for the session producing the error. The error seems to appear after non-usage both below the default session timeout and beyond. The other odd this is that a null pointer exception at line 606 in the BakedBeanProperty has to be the one the writeMethod variable. That variable is created via the PropertyDescriptor.getWriteMethod() call. This should have bombed earlier when creating baked bean (i.e. bakeBeanProperty method).
Any ideas how to debug? The property "searchManager" is resolved correctly since we can use the JSF views normally (both the getter/setter exist).
The search manager is our session scratch pad for propagating stuff between view and request scoped backing beans.
The article explains the issue of using reflection to access methods with covariant return types (see here: https://dzone.com/articles/covariant-return-type-abyssal). The article relates to Java 6 but the background information is very useful.
The issue you're facing and that hit us just this week (using Java 1.7.0_40) is not one of EL but of the java.beans.Introspector.
I have a question concerning an Error I experience while trying to read an XML-File through the XNA 4.0 Content Pipeline in order to build Objects. First I reused old XNA 3.1 Code of mine which worked back in the day but now throws the an Error Message:
Building content threw InvalidOperationException: Instanzen von abstrakten Klassen können nicht erstellt werden. (Unable to build Instances of abstract Classes - roughly translated)
at ReflectionEmitUtils()
...and goes on forever, I can post it, if it's needed, but for better readability of my initial request..
Then I used this Method but it throws the same error.
These are the relevant pieces of source code:
I've written a class to define the content/structure of the XML-File:
public class Command
{
public List<bool> mButtons;
public List<Keys> keys;
public Enum iD;
}
And this is my XML File, with which I want to build Command-Objects
<?xml version="1.0" encoding="utf-8" ?>
<XnaContent>
<Asset Type="KinectRTS_Input.Command">
<mButtons>true/mButtons>
<keys>
<Item>LeftControl/Item>
</keys>
<iD>SMulti/iD>
</Asset>
</XnaContent>
(In my code, the Brackets are all correct, though since this Form processes XML-Tags...;))
I used a Test-Application in order to find out, which Format the XNA-Serializer uses to output List-Items and enums, so I'm reasonably sure, that there's not the error.
It looks like either your XML is invalid or your Model is. For the mButtons field, you have defined it as a List<bool> but in the XML it's a bool not a List<bool>. I would either edit the XML to have the <mButtons> element contain a single <Item> element or change the declaration of mButtons in the Model to be a bool not List<bool>.
Too easy...the problem wasn't with the Lists, in fact the Test-Application mentioned in my request actually returned XML-Tags with Item-Tags for the keys-List and without Item-Tags for the bool-list. Wrapping the bool into Item-Tags resulted in an " at not expected"-Error. I have no idea, why the Serializer handles List and List differently, though.
The problem was the Enum 'iD', which is an abstract class and thus throws the Error mentiones above. It seems that I was overwhelmed by the sheer size of the error-message and just disregarded the crucial bit of info - that the Serializer tries to build an abstract class.
But thanks anyway. – Kuroni Kaimei
When I access a JPA managed date value from JSF, it comes back with an javax.faces.component.UdateModelException saying
'Cannot convert 01.01.10 00:00 of type class java.util.Date to class org.apache.openjpa.util.java$util$Date$proxy
Using a JPA-managed date value (which means it is proxied) works fine when it is used directly from the EL likes this:
'<h:outputLabel value="MyDateValue" for="input"/>
'<h:inputText id="inputDate" value="#{bean.myDate}"/>
However, it causes trouble when trying to use it with composite components
and gives back the following converter exception and thus can't update the model...
The (simplified) JSF composite component inputDate.xhtml
<head>
<title>A date input field</title>
</head>
<composite:interface>
<composite:attribute name="dateValue"/>
</composite:interface>
<composite:implementation>
<h:outputLabel value="MyDateValue" for="input"/>
<h:inputText id="input" value="#{cc.attrs.dateValue}"/>
</composite:implementation>
Assumption:
It seems the proxy replacement in OpenJPA is handled differently when the value is being accessed from inside a composite. My guess is the EL-resolver handles calls to object values differently when it is passed to composites. Passing it to composites means it is first accessed within the composite, which is too late and the required replacement of the proxy is not accomplished (thus the converter exception)
So I tried to change the Expression Language for MyFaces, but it didn't work in Websphere, even though I changed the class loading to parent last and provided el-impl and el-api from glassfish in the lib folder and inserted the necessary context-param for MyFaces
How do you guys use JPA-managed dates (or other proxied entities) in composite components???
If you are using the sun EL implementation you might use the following ELResolver which works around this issue:
public class BugfixELResolver extends ELResolver {
//...
#Override
public Class<?> getType(ELContext anElContext, Object aBase, Object aProperty) {
if (aBase.getClass().getCanonicalName().equals("com.sun.faces.el.CompositeComponentAttributesELResolver.ExpressionEvalMap")){
Object tempProperty=((Map)aBase).get(aProperty);
if (tempProperty!=null&&tempProperty.getClass().getCanonicalName().equals("org.apache.openjpa.util.java.util.Date.proxy")) {
anElContext.setPropertyResolved(true);
return java.util.Date.class;
}
}
return null;
}
}
Add it to the faces-config this way:
<el-resolver>
xxx.BugfixELResolver
</el-resolver>
This workaround can also be used in environments where you can not change the EL implementation (like websphere etc.).
Here is the workaround. The problem seems to be WebSpheres' ExpressionLanguage Implementation or rather the order resolvers are executed. Registering the JBoss EL implementation works and resolves the date proxies before calling the composite component. I also tried the Glassfish EL, but it didn't work either...
Registering a alternative EL is quite strange: The setting in web.xml for MyFaces is
<context-param>
<param-name>org.apache.myfaces.EXPRESSION_FACTORY</param-name>
<param-value>org.jboss.el.ExpressionFactoryImpl</param-value>
</context-param>
Additionally under WebContent/META-INF/services/ a file named javax.el.expressionFactory is needed with this single line org.jboss.el.ExpressionFactoryImpl. The class comes from jboss-el-2.0.2.CR1.jar
(sorry, couldn't find the link to a maven repo)
I will keep you updated once I find a better solution...
I try to execute raw SQL in Grails with this code:
class PlainSqlService {
def dataSource // the Spring-Bean "dataSource" is auto-injected
def newNum = {
def sql = new Sql(dataSource) // Create a new instance of groovy.sql.Sql with the DB of the Grails app
def q = "SELECT a.xaction_id, a.xdin FROM actions a WHERE a.is_approved = 0"
def result = sql.rows(q) // Perform the query
return result
}
}
But I get this exception at runtime.
sql object is not null!
How can I debug it?
2011-02-13 15:55:27,507 [http-8080-1] ERROR errors.GrailsExceptionResolver - Exception occurred when processing request: [GET] /moderator/login/index
Stacktrace follows:
java.lang.NullPointerException
at moderator.PlainSqlService$_closure1.doCall(PlainSqlService.groovy:17)
at moderator.PlainSqlService$_closure1.doCall(PlainSqlService.groovy)
at moderator.LoginController$_closure1.doCall(LoginController.groovy:29)
at moderator.LoginController$_closure1.doCall(LoginController.groovy)
at java.lang.Thread.run(Thread.java:662)
It's hard to tell what's going on from the limited code you're providing, but there are some things to check. Is the service injected into the controller with a class-scope field "def plainSqlService" like you have here for the dataSource, or are you calling new PlainSqlService()? If you're creating a new instance then the dataSource bean won't be injected and the groovy.sql.Sql constructor won't fail, but queries will.
One thing to try is grails clean - whenever something like this that should work doesn't, a full recompile often helps.
One important but unrelated point - you should never use Closures in services. Controllers and taglibs require that actions and tags be implemented with a Closure, but a Service is just a Spring bean defined in Groovy. Spring knows nothing about Closures and since they're just a field that Groovy executes as if it were a method, any proxying that you're expecting from Spring (in particular transactional behavior, but also security and other features) will not happen since Spring only looks for methods.
So newNum should be declared as:
def newNum() {
...
}