I couldn't see any thing.Here is my ManagedBean;
public class AralikKontrolEvent {
private String sayi;
private String mesaj="";
public String getMesaj() {
return mesaj;
}
public void setMesaj(String mesaj) {
this.mesaj = mesaj;
}
public String getSayi() {
return sayi;
}
public void setSayi(String sayi) {
this.sayi = sayi;
}
public void SayiKontrolEt(ActionEvent event){
int a = Integer.parseInt(sayi);
if(event.getComponent().getId().equals("gonder")){
if(a>10){
mesaj+="Sayı büyük";
}else{
mesaj+="Sayı küçük";
}
}
}
I called SayiKontrolEt method like below;
< h : commandButton value="Gönder" id="gonder" action="#{ake.SayiKontrolEt}"/>
But I get this error.I have looked lots of examples about jsf event.Everybody calls like I have called the method.What is the wrong which I haven't seen?
You have two options:
Remove ActionEvent from the method
Or change action to actionListener
Remove the ActionEvent argument from the method.
Related
I am trying to deserialize a simple xml with pojo but getting error as below:
Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of classname (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('checka')
at [Source: (com.ctc.wstx.sr.ValidatingStreamReader); line: 3, column: 15] (through reference chain: classname["testData"]->java.util.ArrayList[0])
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
<tc>
<testData>
<post>checka</post>
<xtenantid>netwebshopa</xtenantid>
<jsonbody>Testa</jsonbody>
</testData>
<testData>
<post>check</post>
<xtenantid>netwebshop</xtenantid>
<jsonbody>Test</jsonbody>
</testData>
#JacksonXmlRootElement(localName = "tc")
public class TC {
private List<TestData> testData;
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
public class TestData {
private String post;
private String xtenantid;
private String jsonbody;
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
public String getXtenantid() {
return xtenantid;
}
public void setXtenantid(String xtenantid) {
this.xtenantid = xtenantid;
}
public String getJsonbody() {
return jsonbody;
}
public void setJsonbody(String jsonbody) {
this.jsonbody = jsonbody;
}
}
You need a constructor with all parameters:
public class TestData(String post, String xtenantid, String jsonbody) {
this.post= post;
this.xtenantid= xtenantid;
this.jsonbody= jsonbody;
If you try to deserialize the class. You get something like this.
<tc>
<testData>
<testData>
<post>checka2</post>
<xtenantid>netwebshopa2</xtenantid>
<jsonbody>Testa2</jsonbody>
</testData>
<testData>
<post>checka1</post>
<xtenantid>netwebshopa1</xtenantid>
<jsonbody>Testa1</jsonbody>
</testData>
</testData>
The TestData class is duplicated because jackson uses elementWrapper by default.
To remove it, you must use #JacksonXmlElementWrapper(useWrapping = false).
The result should look like this.
public class ParrentXml {
#JacksonXmlElementWrapper(useWrapping = false)
List<ChildXml> childxmls = new ArrayList<>();
public List<ChildXml> getChildxmls() {
return childxmls;
}
public void setChildxmls(List<ChildXml> childxmls) {
this.childxmls = childxmls;
}
}
Can someone help me to convert the below line of code from StructureMap 2.6 to Structure Map 4.6
public class EventAggregatorInterceptor : TypeInterceptor
{
public object Process(object target, IContext context)
{
IEventPublisher eventPublisher = context.GetInstance<IEventPublisher>();
eventPublisher.RegisterHandlers(target);
return target;
}
public bool MatchesType(Type type)
{
bool matchesType = type.ImplementsInterfaceTemplate(typeof(IEventHandler<>));
return matchesType;
}
}
I will appreciate any help
I got it working, below is the code
public class EventListenerRegistration : IInterceptorPolicy
{
public string Description
{
get
{
return "Adds the constructed object to the EventAggregator";
}
}
public IEnumerable<IInterceptor> DetermineInterceptors(Type pluginType, Instance instance)
{
if (instance.ReturnedType.FindInterfacesThatClose(typeof(IEventHandler<>)).Any())
{
Expression<Action<IContext, object>> register = (c, o) => c.GetInstance<IEventPublisher>().RegisterHandlers(o);
yield return new ActivatorInterceptor<object>(register);
}
}
}
And then I register it inside my Registry constructor
Policies.Interceptors(new EventListenerRegistration());
I was trying to map ResultSet data to an object and returning it. Here is how i'm mapping data to an object. Now i'm having only 7 columns in resultset so this is working fine but what if i'm having 20 or 30 columns. How can i map dynamically those columns.
public class ProductsWrapperMapper implements ResultSetMapper<ProductsWrapper> {
public ProductsWrapper map(int i, ResultSet resultSet,
StatementContext statementContext) throws SQLException {
ProductsWrapper product = new ProductsWrapper();
if ((isColumnPresent(resultSet,"a_productid"))) {
product.setId(resultSet.getInt("a_productid"));
}
if ((isColumnPresent(resultSet,"a_productname"))) {
product.setProductName(resultSet.getString("a_productname"));
}
if ((isColumnPresent(resultSet,"a_productlink"))) {
product.setLink(resultSet.getString("a_productlink"));
}
if ((isColumnPresent(resultSet,"a_productimagelink"))) {
product.setImageLink(resultSet.getString("a_productimagelink"));
}
if ((isColumnPresent(resultSet,"a_websiteid"))) {
product.setWebsiteId(resultSet.getInt("a_websiteid"));
}
if ((isColumnPresent(resultSet,"a_productidentification"))) {
product.setProductIdentification(resultSet
.getString("a_productidentification"));
}
if ((isColumnPresent(resultSet,"a_adddate"))) {
product.setAddDate(resultSet.getString("a_adddate"));
}
return product;
}
public boolean isColumnPresent(ResultSet resultSet,String column) {
try {
#SuppressWarnings("unused")
int index = resultSet.findColumn(column);
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
return false;
}
}
}
Below one is my class which i was returning the object from mapper class above.
#JsonInclude(Include.NON_NULL)
public class ProductsWrapper {
private int id;
private String productName;
private String link;
private String imageLink;
private int websiteId;
private String productIdentification;
private String addDate;
int getWebsiteId() {
return websiteId;
}
public void setWebsiteId(int websiteId) {
this.websiteId = websiteId;
}
public String getProductIdentification() {
return productIdentification;
}
public void setProductIdentification(String productIdentification) {
this.productIdentification = productIdentification;
}
public String getAddDate() {
return addDate;
}
public void setAddDate(String addDate) {
this.addDate = addDate;
}`enter code here`
public ProductsWrapper(int id) {
this.setId(id);
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getImageLink() {
return imageLink;
}
public void setImageLink(String imageLink) {
this.imageLink = imageLink;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
You can also try Jdbi-folder. It automatically takes care of dynamic bynding and also it provides one to many mapping relationship.
You can add Rosetta as a mapper for your JDBI result sets (it also works for bindings). Have a look at the advanced features to map column names with underscores to snake snake case java names.
Beware that there is no warning message if Rosetta is unable to map a value: any missed property in the target bean will just be empty. I found that my database returned column names in capital letters, therefore the LowerCaseWithUnderscoresStrategy in the example didn't work for me. I created a UpperCaseWithUnderscoresStrategy.
To skip writing getters and setters in ProductsWrapper have a look at Lombok's #Data annotation.
Consider below action class with three action mappings. Two of them are annotated with a custom annotation #AjaxAction
public class MyAction extends ActionSupport{
#Action("action1")
#AjaxAction //My custom anotation
public String action1(){
}
#Action("action2")
public String action2(){
}
#Action("action3")
#AjaxAction //My custom anotation
public String action3(){
}
}
In an interceptor I want to access the #AjaxAction annotation. Is there any built in support for this?!
If not can I shall read the action name with ActionContext.getContext().getName(); and save a list of ajaxAction names in interceptor as an array and compare action name with this array! any better way?!
private static final String[] AJAX_ACTIONS = new String[] {"action1", "action3"}
//in interceptor
String actionName = ActionContext.getContext().getName();
if (Arrays.asList(AJAX_ACTIONS).contains(actionName)) {
// do something
}
Here is the way
import java.lang.reflect.Method;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class YourInterceptor implements Interceptor {
#Override
public String intercept(ActionInvocation inv) throws Exception {
Class myActionClass = inv.getAction().getClass();
for (Method method : myActionClass.getMethods())
{
if(method.isAnnotationPresent(AjaxAction.class))
{
// do something
}
}
return inv.invoke();
}
}
Alternative is
import com.opensymphony.xwork2.util.AnnotationUtils;
import java.lang.reflect.Method;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class YourInterceptor implements Interceptor {
#Override
public String intercept(ActionInvocation inv) throws Exception {
AnnotationUtils myutil = new AnnotationUtils();
Class myActionClass = inv.getAction().getClass();
for (Method method : myActionClass.getMethods())
{
if(myutil.getAnnotatedMethods(myActionClass, AjaxAction.class).contains(method))
{
// do something
}
}
return inv.invoke();
}
}
Edit :
To find exact executed method.
Note: Change Namespace="/" as per your configuration in struts.xml.
import org.apache.struts2.dispatcher.Dispatcher;
ActionContext context = inv.getInvocationContext();
String executedAction=context.getName();
String executedMethod=Dispatcher.getInstance().getConfigurationManager().getConfiguration().getRuntimeConfiguration().getActionConfigs().get("/").get(executedAction).getMethodName();
if(executedMethod==null)
{
executedMethod="execute";
}
for (Method method : myActionClass.getMethods())
{
if(method.getName().equalsIgnoreCase(executedMethod) || method.isAnnotationPresent(Action.class))
{
// do something
}
}
Class myActionClass = inv.getAction().getClass();
for (Method method : myActionClass.getMethods())
{
//check whether called method has annotation?
if(method.getName().equalsIgnoreCase(executedAction) && method.isAnnotationPresent(AjaxAction.class))
{
// do something
}
}
I hope this will work.
Note: This is just a workaround I found. Better way would be possible....
I'm going through the NerDinner free tutorial
http://nerddinnerbook.s3.amazonaws.com/Intro.htm
I got to somewhere in Step 5 where it says to make the code cleaner we can create an extension method. I look at the completed code and it has this to use the extension method:
catch
{
ModelState.AddModelErrors(dinner.GetRuleViolations());
return View(new DinnerFormViewModel(dinner));
}
And then this as the extension method's definition.
namespace NerdDinner.Helpers {
public static class ModelStateHelpers {
public static void AddModelErrors(this ModelStateDictionary modelState, IEnumerable<RuleViolation> errors) {
foreach (RuleViolation issue in errors) {
modelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
}
}
}
I try to follow what the tutorial says combined with what the code contains but receive the expected error that there is no AddModelErrors method that accepts only 1 argument.
I'm obviously missing something very important here. What is it?
You need to include the helpers reference;
using NerdDinner.Helpers;
and
using NerdDinner.Models;
Then check for valid and add the errors;
if (!dinner.IsValid)
{
ModelState.AddModelErrors(dinner.GetRuleViolations());
return View(dinner);
}
You must also have a partial class for your dinner;
public partial class Dinner
{
public bool IsValid
{
get { return (GetRuleViolations().Count() == 0); }
}
public IEnumerable<RuleViolation> GetRuleViolations()
{
if (String.IsNullOrEmpty( SomeField ))
yield return new RuleViolation("Field value text is required", "SomeField");
}
partial void OnValidate(ChangeAction action)
{
if (!IsValid)
throw new ApplicationException("Rule violations prevent saving");
}
}
Don't forget the RuleViolation class;
public class RuleViolation
{
public string ErrorMessage { get; private set; }
public string PropertyName { get; private set; }
public RuleViolation(string errorMessage)
{
ErrorMessage = errorMessage;
}
public RuleViolation(string errorMessage, string propertyName)
{
ErrorMessage = errorMessage;
PropertyName = propertyName;
}
}
If you are receiving the same error message as this poster:
"'System.Web.Mvc.ModelStateDictionary' does not contain a definition for 'AddModelErrors' and no extension method 'AddModelErrors' accepting a first argument of type 'System.Web.Mvc.ModelStateDictionary' could be found (are you missing a using directive or an assembly reference?)"
You may be having this problem:
http://p2p.wrox.com/book-professional-asp-net-mvc-1-0-isbn-978-0-470-38461-9/74321-addmodalerrors-allcountries-page-87-view-data-dictionary.html#post248356