primefaces reload galleria - jsf

reference: http://www.primefaces.org/showcase/ui/galleria.jsf
my page:
<p:galleria id="merchant-gallery" value="#{testController.imageIds}" var="item" autoPlay="false" >
<p:graphicImage width="300" value="#{imageStreamer.image}" >
<f:param name="id" value="#{item}" />
</p:graphicImage>
</p:galleria>
i tried enclosing <p:galleria> in a form and added a <p:remoteCommand name="updateme" update="#form"/> but after calling updateme it simply just make the galleria blank.
*Update
testController bean:
public List<Integer> getImageIds() {
int aId = (Integer) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user_id");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("TEST2PU");
EntityManager em = emf.createEntityManager();
TypedQuery<Merchant> tp = em.createQuery("SELECT a FROM Account a WHERE a.id = :id", Account.class);
tp.setParameter("id", aId);
current = tp.getSingleResult();
Collection rawPhotoCollection = current.getPhotoCollection();
imageIds = new ArrayList<Integer>(rawPhotoCollection);
List<Photo> photoList = new ArrayList<Photo>(rawPhotoCollection);
for (int i = 0; i < photoList.size(); i++) {
int imageId = photoList.get(i).getId();
imageIds.set(i, imageId);
}
return imageIds;
}
imageStreamer bean:
#EJB
private test.controller.photo.PhotoFacade ejbFacade;
public StreamedContent getImage() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
return new DefaultStreamedContent();
} else {
Map<String, String> param = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String id = param.get("id");
Photo image = ejbFacade.find(Integer.valueOf(id));
return new DefaultStreamedContent(new ByteArrayInputStream(image.getImage()));
}
}

I reworked your example and have the same issue. It is not related to your upload or remotecommand. I think it is a bug in primefaces. See http://code.google.com/p/primefaces/issues/detail?id=4840 for similar issue.
When I do the command
PrimeFaces.cw('Galleria','widget_companydetail_merchant-gallery',{id:'companydetail:merchant-gallery',transitionInterval:0,panelWidth:640,panelHeight:480,custom:false},'galleria');
in firebug console, the galleria reappears.
So when changing the remotecommand and adding the javascript to oncomplete it works.
<p:remoteCommand name="updateme" update="#form" oncomplete="PrimeFaces.cw('Galleria','widget_companydetail_merchant-gallery',{id:'companydetail:merchant-gallery',transitionInterval:0,panelWidth:640,panelHeight:480,custom:false},'galleria');"/>

Related

rendered attribute not working with request parameter

I am using JSF2.2 with primefaces 5.0. I have a xhtml file where there are two file Uploads where one should always be visible while other should be visible only when request parameter, named signmethod, is JAVAME.
<h:panelGrid>
<h:panelGroup>
<h:outputLabel for="selected_signmethod" value="Selected Signethod : "/>
<h:outputText id="selected_signmethod" value="#{param.signmethod}" />
</h:panelGroup>
<h:panelGroup>
<b>Select file(s) to upload:</b>
</h:panelGroup>
</h:panelGrid>
<h:form id="uploadForm" enctype="multipart/form-data">
<p:message for="file_upload"/>
<p:fileUpload id="file_upload" allowTypes="#{fileUploadView.allowedTypes}" label="Select file" fileUploadListener="#{fileUploadView.handleFileUpload}"
mode="advanced" dragDropSupport="false" update="growl" multiple="true" fileLimit="5"/>
<p:message for="javame_upload"/>
<h:panelGroup rendered="#{param.signmethod == 'JAVAME'}" >
<b>Select corresponding jar file(s) to upload:</b>
<p:fileUpload id="javame_upload" allowTypes="" label="Select Jar file for javame" fileUploadListener="#{fileUploadView.handleFileUpload}"
mode="advanced" dragDropSupport="false" multiple="true" fileLimit="5"/>
</h:panelGroup>
<p:commandButton ajax="false" id="signProceed" value="Proceed" action="#{fileUploadView.submit}"/>
</h:form>
But this seems to be not happening. Second upload component is not getting rendered at all. I am also printing value of param.signmethod so that to be sure that right value is getting into param.signmethod, which is correct. So whats stopping this component to get rendered.
Managed Bean code :
#ManagedBean
#ViewScoped
public class FileUploadView implements Serializable {
#ManagedProperty(value = "#{signBundleBean}")
private SignBundleBean signBundleBean;
static String uploadDirRoot = InitialisationHelper.getUploadDirRoot();
transient Map<String, Object> sessionMap;
ArrayList<Signing> signings;
String username;
SignMethod signMethod;
public FileUploadView() {
System.out.println("NEW FileUploadView created.");
}
#PostConstruct
public void init() {
System.out.println("#POstConstruct FileuploadView");
System.out.println("signMethod : " + signMethod);
sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
signings = signBundleBean.getSignings();
username = (String) sessionMap.get("username");
}
public void handleFileUpload(FileUploadEvent e) {
String signId = "" + DatabaseHelper.genrateSigningId();
FacesContext ctx = FacesContext.getCurrentInstance();
UploadedFile uploadedFile = e.getFile();
String filename = uploadedFile.getFileName();
if (signId.equals("-1")) {
FacesMessage fm = new FacesMessage();
fm.setDetail("Database Connection not working. Please try later.");
fm.setSummary("DBConnection_Error");
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
//ctx.addMessage(null, fm);
ctx.addMessage("uploadForm:file_upload", fm);
return;
}
if (username == null) {
FacesMessage fm = new FacesMessage();
fm.setDetail("You are not in session to upload.");
fm.setSummary("Session_Error");
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
ctx.addMessage("uploadForm:file_upload", fm);
return;
}
Signing sg;
sg = new Signing(signId, username, filename, signMethod, false);
signings.add(sg);
System.out.println("Signing added : " + sg);
signBundleBean.setMaxParameters(SignParametersInitialisation.getNumberOfParameters(signMethod));
try {
InputStream is = uploadedFile.getInputstream();
OutputStream os = new FileOutputStream(sg.getUploadfile());
byte[] bytes = new byte[1024];
int read = 0;
while ((read = is.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
sg.setUploaded(true);
is.close();
os.close();
} catch (IOException ex) {
signings.remove(sg);
Logger.getLogger(FileUploadView.class.getName()).log(Level.SEVERE, null, ex);
}
FacesMessage fm = new FacesMessage();
fm.setDetail(filename);
fm.setSummary("FileUploaded");
fm.setSeverity(FacesMessage.SEVERITY_INFO);
//ctx.addMessage(null, fm);
ctx.addMessage(null, fm);
System.out.println(sg + " File uploaded to " + sg.getUploadfile());
}
}

Dynamic Graphic Image

I am trying to have dynamic graphic image from database.
I found a few according questions here in SO but somehow it does not work.
Page:
<p:dataList styleClass="routeDatalist" value="#{searchRoutesBean.foundRoutes}" var="uiRoute">
<p:outputLabel value="USERID #{uiRoute.owner.id}"/>
<h:graphicImage value="#{photoStreamer.streamedContent}" styleClass="userProfileImage">
<f:param name="userId" value="#{uiRoute.owner.id}" />
</h:graphicImage>
<p:/dataList>
I get my list of objects from backing bean
#SessionScoped
#ManagedBean
public class SearchRoutesBean{
private List<UIRoute> foundRoutes;
...
}
I created a backing bean which should take the userimage bytearray and create a streamed content
#ManagedBean(name = "photoStreamer")
#ApplicationScoped
public class PhotoStreamer implements Serializable {
#Autowired
UserService userService;
private StreamedContent streamedContent;
public StreamedContent getStreamedContent() {
ExternalContext externalContext = FacesContext.getCurrentInstance()
.getExternalContext();
String userId = externalContext.getRequestParameterMap().get("userId");
if (StringUtils.isNotBlank(userId)) {
User user;
try {
user = userService.getUserById(Long.valueOf(userId));
byte[] image = user.getProfileJpegImage();
if (image != null && image.length > 0) {
return new DefaultStreamedContent(new ByteArrayInputStream(
image), "image/jpeg");
} else {
BufferedImage bufferedImg = new BufferedImage(250, 350,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bufferedImg.createGraphics();
g2.drawString("User has no ProfilImage", 50, 175);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedImg, "png", os);
return new DefaultStreamedContent(new ByteArrayInputStream(
os.toByteArray()), "image/png");
}
} catch (NumberFormatException | UserServiceException | IOException e) {
throw new IllegalStateException(e);
}
}
return null;
}
}
I dont know why but the given parameter userId is always null.
Does someone know what could be the problem?
BR
What about
<p:dataList styleClass="routeDatalist" value="#{searchRoutesBean.foundRoutes}" var="uiRoute">
<p:outputLabel value="USERID #{uiRoute.owner.id}"/>
<h:graphicImage value="#{photoStreamer.streamedContent(uiRoute.owner.id)}" styleClass="userProfileImage"/>
<p:/dataList>
+
public StreamedContent getStreamedContent(String userId) {
if (StringUtils.isNotBlank(userId)) {
User user;
try {
...
}
The problem was that dataList need to be wrapped into h:form.
Thx to Makky who send me this tutorial
http://www.youtube.com/watch?v=imiBwk_xqaE

jsf search and result pages

I have two pages - search and result and one bean. If I use ViewScoped, my results do not show. If I use RequestScoped, my page links do not work. How can I fix it? If I place the submit into init with Viewscoped, everything is working fine, but if I do that, how should I get the variables from the form?
My bean:
#Named
#ViewScoped
public class Result implements Serializable {
private static final long serialVersionUID = 1L;
private DAOFactory javabase = DAOFactory.getInstance("javabase.jdbc");
private RecipeDAO recipeDAO = javabase.getRecipeDAO();
private ResourceBundle messages;
#Inject
LocaleBean locale;
private List<Recipe> recipes;
private List<Recipe> recipesView;
private String language;
private List<Page> pagesArray;
private Integer currentPage;
public void init() {
System.out.println("Language is: " + language);
String language1 = "en";
recipes = new ArrayList<>();
recipes = recipeDAO.searchRecipe(language1);
int showValue = 5; //split value
int pages = recipes.size() / showValue; //pages value
if (recipes.size() % showValue != 0) {
pages = pages + 1;
}
for (int i = 0; i < recipes.size(); i++) {
int a = i + 1;
//System.out.println("i is: " + i + " recipe number is: " + a);
}
//System.out.println("pages is: " + pages + " size is: " + recipes.size());
pagesArray = new ArrayList<>();
Page page;
for (int i = 0; i < recipes.size(); i = i + showValue) {
page = new Page();
page.setPageDisabled(false);
page.setFirstItem(i);
page.setLastItem(i + showValue - 1);
pagesArray.add(page);
}
for (int i = 0; i < pagesArray.size(); i++) {
pagesArray.get(i).setPageNumber(i + 1);
}
pagesArray.get(pagesArray.size() - 1).setLastItem(recipes.size() - 1);
/* for (int i = 0; i < pagesArray.size(); i++) {
System.out.println(pagesArray.get(i).getPageNumber() + " " + pagesArray.get(i).getFirstItem() + " " + pagesArray.get(i).getLastItem() + " " + pagesArray.get(i).isPageDisabled());
}*/
recipesView = new ArrayList<>();
Recipe recipe;
for (int i = pagesArray.get(0).getFirstItem(); i <= pagesArray.get(0).getLastItem(); i++) {
recipe = new Recipe();
recipe.setAuthor(recipes.get(i).getAuthor());
recipe.setId(recipes.get(i).getId());
recipe.setCreateDate(recipes.get(i).getCreateDate());
recipe.setTitle(recipes.get(i).getTitle());
recipesView.add(recipe);
}
pagesArray.get(0).setPageDisabled(true);
}
public void doPages() {
FacesContext fc = FacesContext.getCurrentInstance();
this.currentPage = Integer.parseInt(getCountryParam(fc));
System.out.println(currentPage);
recipesView = new ArrayList<>();
Recipe recipe;
for (int i = pagesArray.get(currentPage - 1).getFirstItem(); i <= pagesArray.get(currentPage - 1).getLastItem(); i++) {
System.out.println(i);
recipe = new Recipe();
recipe.setAuthor(recipes.get(i).getAuthor());
recipe.setId(recipes.get(i).getId());
recipe.setCreateDate(recipes.get(i).getCreateDate());
recipe.setTitle(recipes.get(i).getTitle());
recipesView.add(recipe);
}
for (int i = 0; i < pagesArray.size(); i++) {
pagesArray.get(i).setPageDisabled(false);
}
pagesArray.get(currentPage - 1).setPageDisabled(true);
}
public String getCountryParam(FacesContext fc) {
Map<String, String> params = fc.getExternalContext().getRequestParameterMap();
return params.get("currentPage");
}
//setters&getters
}
My search view:
<h:form>
<h:selectOneMenu value="#{search.language}">
<f:selectItem itemLabel="English" itemValue="en"/>
<f:selectItem itemLabel="Select" itemValue=""/>
<f:selectItem itemLabel="Bulgarian" itemValue="bg"/>
</h:selectOneMenu>
<h:commandButton value="Submit" type="submit" action="#{search.submit()}">
<f:param name="lang" value ="#{search.language}"/>
</h:commandButton>
</h:form>
My result view:
<f:metadata>
<f:viewParam name="lang" value="#{result.language}" />
<f:viewAction action="#{result.init()}" />
</f:metadata>
<h:form>
<ui:repeat value="#{result.recipesView}" var="rec">
<h:link value="#{rec.title}" outcome="recipeshow">
<f:param name="id" value="#{rec.id}" />
</h:link>
<br/>
<h:outputText value="#{rec.id}"/><br/>
<h:outputText value="#{rec.author}"/><br/>
<h:outputText value="#{rec.createDate}"/><br/>
<br/>
</ui:repeat>
<br/>
<ui:repeat value="#{result.pagesArray}" var="page">
<h:commandLink value="#{page.pageNumber}" disabled="#{page.pageDisabled}">
<f:ajax listener="#{result.doPages()}" render="#form"/>
<f:param name="currentPage" value="#{page.pageNumber}"/>
</h:commandLink>
</ui:repeat>
</h:form>
My page.java
public class Page {
private int pageNumber;
private boolean pageDisabled;
private int firstItem;
private int lastItem;
public int getPageNumber() {
return pageNumber;
}
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
public boolean isPageDisabled() {
return pageDisabled;
}
public void setPageDisabled(boolean pageDisabled) {
this.pageDisabled = pageDisabled;
}
public int getFirstItem() {
return firstItem;
}
public void setFirstItem(int firstItem) {
this.firstItem = firstItem;
}
public int getLastItem() {
return lastItem;
}
public void setLastItem(int lastItem) {
this.lastItem = lastItem;
}
}
You returned a navigation case outcome from an action method, so your view scoped bean will be recreated, that's why you don't see your results. On the other hand, as you seem to be doing a pagination basing on the information held in the view scope, thus your request scoped beans do not allow for proper pagination.
As to the solution, you should either be doing a postback from your action method, thus returning null or void, or pass the necessary information to the result view using get parameters.
It is also worth noting that you're preloading too much information in recipes = recipeDAO.searchRecipe(language);: you should be loading as much information as is shown in your view, like in: recipes = recipeDAO.searchRecipe(language, min, max);.

p:fileupload won't invoke listener at first browse?

I find it really weird I don't know why but when I first select an image it won't invoke the upload listener but at the second select it work perfectly.
View code :
<h:form enctype="multipart/form-data;charset='UTF-8'">
<p:fileUpload id="clientProfile" auto="true" sizeLimit="2097152" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" fileUploadListener="#{clientController.uploadListener}" mode="advanced" multiple="true" label="browse" update="imagePreview" invalidFileMessage="Invalid image" invalidSizeMessage="too large size"/>
<p:outputPanel id="imagePreview">
<ui:repeat value="#{clientController.listImages}" var="imageId">
<div style="float:left;margin-right:10px; margin-bottom: 5px;">
<p:graphicImage value="#{clientController.previewImage}" height="135" width="135" styleClass="images">
<f:param name="imageId" value="#{imageId}"/>
</p:graphicImage>
</div>
</ui:repeat>
</p:outputPanel>
</h:form>
Bean code :
private Map<UUID, UploadedFile> uploadedFiles = new HashMap<UUID, UploadedFile>();//used for preview
private List<String> listImages = new ArrayList<String>(); //list of id from map which is UUID
private List<UploadedFile> clientProfile = new ArrayList<UploadedFile>();
public void uploadListener(FileUploadEvent event) {
clientProfile.add(event.getFile());
final UUID uuid = UUID.randomUUID();
uploadedFiles.put(uuid, event.getFile());
listImages.add(uuid.toString());
System.out.println(listImages.size());
System.out.println(clientProfile.size());
}
public List<String> getListImages() {
return listImages;
}
public StreamedContent getPreviewImage() {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
return new DefaultStreamedContent();
} else {
StreamedContent image = null;
String imageId = JsfUtil.getRequestParameter("imageId");
System.out.println(imageId);
if (imageId != null) {
UUID imageIndex = UUID.fromString(imageId);
return new DefaultStreamedContent(new ByteArrayInputStream(uploadedFiles.get(imageIndex).getContents()));
}
}
return null;
}

JSF UIRepeat and PostBack

I have a simple page where a I use <ui:repeat> and it gets the value from a backing bean.
The initial request will give it an empty list. The postback then will invoke an action that will change the model behind the <ui:repeat> but it is not rendered?!
I debugged through it and I saw that the <ui:repeat> evaluates the value at restore view phase but thats it. When it reaches render response it does not use the latest value from my bean. Is that the expected behavior?
How can I make that work? Do I have to write my own repeat tag?
I can't really tell what could be the problem without some of your code, but these are the basics:
Backing bean:
public class ObjectService{
private DataModel objectDataModel;
private List<Object> objectList;
private Pagination paginationHelper;
private ObjectDao objectDao = new ObjectDao();
private String queryOption;
public void setQueryOption(String queryOption){
this.queryOption = queryOption;
}
public String getQueryOption(){
return this.queryOption;
}
public <E> PaginationHelper getPagination(final List<E> list) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return list.size();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(list);
}
};
return pagination;
}
public void setPagination(PaginationHelper pagination) {
this.pagination = pagination;
}
public List<Object> getObjectList(){
this.objectList = objectDao.readObjectsWhere(queryOption);
return this.objectList;
}
public void setObjectList(List<Object> objectList){
this.objectList = objectList;
}
public DataModel getObjectDataModel(){
if (objectDataModel == null) {
objectDataModel = getPagination(getObjectList()).createPageDataModel();
}
return objectDataModel;
}
public void setObjectDataModel(DataModel objectDataModel){
this.objectDataModel = objectDataModel
}
public String changeModel(){
objectDataModel = null;
return null;
}
}
XHTML page:
...
<h:form>
<fieldset>
<label>
<span>Option:</span>
<h:inputText value="#{objectService.queryOption}" />
</label>
<h:commandButton action="#{objectService.changeModel}" value="request data" />
</fieldset>
<ui:repeat value="#{objectService.objectDataModel}" var="objectVar">
<h:outputLabel value="#{objectVar.property1}" />
<h:outputLabel value="#{objectVar.property2}" />
<h:outputLabel value="#{objectVar.property3}" />
</ui:repeat>
</h:form>
...

Resources