date validation in tapestry server side - java

Im trying to put some validation in the date field. The condition is the effective date field should be less or equal to the current date and it should be 1st of month.
Im doing it in tapestry.The data type is DATE. im using tapestry as yo know you will have .html page a, .java file and .page file. Im doing it in the java file . So please help me on this.

When the form is submitted t5 emits various events during the different stages. On EventConstants.VALIDATE is a good place to perform more complex validations that are not supported by t5 out of the box, or to perform cross-field validation serverside.
#Component
private Form myForm;
...
#OnEvent(value = EventConstants.VALIDATE, component = "myForm")
public void onCreateEditValidate() {
// do validation and if any error record it
myForm.record(theDateField, "Dang, try again!");
...
http://tapestry.apache.org/forms-and-validation.html

You can use the onValidate event too as stated at the end of the link jon martin solas posted.
Something like:
void onValidateFromYouDateFieldId(..) throws ValidationException{
//your custom validations
}
you can check out this example for more information:
http://jumpstart.doublenegative.com.au/jumpstart/examples/input/morevalidation
http://tapestry.apache.org/forms-and-validation.html#FormsandValidation-OverridingtheTranslatorwithEvents

Related

CommandExecuteIn Background throws a "Not an (encodable) value" error

I am currently trying to implement file exports in background so that the user can do some actions while the file is downloading.
I used the apache isis CommandExexuteIn:Background action attribute. However, I got an error
"Not an (encodable) value", this is an error thrown by the ScalarValueRenderer class.
This is how my method looks like:
#Action(semantics = SemanticsOf.SAFE,
command = CommandReification.ENABLED)
commandExecuteIn = CommandExecuteIn.BACKGROUND)
public Blob exportViewAsPdf() {
final Contact contact = this;
final String filename = this.businessName + " Contact Details";
final Map<String, Object> parameters = new HashMap<>();
parameters.put("contact", contact);
final String template = templateLoader.buildFromTemplate(Contact.class, "ContactViewTemplate", parameters);
return pdfExporter.exportAsPdf(filename, template);
}
I think the error has something to do with the command not actually invoking the action but returns the persisted background command.
This implementation actually worked on the method where there is no return type. Did I miss something? Or is there a way to implement background command and get the expected results?
interesting use case, but it's not one I anticipated when that part of the framework was implemented, so I'm not surprised it doesn't work. Obviously the error message you are getting here is pretty obscure, so I've raised a
JIRA ticket to see if we could at least improve that.
I'm interested to know in what user experience you think the framework should provide here?
In the Estatio application that we work on (that has driven out many of the features added to the framework over the last few years) we have a somewhat similar requirement to obtain PDFs from a reporting server (which takes 5 to 10 seconds) and then download them. This is for all the tenants in a shopping centre, so there could be 5 to 50 of these to generate in a single go. The design we went with was to move the rendering into a background command (similar to the templateLoader.buildFromTemplate(...) and pdfExporter.exportAsPdf(...) method calls in your code fragment, and to capture the output as a Document, via the document module. We then use the pdfbox addon to stitch all the document PDFs together as a single downloadable PDF for printing.
Hopefully that gives you some ideas of a different way to support your use case
Thx
Dan

How to handle complexity in jsps

This may be more of a rant than a question that can actually be answered. I'm not sure yet. I suspect it may be a situation that lots of people encounter though so hopefully it's a useful question.
We have jsps that present information that can be in about 40 different statuses. Let's say it's the status of a complicated financial product. So we want to output messages that are dependent on the status, for example status 10 might be "Your product is pending activation" and status 15 might be "Your product is active" and so on.
So it would seem that we could have a simple lookup that returns the appropriate messages depending on the status and it all works neatly.
But in reality, the status alone is not enough to determine the right message. If it's status 10 (pending activation) but it's within 1 week of the activation then we want to color the message red. If it's status 10 (pending activation) but there's an external reason delaying it, we want a message that provides a link to an explanation page. And so on.
So the status by itsef doesn't capture all the information needed to determine and create the message. There are lots of other extraneous pieces of information that are also required.
The way the legacy code works, all these pieces of information are loaded into the jsp, and then the jsp makes determinations based on this non-status information.
Now that we are redoing the site, I'm faced with the situation that we need this same status logic in multiple different places, but outputting different wrapping html.
In short, it's a big mess.
I think the ideal answer would be to refactor things so that all the decisions are taken out of the jsps. Ugh, I'm not sure what the correct way to handle it is. There's a lot of stringy complexity and I'm not sure where to start.
I'm not sure I've given enough detail to even make the problem clear, but if anyone has any advice, I'd be very grateful..
EDIT: Thanks for all your answers! The code is so tangly that I've sort of refactored it a bit by pulling common code into include files, so that I can include those files where they're needed. I'll definitely look at encapsulating things further with functions as you suggest. Will circle back round to your answers soon. Thanks again.
I believe your existing JSPs are using a lot of <% // scriptlets %> to achieve at the final status message. I suggest you write a custom tag that factors all of that Java logic out of the JSP.
Handling message content
Implement the tag so that it takes anything that's required to generate the message (like your Product object itself) as one of its attributes.
WEB-INF/status.tld (Tag library descriptor)
<taglib ... >
<uri>WEB-INF/status.tld</uri>
<tag>
<name>statusMesg</name>
<tag-class>com.foo.StatusMesgTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>product</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>com.foo.beans.Product</type>
</attribute>
</tag>
</taglib>
Implement the Tag class with the Java code that's currently present in your scriptlets.
pubic class StatusMesgTag extends SimpleTagSupport {
private Product product;
public void setProduct(Product product) {
this.product = product;
}
public void doTag() throws JspException, IOException {
StringBuilder statusMesg = new StringBuilder();
// process Product info to generate mesg
getJspContext().getOut().println(statusMesg);
}
}
Then invoke it in your JSP (with the Product object mapped as "product" in any one of your page, request or session scopes) as follows
<custom:statusMesg product="${product}" />
after adding the taglib directive to your JSP
<%# taglib prefix="custom" uri"WEB-INF/status.tld" %>
Handling message rendering (view)
The part where you need to decide the colour the message should be rendered in should be handled with CSS stylesheets. You could have your custom tag determine the message priority and then return your message with an appropriate CSS style class like
<span class="priorityHigh">Needs activation within 1 week</span>
Your CSS would map different priorities to different colours like
.priorityHigh {color: red};
.priorityNormal {color: black};
.priorityLow {color: green};
Create one Util class with a method to receive by parameter the status, date, etc... So the return of the method will be an object with properties for all the info that the jsp will need to render it.
Something like this:
class MyStatusUtil{
public static StatusInfo getStatusInfo(int status, Date date, etc...){
StatusInfo info = new StatusInfo();
if(status==10){
info.setStatusName("....");
}
.....
if(date==....){
info.setColor("...");
}
if(somethinElse){
info.setComment("....");
}
return info;
}
}
StatusInfo class:
class StatusInfo{
private String statusName;
private String color;
private String comment;
}
jsp:
<% StatusInfo info = MyStatusUtil.getStatusInfo(....)
//now render the html based on the StatusInfo data.
%>
Can you use a custom jstl tag with a couple parameters?

Eclipse custom texteditor - marker annotation presentation issue

I want to write an eclipse plugin for my computer science lecturer. It's a custom editor with an xml based file format.
I've implemented syntax highlighting and other stuff. But I stuck when it comes to the usage of annotations/marker to show invalid content.
This is how it looks like, if the content is valid:
image of valid conent http://image-upload.de/image/aPcsaa/6c799a671c.png
This is how it looks like, if the content is invalid:
image of invalid conent http://image-upload.de/image/4TdooQ/04d662f397.png
As you can see, invalid attributes will get marked, but the problem is, the whole formatting seems to be lost between these annotations.
I use org.eclipse.jface.text.reconciler.Reconciler for delayed parsing of the content to create the document model. The model is used to format the text and display annotations. All this happens in the void void process(DirtyRegion dirtyRegion) method of the Reconciler.
For text formatting I use <ITextViewer>.changeTextPresentation(textAttributes, false) and for annotation handling I use
IAnnotationModel annotationModel = <ISourceViewer>.getAnnotationModel();
IAnnotationModelExtension annotationModelExtension = (IAnnotationModelExtension) annotationModel;
annotationModelExtension.replaceAnnotations(oldAnnotations, newAnnotations);
Since the Reconciler does not use the swt thread I have to use this construct to avoid exceptions:
<ITextViewer>.getTextWidget().getDisplay().asyncExec(new Runnable() {
#Override
public void run() {
<ITextViewer>.changeTextPresentation(textAttributes, false);
updateAnnotations(nodes);
}
});
By the way ITextViewer and ISourceViewer are meant as the same viewer object.
As annotation type I've testet: org.eclipse.ui.workbench.texteditor.spelling and some others, also custom types, but all with the same result.
I'm not quite sure, what I do wrong, could it be because it is all in a single call?
I hope someone can help me with this problem.
Thank you in advance.

Wiquery DatePicker displays time, validation fails

I'm having problems with the Wiquery DatePicker in the following code in a Wicket page (using a CompundPropertyModel, the date property is of type java.util.Date):
DatePicker<Date> datePicker = new DatePicker<Date>("date"){
#Override
public boolean isVisible() {
return selectedType.hasDate();
}
};
datePicker.setDateFormat(DateUtil.DATE_PATTERN); // pattern is "dd.MM.yyyy"
form.add(datePicker);
The HTML this is bound to:
<input wicket:id="date" id="date"/>
The problem is that when editing existing data, the input field displays the time along with the date, and when submitting the form, validation fails because this does not fit the pattern.
How can I get the DatePicker to display the current value correctly?
This seems to be a bug in the relatively obscure Wiquery DatePicker component. I've switched to org.apache.wicket.extensions.yui.calendar.DatePicker, which does not have this problem.
Being the DatePicker component a TextField, why not use a custom IConverter in it to return only dd.MM.yyyy in its convertToObject?
I haven't been able to see browsing its sources any registered IConverter or other way to convert input, so this will probably be conflicting with whatever is formatting input in this component.
UPDATE
After debugging this in a quickstart using WiQuery 1.2.4 and Wicket 1.4.17, it shows that the initial value of the DatePicker (which is a TextField) is the standard conversion performed by Component.getDefaultModelObjectAsString().
Since the TextField has a IModel<Date>, it will use whatever IConverter is registered for the Date class. In your case it might be using a custom IConverter that's formatting with the time. I'd try overriding DatePicker's getConverter() and using a SimpleDateFormat that honours the format specified in setDateFormat().
This issue gives a hint on that an IConverter should be specified along with the DatePicker: Issue 168: Invalid (or uncommon) date format for NL in DatePicker
You might also find this discussion on the Wicket users list useful: DatePicker to pick a year. Julien Roche (one of the owners of the project) states there that setDateFormat only works on the client side with JQuery:
I think you have to set the right converter on your wicket textfield (with
the override of the method getConverter and with the class
PatternDateConvert). The "dateFormat" option works only on the client side
with jQuery.
first take a look at https://cwiki.apache.org/WICKET/using-custom-converters.html
then you know that wicket convert you object to a text from that mechanic so.. all you have to do
Override newConverterLocator() method in Application class to provide custom ConverterLocator.
protected IConverterLocator newConverterLocator() {
ConverterLocator converterLocator = new ConverterLocator();
converterLocator.set(Date.class, new DateConverter());
return converterLocator;
}
tip: watch out with java.sql.Date class converter

GAE Arabic Support

using this code i persist data to GAE Store
but when storing Arabic it's format in Store become ?????
how to support persist Arabic Text in GAE ?
the code :
PersistenceManager manager = PMF.get().getPersistenceManager();
Category category = new Category(categoryName);
manager.makePersistent(category);
manager.refresh(category);
manager.close();
It's more likely that the text is corrupted when you submit it from a form, or render it to HTML, rather than when it is stored (or retrieved).
As a quick test, try this:
String test = "\u0627\u0644\u0633\u0644\u0627\u0645";
PersistenceManager manager = PMF.get().getPersistenceManager();
Category category = new Category(test);
manager.makePersistent(category);
manager.refresh(category);
manager.close();
If that displays correctly (السلام), then the problem is with the way the input is handled on its way into the application. If it still appears corrupted, try another test where you retrieve the category name, and within your application, compare it to the original value of test. The test might look something like this:
boolean okay = "\u0627\u0644\u0633\u0644\u0627\u0645".equals(category.getName());
Log (or display) the value of okay. If false, then it really is the persistence layer that can't handle Arabic. Post your findings, and we'll work toward a solution once we are more confident where the problem truly is.
Update: The servlet engine is not guaranteed to recognized the character encoding if you set it via setHeader(). Use the setContentType() method or the setCharacterEncoding() method instead.

Categories

Resources