I have the below code where incremental command is not working as expected. I have the below radio button once it is selected I will get the value from the txt box of product and do an RPC. Based on the output I would like to form the where clause and run the resulting query.
I have the below class variables
private static boolean isLoaded = false;
StringBuilder whereClause = new StringBuilder("select * from grocery_shop where ");
StringBuilder productCode = new StringBuilder("(");
ArrayList<String> productList = null;
Below code is the place where RPC is called in Incremental command
if (Dialog.getRadioproduct().getValue()) {
DeferredCommand.addCommand(new IncrementalCommand() {
#Override
public boolean execute() {
if (isLoaded) {
ProductServiceAsync Service =
ServiceFactory.getService(ProductReportService.class);
Service.getBasicProducts(Dialog.getTxtProduct().getValue(),
new AsyncCallback<ArrayList<String>>() {
#Override
public void onServiceFailure(Throwable ex) {
showError("Error");
}
#Override
public void onServiceSuccess(ArrayList<String> result) {
productList = result;
while(productList.iterator.hasnext())
whereClause.append(" AND PROD = '" + productList.iterator.next() + "'");
isLoaded = true;
}
});
return false;
}
return true;
}
});
}
I wanted this execute query to be executed after the above RPC is success however the below line is executed before RPC.
ResultSet rs = stmt.executeQuery(whereClause);
Plz let me know if there is anything I have missed.
Well IncrementalCommand has been deprecated. Now you should use: Scheduler.RepeatingCommand or Scheduler.scheduleIncremental()
Apart from that, it is normal the execution of your query before the success answer because RPC is async (a new thread starts on that part), so, you should control your code on the onServiceSuccess and onServiceFailure (basically do the query on those methods according to your requirements).
Other option is to use the Promises pattern which is implemented on GQuery. something like
doTheRPC(...).done(...).always(...); (but if you do not have much experience on GWT the easiest solution is described above).
Related
so, here is my today problem:
First of all, please note that I do NOT have the Matlab parallel toolbox available.
I am running java code witch interact with Matlab. Sometime Matlab directly call some java functions, sometimes it is the opposite. In this case, we use a notification system which comes from here:
http://undocumentedmatlab.com/blog/matlab-callbacks-for-java-events
We then address the notification in proper callbacks.
Here is a simple use case:
My user select a configuration file using the java interface, loaded into Matlab.
Using an interface listener, we notify Matlab that the configuration file has been selected, it then run a certain number of functions that will analyzes the file
Once the analysis is done, it is pushed into the java runtime, which will populate interface tables with the result. This step involve that matlab will call a java function.
Finally, java request the interface to be switched to an arbitrary decided tab.
This is the order of which things would happen in an ideal world, however, here is the code of the listener actionPerformed method:
#Override
public void actionPerformed(ActionEvent arg0) {
Model wModel = controller.getModel();
Window wWindow = controller.getWindow();
MatlabStructure wStructure = new MatlabStructure();
if(null != wModel) {
wModel.readMatlabData(wStructure);
wModel.notifyMatlab(wStructure, MatlabAction.UpdateCircuit);
}
if(null != wWindow) {
wWindow.getTabContainer().setSelectedComponent(wWindow.getInfosPannel());
}
}
What happen here, is that, when the notifyMatlab method is called, the code does not wait for it to be completed before it continues. So what happen is that the method complete and switch to an empty interface page (setSelectedComponent), and then the component is filled with values.
What I would like to, is for java to wait that my notifyMatlab returns a "I have completed !!" signal, and then pursue. Which involves asynchrounous code since Matlab will code java methods during its execution too ...
So far here is what I tried:
In the MatlabEventObject class, I added an isAcknowledge member, so now the class (which I originaly found in the above link), look like this (I removed all unchanged code from the original class):
public class MatlabEventObject extends java.util.EventObject {
private static final long serialVersionUID = 1L;
private boolean isAcknowledged = false;
public void onNotificationReceived() {
if (source instanceof MatlabEvent) {
System.out.println("Catched a MatlabEvent Pokemon !");
MatlabEvent wSource = (MatlabEvent) source;
wSource.onNotificationReceived();
}
}
public boolean isAcknowledged() {
return isAcknowledged;
}
public void acknowledge() {
isAcknowledged = true;
}
}
In the MatlabEvent class, I have added a future task which goal is to wait for acknowledgement, the methods now look like this:
public class MatlabEvent {
private Vector<IMatlabListener> data = new Vector<IMatlabListener>();
private Vector<MatlabEventObject> matlabEvents = new Vector<MatlabEventObject>();
public void notifyMatlab(final Object obj, final MatlabAction action) {
final Vector<IMatlabListener> dataCopy;
matlabEvents.clear();
synchronized (this) {
dataCopy = new Vector<IMatlabListener>(data);
}
for (int i = 0; i < dataCopy.size(); i++) {
matlabEvents.add(new MatlabEventObject(this, obj, action));
((IMatlabListener) dataCopy.elementAt(i)).testEvent(matlabEvents.get(i));
}
}
public void onNotificationReceived() {
ExecutorService service = Executors.newSingleThreadExecutor();
long timeout = 15;
System.out.println("Executing runnable.");
Runnable r = new Runnable() {
#Override
public void run() {
waitForAcknowledgement(matlabEvents);
}
};
try {
Future<?> task = service.submit(r);
task.get(timeout, TimeUnit.SECONDS);
System.out.println("Notification acknowledged.");
} catch (Exception e) {
e.printStackTrace();
}
}
private void waitForAcknowledgement(final Vector<MatlabEventObject> matlabEvents) {
boolean allEventsAcknowledged = false;
while(!allEventsAcknowledged) {
allEventsAcknowledged = true;
for(MatlabEventObject eventObject : matlabEvents) {
if(!eventObject.isAcknowledged()) {
allEventsAcknowledged = false;
}
break;
}
}
}
}
What happen is that I discover that Matlab actually WAIT for the java code to be completed. So my waitForAcknowledgement method always wait until it timeouts.
In addition, I must say that I have very little knowledge in parallel computing, but I think our java is single thread, so having java waiting for matlab code to complete while matlab is issuing calls to java functions may be an issue. But I can't be sure : ]
If you have any idea on how to solve this issue in a robust way, it will be much much appreciated.
I have enable hashtag feature in my app, which I'm not really sure if this is the way how it has to be implemented or not , since I can't test it. it is crashing every time I'm trying to run it.
So I have Image class that has field (tag) of relation type .
HashTags has tagName as string and img as pointer to Image class.
This is the code I've started.
final ParseQuery<ParseObject> query = ParseQuery.getQuery("Image");
final ParseQuery<ParseObject> query1 = ParseQuery.getQuery("HashTags");
final ParseObject tag = ParseObject.create("HashTags");
query.getInBackground(objectId, new GetCallback<ParseObject>() {
public void done(final ParseObject object, ParseException e) {
if (e == null) {
final String hashTag = add_tag.getText().toString().trim();
String text = add_tag.getText().toString().trim();
String regexPattern = "(#\\w+)";
Pattern p = Pattern.compile(regexPattern);
Matcher m = p.matcher(text);
while (m.find()) {
final String hashtag = m.group(1);
if (hashtag.trim().matches("")) {
object.put("location", point);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
done = true;
finish();
}
}
});
} else {
query1.whereEqualTo("name", hashtag);
the problem occurs at the last line, when [ query1.whereEqualTo("name", hashtag);]
I think because hashtag is not single value, it's more than one hashtag. so it's throwing that error.
any suggestions how to fix it ?
Why dont you just add a listener to that initial GetQuery and put the rest of the code inside so it can be executed when it completes. That should solve the concurrent queries.
Something like this
query.getInBackground(new GetCallbacks(){
onComplete(){
final ParseQuery<ParseObject> query1 = ParseQuery.getQuery("HashTags");
query1.getInBackground(new GetCallbacks(){
onComplete(){
//The rest of the code.
}
});
)
I don't have any projects currently to make the code pretty, but this is the gist of it. Sounds like query1 is still executing when you are trying to view its data, You should be chaining together getInBackground anonymous inner classes. By doing this you are ensuring that the rest of the code is executed once query1 completes or fails..
I am building a phonegap application and have called a java native plugin from it using cordova.exec.
I am stuck somewhere unexpected.
I am calling cordova.exec multiple times in a loop.Also those native plugins are performing async task.But to amazement ,its returning callback only for first cordova.exec() call. I want it to return to javascript at my last cordova.exec() call.
Please help.
My code is as follows----
Javascript code-
$( "input:checked" ).each(function()
{
cordova.exec(callbacksuccess,callbackerror,'MyPlugin','plugin1',[path,pckg,id]);
});
function callbacksuccess(e)
{
alert(e);
}
function callbackerror()
{
alert('error');
}
Java Native Plugin code-
if (action.equals("plugin1"))
{
new DownloadManager().execute(myurl);
return true;
}
public class DownloadManager extends AsyncTask<String, String, String>
{
#Override
public String doInBackground(final String... arg0)
{
try
{
downloadapk(arg0[0]);
installapk();
System.out.println("Download Complete");
PluginResult result = new PluginResult(PluginResult.Status.OK, "success");
result.setKeepCallback(true);
callback.success("done");
return null;
}
catch(Exception e)
{
callback.error("Some problem occured.Try again later");
return null;
}
}
}
Suppose I have 5 listitems selected. It returns "done" just once. callbacksuccess function is called just once for the first cordova.exec function.I didnot find any solution.
Thanx in advance
Try this.
1.In your execute() method of your plugin save the callbackId you get and return a NO_RESULT plugin result and set keep callback id to true.
PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true);
return pluginResult;
2.When your async java method finishes return another plugin result like this:
PluginResult result = new PluginResult(PluginResult.Status.OK, data);
result.setKeepCallback(false);
this.success(result, this.myCallbackId);
So, I'm trying to write code for a search JTextField that retrieves results from the web (kinda like Google's fancy search tips). The only problem is... probably my lack of programming experience. More specifically, I have it set up to whenever a user hits a key, it sends out a request with the JTextField input through an HttpURLConnection and retrieves the results then updates. But whenever the HttpURLConnection is running, it freezes the program for a couple seconds while it does its thing, which mainly prohibits entering in more characters into the search field if I didn't mind anything else. I've considered using separate threads, but I'm not sure how I would properly interrupt a thread and have it start over using new data while having everything else wait on it but still accepting new data. I've considered using
thread.stop();
to help manage the issue, but from what I've read, that seems taboo (am I right?). Anyways, here's pretty much what I'm using:
public class SearchField extends JTextField implements KeyListener {
public SearchField() {
addkeyListener(this);
}
public void updateData(ArrayList<String results) {
/*Pass the data off the the GUI*/
{
#Override
public void keyTyped(KeyEvent e) {
SearchQuery query = new SearchQuery(this.getText());
updateData(query.getResults());
}
}
public class SearchQuery {
ArrayList<String> results = new ArrayList<String>();
public SearchQuery(String search) {
String search_path = "http://www.whatever.com/" + search;
URL url = new URL(search_path);
conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("User-Agent", "Mozilla/4.76");
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuffer buf = new StringBuffer();
int i;
while((i = in.read()) != -1) {
buf.append((char) i);
}
String data = buf.toString();
parse(data);
}
public void parse(String data) {
/*Parse a bunch of JSON, return the results in an array*/
results.add(data);
}
public ArrayList<String> getResults() {
return results;
}
}
I'm just at a loss for how to synchronise recieving continuous input while getting new results for each key stroke and dismissing unfinished connections and their respective data processing when it becomes invalid at the next key stroke.
You are doing the download in the same thread that responds to user events. You need to do the download in another thread, perhaps by making SearchQuery extend Thread and doing the query in the run method. When it comes time to update the text field, you can use SwingUtilities.invokeLater to update the text field. Here’s an example:
public class SearchQuery extends Thread {
private SearchField f;
public SearchQuery(JTextField f) {
this.f = f;
}
public void run() {
// do the query here
SwingUtilities.invokeLater(new Runnable() {
public void run() {
f.updateData(results);
}
});
}
}
Then change the line:
SearchQuery query = new SearchQuery(this.getText());
to this:
SearchQuery query = new SearchQuery(this);
(That title alone should cause people to come out of the woodwork to bash me with clubs, but hear me out).
I have a use case where I need to return a value from a asynchronous call. (I'm using GWT-Platform, but the concepts are the same.) I declared a final JavaScriptObject array, then assigned the value within the AsyncCallback. However, I need to return the value, and the method returns before the AsyncCallback completes. Therefore, I need to block somehow until the AsyncCallback completes. I need the returned value in another method, or I'd just do what I need to in onSuccess().
I've tried loops, Timers, and a few other methods with no luck. Can anyone help?
#Override
public JavaScriptObject doGetWhereAmIMarker(final double lng, final double lat) {
final JavaScriptObject[] markerArray = new JavaScriptObject[1]; // ugly hack, I know
dispatch.execute(new GetLocationDescriptionsAction(lng, lat), new AsyncCallback<GetLocationDescriptionsResult>() {
#Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
#Override
public void onSuccess(GetLocationDescriptionsResult result) {
Map<String, Location> resultMap = result.getResult();
StringBuffer message = new StringBuffer();
for (String key : resultMap.keySet()) {
message.append(key).append(": ").append(resultMap.get(key)).append("\n");
}
Map tempMap = new HashMap();
tempMap.put("TITLE","Location Information");
tempMap.put("LAT", lat);
tempMap.put("LNG", lng);
tempMap.put("CONTENTS", message.toString());
JavaScriptObject marker = GoogleMapUtil.createMarker(tempMap);
markerArray[0] = marker;
if (markerArray[0] != null) {
GWT.log("Marker Array Updated");
}
}
});
return markerArray[0];
}
UPDATE: As requested, here is the code that calls doGetWhereIAmMarker(). I've tried having a separate native method with the Google Map object (as a JavaScriptObject) as a parameter, but it appears that passing that object between native methods kills the ability to update said object.
public native void initMap(JavaScriptObject mapOptions, JavaScriptObject bounds, JavaScriptObject border, JsArray markerArray, Element e) /*-{
// create the map and fit it within the given bounds
map = new $wnd.google.maps.Map(e, mapOptions);
if (bounds != null) {
map.fitBounds(bounds);
}
// set the polygon for the borders
if (border != null) {
border.setMap(map);
}
// set up the info windows
if (markerArray != null && markerArray.length > 0) {
var infoWindow = new $wnd.google.maps.InfoWindow({
content:"InfoWindow Content Goes Here"
});
for (var i = 0; i < markerArray.length; i++) {
var marker = markerArray[i];
marker.setMap(map);
$wnd.google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(marker.content);
infoWindow.open(map, this);
});
}
}
// need to reference the calling class inside the function(), so set a reference to "this"
var that = this;
$wnd.whereAmI=function(lng, lat) {
that.#org.jason.mapmaker.client.view.MapmakerMapViewImpl::whereAmI(DD)(lng,lat);
}
$wnd.google.maps.event.addListener(map, 'click', function(event) {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
$wnd.whereAmI(lng, lat);
});
}-*/;
At some point I had to do something similar but eventually I eliminated that code in favor of asynchronous stuff. Therefore, I can't give exact code that you need to use but only few pointers on how to approach it.
Firstly, this blog describes how to do synchronous AJAX using javascript.
Second, you must provide support for sync calls. The problem is that GWT does not support the parameter that provides synchronous AJAX calls. Most likely is that they don't want to encourage its use. Therefore you would need to use JSNI to add appropriate method to XMLHttpRequest (which you probably would extend) and then to RequestBuilder (also should extend it).
Finally, amend your service using extended RequestBuilder. Something like
((ServiceDefTarget)service).setRpcRequestBuilder(requestBuilder);
And in conclusion - from the same blog post (slightly out of context):
Because of the danger of a request getting lost and hanging the browser,
synchronous javascript isn't recommended for anything outside of
(onbefore)unload event handlers.
I Think its all fate....
We cannot do in Gwt to catch the Response and Send it, because immediately after the request is send the next method starts executing, neither bothering the response
Still however they satisfy us to use the Timers, is what i think...
Timer t = new Timer() {
#Override
public void run() {
Window.alert("Nifty, eh?");
}
};
t.schedule(5000);