How to handle error with primefaces filedownload
<p:fileDownload value="#{testBean.file}" />
TestBean.java
public StreamedContent getFile() {
if(selectedReport ==null){
FacesContext.getCurrentInstance().addMessage(.."Please select a file");
return null;//What to do here
}
InputStream inps = ReportGenerator.getPDF(selectedReport);
return new DefaultStreamedContent(inps, "application/pdf", "report.pdf");
}
This helped http://forum.primefaces.org/viewtopic.php?f=3&t=8263
<p:commandButton ajax="false"
value="Download Detailed Report"
actionListener="#{reportBean.generateDetailedReport}">
<p:fileDownload value="#{reportBean.detailedReport}"/>
</p:commandButton>
public void generateDetailedReport(ActionEvent ae) {
......
reportStream = ExcelReport.generate(reportList);
if (reportStream == null) {
FacesUtil.addError("Error generating report");
throw new AbortProcessingException();
}
}
public StreamedContent getDetailedReport() {
return new DefaultStreamedContent(reportStream, "application/xls", "report.xls");
}
If you mean handle error by show an html message to the user, then you should put the code that can throw an exception inside a try...catch block, and the catch block changes the content type back to text/html and display the error in the way you want.
But since the content type is added in the DefaultStreamedContent, maybe only a redirection can solve this.
Better to use obtain all exception in one like ;
} catch (Exception e) {
handleError(e);
}
handleError method ;
private void handleError (Throwable t) {
try {
throw t;
} catch (AccessException ae) {
FacesUtil.setErrorMessage("CCCCCCC");
} catch (SQLException sqle) {
FacesUtil.setErrorMessage("CCCCCCC");
} catch (ConnectException ce) {
FacesUtil.setErrorMessage("CCCCCCC");
} catch (RemoteException re) {
FacesUtil.setErrorMessage("CCCCCCC");
} catch (NotBoundException nbe) {
FacesUtil.setErrorMessage("CCCCCCC");
} catch (IOException ioe) {
FacesUtil.setErrorMessage("CCCCCCC");
} catch (IllegalArgumentException iae) {
FacesUtil.setErrorMessage("CCCCCCC");
} catch (Throwable tt) {
FacesUtil.setErrorMessage("CCCCCCC");
}
FacesUtil.completeResponse();
}
Related
I am trying to login to our Application. When I input the username and the password and click login. It throws an error in the API. Saying: Incorrect Syntax near the keywoard 'IF'.
Here is the image for full exception details.
Full Exception Details
I tried to debug the solution and it starts from here:
[HttpGet]
[ActionName("checkUser")]
public HttpResponseMessage IsUserActive(string userNames)
{
try
{
var isActive = _userService.IsUserActive(userNames);
return Helper.ComposeResponse(HttpStatusCode.OK, isActive);
}
catch (Exception e)
{
throw e;
}
}
After this, it will then be redirected to this method/function:
public bool IsUserActive(string username)
{
try
{
var result = RetrieveAll().Where(x => x.Username.Equals(username));
return result.Any();
}
catch (Exception e)
{
throw e;
}
}
After this function, it will then be redirected to below function.
Then it will throw the exception in this line of code specifically in
return GetDbSet<User>().Where(x => x.DeleteFlag == false).OrderByPropertyName("LastName", SortDirection.Ascending);
public IQueryable<User> RetrieveAll()
{
try
{
return GetDbSet<User>().Where(x => x.DeleteFlag == false).OrderByPropertyName("LastName", SortDirection.Ascending);
}
catch (Exception e)
{
throw e;
}
}
GetDbSet Contains this line of code.
protected virtual DbSet<TEntity> GetDbSet<TEntity>() where TEntity : class
{
return Context.Set<TEntity>();
}
OrderByPropertyName Contains this line of code.
public static IQueryable<T> OrderByPropertyName<T>(this IQueryable<T> query, string attribute, SortDirection direction)
{
return ApplyOrdering(query, attribute, direction, "OrderBy");
}
I don't know what's wrong or where is that "IF" coming from or where should I edit for me to go proceed in logging in the application. I really appreciate your help. Thanks in advance.
I used Roster to create Roster Entry by Roster's method createEntry(BareJid user, String name, String[] groups),but I don't know how to get a BareJid. Anybody could help me?Here are my code,my userJid is a String:
Roster roster = XmppConnectionManager.getInstance().getRoster();
if (roster != null) {
try {
// String[] jids = userJid.split("#");
roster.createEntry(userJid, nickname, null);
} catch (SmackException.NotLoggedInException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
Log.w(TAG,"roster is null");
}
I just found it by Google, there is a JID helper class JidCreate:
JidCreate.bareFrom(userJid)
In C# 2005, I used the Nokia E63, I want to check SerialPort Exist Modem, While it run does not get run COM port, you see my code
private void btnGetPort_Click(object sender, EventArgs e)
{
cmbPort.Items.Clear();
foreach (string portName in SerialPort.GetPortNames())
{
try
{
using (SerialPort sp = new SerialPort(portName, 9600))
{
if (!(sp.IsOpen)) sp.Open();
sp.DiscardInBuffer();
sp.DiscardOutBuffer();
sp.Write("AT\r\n");
System.Threading.Thread.Sleep(100);
string response = sp.ReadExisting();
if (response == "OK")
{
cmbPort.Items.Add(portName);
}
}
}
catch (Exception ex)
{
continue;
}
}
}
i have read the post that have same problem as mine
JSF ViewScope - returning null on actions do not update the view
but it haven't worked for me cause i already use the h:commandLink in another page and its works perfectly but in this page it doesn't .
this is the request Bean
public class AddSectionBean {
public String delete(String id) {
try {
HttpSession session = SessionUtil.getSession();
UserVO userVOCreater = (UserVO) session.getAttribute("userVO");
SectionsDao.getInstance().deleteSectionById(
Integer.parseInt(id));
LoggerVO loggerVO =new LoggerVO();
loggerVO.setUserid(userVOCreater.getId());
loggerVO.setLog("deleted Section Id:"+id);
LoggerDao.getInstance().insertLogger(loggerVO);
} catch (Exception e) {
e.printStackTrace();
BundleMessages.getInstance().setMessage("error",
FacesMessage.SEVERITY_ERROR);
logger.error(e.getMessage(), e);
}
return null;
}
}
and the link is inside a richtable for every column
<rich:column>
<h:commandLink id="actualDelete" styleClass="delete_#{sectionsBean.datatableSections.rowIndex}" action ="#{addSectionBean.delete(s.id)}" />
</rich:column>
Note That: i tried to return the outcome instead of null but when i do that i lose the style and scripts in page
, note that the scripts have no effect cause i have tested it with them and had the same result
the problem solved by moving the delete method to the bean that view the table and calling the database method again inside the delete function to reload the table even its reloads in the postConstruct function
public class SectionsBean{
List<SectionVO> sectionsList = new ArrayList<SectionVO>();
#PostConstruct
public void postConstruct() {
try {
this.sectionsList = SectionsDao.getInstance().getSections();
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage(), e);
}
}
public String delete(String id) {
try {
HttpSession session = SessionUtil.getSession();
UserVO userVOCreater = (UserVO) session.getAttribute("userVO");
SectionsDao.getInstance().deleteSectionById(
Integer.parseInt(id));
LoggerVO loggerVO =new LoggerVO();
loggerVO.setUserid(userVOCreater.getId());
loggerVO.setLog("deleted Section Id:"+id);
LoggerDao.getInstance().insertLogger(loggerVO);
//reload the database table
this.sectionsList = SectionsDao.getInstance().getSections();
} catch (Exception e) {
e.printStackTrace();
BundleMessages.getInstance().setMessage("error",
FacesMessage.SEVERITY_ERROR);
logger.error(e.getMessage(), e);
}
BundleMessages.getInstance().setMessage("success",
FacesMessage.SEVERITY_INFO);
System.out.println("calling delete id="+id);
return null;
}
}
I have simple code to send sms. It works fine. Just little problem. How can I figure out that sms can not be send? Some timeout for Connection or other way? Let's say if there is no network, no sim card or no credit. Thanks
Here is code:
public static void sendSMS(String content, String number) {
MessageConnection mc = null;
TextMessage msg;
try {
mc = (MessageConnection) Connector.open("sms://" + number,Connector.WRITE,true);
msg = (TextMessage) mc.newMessage(MessageConnection.TEXT_MESSAGE);
msg.setPayloadText(content);
mc.send(msg);
} catch (final Exception e) {
e.printStackTrace();
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(e.getMessage());
}
});
} finally {
try {
if (mc != null) {
mc.close();
}
} catch (IOException e) {
}
}
}
private void sendSMS(final String no, final String msg) {
try {
new Thread() {
public void run() {
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + no);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
System.out.println("Message Sent Successfully : Datagram");
Dialog.alert("Message Sent Successfully");
} catch (Exception e) {
System.out.println("Exception **1 : " + e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
System.out.println("Exception 1 : " + e.toString());
e.printStackTrace();
} finally {
try {
dc.close();
dc = null;
} catch (IOException e) {
System.out.println("Exception 2 : " + e.toString());
e.printStackTrace();
}
}
} else {
MessageConnection conn = null;
try {
conn = (MessageConnection) Connector.open("sms://" + no);
//generate a new text message
TextMessage tmsg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
//set the message text and the address
tmsg.setAddress("sms://" + no);
tmsg.setPayloadText(msg);
//finally send our message
conn.send(tmsg);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
System.out.println("Message Sent Successfully : TextMessage");
Dialog.alert("Message Sent Successfully : TextMessage");
} catch (Exception e) {
System.out.println("Exception **1 : " + e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
System.out.println("Exception 3 : " + e.toString());
e.printStackTrace();
} finally {
try {
conn.close();
conn = null;
} catch (IOException e) {
System.out.println("Exception 4 : " + e.toString());
e.printStackTrace();
}
}
}
}
}.start();
} catch (Exception e) {
System.out.println("Exception 5 : " + e.toString());
e.printStackTrace();
}