How do I load test data into my GWT Widget? - java

I am using eclipse with the Google Toolkit and I have created a widget with a listbox, vertical split panel and a couple of buttons. What I am trying to do is have a list of files in a local directory listed in the listbox and I want to be able to click on a file and have it displayed in the top part of the split panel. I found out the hard way about browsers and file IO and not being able to use java.io.File.
What are my options? Can I put the data files inside a jar or something and have the widget read it in that way? I need to do this as a test run, to implement an new feature with working with the data. It's not going to be any kind of final server hosted application, I am not concerned about how the actual files will be loaded in the future.
Any suggestions would be greatly appreciated.
Respectfully,
DemiSheep

If you just need a hard-coded list of values to visually test your widget, you can simply put these values in a String array and load it from there. Or you can http GET the strings from a server using RequestBuilder. You can keep a simple file (CSV, XML, JSON etc.) in your war directory and load this file using Request builder.
Example code from GWT developer guide:
import com.google.gwt.http.client.*;
...
String url = "http://www.myserver.com/getData?type=3";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// Couldn't connect to server (could be timeout, SOP violation, etc.)
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// Process the response in response.getText()
} else {
// Handle the error. Can get the status text from response.getStatusText()
}
}
});
} catch (RequestException e) {
// Couldn't connect to server
}
Make sure you inherit HTTP module:
<inherits name="com.google.gwt.http.HTTP" />

Create testcases with JUnit!
This is the official Google site describing Testing with JUnit and varios test methods: Google Web Toolkit: Testing. You definitly find a solution here^^

As it comes to GWT, there is no such thing sent to a browser as a .jar-file.
The easiest thing to fetch the file would be to
put the files on a server
fetch them via a http-call
Remember the same-origin-policy that applies to GWT as it is underlying all javascript-Restrictions

Related

How to implement a catch all route with java spark for an SPA

The app I'm trying to get working uses Vue.js and Java Spark. I am trying to get the SPA to work with HTML5 history mode. Right now it serves the index page and the app takes over routing from there. Because of html5 routing, if I try to go straight to a url such as "/about", i'll get an error. I tried to add a catch all route using:
get("/*", (rq, rs) -> new ModelAndView(map, "index.hbs"), new HandlebarsTemplateEngine());
But this overrides the previously defined static file routing in:
staticFileLocation("/public");
How can I implement a catch all route for all other pages without overriding the static file routes? I'd rather not have to redefine every route on the server to the same page. I've accomplished this in node.js with express, It has to be possible with Spark.
Spark.get("*", (request, response) ->
{
response.type("application/json");
return "not supported";
});
Should do the trick.

Dynamic BlazeDS endpoint configuration

I search for some help creating a web Flex application using BlazeDS and Java server with dynamic BlazeDS endpoint configuration.
First, I will try to explain my current situation.
I have a Flex 3.2 application that provides GUI of the application. From the ActionScript I call Java methods using BlazeDS. To access the BlazeDS I use a Config class that provides the endpoint as shown below (it is a constructor):
public function Config(): void {
if (_serviceUrl == null) {
try {
var browser: IBrowserManager = BrowserManager.getInstance();
browser.init();
var url: String = browser.url;
var host: String = mx.utils.URLUtil.getServerName(url);
var port: uint = mx.utils.URLUtil.getPort(url);
var parts: Array = url.split('/');
if (parts[2] == '') {
url = DEFAULT_URL;
Alert.show("Unable to determine server location, using default URL: " + DEFAULT_URL, "Connection error");
}
else {
url = parts[0] + '//' + parts[2] + '/' + parts[3] + '/messagebroker/amf';
}
_serviceUrl = url;
} catch (e: Error) {
Alert.show("Exception while trying to determine server location, using default URL: " + DEFAULT_URL, "Connection exception");
_serviceUrl = DEFAULT_URL;
}
}
}
The idea of the class is to determine the endpoint from the request URL. I use a Delegate class to call the remote methods using BlazeDS like the following:
{
import com.adobe.cairngorm.business.ServiceLocator;
import mx.rpc.IResponder;
import mx.rpc.remoting.RemoteObject;
public class AbstractRemoteDelegate
{
public function AbstractRemoteDelegate(responder:IResponder,serviceName:String)
{
_responder=responder;
_locator=ServiceLocator.getInstance();
_service=_locator.getRemoteObject(serviceName);
_service.showBusyCursor=true;
_service.endpoint = Config.instance.serviceUrl;
}
private var _responder:IResponder;
private var _locator:ServiceLocator;
private var _service:RemoteObject;
protected function send(operationName:String,... args:Array) : void {
_service.getOperation(operationName).send.apply(_service.getOperation(operationName),args).addResponder(_responder);
}
}
}
This approach actually works fine. However, I got across a situation where I can't use dynamically determined URL. In such a situation, I need a hard-coded URL in the Config.as file. And this is the problem. When trying to deploy the application to another server, I always need to rebuild the application with a new URL configuration in the ActionScript class Config.
Therefore I search for a way to define a static configuration for the Flex application to connect to a BlazeDS server. And the way to change such configuration without rebuilding the application so I can give the customer his own way to reconfigure and move the Flex application.
I thought about using a configuration file, but Flex runs on the client side and there is no configuration file!
I thought about using database configuration, but I don't have any database on the client side!
To sum up, I am looking for a way, how to get BlazeDS URL from a configuration to be able to change it without rebuilding the whole app.
Thanks for any useful suggestions.
EDIT: Revised the question to be more actual. I improved the way to determine the URL dynamically from the request URL, so it works now even for proxy server. However, my curiosity persists for the configuration of flex without rebuilding.
Here is an old example Blaze DS Service of mine which does basically the same as you did. It's just the string which needs to be created correctly. If the endpoint address is wrong, catch the error accordingly.
My project may currently not build because of Flexmojos ... I'm not able to test that yet.
Since it did not read you question properly, I misunderstood you: You can put a configuration file next to the SWF and load it via URLLoader or pass it via FlashVars. That should give you the freedom to pass the endpoint dynamically.

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

How do I handle file uploads with GWT?

I was looking through for some solutions to read a file after uploading and I found this:
Read text file in google GWT?
that has a solution of
new RequestBuilder(Method.GET, "path/to/file.txt").sendRequest("", new RequestCallback() {
#Override
public void onResponseReceived(Request req, Response resp) {
String text = resp.getText();
// do stuff with the text
}
#Override
public void onError(Request res, Throwable throwable) {
// handle errors
}
});
It seems to be a feasible solution for my case, but I am kinda new to this, can any one explain how can I apply this in gwt? i have FileUpload placed in a panel already and a click handler to handle the submit button click.
Can someone help me out with this?
The answer you link to is for reading files from the server. They are just requesting the file from the webserver. It sounds like you want to read files from the client (you are using a FileUpload). There are different methods of doing that based on the stack your app is running on and what clients you support.
The GWT FileUpload is just an input control on the form which allows the user to pick a file. It does not do any part of the actual file reading.
A common approach is to send the file as part of the HTML form to the server and then reflect it back to the client to get it into your web app. This site is a little old but is great at giving you the basics of this approach. There are several examples using this with GWT: for example which also links to this. This option has the widest client support, but costs more in network traffic.
If you know the clients support HTML5 you can also read the file in JavaScript using the File API. Here are some docs from Mozilla. Unfortunately, there's not really integrated GWT support for it, so you'll have to write some JavaScript. This option will not be supported by all clients, but also doesn't generate any network traffic.

Categories