How to resolve JSF1095: The response was already committed by the time (...), thrown in every Request - mojarra

I've read a lot about how Flash is bugged in Mojarra, but I haven't any problems with it since now. I have a JavaEE-Project (1.8) where I have a #ManagedBean (javax.faces.bean) with #ViewScope (javax.faces.bean) and a function like
public void foo() throws IOException{
FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(keepMessages);
FacesContext.getCurrentInstance().addMessage("msg", new FacesMessage(FacesMessage.SEVERITY_INFO, message, detail));
redirectController.redirect("index.html");
}
The Redirect-Function in redirectController is just
public void redirect(String url) throws IOException {
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
}
I'm calling this function from a xhtml-File by
<p:commandLink action="#{bean.foo()}"
update="#form">
buttontext
</p:commandLink>
When I'm pressing the Button, the redirect works and the message appears, but with this and and every following request I get this message in server.log:
Warnung: JSF1095: The response was already committed by the time we tried to set the outgoing cookie for the flash. Any values stored to the flash will not be available on the next request.
I'm using Glassfish 4.1.1 which runs Mojarra 2.2.12 and Primefaces 5.2.
I'm worried that this could cause sideeffects, other then spamming the log. What am I doing wrong?
PS: Since this is my first post on stackoverflow, I would like to say thank you for all the good answers you gave others in the past which saved me a lot of time and trouble. :-)

Related

Force FirebaseCrashlytics print logs to console

Is it possible to force FirebaseCrashlytics to print the log messages to console prior google buy them (and make shit as always) it was possible using the fabric api. But now seems these methods were removed.
Is there any way to do for the android sdk?
Short Answer
IT IS IMPOSSIBLE (USING FIREBASECRASHLYTICS SDK)
Complete Answer
It is a shame that prior to Google buys Crashlytics, watch the log messages on development console was an easy task to do. But now these methods were removed.
The whole problem is, if I'm in the development environment and want to follow the code execution (by watching the log messages) Crashlytics won't show them... I need to intentionally cause an crash, then wait a time for it be uploaded to dashboard them start hunting for the registers among maybe thousands of others... (non sense)
I filled a bug report for firebase
https://github.com/firebase/firebase-android-sdk/issues/3005
For those who don't want wait to google fix their shit there is a workaround:
FirebaseApp.initializeApp(this);
if (BuildConfig.DEBUG) {
try {
Field f = FirebaseCrashlytics.class.getDeclaredField("core");
f.setAccessible(true);
CrashlyticsCore core = (CrashlyticsCore) f.get(FirebaseCrashlytics.getInstance());
f = CrashlyticsCore.class.getDeclaredField("controller");
f.setAccessible(true);
Object controler = f.get(core);
f = controler.getClass().getDeclaredField("logFileManager");
f.setAccessible(true);
f.set(controler, new LogFileManager(null, null) {
#Override
public void writeToLog(long timestamp, String msg) {
super.writeToLog(timestamp, msg);
System.out.println(msg);
}
});
FirebaseCrashlytics.getInstance().log("test");
} catch (Exception e) {
}
}
The code above is replacing the field that was supposed to write the log messages to a file (AND ACTUALLY DOES NOTHING) by a new class which does all the previous one (NOTHING) but prints on the fly all messages logged.
ATTENTION
I've tested this on firebase-analytics:19.0.1 and this will only on versions of the lib with the same fields names
IT WON'T WORK IN OBFUSCATED BUILD, if you obfuscate the code in DEBUG mode the code will break (unless you add the proper rules to proguard)
If this topic reaches google engineers is very likely they will remove/obfuscate the code for next versions
google...

print jfreechart on IE

I print a jfreechart on Internet Explorer and i got a blank page.
Actually, the version of my IE is 11.0.9600.18697CO, 11.0.43 (KB4021558).
I hadn't this problem with older version IE.
I haven't this problme on Chrome and Firefox.
My freechart is generated on the server, showed on the client by a servlet and deleted on the server (it is a jfreechart-one time]).
On the console debug of IE, when i execute window.print(); there are requets sended to server. I think it caused problem (although http code = 200).
If i don't delete the chart on the server, i have no problem.
Someone hit the same problem? Solution?
thanks a lot,
best regards
In a servlet context using ChartUtilities, instead of using one of the save… methods, try using the corresponding write… method.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws … {
OutputStream out = response.getOutputStream();
…
//ChartUtilities.saveChartAsPNG(file, chart, …);
ChartUtilities.writeChartAsPNG(out, chart, …);
}
Could you explain why? I am using ServletUtilities.saveChartAsPNG()
I'm guessing that there's a race condition that allows the file to be deleted prematurely. If you need the ChartRenderingInfo, the corresponding ChartUtilities method would likely be writeChartAsPNG(). If you can't switch, use a DelayQueue<File> to defer deleting the temporary file.

Throwing exception in WCF service operation, anything to look out?

I am just learning WCF and wrote a Windows Service hosting a WCF service. Ever since I started it in service.msc in the remote server (physically remote, and very slow) I think I have already hit and fixed like a hundred errors here and there already. I am now finally stuck.
At this point, I have enabled tracing and message logging. The first and only function call looks like this:
[OperationContract]
public MyServiceResponse ConnectToAXDynamicsViaDotNET2BusinessConnectorWithSadFace()
{
try
{
throw new NotImplemented();
}
catch(Exception ex)
{
return new MyServiceResponse(ex, ex.Message);
}
}
[DataContract]
public class MyServiceResponse
{
// ...
}
Upon calling the operation, the client just sits and waits until timeout. Checking the trace, it records my thrown exception. So it makes me wonder if WCF actually blocks there and ignore my catch clause.
I then tested with just a simple return value without throwing and it FINALLY works.
My question is, how then can I make the above scenario work, ie. catch the exception and return a sensible result back to client? Maybe it's just the tracing that blocks me, but I want to enable tracing during this whole debugging process otherwise it's really hard to work.
Thanks for your precious help!
EDIT: Sorry, I found this right after I posted this question. Happens all the time: http://msdn.microsoft.com/en-us/library/ee942778.aspx but I have yet to read it as I got to run off now. Not sure it it will solve my problem.
Risk being downvoted, but just for documentation sake and general usefulness of having this question:
Through reading the FaultException handling articles, I guess the above behavior is due to Exception class not serializable. And the service silently disconnects itself without returning any error messages eventhough the "send (unknown) faults to client" is enabled. As for why it does so, I have no idea yet. Will update if I find out more.
I have since changed to throw new FaultException() instead of returning my own MyServiceResponses.

How safe or bad is using BasePage for opening and closing SQL connection?

I have BasePage.cs class which is being used by other .cs files instead of System.Web.UI.Page (public partial class page : BasePage).
I am using it for opening and closing SQL connections to make sure every SQL connection gets closed.
Code looks like this
{
public class BasePage: System.Web.UI.Page
{
public SqlConnection globalConnection;
protected override void OnInit(EventArgs e)
{
globalConnection = new SqlConnection();
globalConnection.ConnectionString = ConfigurationManager.ConnectionStrings["kontemiConnectionString"].ToString();
globalConnection.Open();
}
protected override void OnUnload(EventArgs e)
{
if (globalConnection != null)
{
globalConnection.Close();
}
}
}
}
So far it has worked really well for me. It means that every time a connection opens it also gets closed. Or at least I thought so.
My question is whether this solutions is bulletproof and every single connection gets closed in case there is some processing error during code execution. When tracing this code, if I on purpose create error 500 it always goes to OnUnload event and gets closed.
So, do you think is this execution safe?
(To stop discussion whether I shouldn't open SQL when I actually need it, answer is that every page which uses BasePage also opens a SQL connection.)
Opening and closing SQL connections where you are using them is better practice. Under the hood, the CLR manages connection pooling anyway - reusing connections and closing them when it sees fit. Doing lots of open and closes on connections with the same connection string doesn't add up to as much overhead as you might expect.
I might be wrong, but my guess would be that the connection does not get closed if the page lifecycle is ended through an exception before OnUnload fires. The very least you could do to prevent this is make sure you catch all exceptions on a global 'last-chance' level, and close the connection there. I still think using connections locally, ideally with using blocks, is the better solution, because it doesn't keep connections open longer than it needs to, and you don't have to worry about closing them (the semantics of using will do the work for you).

Disable (Politely) a website when the sql server is offline

I work at a college and have been developing an ASP.NET site with many, many reports about students, attendance stats... The basis for the data is an MSSQL server DB which is the back end to our student management system. This has a regular maintenance period on Thursday mornings for an unknown length of time (dependent on what has to be done).
Most of the staff are aware of this but the less regular users seem to be forever ringing me up. What is the easiest way to disable the site during maintenance obviously I can just try a DB query to test if it is up but am unsure of the best way to for instance redirect all users to a "The website is down for maintenance" message, bearing in mind they could have started a session prior to the website going down.
Hopefully, something can be implemented globally rather than per page.
Drop an html file called "app_offline.htm" into the root of your virtual directory. Simple as that.
Scott Guthrie on the subject and friendly errors.
I would suggest doing it in Application_PreRequestHandlerExecute instead of after an error occurs. Generally, it'd be best not to enter normal processing if you know your database isn't available. I typically use something like below
void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
string sPage = Request.ServerVariables["SCRIPT_NAME"];
if (!sPage.EndsWith("Maintenance.aspx", StringComparison.OrdinalIgnoreCase))
{
//test the database connection
//if it fails then redirect the user to Maintenance.aspx
string connStr = ConfigurationManager.ConnectionString["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
try
{
conn.Open();
}
catch(Exception ex)
{
Session["DBException"] = ex;
Response.Redirect("Maintenance.aspx");
}
finally
{
conn.Close();
}
}
}
You could display a message to people who have logged in saying "the site will be down for maintenance in xxx minutes" then run a service to log everyone out after xxx minutes. Then set a flag somewhere that every page can access, and at the top of every page(or just the template page) you test if that flag is set, if it is, send a redirect header to a site is down for maintenance page.
What happens now when the site is down and someone tries to hit it? Does ADO.NET throw a specific exception you could catch and then redirect to the "website down" page?
You could add a "Global.asax" file to the project, and in its code-behind add an "Application_Error" event handler. It would fire whenever an exception is thrown and goes uncaught, from anywhere in your web app. For example, in C#:
protected void Application_Error(object sender, EventArgs e)
{
Exception e = Server.GetLastError().GetBaseException();
if(e is SqlException)
{
Server.ClearError();
Server.Transfer("~/offline.aspx");
}
}
You could also check the Number property on the exception, though I'm not sure which number(s) would indicate it was unable to connect to the database server. You could test this while it's down, find the SQL error number and look it up online to see if it's specifically what you really want to be checking for.
EDIT: I see what you're saying, petebob.
The "offline.html" page won't work if the user was already navigating within the site, or if he's accessing the site from a bookmark/external link to a specific page.
The solution I use is to create a second web site with the same address (IP or host header(s)), but have it disabled by default. When the website is down, a script deactivates the "real" web site and enables the "maintenance" website instead. When it comes back online, another script switches back to the "real" web site.
The "maintenance" web site is located in a different root directory, with a single page with the message (and any required images/css files)
To have the same message shown on any page, the "maintenance" web site is set up with a 404 error handler that will redirect any request to the same "website is down for maintenance" page.
A slightly more elegant version of the DB check on every page would be to do the check in the Global.asax file or to create a master page that all the other pages inherit from.
The suggestion of having an online site and an offline site is really good, but only really applicable if you have a limited number of sites to manage on the server.
EDIT: Damn, the other answers with these suggestions came up after I loaded the page. I need to remember to refresh before replying :)
James code forgets to close the connection, should probably be:
try
{
conn.Open();
}
catch(Exception ex)
{
Session["DBException"] = ex;
Response.Redirect("Maintenance.aspx");
}
finally
{
conn.Close();
}
Thanks for the replies so far I should point out I'm not the one that does the maintenance nor does I have access all the time to IIS. Also, I prefer options where I do nothing as like all programmers I am a bit lazy.
I know one way is to check a flag on every page but I'm hoping to avoid it. Could I not do something with the global.asax page, in fact, I think posting has engaged my brain:
Think I could put in Application_BeginRequest a bit of code to check the SQL state then redirect:
HttpContext context = HttpContext.Current;
if (!isOnline())
{
context.Response.ClearContent();
context.Response.Write("<script language='javascript'>" +
"top.location='" + Request.ApplicationPath + "/public/Offline.aspx';</scr" + "ipt>");
}
Or something like that may not be perfect not tested yet as I'm not at work. Comments appreciated.