I have a website with some images using the p:graphicsimage tag with the rendered attribute. So the images are only shown if the bean (db query) returns a true.
I also have a login form checking the user against a db. This works fine but my current problem is that the page needs a lot of time for loading the page(arround 25sec).
The bean method of the loginbutton is called ~20sec after pressing the loginbutton but I don't know what the server is doing during this time. Any idea how to check the server states or how to fix that problem?
My beans are ManagedBeans
Thanks in advance!
You can debug your method and benchmark the potential areas very old-school like
long startTime = System.currentTimeMillis();
method();
long endTime = System.currentTimeMillis();
System.out.println((endTime - startTime) + "ms")
or use a profiler like yourkit.
There are a couple of things you can do to improve performance of your screens
GZIP filter will reduce the initial load time significantly. It compresses the page contents while transferring to client browser. Refer to https://stackoverflow.com/a/35567295/5076414
You can additionally implement a cacheFilter to bring performance of
your screens at par with JavaScript based UI. This will cache the static content of your screen such as icons, images, stylesheets, javascripts etc. You can control what to cache and what to exclude. Refer to https://stackoverflow.com/a/35567540/5076414
For client side UI components, you can use Primefaces which is JQuery
based UI.
How to verify if my screen is using gzip and cache
To see if your contents are already usign gzip and cache, In your Google Chrome Browser -> right click on your screen -> inspect -> click network tab -> refresh your screen.
Click on the images, icons, stylesheets and see if you see following in response header
Cache-Control:max-age=2592000 if the status of element is 304 (coming from cache)
Content-Encoding:gzip if the status of element is 200
Related
I need to find a way of reading GET/POST requests from the WEB browser(Network) and retrieve the information like Status, Domain, Size, IP and the most important Timeline.
The main purpose of this is to measure requests count after each action on the WEB page and their execution time. Also this will help me to know if any requests(AJAX/JavaScript) are executing before I want to perform any actions on the WEB page.
Could you please help me with solution?
Assuming you don't want to tie yourself to a particular browser (via plugins or particular dev toolbars), need to capture responses from interactive user events (i.e. via simulated use of a website in a real browser, not dynamically created HTTP calls), and need to automate this, then a proxy server is the way to go.
Something like Browsermob can be set up as a proxy for all Selenium traffic. It can capture the entire content of all requests and responses, and let you generate you a (cross-browser) HAR file that you can then persist, visualise, or query via an API.
Obviously you could automate this, schedule the Selenium test runs, and either produce your own custom metrics with your own Java code; pipe the HAR into a JSON-savvy database for querying (say Elasticsearch) and visualisation, or just save the HARs for offline querying and diffing.
Some example code from the tests:
[...]
proxy.newHar("Test");
HttpGet get = new HttpGet(getLocalServerHostnameAndPort() + "/a.txt?foo=bar&a=1%262");
client.execute(get);
Har har = proxy.getHar();
HarLog log = har.getLog();
List<HarEntry> entries = log.getEntries();
HarEntry entry = entries.get(0);
HarRequest req = entry.getRequest();
[...]
Alternatively you can visualise the output by obtaining the HAR in string form and pasting into http://www.softwareishard.com/har/viewer/. That should give you something that looks very similar to the Network tab, but in a format that's easier to export, screenshot, and print.
Chrome comes with devtools by itself. Just hit 'F12'.
https://developer.chrome.com/devtools
Postman, it's useful for testing web services and API
https://www.getpostman.com/
Currently, i using XmlHttpRequest to uploading files to the server using HTML5 capabilities.
There's progress bar:
xhr.upload.addEventListener('progress', function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log(done);
});
... everything works fine, but it doesn't consider processing the file by server. So it shows 100% uploaded even when file weren't created yet.
The file receiver is Java servlet, which able to response only after return. So here's no way to count the percents left by its response.
Whether there are ways around it?
If the processing the server does takes a long time and you want to give feedback while it happens, here's a rough outline of a solution. This will take a while to implement so it's only really worth doing if the processing is slow.
Modify your servlet to do its work asynchronously, and return a 201 Accepted response to the client.
As the server processes the file, set the progress on an object, typically a ConcurrentHashMap injected with Spring if that's what you're using.
Expose an API that queries the current progress of the task without blocking for it to complete.
In your javascript, poll this API until the task completes, and show the progress.
You can return a tracking ID in the response at step 1 if you need to.
I've got a strange issue.
I am doing some screen scraping and then presenting data back to my user to make some selections. I don't have any control over the sites I am working with and I need them to first execute their Javascript.
The process is working fine locally, it just takes up to a minute for everything to happen. But when I push to Heroku the request times out after 30s, although I can see through the logs, that the actual processing keeps happening.
Could you recommend one of these solutions, or some alternative:
Somehow increase Heroku's timeout - I believe this is not possible (I am using PlayFramework 1.2.7 and Java)
Somehow speed up HTMLUnit - I've pasted my code below
Get the page HTML a different way - all I need is the HTML - after the Javscript (Ajax) has executed. Is there a better/faster way to do this?
Do the work in two steps, first use HTMLUnit to grab the page code and save it to a DB. Then grab the page code from the DB and do some processing on it. This is all I can think of.
The code:
LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(Level.OFF);
java.util.logging.Logger.getLogger("org.apache.commons.httpclient").setLevel(Level.OFF);
WebClient webClient = new WebClient();
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.waitForBackgroundJavaScript(20000);
Page page = webClient.getPage(url);
WebResponse response = page.getWebResponse();
String html = response.getContentAsString();
The correct way to run long-running processes is to use asynchronous workers. Even a process that takes 5 seconds will lock your web worker for that amount of time (assuming you're running synchronous workers), so it's always wise to delegate such tasks to asynchronous workers.
Follow this guide to get started: https://devcenter.heroku.com/articles/asynchronous-web-worker-model-using-rabbitmq-in-java
Background: I just finished a registration form for my site on my local host. Within the form users upload their first profile picture. The form is submitted with ajax, validated on the server side, and the image is written on the server side to a folder. Once the image is written I return that users username to the ajax success and then they are redirected to their newly created homepage.
Problem: When I test the form out on my local host all their data is imported into the db as expected. However the files are written to a folder within my eclipse workspace and it is not noticing the new data. I've tweaked my eclipse workspace preferences but it's refusing to refresh when the new images hit the files. So unfortunately, when the user is redirected to their homepage they are shown a 404 where their image should be. It will stay like this until I go into eclipse and refresh my workspace and then it shows up. I've figured out that the images are completely written to the file before the ajax success is called so the function isn't going too fast, the server (or eclipse workspace) is not refreshing.
Question: Is this something I should worry about when I transfer my site to a godaddy VPS? I am concerned that when users upload images the same thing will happen and they'll have to wait for however long it takes the server to realize there is new content. And this could be devastating to site popularity if I am displaying 404 images to users who are having their first experirience with the site. So Is there something I should do to prevent this problem on my local host. But more importantly do you think this will happen on a live server and if so what should I do?
Code: Here's my javascript code. So should I do anything in my success area to maybe check for this problem?
function addNewUser()
{
var form = new FormData();
var ajaxObject = getAjaxObject();
var gender = (getElement('registerMale').checked) ? "his" : "her";
form.append("userName", getValue('registerUserName'));
form.append("email", getValue('registerEmail'));
form.append("password", getValue('registerPassword'));
form.append("fName", getValue('registerFName'));
form.append("lName", getValue('registerLName'));
form.append("displayName", getValue('registerFName') + " " + getValue("registerLName"));
form.append("location", getValue('registerLocation'));
form.append("gender", gender);
form.append("currentDefault", getElement("registerCurrentDefault").files[0]);
form.append("discipline", getValue("registerDiscipline"));
form.append("birthDay", getValue("registerBirthDay"));
form.append("birthMonth", getValue("registerBirthMonth"));
form.append("birthYear", getValue("registerBirthYear"));
ajaxObject.open("POST", "addNewUser", true);
ajaxObject.send(form);
ajaxObject.onreadystatechange = function()
{
if(ajaxObject.readyState == 4 && ajaxObject.status == 200)
{
divLink("profile?user=" + ajaxObject.responseText);
}
};
}
This is not a problem to worry about.
Try running the app from the application server you are using. You will get the expected result.
I need to show a progress bar to the user who requests a file to download. I am using J2EE application to generate the file. User will submit the form data to get the file. The server takes all the submitted data manipulates, generates and sends a PDF file back to Client.
So I want to show a progress bar to the user till the file comes to the Client side.
Is there any way to do this ?
If I understand you well, you want to show a progress bar until your server is ready to send a file, not to show the progress of the file beeing downloaded.
If that is true, you're dealing with a tough excercise. A reliable progressbar needs to know (pretty exact) what you're doing and how long it will take. In your case, there are lots of unreliable factors (one of them, maybe the biggest, is the web itself).
So most developers use some kind of an "endless" animation to display "work in progress".
update
Based on your comment, the easiest way to display a "work in progress" animation would look like
$.ajax({
url: "/myscripts/myserverscript",
type: "POST",
data: {
foo: "bar"
},
dataType: "text",
beforeSend: function(xhr){
// display a progress animation
},
complete: function(xhr, status){
// hide the animation
}
...
});
In the case of a single request. You may also setup a global ajax event handler for both (.ajaxStart() and .ajaxStop()) to setup the show/hide functionallity.
References: .ajax(), .ajaxStart(), .ajaxStop()
progress bar for server side file generation:
We assume that the server needs many seconds to generate the file. This event is triggered by the original request, a blocking operation. When this finishes the file will have been generated and it'll be dispatched back to the client.
At the same time you want, via other requests (ajax), to be calling the server and getting a percentage back for the file which is currently being generated for the particular user.
The glue parts here are:
when the original request is generating the file it needs to store the progress in frequent intervals (i.e every 10%). Storing this data in the http session will work OK.
the other requests (ajax) simply need to be able to pull this information out of the http session
synchronizing (serializing access) on the http session, something that some web apps commonly do, is out of the question, since the other requests (ajax) would simply block until the original request finished
on the client side it's all html+javascript to provide the interaction you need (animated progress bar). Even if the intervals are very rough (jumping from 10% to 20% to 30%) you can animate the bar with jQuery. I've done it once in the past and it looks great.
progress bar for file download:
it's best to leave this to the browser's native dialog.
In Java you just wrap a javax.swing.ProgressMonitorInputStream around the input stream, but be aware that unless the server is sending in chunked streaming mode the display won't really mean anything, as the entire response will have been read into memory before the first byte is delivered to Java.
Using XMLHttpRequest you can download file and show progress.
showProgressBar();
var xhr = new XMLHttpRequest();
xhr.open("GET", 'https://upload.wikimedia.org/wikipedia/commons/d/dd/Big_%26_Small_Pumkins.JPG', true);
xhr.responseType = "blob";
xhr.onprogress = function (e) {
console.log(e.loaded / e.total * 100);//shows downloaded percentage
setProgressBarPercentage(e.loaded / e.total * 100);
}
xhr.onload = function () {
hideProgressBar();
var urlCreator = window.URL || window.webkitURL;
var url = urlCreator.createObjectURL(this.response);
var link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', 'FILENAME');
link.click();
}
xhr.send();