Get file url in JSF 2.2 - jsf-2

I am trying to make an openfiledialog in the backing bean, so that I can get the url of the local file. However it seems that the standard JSF library does not support open/save file dialog. Is there another way of getting an url of a file with something similar to openfiledialog?
Here is what has to happen:
Click on a button --> send action to the backing bean --> show openfiledialog --> get url of the file --> add url of the file to a list of strings.
I am not sure how to accomplish the bold steps above. Is there someone who can give me any leads or help to accomplish this?
(I am using JSF & Primefaces, I would prefer not to use another external library if possible.)

Since you're using JSF 2.2 as well as Primefaces, why not use the primefaces component itself?
Below is the Primefaces 5.0 showcase example for a basic file upload:
<h:form enctype="multipart/form-data">
<p:growl id="messages" showDetail="true" />
<p:fileUpload value="#{fileUploadView.file}" mode="simple" skinSimple="true"/>
<p:commandButton value="Submit" ajax="false" actionListener="#{fileUploadView.upload}" disabled="true" />
</h:form>
Managed Bean
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
#ManagedBean
public class FileUploadView {
private UploadedFile file;
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public void upload() {
if(file != null) {
FacesMessage message = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
}
The enctype attribute for the form is required. Also, for using Primefaces file upload, you need to setup certain context parameters and filters. You may refer the appropriate documentation for the same.

You can get url for file uploaded to path or database, not sure if you make a search in google but I found these URLs maybe will help you:
http://balusc.blogspot.com/2007/07/fileservlet.html
Download a file with JSF?
You just need to open a dialog have link of file, or maybe file url can be stored in variable to add to list too or what ever you want.
Hope this will help you.

Related

Detect when the multiupload primefaces componet ends all the uploads

I´m usig the jsf version 2.1 primefaces 5.1 and tomcat 7.
I have to execute a managed bean method after the all the uploads has been succesfully in a multiple upload component, I used the onComplete atribute, but is executed after each upload. I need to do it after the all files upload was completed.
How identify that?
Thanks in advance for your time and answers
PD I posted this question in the primefaces 1 forum but nobody answer.
This should work:
<p:fileUpload ... oncomplete="doSomething(this);" />
<p:remoteCommand name="rc" actionListener="#{bean.method}" />
and
<script>
function doSomething(fileupload) {
if (fileupload.files.length == 0) {
rc();
}
}
</script>
On the bean:
public void method() {
// Do something here
}

Primefaces Captcha Component not working

I am using PF3.5+JSF2.1.22 and in my web application i am using Primefaces Captcha component. I am getting some weird issue in capcha component,i used captcha component like this in application
<p:captcha id="captcha" label="Captcha" theme="white" />
And i have a PF command page to submit the values to bean
<p:commandButton id="clear" value="Clear" update="captcha" styleClass="kuberbutton" />
When i am using button like above after form submit if any validation issue and other issue coming and age is loading again then Captcha is not visible in page any more but when i am using ajax="false" in PF button then it is working,is this is behavior this component will work i have to do ajax="false"? I checked the PF website they also did same thing Primefaces Captcha
Captcha component in Primefaces currently does not support ajax behavior , that why you must use ajax="false" in your <p:commandButton , you page must be fully reloaded for the captcha to work properly...
If you must have the ajax behavior you could use some other third party solution...
Haven't tried the following, but it might help with ajax issues:
recaptcha - AJAX AP
Displaying reCAPTCHA Without Plugins
How can I load a reCaptcha form using jQuery/AJAX while leaving the reCaptcha scripts in place?
As already said Primefaces Captcha component can't be updated by ajax request. But there is a simple solution - update everything but not Captcha component itself.
Your XHTML:
<h:form id="myForm">
<h:panelGroup id="updateFormAllValuesButNotCaptcha">
Name: <p:inputText id="name" value="#{captchaBean.name}" required="true"/>
<br/>
Comment: <p:inputTextarea id="comment" value="#{captchaBean.comment}" required="true"/>
<br/>
</h:panelGroup>
<p:captcha/>
<p:commandButton value="click me" update="updateFormAllValuesButNotCaptcha"
actionListener="#{captchaBean.someAction}" oncomplete="Recaptcha.reload()"
onerror="Recaptcha.reload()"/>
</h:form>
<p:messages globalOnly="false" autoUpdate="true"/>
Your backing bean:
#ManagedBean
#ViewScoped
public class CaptchaBean implements Serializable {
private String name;
private String comment;
public String getComment() { return comment; }
public void setComment(String comment) { this.comment = comment; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public void someAction() {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Done", "");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
Note that I am updating updateFormAllValuesButNotCaptcha panel which contains all form input fields but not Captcha itself. It is also important to notice that Captcha can't be reused, so you have to reload it always when ajax request has been completed or ended with error.
What you update after commandButton's action succeeded is up to you. You can hide form (do not render it) and show only confirmation message to make sure user won't try to send comment again.

Using bootstrap related tags inside JSF2 h:inputText component

Is there anyway to use bootstrap related tags in JSF2 components? For example I'm interested in using the bootstrap typeahead feature which requires something like
<h:inputText id="typeahead" type="text" data-provide="typeahead"></h:inputText>
but since data-provide doesn't exist for h:inputText it gets stripped out and so the typeahead feature would obviously not work.
Depends on JSF version you're using.
In JSF 2.0/2.1, it's not possible to specify additional attributes. The JSF HTML renderers will only render predefined attributes. You'd need to create a custom renderer to achieve the desired job. To minimize boilerplate code, you're forced to extend the implementation-specific renderer. It's unclear which one you're using, so here's just a Mojarra targeted example:
import com.sun.faces.renderkit.html_basic.TextRenderer;
public class MyTextRenderer extends TextRenderer {
#Override
protected void getEndTextToRender(FacesContext context, UIComponent component, String currentValue) throws IOException {
Object dataProvide = component.getAttributes().get("data-provide");
if (dataProvide != null) {
context.getResponseWriter().writeAttribute("data-provide", dataProvide, null);
}
super.getEndTextToRender(context, component, currentValue);
}
}
Register it as follows in faces-config.xml to get it to run:
<render-kit>
<renderer>
<component-family>javax.faces.Input</component-family>
<renderer-type>javax.faces.Text</renderer-type>
<renderer-class>com.example.MyTextRenderer</renderer-class>
</renderer>
</render-kit>
In JSF 2.2, it's possible by the new passthrough namespace or the <f:passThroughAttribute> tag. See also What's new in JSF 2.2? - HTML5 Pass-through attributes.
Thus, so:
<html ... xmlns:a="http://xmlns.jcp.org/jsf/passthrough">
...
<h:inputText id="typeahead" a:data-provide="typeahead" />
(note that the type attribute defaults to text already)
Or:
<h:inputText id="typeahead">
<f:passThroughAttribute name="data-provide" value="typeahead" />
</h:inputText>
See also:
Custom HTML tag attributes are not rendered by JSF

target="_blank" in h:commandlink not opening page in new tab of browser

My h:commandLink is opening/previewing the pdf document on same page/window when h:commandlink used with target="_blank". I want it to be opened in new tab of the browser
where can be the error?
Preview.xhtml code:
<h:commandLink id="DocUpoadPreview" action="#{documentController.previewUploadedFile}" value="Preview" target="_blank" >
</h:commandLink>
In previewuploadedFile() action encription/decryption and some other process with pdf is required that is why necessary to use and that is why not using h:outputlink here. After the action process i want to redirect to another page(previewUploadedDoc.xhtml) which uses primefaces p:media tag to preview the document.
public String previewUploadedFile() throws Exception {
//decryption process and adding water mark here//
FacesContext.getCurrentInstance().getExternalContext()
.redirect("previewUploadedDoc.xhtml");}
Try it:
<h:commandLink id="DocUpoadPreview" action="#{documentController.previewUploadedFile}" value="Preview" target="_new" />
target="_new" is not valid value of target. It defines _new as a name of new page.
This is the valids values: https://www.w3schools.com/tags/att_a_target.asp

JSF 2.0 commandLink - action not being called, javascript erro

i'm trying to get a plain commandLink to work. Here is a code snippet of the page:
<div class="item-single">
<h:graphicImage value="image/screenshots/#{collectionListBean.collectionListTeaser[0].screenshot}" alt="Screenshot #{collectionListBean.collectionListTeaser[0].title}"/>
<div class="item-title">
<h:form id="teaser0">
<h:commandLink value="#{collectionListBean.collectionListTeaser[0].title}" action="#{collectionBean.showCollection(collectionListBean.collectionListTeaser[0].id)}" />
</h:form>
</div>
<div class="item-description">
<p>
<h:outputText value="#{collectionListBean.collectionListTeaser[0].persons.get(0).person.getFullName()}" />
</p>
</div>
</div>
The title is displayed correctly, so the backing bean and the list is available and accessible. CollectionBean is also available and accessible. The list has a fixed size and is used inside a javascript gallery which is the reason why i didn't use ui:repeat or h/p:dataTable elements.
I have also checked BalusC'S List of common problems
The action is not being invoked in the backing bean, I get following javascript error on the browser console:
Uncaught TypeError: Cannot read property 'teaser0:_idcl' of undefined
Here is the relevant code of the backing bean (collectionBean):
#Named("collectionBean")
#Scope("access")
#ViewController(viewIds = {ViewIds.EDIT_COLLECTION, ViewIds.SHOW_COLLECTION, ViewIds.EDIT_COLLECTION, ViewIds.METADATA_COLLECTION_ADMIN, ViewIds.EDIT_COLLECTION_EXISTING, ViewIds.COLLECTION_LIST, ViewIds.HOME})
public class CollectionBean extends CollectionBeanBase {
.
.
.
public String showCollection(long id) {
//Check if user is admin, if yes, allow to edit metadata
Authentication auth=SecurityContextHolder.getContext().getAuthentication();
this.collection = collectionService.findById(id);
if (!(auth instanceof AnonymousAuthenticationToken)){
role=auth.getAuthorities().iterator().next().getAuthority();
if(role.equalsIgnoreCase("ROLE_ADMIN")) {
this.collection.setEdit_flag(true);
return ViewIds.EDIT_COLLECTION;
}
}
return ViewIds.SHOW_COLLECTION;
}
Does anyone have an idea what the problem might be? Any hint is highly appreciated! thank you guys in advance!
This is commandLink then why are you passing value in method.
Means you can use
<f:param name="id" value="#{collectionListBean.collectionListTeaser[0].id}"/>
you can easily get that value in action.
like
public String showCollection() {
FacesContext fc = FacesContext.getCurrentInstance();
Object id = fc.getExternalContext().getRequestParameterMap().get("id");
System.out.println(id);
return ViewIds.SHOW_COLLECTION;
}
i think this is best way to do it.
I rearranged the element to wrap all of the div's affected by the jQuery gallery and now it works like a charm.

Resources