Show Pdf file in Primefaces page - jsf

I am generating a pdf file with Itextpdf package in jsf managed bean , now I want when user click on p:commandButton , user can see the pdf file in page2.xhtml from p:media .
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<p:inputText value="#{bean.text}" />
<p:commandButton value="Show Pdf File" action="page2" />
</h:form>
</h:body>
</html>
and Page2.xhtml is :
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Page 2</title>
</h:head>
<h:body>
<p:media value="??????????" width="500px" height="500px" player="pdf" />
</h:body>
</html>
and my bean file is :
package pack;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
#ManagedBean
#RequestScoped
public class bean {
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
/**
* Creates a new instance of bean
*/
public bean() {
this.create_pdf();
}
public void create_pdf(){
try {
Document doc = new Document();
OutputStream file = new FileOutputStream(new File("HelloWorld.pdf"));
PdfWriter writer = PdfWriter.getInstance(doc, file);
doc.open();
doc.add(new Paragraph("A Hello World PDF document."));
doc.add(new Paragraph(this.text));
doc.close();
file.close();
} catch (Exception e) { }
}
}

Thanks to Leo & faissalb for response .
Detail of this response is :
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>page 1</title>
</h:head>
<h:body>
<p:media value="#{bean.streamedContent}" width="700px" height="700px" player="pdf" />
</h:body>
</html>
and bean file :
package pack;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
/**
*
* #author alfa
*/
#ManagedBean
#RequestScoped
public class bean {
private static final long serialVersionUID = 1L;
private StreamedContent streamedContent;
#PostConstruct
public void init() {
try {
//----------------------------------
Document doc = new Document();
OutputStream out = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(doc, out);
doc.open();
doc.add(new Paragraph("Hello World. ok........"));
doc.close();
out.close();
InputStream in =new ByteArrayInputStream(((ByteArrayOutputStream)out).toByteArray());
streamedContent = new DefaultStreamedContent(in, "application/pdf");
//-------
Map<String, Object> session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
byte[] b = (byte[]) session.get("reportBytes");
if (b != null) {
streamedContent = new DefaultStreamedContent(new ByteArrayInputStream(b), "application/pdf");
}
} catch (Exception e) {
}
}
//==================================================================
public StreamedContent getStreamedContent() {
if (FacesContext.getCurrentInstance().getRenderResponse()) {
return new DefaultStreamedContent();
} else {
return streamedContent;
}
}
//==================================================================
public void setStreamedContent(StreamedContent streamedContent) {
this.streamedContent = streamedContent;
}
//=====================================================================
}

Related

ace:datatable inside composite component does not work in JSF

I try to use tag <ace:datatable> inside composite component Mainly it works well. I want to getting row data from the table to use it in bean but when I click on the row, I get error message
Internal server error
I need your help (BalusC :)) to fix this bug.
This is my component:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:cc="http://java.sun.com/jsf/composite"
xmlns:ace="http://www.icefaces.org/icefaces/components"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:icecore="http://www.icefaces.org/icefaces/core"
xmlns:ice="http://www.icesoft.com/icefaces/component" >
<head>
<title>IGNORED</title>
</head>
<body>
<ui:composition>
<cc:interface componentType="partnercard">
<!-- properties -->
...
</cc:interface>
<cc:implementation>
<div id="#{cc.clientId}">
<ace:dataTable id="partnerTable"
value="#{cc.partnersList}"
binding="#{cc.partnersTable}"
var="partner"
paginator="true"
paginatorPosition="bottom"
rows="10"
style="font-size: 11px;margin-top: 10px;"
selectionMode="single"
stateMap="#{cc.stateMap}" >
<ace:ajax event="select" render="#this" execute="#this" />
<ace:column id="id"
headerText="ID"
sortBy="#{partner.id}"
filterBy="#{partner.id}"
filterMatchMode="contains"
rendered="false">
<h:outputText id="idCell" value="#{partner.id}"/>
</ace:column>
<ace:column id="name"
headerText="Name"
sortBy="#{partner.name}"
filterBy="#{partner.name}"
filterMatchMode="contains">
<h:outputText id="nameCell" value="#{partner.name}"/>
</ace:column>
</ace:dataTable>
</div>
</cc:implementation>
</ui:composition>
</body>
</html>
Component backing bean
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.component.FacesComponent;
import javax.faces.component.NamingContainer;
import javax.faces.component.UIInput;
import javax.faces.component.html.*;
import javax.faces.component.UINamingContainer;
import javax.faces.context.FacesContext;
import javax.faces.component.UIData;
import org.icefaces.ace.model.table.RowStateMap;
#FacesComponent("partnercard")
public class partnercard extends UINamingContainer implements Serializable {
private RowStateMap stateMap = new RowStateMap();
private List<PartnerData> partnersList = new ArrayList<PartnerData>();
private UIData partnersTable; // поиск партнера - таблица со списком партнеров
#Override
public String getFamily() {
return UINamingContainer.COMPONENT_FAMILY;
}
public void encodeBegin(FacesContext context) throws IOException {
super.encodeBegin(context);
}
public UIData getPartnersTable() {
return partnersTable;
}
public void setPartnersTable(UIData partnersTable) {
this.partnersTable = partnersTable;
}
public RowStateMap getStateMap() {
return stateMap;
}
public void setStateMap(RowStateMap stateMap) {
this.stateMap = stateMap;
}
public List<PartnerData> getPartnersList() {
return partnersList;
}
public void setPartnersList(List<PartnerData> partnersList) {
this.partnersList = partnersList;
}
}
This is PartnerData.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
public class PartnerData implements Serializable {
private long id = 0;
private String name = "";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}

orderlist is not working in PrimeFaces 3.5

I am using PrimeFaces 3.5. I want to use orderList on my page. Following is my bean class.
package test;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
#ManagedBean
public class OrderListView {
#ManagedProperty("#{themeService}")
private List<String> cities;
#PostConstruct
public void init() {
//Cities
cities = new ArrayList<String>();
cities.add("San Francisco");
cities.add("London");
cities.add("Paris");
cities.add("Istanbul");
cities.add("Berlin");
cities.add("Barcelona");
cities.add("Rome");
//Themes
}
public List<String> getCities() {
return cities;
}
public void setCities(List<String> cities) {
this.cities = cities;
}
public void onSelect(SelectEvent event) {}
public void onUnselect(UnselectEvent event) {}
public void onReorder() {}
}
And Here is my page content.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:p="http://primefaces.org/ui"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c = "http://java.sun.com/jsp/jstl/core">
<h:body>
<h:form >
<p:panel>
<p:orderList value="#{orderListView.cities}" var="city" controlsLocation="none" itemLabel="#{city}" itemValue="#{city}" />
</p:panel>
</h:form>
</h:body>
</html>
I am getting exception for this.
java.lang.NullPointerException
at org.primefaces.component.orderlist.OrderListRenderer.encodeOptions(OrderListRenderer.java:150)
at org.primefaces.component.orderlist.OrderListRenderer.encodeList(OrderListRenderer.java:109)
at org.primefaces.component.orderlist.OrderListRenderer.encodeMarkup(OrderListRenderer.java:80)
at org.primefaces.component.orderlist.OrderListRenderer.encodeEnd(OrderListRenderer.java:50)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:519)
at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:63)
at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:47)
at
I have tried this example from PrimeFaces showcase still its not working.
Can anybody tell me what went wrong?
The nullpointer exception that is thrown indicates that the cities list or the bean is null. Try to debug the code at see if the init() method actually fires.
I don't know what server you are using, but a restart may help to register the newly created managed bean.
Edit 1:
Could you try to remove #ManagedProperty("#{themeService}") from above the list and try again?

ManagedBean with ArrayList, how to add elements?

I'm trying to do SIMPLE webapp which show partyguest list and allow me to add new guest. I want to store guests in ArrayList. I don't know where and how to invoke party.addGuest() method.
index.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Big Party</title>
</h:head>
<h:body>
<h2>Add new guest to Big Party: </h2>
<h:form>
<h:inputText id="guestName" value="#{guest.name}"/>
<h:commandButton value="Add guest" action="guests" />
</h:form>
<h:link value="GuestList" outcome="guests" />
</h:body>
</html>
guests.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title>Super Party</title>
</h:head>
<h:body>
<h2>New guest:</h2>
<h:outputLabel value="#{guest.name}" />
<h2>Guests:</h2>
<ul>
<ui:repeat value="#{party.guests}" var="curr">
<li>#{curr}</li>
</ui:repeat>
</ul>
<h2>Guests count:</h2>
<h:outputLabel value="#{party.cnt}"/>
</h:body>
</html>
Party.java
package managedBeans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
#ManagedBean(name = "party")
#ApplicationScoped
public class Party implements Serializable {
private List<String> guests;
private int cnt;
public Party() {
}
#PostConstruct
public void init() {
guests = new ArrayList<>();
guests.add("Guest A");
guests.add("Guest B");
}
public List<String> getGuests() {
return guests;
}
public void addGuest(String guest) {
guests.add(guest);
}
public int getCnt() {
cnt = guests.size();
return cnt;
}
}
Guest.java
package managedBeans;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
#ManagedBean(name = "guest")
#RequestScoped
public class Guest implements Serializable{
private String name;
public Guest() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
If you are using JSF 2, you can have something like this in your index.xhtml (but it can be easily converted to earlier JSF version):
...
<h:form>
<h:inputText id="guestName" value="#{party.newGuest}"/>
<h:commandButton value="Add guest" action="#{party.addGuest()}" />
</h:form>
...
And, in Party.java:
private String newGuest;
....
public String getNewGuest() {
return this.newGuest;
}
public void setNewGuest(String guest) {
this.newGuest = guest;
}
....
public void addGuest() {
guests.add(newGuest);
newGuest = null;
}
No need for Guest.java in this use case. Could be done in a nicer way, though.

How to print ArrayList in JSF Facelets

I have been trying to print the values from an ArrayList<String> in JSF Facelets, but with no luck. The value is getting stored in an ArrayList but the output is blank on the page.
Bean file:
import java.io.Serializable;
import java.util.ArrayList;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
#ManagedBean(name="newCompanyName")
#SessionScoped
public class CompanyNames implements Serializable {
private static final long serialVersionUID = 1L;
private ArrayList<String> list = new ArrayList<String>();
private String companyName;
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
list.add(companyName);
System.out.println("Size of array list is : "+list.size());
for (String number : list) {
System.out.println("Number = " + number);
}
}
public CompanyNames(String companyName) {
this.companyName = companyName;
}
public CompanyNames() {
}
}
Here is my JSF file from an XHTML 1.0 Transitional file:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</h:head>
<h:body>
<ui:repeat var="item" value="#{CompanyNames.list}">
<h1>#{item}</h1>
</ui:repeat>
</h:body>
</html>
Instead of
<ui:repeat var="item" value="#{CompanyNames.list}"> <h1>#{item}</h1> </ui:repeat>
use
<ui:repeat var="item" value="#{newCompanyName.list}"> <h1>#{item}</h1> </ui:repeat>
You will also need a getList method for the class CompanyNames
public List<String> getList() {
return this.list;
}
Use companyNames.list instead of CompanyNames.list and you will also need the get() function of list.

POST http://localhost:8080/Languages/WEB-INF/inventory.xhtml 404 (No Encontrado)

I am using facelets in my views with JSF 2.0. I have two backing beans, two xhtml view files and another xhtml template file. When I have the second view in the webapp directory and I change the language all is Ok but when I put mi second view into the WEB-INF folder and I change the language I have the following error in the chrome network console:
POST http://localhost:8080/Languages/WEB-INF/inventory.xhtml 404 (No Encontrado)
These are my backings beans:
LanguageBean.java:
package com.testapp;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
#ManagedBean(name = "language")
#SessionScoped
public class LanguageBean implements Serializable {
private static final long serialVersionUID = 1L;
private String localeCode;
private static final String DEFAULT_LOCAL_CODE = "es";
private static Map<String, Object> countries;
static {
countries = new LinkedHashMap<String, Object>();
countries.put("English", Locale.ENGLISH); // label, value
countries.put("Français", Locale.FRENCH);
countries.put("Español", new Locale("es"));
}
public Map<String, Object> getCountriesInMap() {
return countries;
}
public String getLocaleCode() {
if(localeCode == null) {
localeCode = DEFAULT_LOCAL_CODE;
}
return localeCode;
}
public void setLocaleCode(String localeCode) {
this.localeCode = localeCode;
}
public void changeLanguage() {
// loop a map to compare the locale code
for (Map.Entry<String, Object> entry : countries.entrySet()) {
if (entry.getValue().toString().equals(localeCode)) {
FacesContext.getCurrentInstance().getViewRoot().setLocale((Locale) entry.getValue());
}
}
}
}
InventoryBean.java:
package com.testapp;
import java.io.Serializable;
import java.util.Locale;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#ManagedBean(name = "inventory")
#ViewScoped
public class InventoryBean implements Serializable {
private static final long serialVersionUID = 4576404491584185639L;
Logger logger = LoggerFactory.getLogger(InventoryBean.class);
// Failing path
private static final String INVENTORY_MAIN_VIEW = "/WEB-INF/inventory";
// Working path
// private static final String INVENTORY_MAIN_VIEW = "/views/inventory";
public String findProducts() {
try {
System.err.println("In inventory backing bean");
} catch (Exception exception) {
}
return INVENTORY_MAIN_VIEW;
}
public void changeLanguage() {
FacesContext.getCurrentInstance().getViewRoot().setLocale((Locale.ENGLISH));
}
}
These are the view files:
default.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="/WEB-INF/header.xhtml">
<ui:define name="contentBody">
<f:view locale="#{language.localeCode}">
<h:form id="contentForm">
<h:outputText value="#{msg['internationalization.test']}" />
<p:commandButton id="gettingProducts"
value="Getting the products..." action="#{inventory.findProducts}" />
</h:form>
</f:view>
</ui:define>
</ui:composition>
inventory.xhtml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets"
template="/WEB-INF/header.xhtml">
<ui:define name="contentBody">
<f:view locale="#{language.localeCode}">
<h:form id="contentForm">
<h:outputText value="#{msg['internationalization.test']}" />
</h:form>
</f:view>
</ui:define>
</ui:composition>
And this is the template xhtml file (header.xhtml):
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<f:view contentType="text/html">
<h:head>
</h:head>
<h:body>
<div id="content">
<h:form id="headerForm">
<h:panelGrid columns="2">
<p:outputLabel value="Language :" for="languages" />
<h:selectOneMenu required="true" id="languages"
value="#{language.localeCode}">
<f:selectItems value="#{language.countriesInMap}" />
<p:ajax event="change" update="#all"
listener="#{language.changeLanguage}" />
</h:selectOneMenu>
</h:panelGrid>
</h:form>
<ui:insert name="contentBody" />
</div>
</h:body>
</f:view>
</html>
What is happening?
A HTTP 404 error simply means "Page Not Found". And indeed, files inside /WEB-INF folder are not publicly accessible. Put files which are intented to be publicly accessible outside /WEB-INF folder.
Note that this has further completely nothing to do with internationalization. You'd have had exactly the same problem when not doing anything with regard to internationalization (e.g. a simple navigation).
See also:
Which XHTML files do I need to put in /WEB-INF and which not?

Resources