Images not displaying after ajax function until workspace refresh - 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.

Related

How to download files in background regardless of Application state?

This has been asked a couple of times on Unity Questions, but never answered.
All I need to do is creare an Android pluugin which downloads few files from given urls and show a downloading progress in notification panel. Downloading should continue even if my Unity application is out of focus.
(source: cuelogic.com)
Here is a peice of code that I have right now:
void DownloadFiles(string[] urls)
{
foreach(var url in urls)
{
StartCoroutine(DownloadFile_CR(url));
}
}
IEnumerator DownloadFile_CR(string url)
{
WWW www = new WWW(url);
while(!www.isDone)
{
yield return null;
}
if(www.error == null)
{
//file downloaded. do something...
}
}
These are some texture files. So How do I get the texture result back from native android code?
Any king of help is appreciated.
I had the same problem. At first, I used a service that worked in the background and downloaded the files I needed, including calculating progress and on complete events.
Then, I made my plugin a little more simple and easy to use. You make an instance of a Java object, providing it with the GameObject name and method name for the responses. I used json to serialize and deserialize java and C# objects, because only strings can be passed between Unity's MonoBehaviour objects and java objects.
Here is how the downnload looks in the android plugin:
Uri Download_Uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
//Restrict the types of networks over which this download may proceed.
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//Set whether this download may proceed over a roaming connection.
request.setAllowedOverRoaming(true);
//Set the local destination for the downloaded file to a path within the application's external files directory
String[] split = url.split("/");
request.setDestinationInExternalFilesDir(activity, null, split[split.length-1]);
//Set the title of this download, to be displayed in notifications (if enabled).
request.setTitle("Downloading " + title);
//Set a description of this download, to be displayed in notifications (if enabled)
request.setDescription("Downloading " + name);
request.setVisibleInDownloadsUi(false);
//Enqueue a new download and get the reference Id
long downloadReference = downloadManager.enqueue(request);
Then you could send back to unity the reference Id so you can get the progress and check if a file is still downloading once your app is been restarted (use SharedPreferences \ PlayerPrefs to store them)
If you want it to continue even when unity is not in focus then you cannot do it in C# in Unity with the WWW class.
If i wanted to do this i would probably write a native Android plugin that starts a download service.
From the official google docs:
A Service is an application component that can perform long-running
operations in the background, and it does not provide a user
interface. Another application component can start a service, and it
continues to run in the background even if the user switches to
another application.
Services are not that complex, you start them with Intents just as you would an activity and there are lots of examples online for this type of service.
Here is the official Android documentation regarding services: https://developer.android.com/guide/components/services.html

JSF page load is very slow

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

Java - refresh opened html page from application

I have an application that creates a html page from app (I use freemarker). After that, I open the generated webpage from application using Desktop like this:
public void openPage() {
if (Desktop.isDesktopSupported()) {
try {
File file = new File("index.html");
Desktop.getDesktop().open(file);
} catch (IOException ex) {
System.out.println("Error opening a html page.");
ex.printStackTrace();
}
}
}
Now, my question is: Is there a way to refresh the page from my application? I am changing the concent dynamically and I would like to refresh the page in the browser every few seconds.
Or would it be better to just update the page on background and refresh it directly in the html code using javascript?
Thanks for any tips!
EDIT: Note, that I would like to communicate back to my java application from some form on that webpage (for example sending parametres to specify the way my page is updated)
Use AJAX technology (jQuery pretty much fits your needs) to invoke a server side controller in your application. You can then negotiate the need for a data update. A JSON API is recommended for this. You can use Jackson for JSON-related operations in your Java code.
To save bandwidth, you could poll for only a boolean value to determine whether the server has new data since your last update (e.g. provide since=[some_timestamp] as request param) and query for the actual data only if it makes sense (that is, the server returned true).

Why is this URL not opened from Play! Framework 1.2.4?

I have a URL in my Play! app that routes to either HTML or XLSX depending on the extension that is passed in the URL, with a routes line like :-
# Calls
GET /calls.{format} Call.index
so calls.html renders the page, calls.xlsx downloads an Excel file (using Play Excel module). All works fine from the browser, a cURL request, etc.
I now want to be able to create an email and have the Excel attached to it, but I cannot pull the attachment. Here's the basic version of what I tried first :-
public static void sendReport(List<Object[]> invoicelines, String emailaddress) throws MalformedURLException, URISyntaxException
{
setFrom("Telco Analysis <test#test.com>");
addRecipient(emailaddress);
setSubject("Telco Analysis report");
EmailAttachment emailAttachment = new EmailAttachment();
URL url = new URL("http://localhost:9001/calls.xlsx");
emailAttachment.setURL(url);
emailAttachment.setName(url.getFile());
emailAttachment.setDescription("Test file");
addAttachment(emailAttachment);
send(invoicelines);
}
but it just doesn't pull the URL content, it just sits there without any error messages, with Chrome's page spinner going and ties up the web server (to the point that requests from another browser/machine don't appear to get serviced). If I send the email without the attachment, all is fine, so it's just the pulling of the file that appears to be the problem.
So far I've tried the above method, I've tried Play's WS webservice library, I've tried manually-crafted HttpRequests, etc. If I specify another URL (such as http://www.google.com) it works just fine.
Anyone able to assist?
I am making an assumption that you are running in Dev mode.
In Dev mode, you will likely have a single request execution pool, but in your controller that send an email, you are sending off a second request, which will block until your previous request has completed (which it won't because it is waiting for the second request to respond)...so....deadlock!
The resaon why external requests work fine, is because you are not causing the deadlock on your Play request pool.
Simple answer to your problem is to increase the value of the play.pool in the application.conf. Make sure that it is uncommented, and choose a value greater than 1!
# Execution pool
# ~~~~~
# Default to 1 thread in DEV mode or (nb processors + 1) threads in PROD mode.
# Try to keep a low as possible. 1 thread will serialize all requests (very useful for debugging purpose)
play.pool=3

Save Java Applet Variable to Mysql

Hi
I've done a lot of research on the best way to communicate between a java applet and MySql Database.
I have a tune player which I have students logging onto, it's a java applet with a speed slider. I want to save the speed that they play each tune at so it goes back to the same speed the next time they open that tune.
It seems I have a number of options, none of which seem very neat.
Use a javascript function to
periodically check the speed and
save it to a cookie, then each page
of the site would have to check
cookies relationg to each tune.
Make each link on the page call a
javascript function to check the
speed variable in the applet and add
it to a perameter in the url then
redirect so the next php page can
save the speed to a database. This
way when the user navigates away the
speed will be saved, but this won;t
work if the back button is used.
Is there a better way of doing this?
Use the JNLP API and the problems should be solved.
Since Java 1.6.0_10+, it is possible to use the Java Web Start API services (JNLP API) within an embedded applet. The JNLP API provides the PersistenceService. Here is a small demo. of the PersistenceService.
If the user hits the back button (or otherwise leaves the page), the destroy() method will be called. Override the destroy method and persist the data at that time.
No need to use JavaScript.
The java code below posts variables to a PHP script on the web server then
shows the server response on the console
private void post()
throws MalformedURLException, IOException
{ URL url;
URLConnection con;
OutputStream oStream;
String parametersAsString;
byte[] parameterAsBytes;
String aLine; // only if reading response
parametersAsString = "msg=hi&to=memo";
parameterAsBytes = parametersAsString.getBytes();
// send parameters to server
url = this.getCodeBase();
url = new URL(url + "scriptfile.php");
con = url.openConnection();
con.setDoOutput(true);
// setDoInput(true); // only if reading response
con.setDoInput(false);
con.setRequestProperty("Content=length", String.valueOf(parameterAsBytes.length));
oStream = con.getOutputStream();
oStream.write(parameterAsBytes);
oStream.flush();
// read response from server & show the server response on the Java console or whatever ...
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
aLine = in.readLine();
while (aLine != null)
{ System.out.println(line);
aLine = in.readLine();
}
in.close();
oStream.close();
}
I'd suggest you get the applet to update the database. Whenever the speed slider changes you can fire off an update to the database, or you might need to coalesce multiple changes into one request depending on usage.
When the applet changes tune it can also do its own lookup of the correct speed.
Note that the applet will probably not be able to hit the database directly - browsers should restrict what I/O operations are available to applets - but you should be able to get the applet to hit a URL on the server that will actually perform the update. Signing the applet may let you hit the database but you should read up on the applet security model and the various browser quirks first.
It's not really clear how all of this is set up since you don't have a lot of details. However, assuming that you have an actual Java applet, I'd say the following:
If the Java applet requires a login (that is, it knows who the user is) then it can store the preference on the server. To do this you could have the applet connect to the server using JDBC, which isn't generally a good idea for internet-facing applets, or you could have the applet send a message to a server process such as a web server. That process connects to the mysql server.
The applet can communicate directly with the browser using Javascript. So you can have the applet set the cookie when the slider changes, instead of having the Javascript set it.

Categories