In my panel class I have the following code:
private Fragment fileUploadField(String id, UploadFeedbackPanel feedbackPanel, ComponentFeedbackPanel componentFeedbackPanel) {
String uploadType = isJSEnabled ? "multiple" : "single";
Fragment uploadFragment = new Fragment( "uploadContainer", uploadType, this );
if (isJSEnabled) {
multipleUpload = new MultiFileUploadField( id, new PropertyModel<Collection<FileUpload>>( this, "multiUploads" ), MAX_FILES );
uploadFragment.add( multipleUpload = multipleUpload);
multipleUpload.add( newOnChangeAjaxBehavior( feedbackPanel, componentFeedbackPanel ) );
} else {
uploadFragment.add( singleUpload = new FileUploadField( id ) );
singleUpload.add( newOnChangeAjaxBehavior( feedbackPanel, componentFeedbackPanel ) );
}
return uploadFragment;
}
I want to add a label for this field but I'm unable to get the actual input fields ID. You can see this working for the single upload field because the input field itself is render without any surrounding elements. This however doesn't seem to be exposed when using MultiFileUploadField.
An alternative acceptable answer would be using FileUploadField and a collection of files with the multiple=true attribute. However I am unsure how to limit the number of files to be MAX_FILES only.
<label wicket:for="file"><wicket:msg key="file">File:</wicket:msg></label>
<div wicket:id="uploadContainer" class="col-right">[upload fragment shows here]</div>
<wicket:fragment wicket:id="single">
<input wicket:id="file" type="file"/>
</wicket:fragment>
<wicket:fragment wicket:id="multiple">
<div wicket:id="file" class="mfuex"></div>
</wicket:fragment>
Wicket version 6.15.0.
MultiFileUploadField uses JavaScript to generate the input fields: https://github.com/apache/wicket/blob/master/wicket-core/src/main/java/org/apache/wicket/markup/html/form/upload/MultiFileUploadField.js#L91
See whether you can plug there somehow. If you find an elegant way we would be glad to include it in the next version of Wicket!
If you use 'multiple' attribute then check:
How do I limit the number of file upload in html?
Related
I have a jsp page , from which I am getting the list of the checkboxes selected by a user.
And as per the selected checkboxes I want to call my controller using the jQuery.
<input type="checkbox" name="XYZ" value="hello1"/>Hello1<br>
<input type="checkbox" name="XYZ" value="hello2"/>Hello2<br>
I obtained all the values in the jQuery and set all the parameters into a variable as given below.
var allVals = [];
$("input[name=XYZ]:checked").each(function() {
allVals.push($(this).val());
});
and I am using an AUI to call my controller, I am passing the value as parameter.
AUI().use('aui-base',
'aui-io-request',
'liferay-portlet-url',
function(A) {
var A = AUI();
var myResourceURL = Liferay.PortletURL.createResourceURL();
myResourceURL.setResourceId('getABC');
myResourceURL.setParameter("action",'ZYX');
myResourceURL.setPortletId(pid);
myResourceURL.setParameter("list",allVals);
A.io.request(myResourceURL.toString(),
{
method : 'post',
dataType : 'text',
on : {
start : function() {
.
.
.});
And in my controller I want to obtain the list and my controller is like this:
System.out.println(request.getParamter("list"));
This statement is just giving me the first selected element, not the complete list of the elements.
Is there something I am missing , or any other way to do it??
I think you will need to go with 'getParameterNames()' instead http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterNames()
Hope it helps
The problem in a nut shell:
Two forms with more or less identical code, both take a single value "ean". One form works as intended, the other always fails to bind. I Included
println(form.data)
in each controller to see what was going on. When entering the value "h", for example, into each form the working form prints out
Map(ean -> h)
where as the "broken" form prints out
Map()
So why is the second form not binding values?
The story:
I have been doing a project in Scala using the Play framework. Things were going well until I wanted to create a new form. For some reason this form always fails to bind. I couldn't see why this was happening so I decided to make a "copy" of a currently working form, only changing the names of the variables etc. However this "copy" form also has the same problem! I've looked online for a bit of help and the closest problem I can find is the following:
Issue with bindFromRequest in Play! Framework 2.3
But after trying the posted solution it doesn't seem to help at all. Below I've posted the relevant chunks of code, the "ProductPartForm" is the original working form and the "AddDealForm" is the broken copy form. Am I making a silly trivial error somewhere? Any help would be greatly appreciated. Please also note that I'm aware that the "success" message doesn't work (as you can see from the comment), however that shouldn't have any effect on the problem I'm considering.
Thanks!
The code:
Classes:
package models
case class ProductPartForm(ean: Long) {
}
and
package models
case class AddDealForm(ean : Long) {
}
Controller:
package controllers
class Suppliers extends Controller {
private val productForm: Form[ProductPartForm] = Form(mapping("ean" -> longNumber)(ProductPartForm.apply)(ProductPartForm.unapply))
private val dealForm: Form[AddDealForm] = Form(mapping("ean" -> longNumber)(AddDealForm.apply)(AddDealForm.unapply))
def supplierList = Action {
implicit request =>
val suppliers = Supplier.findAll
Ok(views.html.supplierList(suppliers, productForm, dealForm))
}
def findByProduct = Action { implicit request =>
val newProductForm = productForm.bindFromRequest()
newProductForm.fold(
hasErrors = { form =>
println(form.data)
val message = "Incorrent EAN number! Please try again."
Redirect(routes.Suppliers.supplierList()).flashing("error" -> message)
},
success = { newProduct =>
val productSuppliers = Supplier.findByProduct(newProductForm.get.ean)
val message2 = "It worked!" //can't display message?
Ok(views.html.supplierList(productSuppliers, productForm ,dealForm)).flashing("success" -> message2)
}
)
}
def addDeal = Action { implicit request =>
val newDealForm = dealForm.bindFromRequest()
dealForm.fold(
hasErrors = { form =>
println(form.data)
val message = "Incorrent EAN number! Please try again."
Redirect(routes.Suppliers.supplierList()).flashing("error" -> message)
},
success = { newDeal =>
val message2 = "a"
Redirect(routes.Products.list).flashing("success" -> message2)
}
)
}
HTML:
#helper.form(action = routes.Suppliers.findByProduct()) {
<fieldset style="margin-left:200px">
<legend>
#helper.inputText(productForm("ean"))
</legend>
</fieldset>
<div style="padding-bottom:60px">
<input type="submit" class="btn primary" value="Submit" style="margin-left:400px">
</div>
}
#helper.form(action = routes.Suppliers.addDeal()) {
<fieldset style="margin-left:200px">
<legend>
#helper.inputText(dealForm("ean"))
</legend>
</fieldset>
<div style="padding-bottom:60px">
<input type="submit" class="btn primary" value="Submit" style="margin-left:400px">
</div>
}
Routes:
POST /Suppliers controllers.Suppliers.findByProduct
POST /Suppliers/b controllers.Suppliers.addDeal
I had exactly some problem with play 2.4.6 version. In my case problem was that I not specified a request body parser. More about body parsers can be found there:
https://www.playframework.com/documentation/2.5.x/ScalaBodyParsers .
You should specify body parser in your action (use urlFormEncoded if you use simple form)
def findByProduct = Action(parse.urlFormEncoded) { implicit request =>
}
I have a ppc landing page that I want to change the hidden value of a form field based on the URL parameter.
The field
<input id="Campaign_ID" name="Campaign_ID" type="hidden" value="7g012455dv5441vdf">
The URL would be something like mysite.com/?campaignidvalue=7g012455dv5441vdf
There will be other field "values" that are also based on the URL parameter, so it has to tie the "input id" (or name) to that specific value.
EDIT: There was an error in my code.
PHP would be the easiest!
<?php
if(!empty($_GET['campaignidvalue']))
{
echo '<input id="Campaign_ID" name="Campaign_ID" type="hidden" value="'. $_GET['campaignidvalue'].'"/>';
}
?>
This block will check to see if the value is passed in a GET parameter, and then echo it out into a hidden form field.
The first part:
if(!empty($_GET['campaignidvalue']))
Is checking to see if a parameter named Campaign_ID is being passed.
So your URL of:
mysite.com/?campaignidvalue=7g012455dv5441vdf
Would allow the code to continue, as it is not empty.
This section is the part that actually displays it on the page.
echo '<input id="Campaign_ID" name="Campaign_ID" type="hidden" value="'. $_GET['campaignidvalue'].'"/>';
If you view the source of the HTML page, you would see
By using this function:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null) {
return "";
} else {
return decodeURIComponent(results[1]);
}
}
You'll be able to get any URL parameter by name, like so:
var cid = getParameterByName(campaignidvalue);
Then, once you have the value you can use jQuery to set it, like so:
$(function() {
$("#Campaign_ID").val(cid);
});
Using Apache Velocity Api we can combine Java objects (Lists, POJOs etc.) with a (HTML) template and create the (HTML) output.
Is there any Java API that can help reverse engineer this ? The input of this API could be HTML output and the template used, the output should be the data (in Java/XML format) that was used to generate the output.
I am aware of HTTP Unit API, but this just lets me extract HTML elements (like Tables). I am looking for something that extracts the data based on some template.
You can use google protobuf in order to convert messages for different types. And it is very easy to define templates as well. I create JavaScript Objects using JSON.parse(), and in Java you can use protobuf to convert JSON to Java objects.
http://code.google.com/p/protobuf/
http://code.google.com/p/protobuf-java-format/
My answer won't probably be useful to the writer of this question (I have 5 years late so not the right timing I guess) but as this is the first result I found on Google when typing HTML to POJO, I think it will probably be useful for many other developers that might come across this answer.
Today, I just released (in the name of my company) an HTML to POJO complete framework that you can use to map HTML to any POJO class with simply some annotations. The library itself is quite handy and features many other things all the while being very pluggable. You can have a look to it right here : https://github.com/whimtrip/jwht-htmltopojo
How to use : Basics
Imagine we need to parse the following html page :
<html>
<head>
<title>A Simple HTML Document</title>
</head>
<body>
<div class="restaurant">
<h1>A la bonne Franquette</h1>
<p>French cuisine restaurant for gourmet of fellow french people</p>
<div class="location">
<p>in <span>London</span></p>
</div>
<p>Restaurant n*18,190. Ranked 113 out of 1,550 restaurants</p>
<div class="meals">
<div class="meal">
<p>Veal Cutlet</p>
<p rating-color="green">4.5/5 stars</p>
<p>Chef Mr. Frenchie</p>
</div>
<div class="meal">
<p>Ratatouille</p>
<p rating-color="orange">3.6/5 stars</p>
<p>Chef Mr. Frenchie and Mme. French-Cuisine</p>
</div>
</div>
</div>
</body>
</html>
Let's create the POJOs we want to map it to :
public class Restaurant {
#Selector( value = "div.restaurant > h1")
private String name;
#Selector( value = "div.restaurant > p:nth-child(2)")
private String description;
#Selector( value = "div.restaurant > div:nth-child(3) > p > span")
private String location;
#Selector(
value = "div.restaurant > p:nth-child(4)"
format = "^Restaurant n\*([0-9,]+). Ranked ([0-9,]+) out of ([0-9,]+) restaurants$",
indexForRegexPattern = 1,
useDeserializer = true,
deserializer = ReplacerDeserializer.class,
preConvert = true,
postConvert = false
)
// so that the number becomes a valid number as they are shown in this format : 18,190
#ReplaceWith(value = ",", with = "")
private Long id;
#Selector(
value = "div.restaurant > p:nth-child(4)"
format = "^Restaurant n\*([0-9,]+). Ranked ([0-9,]+) out of ([0-9,]+) restaurants$",
// This time, we want the second regex group and not the first one anymore
indexForRegexPattern = 2,
useDeserializer = true,
deserializer = ReplacerDeserializer.class,
preConvert = true,
postConvert = false
)
// so that the number becomes a valid number as they are shown in this format : 18,190
#ReplaceWith(value = ",", with = "")
private Integer rank;
#Selector(value = ".meal")
private List<Meal> meals;
// getters and setters
}
And now the Meal class as well :
public class Meal {
#Selector(value = "p:nth-child(1)")
private String name;
#Selector(
value = "p:nth-child(2)",
format = "^([0-9.]+)\/5 stars$",
indexForRegexPattern = 1
)
private Float stars;
#Selector(
value = "p:nth-child(2)",
// rating-color custom attribute can be used as well
attr = "rating-color"
)
private String ratingColor;
#Selector(
value = "p:nth-child(3)"
)
private String chefs;
// getters and setters.
}
We provided some more explanations on the above code on our github page.
For the moment, let's see how to scrap this.
private static final String MY_HTML_FILE = "my-html-file.html";
public static void main(String[] args) {
HtmlToPojoEngine htmlToPojoEngine = HtmlToPojoEngine.create();
HtmlAdapter<Restaurant> adapter = htmlToPojoEngine.adapter(Restaurant.class);
// If they were several restaurants in the same page,
// you would need to create a parent POJO containing
// a list of Restaurants as shown with the meals here
Restaurant restaurant = adapter.fromHtml(getHtmlBody());
// That's it, do some magic now!
}
private static String getHtmlBody() throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(MY_HTML_FILE));
return new String(encoded, Charset.forName("UTF-8"));
}
Another short example can be found here
Hope this will help someone out there!
I am trying to add a Flash (*.swf) file to my Wicket application. I found some information here, but unfortunately it is not working, and I don't know why. On a web page, the elements and tag
<object wicket:id="swf" data="resources/test.swf" width="700" height="70" style="float: right; margin: 15px 0 0 0;"></object>
render as
<object height="70" style="float: right; margin: 15px 0 0 0;" width="140" data="../../resources/wicketapp.ViewPanel/resources/test.swf" type="application/x-shockwave-flash"><param name="movie" value="../../resources/wicketapp.ViewPanel/resources/test.swf">
</object>
Clearly, this is not the path of my Flash file. Also, I want to load the file dynamically, but the method of embedding Flash discussed in the above link is static. How can I load swf files dynamically?
Looking at the linked implementation, if you want an absolute path you should precede it with a slash:
// if it's an absolute path, return it:
if( src.startsWith( "/" ) || src.startsWith( "http://" ) || src.startsWith( "https://" ) )
return(src);
Otherwise a wicket resource path is generated.
I'd actually recommend using swfobject for embedding flash - there is some nice wicket integration code at the start of this page, along with a flash-based component that uses it.
As I have understood your question, your want change swf file in runtime. I have solve this problem as shown below (this is Scala code, but I suppose that you understand it):
class SWFObject(id: String) extends WebComponent(id)
with LoggerSupport {
def script: String = """
var swfVersionStr = "10.0.0";
var xiSwfUrlStr = "flash/playerProductInstall.swf";
var flashvars = {};
var params = {};
params.quality = "high";
params.bgcolor = "#ebf4ff";
params.allowscriptaccess = "sameDomain";
params.allowfullscreen = "true";
var attributes = {};
attributes.align = "middle";
swfobject.embedSWF(
"${name}", "flashContent",
"100%", "100%",
swfVersionStr, xiSwfUrlStr,
flashvars, params, attributes);
swfobject.createCSS("#flashContent", "display:block;text-align:left;");
"""
/**
* Path to SWF file.
*/
var swfFile: String = _;
override def onComponentTag(tag: ComponentTag) = {
checkComponentTag(tag, "script")
}
override def onComponentTagBody(markupStream: MarkupStream, openTag: ComponentTag) = {
val relativeName = getRequestCycle()
.getProcessor()
.getRequestCodingStrategy()
.rewriteStaticRelativeUrl(swfFile)
val body = body.replace("${name}", relativeName)
replaceComponentTagBody(markupStream, openTag, body)
}
}
Here are example of using:
private val gameObject = new SWFObject("game");
gameObject.swfFile = "flash/" + swfFile;
HTML is used swfobject script and based on standard FlashBuilder export.