in metaworks, when I use TreeFace.ejs, Error message 'Please add #Name for the nameField to...' in metaworks3 application - ejs

Eventhough I have added #Name field in the domain class, the error message that the TreeFace.ejs (actually TreeNodeFace.ejs) couldn't find the Name field.

There must be getter and setters, I found i have missed defining the setter in this case:
#Name
#Face(displayName = "name")
public String getDisplayName() {
return displayName
}
after adding setDisplayName(String dispName), the error has been gone.

Related

How to add element to array with Drools (mvel)

I need insert a new value in a exist array with Drools. My example:
rule "insert new address"
dialect "java"
when
$data : Data( source.address != null)
then
Address address = (Address) $data.source.address
System.out.println("Element: "+address );
$data.target.addressList.add(address);
end
The error that happend is this:
Exception executing consequence for rule "insert new address" in rules: [Error: $data.target.addressList.add(address): null]
EDIT: Added the model
public class Data {
private Source source;
private Client target;
}
public class Source {
...
private Address address;
}
public class Client {
...
private List<Address> addressList;
}
In answer to the question in your title, which is how to add an element to array -- the answer is basically "the same way you would in Java."
To answer the question you actually asked, which has no arrays, your error is effectively a NullPointerException, or another indicator that the field cannot be modified (eg an immutable list.)
This:
Error: $data.target.addressList.add(address): null]
Means that either $data.target or $data.target.addressList is null, or possibly $data.target.addressList is an immutable list.
Make sure that whatever "target" is has been initialized, and that its "addressList" is also initialized as a mutable list type.

Play Framework 2.3 How to add unique constraint to sample application

Given the Play Framework 2.3 Computer Database sample application, I would like to practice adding a unique constraint on an attribute. Let's say I want the name attribute of the Computer class to be unique. I've tried to do this by adding a validate() function (and a getter) to Computer.java:
public List<ValidationError> validate() {
List<ValidationError> errors = new ArrayList<ValidationError>();
if(Computer.find.where().eq("name", getName()).findRowCount() != 0){
errors.add(new ValidationError("name", "Name must be unique. That value is already taken."));
}
return errors;
}
public String getName() {
return name;
}
This check works when creating new records in the database, however, this now causes a validation error when you update a Computer object but don't change the name. Is there a way to add a uniqueness constraint, similar to Rails? How can I validate uniqueness in Play?
Thanks!
UPDATE: see the answer by davide.
I ended up using the #Column(unique = true) constraint from the javax.persistence API. This doesn't generate an error in Play forms; instead, it throws a PersistenceException. Therefore I had to add change my controller to achieve the behavior I wanted. Both the create() and update() actions need a try/catch like this:
try {
computerForm.get().save();
} catch (PersistenceException pe) {
flash("error", "Please correct errors below.");
formData.reject("name", "Name conflict. Please choose a different name.");
return badRequest(createForm.render(computerForm));
}
UPDATE 2: each of the answers below is a possible solution
You need to exclude current entity from unique checking, i.e. like that:
if(Computer.find.where().eq("name", getName()).ne("id", getId()).findRowCount() != 0){
errors.add(new ValidationError("name", "Name must be unique."));
}
It will give you SQL query during update:
select count(*) from computer t0 where t0.name = 'Foo' and t0.id <> 123
And this during create:
select count(*) from computer t0 where t0.name = 'Foo' and t0.id is not null
P.S. ne() expression stands for Not Equal To and of course this approach assumes that your name field is Required
Edit: I sent you pull request with working solution, all you need is to add hidden field in your editForm like:
<input name="id" type="hidden" value='#computerForm("id").value'/>
Other thing is that you can simplify your model, i.e. don't need for getters for public fields.
I not sure if this answer your question, because I'm not familiar with Ruby syntax.
To "create a uniqueness constraint in the database" you can use the javax persistence API. Ebean will also recognize this.
To have a plain uniqueness constraint which involves a single field, you can use the #Column annotation:
#Entity
public class Computer extends Model {
...
#Column(unique = true)
public String name;
...
}
If you need some combination of fields to be unique, instead use the
#Table annotation
#Table(
uniqueConstraints=
#UniqueConstraint(columnNames={"name", "brand"})
)
#Entity
public class Computer extends Model {
...
public String name;
public String brand;
...
}
I hope it helps!

GORM - unique constraint seems to be ignored when using mongoDB

Here is the domain class:
class User {
String name
String email
static constraints = {
name()
email(unique: true)
}
}
The email unique property is being ignored when I call save method, and a duplicated records is created. Am I missing something here?
found the solution:
static mapping = {
email index:true, indexAttributes: [unique:true]
}

Define own feedback messages in Wicket

How do I define my own feedback messages in Wicket?
For example: if I give an incorrect username, I want to get an error message like "The user name in incorrect, try to login again." instead of using the default error message.
What would an example be like?
You can display your own error messages using error() and warn() and info(). If you want to show errors dependent on validators or the required flag you can define a properties file with the same name as the class which contains a mapping of field -> message. For example:
Index.java
Form form = new Form("myform");
form.add(new TextField("name").setRequired(true));
form.add(new PasswordTextField("password").setRequired(true));
form.add(new TextField("phonenumber").setRequired(true));
Index.properties
Required=Provide a ${label} or else...
All required fields
myform.name.Required=You have to provide a name
The field name in the form myform when it is required.
password.Required=You have to provide a password
Any field with the name password when it is required.
phonenumber.Required=A telephone number is obligatory.
Any field with the name phonenumber when it is required.
This shows a variety of ways of setting a feedback message for specific components.
You can also put the properties files next to the following component level (in order of importance, top highest):
Page Class
Component Class
Your Application Class
Wickets Application Class
Hope that helps
#user1090145: I've used overloaded Component's error() method in Validator's class:
private void error(IValidatable<String> validatable, String errorKey) {
ValidationError error = new ValidationError();
error.addMessageKey(errorKey);
validatable.error(error);
}
and invoked it in validate() by
error(validatable, "your-form.field.text-id");
Properties your-form.field.text-id must be defined in YourPage.properties
Sources:
Create custom validator in Wicket and
Form validation messages
you should set Feed back message to Session
message = "message";
Session.get().getFeedbackMessages().success(null, message);
You can use an anonymous IValidationError class and the messageSource.getMessage method to get a custom message from your property file:
error(new IValidationError() {
#Override
public Serializable getErrorMessage(IErrorMessageSource messageSource) {
//create a list of the arguments that you will use in your message string
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("invalidUsername", getInvalidUsernameInput());
//get the message string from the property file
return messageSource.getMessage("mysettings.invalid_username", vars);
}
});
Sample property file:
mysettings.invalid_username=The user name "${invalidUsername}" is incorrect.

How to change ErrorMessage property of the DataAnnotation validation in MVC2.0

My task is to change the ErrorMessage property of the DataAnnotation validation attribute in MVC2.0. For example I should be able to pass an ID instead of the actual error message for the Model property and use that ID to retrieve some content(error message) from a another service e.g database, and display that error message in the View instead of the ID. In order to do this I need to set the DataAnnotation validation attribute’s ErrorMessage property.
[StringLength(2, ErrorMessage = "EmailContentID.")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
It seems like an easy task by just overriding the DataAnnotationsModelValidatorProvider ‘s
protected override IEnumerable GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable attributes)
However it seems to be a complicated enough.
a. MVC DatannotationsModelValidator’s ErrorMessage property is read only. So I cannot set anything here
b. System.ComponentModel.DataAnnotationErrorMessage property(get and set) which is already set in MVC DatannotationsModelValidator so we cannot set again. If you try to set you get “The property cannot set more than once…” error message appears.
public class CustomDataAnnotationProvider : DataAnnotationsModelValidatorProvider
{
protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
{
IEnumerable<ModelValidator> validators = base.GetValidators(metadata, context, attributes);
foreach (ValidationAttribute validator in validators.OfType<ValidationAttribute>())
{
messageId = validator.ErrorMessage;
validator.ErrorMessage = "Error string from DB And" + messageId ;
}
//......
}
}
Can anyone please help me on this?
Here is the question: What is your motivation to changing the error message property?
Think this through very carefully, as you are heading down a path where you are obfuscating what is actually happening in the application. Certainly the database informatino is useful, but it is not really part of the validation, nor should it be.
When you head in this direction, you are essentially saying that the validation can only be invalid if there is a database problem. I see two issues with this:
It breaks the separation of concerns. You are reporting a persistance error in the model, which is not where it occurred.
The solution is not unit testable, as you must engage the database.
I don't like either of the two above.
Can you solve this? Possibly if you will create your own custom validation attribute. I would have to check and ensure that is correct. Another option is to aim for custom validation:
http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx
This article can also help you head in the direction you desire:
http://ryanrivest.com/blog/archive/2010/01/15/reusable-validation-error-message-resource-strings-for-dataannotations.aspx
Do you want to solve this? Not really if you are attempting to keep a proper separation of concerns in your application. I would not polute my validation error message (this is not valid) with a database error (I am not valid, but the database also blew up). Just my two cents.
There are built in ways to get the error message via a resource. Instead of a database lookup to get a resource at runtime, generate resources from your database and use that for your error messages.
You can then use the ErrorMessageResourceName and ErrorMessageResourceType to allow the DataAnnotation to perform a resource lookup instead of hard-coding a specific string.
public sealed class MyModel
{
[Required(
ErrorMessageResourceName="MyDescriptionResource",
ErrorMessageResourceType=typeof(MyCustomResource))]
public string Description { get; set; }
}
Also you may want to have a look at ValidationAttribute.FormatErrorMessage Method on msdn.
This method formats an error message
by using the ErrorMessageString
property. This method appends the name
of the data field that triggered the
error to the formatted error message.
You can customize how the error
message is formatted by creating a
derived class that overrides this
method.
A quick sample (and not meant to be a definitive example)
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false,
Inherited = true)]
public sealed class PostCodeValidationAttribute
: ValidationAttribute
{
public override bool IsValid(object value)
{
if( value == null )
return true;
string postCode = value as string;
if( string.IsNullOrEmpty(postCode) )
return true;
if ( !PostCode.IsValidPostCode(postCode, this.PostCodeStyle) )
return false;
return true;
}
public PostCodeStyle PostCodeStyle { get; set; }
public override string FormatErrorMessage(string name)
{
return string.Format(
"{0} is not a valid postcode for {1}", name, PostCodeStyle);
}
}
* I've omitted the PostCodeStyle enumeration as well as the PostCode class for validating a postcode.