Track completed downloads from glassfish - servlets

I want to be able to track completed downloads served by my glassfish server. I couldn't find a 100% correct solution using servlet life cycle listeners.
Does anyone have a better idea?

Put a try-catch on IOException while serving the file download. If it's thrown, then serving the file download has failed.
E.g. in a custom file servlet:
try {
response.getOutputStream().write(...);
// Success!
} catch (IOException e) {
// Fail!
throw e;
}
Or in a servlet filter which is mapped on the appropriate URL pattern matching file downloads:
try {
chain.doFilter(request, response);
// Success!
} catch (IOException e) {
// Fail!
throw e;
}

Related

Configure Windows Service to restart on both graceful AND ungraceful shutdown

I am aware of the Recovery section of the Service control, and how we can set an app to restart after failure.
I have created a .NET 6 worker service to run as a windows service. The problem is that whenever there is an exception in the code, the app logs the error but then shuts down gracefully. This does not signal to windows that the service should be restarted since it returns an exit code of 0.
I've tried returning an exit code of -1 (by setting Environment.ExitCode and returning -1 from Main()) but it's ignored.
I've also tried setting the exit code of the underlying WindowsServiceLifetime and that also does not work.
Are there any ways to have the SCM restart the service no matter how it shut down?
Exceptions should not bring down the host. Exceptions do not bring down IIS and they should not bring down a Windows Service.
You should put try/catch where work begins – every endpoint and background service. In the catch you should log the error.
Here is an endpoint example:
[Route("Get")]
[HttpGet]
public async Task<IActionResult> GetAsync()
{
try
{
return Ok(await BusinessRules.GetSomethingAsync());
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
throw;
}
}
Here is a background service example:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
//Need a try/catch round Task.Delay because exception will the thrown
//if stoppingToken is activated and we don't care about logging this exception.
try
{
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
}
catch { }
await BusinessRules.DoSomethingAsync(stoppingToken);
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
//In a loop, log file can fill up quickly unless we slow it down after error.
try
{
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
}
catch { }
}
}
}

How to make a method transactional in micronaut

I am using micronaut with sqlite db in my appliation and service class method looks like this:-
private void loadListIntoDb(Stream<EmpDto> lines) {
try {
empRepository.deleteAll();
lines.forEach(empRepository::saveEmpList);
} catch (Exception ex) {
throw new RuntimeException("error while loading file into db", ex);
}
}
What I want is if saveEmpList get failed, all the deleted data by deleteAll method should also get reverted back.
I have tried like this to test but it didn't rolled back the deleted items:
#Transactional
private void loadListIntoDb(Stream<EmpDto> lines) {
try {
empRepository.deleteAll();
throw new Exception("test exception");
} catch (Exception ex) {
throw new RuntimeException("error while loading file into db", ex);
}
}
Is there anything that I am missing.
Regards,
Finally resolved it. We can't make a private method transactional in Micronaut. We need to make the method as public.

Error in ServletFileUpload#parseRequest(request) with tomcat 10

Working on a simple file upload program. I had to use jakarta.servlet.* classes as I am using Tomcat v10. I am getting compile time error on parseRequest(request) line.
Code :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ServletFileUpload sf = new ServletFileUpload(new DiskFileItemFactory());
try {
List<FileItem> multifiles = sf.parseRequest(request);
for(FileItem i : multifiles) {
i.write(new File("C:/Users/Luffy/Documents/FileUploadDemo/"+i.getName()));
}
response.getWriter().print("The file is uploaded");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.getWriter().print("The file is uploaded");
}
The error is as below:
The method parseRequest(javax.servlet.http.HttpServletRequest) in the type ServletFileUpload is not applicable for the arguments (jakarta.servlet.http.HttpServletRequest)
I searched a lot on google but couldn't find a solution.
Please suggest a workaround or possible solution. Thanks in advance.
This is my first post in Stack overflow. So ignore my mistakes if any :)
You are trying to use the ServletFileUpload class from commons-fileupload, which doesn't work with a jakarta.servlet.http.HttpServletRequest. The library must be adapted to work with Servlet 5.0 classes.
Fortunately since Servlet 3.0 (Tomcat 8.0) multipart/form-data requests can be parsed by the servlet. You just need to:
Add a #MultipartConfig annotation to your servlet,
Use HttpServletRequest#getParts():
try {
final Collection<Part> parts = request.getParts();
for (final Part part : parts) {
part.write("C:/Users/Luffy/Documents/FileUploadDemo/"+part.getSubmittedFileName());
}
response.getWriter().print("The file has been uploaded successfully.");
} catch (Exception e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Upload failed.");
}

Xamarin forms local store exception when insert item

Almost everything works great except one form that doesn't save some data to Azure database and I can't catch any info about exception i.e exception instance is null when break point stop in exception of type MobileServiceLocalStoreException. I checked the initialization of the local store and there is no problem with it, so what could be the reason behind this exception.
public async Task<T> CreateItemAsync(T item)
{
try
{
await table.InsertAsync(item);
}
catch(MobileServiceLocalStoreException ex)
{ // here exception occurd
Debug.WriteLine(ex.Message);
}
catch(Exception ex)
{
}
return item;
}

asp.net + exceptions and redirecting

My intention is to log an error(I am using Log4Net) when an exception is caught and redirect to a pretty looking page with some error message. I have a class that returns a Type T object , mostly a DataSet.
In my Catch statement I wrote this, it works but I am not sure if there's a more appropriate way of handling, can someone please advice. Thanks. Note that the throw cannot be omitted because the class has a return type.:
catch (Exception ex)
{
log.Error(ex);
HttpContext.Current.Response.Redirect("~/errorPage.aspx");
throw ex;
}
It depends upon how you want to handle error on the page, In general , unhandled exception should be bubbled up to application_error in gloabl.asax file to it generic.Here is one simple way to handle this error.
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
// Get the exception object.
Exception exc = Server.GetLastError();
// Handle HTTP errors
if (exc.GetType() == typeof(HttpException))
{
// The Complete Error Handling Example generates
// some errors using URLs with "NoCatch" in them;
// ignore these here to simulate what would happen
// if a global.asax handler were not implemented.
if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength"))
return;
//Redirect HTTP errors to HttpError page
Server.Transfer("HttpErrorPage.aspx");
}
// For other kinds of errors give the user some information
// but stay on the default page
Response.Write("<h2>Global Page Error</h2>\n");
Response.Write(
"<p>" + exc.Message + "</p>\n");
Response.Write("Return to the <a href='Default.aspx'>" +
"Default Page</a>\n");
// Log the exception and notify system operators
ExceptionUtility.LogException(exc, "DefaultPage");
ExceptionUtility.NotifySystemOps(exc);
// Clear the error from the server
Server.ClearError();
}

Resources