In Silverlight, a frequently used pattern is:
Request data
Get back an empty container for the data
Asynchronously fire off a query to fill the container
When the query returns, fire an event on the container
Update the UI according to the container's contents
Can this be done in GWT?
The reason I ask is that I'm trying to make a SuggestBox that contains a list of group names and icons. First, I query Facebook to get a list of groups IDs that are close to the current String in the SuggestBox. Then, I fire off queries to get icons for each group id. The problem is that I have to return the suggestions before those queries are done. I'm not sure how to go back and insert the data after I have it. I don't want to block until the calls are complete, and there's no real way to know in advance what data to load.
I could return a widget for the suggestion that loads an image, but the suggestion must be a plain String.
What is the right approach here?
Let's assume you're using GWT RPC. You'll have some service interface that lets you fetch the groupIds for a suggestion and the icon for a specific group id.
public interface FacebookService extends RemoteService {
List<String> getFacebookGroupIds(String suggestion);
Icon getIconForGroup(String groupId);
}
You should build your own implementation of Suggestion that can display itself with either just a groupId or a groupId and an Icon.
public class FacebookGroupSuggestion implements Suggestion {
private String groupId;
private Icon icon;
public FacebookGroupSuggestion(String groupId) {
this.groupId = groupId;
}
public String getDisplayString() {
StringBuilder builder = new StringBuilder();
builder.append("<b>");
builder.append(this.groupId);
builder.append("</b>");
if (this.icon != null) {
builder.append(this.icon.toSafeHtml());
}
return builder.toString();
}
}
I'm using Icon as your own implementation of an icon, it's not a standard class.
Then, you can make your implementation of SuggestOracle to fetch the groupIds and icons asynchronously. The SuggestOracle uses a callback to inform the suggestBox that some response to a request is available. So fetch your results, and call the callback when you get them. It'll look something like this.
public class FacebookSuggestOracle extends SuggestOracle {
private FacebookServiceAsync service = GWT.create(FacebookService.class);
private Request currentRequest;
private Callback currentCallback;
#Override
public void requestSuggestions(Request request, Callback callback) {
// Save request & callback for future use.
this.currentRequest = request;
this.currentCallback = callback;
// Fetch the groupIds
service.getFacebookGroupIds(request.getQuery(), new AsyncCallback<List<String>>() {
public void onSuccess(List<String> result) {
createSuggestionsForGroupIds(result);
}
});
}
private void createSuggestionsForGroupIds(List<String> groupIds) {
List<FacebookGroupSuggestion> suggestions = new ArrayList<FacebookGroupSuggestion>();
for (String groupId : groupIds) {
suggestions.add(new FacebookGroupSuggestion(groupId));
}
Response response = new Response(suggestions);
// Tell the suggestBox to display some new suggestions
currentCallback.onSuggestionsReady(currentRequest, response);
// Fetch the icons
for (String groupId : groupIds) {
service.getIconForGroup(groupId, new AsyncCallback<Icon>() {
public void onSuccess(Icon result) {
// match the icon to the groupId in the suggestion list
// use the callback again to tell the display to update itself
}
});
}
}
}
Related
I'm trying to figure out how to sort my recyclerview's data by click of a button. So far I've got it sorted initially as I start the application and add new items on the list. But I'd like to be able to sort it by different parameters as I'm using the app, by clicking a button "Sort by distance".
I'm using the MVVM architecture and am working with LiveData.
Here's my MainActivity (Not completely, but irrelevant parts are omitted)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
final RunListAdapter adapter = new RunListAdapter(new RunListAdapter.RunDiff());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mRunViewModel = new ViewModelProvider(this).get(RunViewModel.class);
mRunViewModel.getAllRuns().observe(this, runs -> {
adapter.submitList(runs);
});
sortByDistanceButton = findViewById(R.id.sortByDistance);
sortByDistanceButton.setOnClickListener(view -> {
//DO SOMETHING
});
Here's my RunViewModel
public class RunViewModel extends AndroidViewModel {
private RunRepository mRepository;
private final LiveData<List<Run>> mAllRuns;
public RunViewModel(Application application) {
super(application);
mRepository = new RunRepository(application);
mAllRuns = mRepository.getAllRuns();
}
LiveData<List<Run>> getAllRuns() {
return mRepository.getAllRuns();
}
public void insert(Run run) {
mRepository.insert(run);
}
public void delete(Run run) {
mRepository.delete(run);
}
}
Here's my RunRepository
public class RunRepository {
private RunDao mRunDao;
private LiveData<List<Run>> mAllRuns;
RunRepository(Application application) {
RunRoomDatabase db = RunRoomDatabase.getDatabase(application);
mRunDao = db.runDao();
mAllRuns = mRunDao.getRunsByDate();
}
LiveData<List<Run>> getAllRuns() {
return mRunDao.getRunsByDate();
}
void insert(Run run) {
RunRoomDatabase.databaseWriteExecutor.execute(() ->
mRunDao.insert(run));
}
public void delete(Run run) {
RunRoomDatabase.databaseWriteExecutor.execute(() -> {
mRunDao.deleteRun(run);
});
}
}
And finally here's my RunDao
public interface RunDao {
#Insert(onConflict = OnConflictStrategy.IGNORE)
void insert(Run run);
#Query("DELETE FROM run_table")
void deleteAll();
#Query("SELECT * FROM run_table ORDER BY date")
LiveData<List<Run>> getRunsByDate();
#Query("SELECT * FROM run_table ORDER BY distance ASC")
LiveData<List<Run>> getRunsByDistance();
#Query("SELECT * FROM run_table ORDER BY duration ASC")
LiveData<List<Run>> getRunsByDuration();
#Delete
void deleteRun(Run run);
}
I've tried to pass on a "choice" argument and setting the choice to a different one, but to no avail. I've tried to read about other's having similar problems, but I haven't been able to figure how to apply any of them to my situation. I'm completely stumped.
Here are some SO questions I've read and tried to wrap my head around.
This one actually is very similar to mine and the original question asked figured out a solution, but never shared the details of the implementation =)
How to sort LiveData from Room Database? Doing a button to switch recyclerview's item's order
https://www.reddit.com/r/androiddev/comments/n9nraa/i_want_to_sort_a_livedatalistplayers_from_room_in/
how to properly sort a list using repository pattern and live data in an MVVM android application?
Moving from top to bottom,
You are observing mRunViewModel.getAllRuns()
Your mRunViewModel.getAllRuns() is mRepository.getAllRuns();
Your mRepository.getAllRuns(); is mRunDao.getRunsByDate();
So you are so far just unconditionally routing LiveData from Room to your view.
Simplest way to achieve switching could be this:
Change your RunDao to have single parameterized method like this example
#Query("SELECT * FROM Persons ORDER BY
CASE WHEN :isAsc = 1 THEN first_name END ASC,
CASE WHEN :isAsc = 0 THEN first_name END DESC")
List<Person> getPersonsAlphabetically(boolean isAsc);
(your implementation will be different, including return type and parameter type, but the above should give the idea)
Route the above dao method into repo and use updated repo inside vm. Every time view decides it's time to show some different sorting order, it will talk to view model, viewmodel will pull repo's method and repo will pull dao with proper parameter, dao will give you back livedata with properly sorted content.
I'm trying to pass data from DAO with flexbile search query trough to the zul page using de the widgetModel. But when I print the widgetModel.orders it says...
(index):93 Uncaught ReferenceError: LazyList is not defined
at window.onload ((index):93)
zul page
window.onload = function () {
const myChart = new Chart(
document.getElementById('myChart'),
config
);
const test = [[${widgetModel.orders}]];
console.log(test);
};
controller class
public class customGraphController extends DefaultWidgetController {
private static final long serialVersionUID = 7954736389190109887L;
#WireVariable
private transient customGraphService customGraphService;
#Override
public void preInitialize(Component comp) {
super.preInitialize(comp);
WidgetModel model = getWidgetInstanceManager().getModel();
model.put("orders", customGraphService.getAllOrders());
}
}
service class
public class customGraphService {
#Autowired
private OrdersDataDao ordersDataDao;
public List<OrderModel> getAllOrders() {
return ordersDataDao.getAllOrders();
}
}
dao class
public class OrdersDataDao {
#Resource
private FlexibleSearchService flexibleSearchService;
public List<OrderModel> getAllOrders() {
final String stringQuery = "select {o.pk} from {order as o}";
final FlexibleSearchQuery query = new FlexibleSearchQuery(stringQuery);
final SearchResult<OrderModel> result = flexibleSearchService.search(query);
if (null != result.getResult()) {
return result.getResult();
} else {
return null;
}
}
}
Does someone knows a solution?
window.onLoad is always too early to manipulate ZK widgets. The onLoad callback will trigger once the initial document has been loaded, but that document itself will load ZK libaries, initialize the client engine, etc.
If you need to do something "after libraries have been loaded", you can use zk.afterload. This hook is good if you need to modify a framework function before the widgets actually use it.
However, this is still before widget instantiation by the client engine, so if your goal is to access a widget, it is still too early.
If you want to do something to a widget after that widget has been added to the page an initialized, what you actually need is a client-side onBind listener.
You can set that listener in zul or in java, but the simplest way to do that is like this: https://zkfiddle.org/sample/1v9phuk/1-Another-new-ZK-fiddle
Lastly, if you are going to use ZK's client-side API to access / modify content at client-side, I'd recommend looking into the ZK client-side selectors. Way easier than trying to manually lookup elements by ID, and way more robust in the long run.
document.getElementById('myChart') will only work if you have a dom element with the actual ID "myChart", which is not how ZK works (not with default UUID generator anyway).
Instead, you can select a widget by it's ZK ID.
Assuming you have <charts id="myChart" /> in your zul, you can get the ZK widget directly as argument to the onBind listener, or you can get it with the ZK selector:
zk.$("$myChart"), and from there you can get the DOM node: zk.$("$myChart").$n()
Make sure you know what is client-side (JavaScript), and what is Server side.
(Lastly)^2, keep in mind that in a ZK architecture, the server is the source of the state, and the client only update the state by sending client commands back to the server.
If you use JS to modify the client-side state, you can create desynchronization between the server-side state and the client-side state, so proceed with caution.
I found a solution, I used GSON to stringify the list and than pass it to the zul page :-)
private Object convertAllOrderModelsToJSON() {
//get all the models
List list = customGraphService.getAllOrdersModels();
//convert models to JSON
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(list);
return json;
}
I am new to Hazelcast jet and in my application on data I am doing some aggregation and getting data but I want to send that in rest response so how can I change it to normal list?
public class ResponseMessage<T> {
private T responseClassType;
private ResponseMessage() {}
private ResponseMessage(T t) {
this.responseClassType = t;
}
public static <T> ResponseMessage<T> withResponseData(T classType) {
return new ResponseMessage<T>(classType);
}
public static ResponseMessage<Void> empty() {
return new ResponseMessage<>();
}
public T getResponseClassType() {
return responseClassType;
}
public void setResponseClassType(T responseClassType) {
this.responseClassType = responseClassType;
}
}
This is my generic response class and as below I am sending response after all calculations:
public ResponseMessage<?> runProcess(Pipeline pl) {
Map<String, BatchStage<Object>> allBatch = new HashMap<String,BatchStage<Object>>();
allBatch.put(z.get("id").toString(), new SomeCalulation().readSource(pipeline));
BatchStage<Object> h = allBatch.values().iterator().next();
h.writeTo(Sinks.list("abc"));
IList<Object> abc = jetInstance.getList("abc");
List<Object> result = new ArrayList(abc);
abc.destroy();
return ResponseMessage.withResponseData(result);
}
Now this is working but everytime I call rest request it is increasing the list and if I clear the list it is showing blank records, please help how can I convert it to normal list or best way to send response?
It was not working because I was joining it after method call:
runProcess(pl);
job.join(); // so because I am joining it after runProcess not working but if I directly return ResponseMessage.withResponseData(jetInstance.getList("abc")); and then join it will work.
I don't see submitting the pipeline as a job and waiting for the result (job.join()). I suppose you have omitted this from your code sample.
To solve your issue with empty list simply copy the result before destroying the list:
job.join();
IList<Object> abc = jetInstance.getList("abc");
List<Object> result = new ArrayList(abc)
abc.destroy();
return ResponseMessage.withResponseData(result);
Also, the list should have a unique name for each request, otherwise, multiple requests will write to the same list, having unpredictable results.
I'm trying to update an app from to Play 2.7. I see that now the access to the session object via Http.Context is deprecated. Instead I have to use the Http.Request object. Additionally before I could just change the Session object right away - now it seems like I have to create a new Session and add to the Result by myself. But how can I achieve this within an Action composition where I don't have access to the Result object?
An Action composition can look like:
public class VerboseAction extends play.mvc.Action.Simple {
public CompletionStage<Result> call(Http.Request req) {
...
return delegate.call(req);
}
}
I can't see how to add something to the Session here!
EDIT:
I couldn't find an easy solution but a workaround with a second action annotation. It's possible to access the Result object via .thenApply and attache the new Session object.
public CompletionStage<Result> call(Http.Request request) {
return delegate.call(request).thenApply(result -> {
Http.Session session = ... change the session
return result.withSession(session);
});
}
Still if someone has a better idea how to change the Session directly in the action composition please feel free to answer.
A session in cleared by withNewSession(). A new session is created when you add something with addingToSession(...), perhaps after a login. Here is my complete working code : I have 2 timestamp : one for the log file and one for an application timeout.
public class ActionCreator implements play.http.ActionCreator {
private final int msTimeout;
#Inject
public ActionCreator(Config config) {
this.msTimeout = config.getInt("application.msTimeout");
}
#Override
public Action<?> createAction(Http.Request request, Method actionMethod) {
return new Action.Simple() {
#Override
public CompletionStage<Result> call(Http.Request req) {
// add timestamp for the elapsed time in log
req.getHeaders().addHeader("x-log-timestamp", "" + System.currentTimeMillis());
// did a session timeout occur
boolean timeout = SessionUtils.isTimeout(req, msTimeout);
// apply current action
return delegate.call(req).thenApply(result -> {
// display some info in log
Utils.logInfo(req);
// return final result
if (timeout) {
return result.withNewSession();
} else if (SessionUtils.isOpen(req)) {
return result.addingToSession(req, "timestamp", "" + System.currentTimeMillis());
} else {
return result;
}
});
}
};
}
}
I'm struggling with a very basic Wicket issue. I'm trying to query a backend database, but can't get the results to display. Below is the code I'm using. currentQuery and currentResult is correctly updated after submission, but my SearchResults class is never rerendered with the new data in currentResults. I suppose that the results class just doesn't notice that the model has in fact been updated. I've been experimenting with modelChanged, but can't get it to work. I'm a bit new to Wicket, so I'm probably doing something fundamental completely wrong. Any help is much appreciated!
public class SearchPage extends WebPage {
Query currentQuery = new Query();
Result currentResult = new Result();
public SearchPage() {
add(new SearchForm("searchForm", new CompoundPropertyModel<Query>(currentQuery)));
add(new SearchResults("searchResults", new PropertyModel<List<Hit>>(currentResult, "hits")));
}
public void doSearch(Query Query) {
currentResult = getResults(query);
}
public class SearchForm extends Form<Query> {
public SearchForm(String id, CompoundPropertyModel<Query> model) {
super(id, model);
add(new TextField<String>("query"));
}
protected void onSubmit() {
super.onSubmit();
doSearch(currentQuery);
}
}
public class SearchResults extends WebMarkupContainer {
public SearchResults(String id, PropertyModel<List<Hit>> model) {
super(id, model);
add(new ListView<Hit>("hit", model) {
protected void populateItem(ListItem<Hit> item) {
item.add(new Label("column", item.getModelObject().getColumnValue("column")));
}
});
}
}
}
PropertyModel uses reflection to look up the named property on a given target object instance. When you constructed the PropertyModel, you passed it a specific instance of Result, i.e. the new Result() from SearchPage's constructor. The PropertyModel will continue to hold a reference to that same Result instance from render to render of this page, serializing the Result at the end and then deserializing the Result at the start of each new request cycle (page view). The fact that you later change the page's currentResult variable to reference a different Result instance does not affect which Result instance the PropertyModel uses to look up its model value. Your PropertyModel does not care what currentResult later refers to.
There are two possible solutions that I can think of off the top of my head.
Have the PropertyModel read hits from the actual current value of the Page's currentResult variable:
new PropertyModel<List<Hit>>(SearchPage.this, "currentResult.hits")
Use a LoadableDetachableModel to load hits once per request cycle/page view:
new LoadableDetachableModel<List<Hit>>()
{
protected Object load()
{
return getResults(currentQuery);
}
}
Note that a LoadableDetachableModel has to be detached at the end of the request cycle or it will never again call getObject() to recalculate the List<Hit>. That said, since your code shows you'd be using it as the default model of the SearchResults component, the SearchResults component would detach the model for you at the end of the request cycle automatically.
I got it working. This seems to be the offending row:
add(new SearchResults("searchResults", new PropertyModel<List<Hit>>(currentResult, "hits")));
The type of the PropertyModel, i.e. List<Hit>, must have been making the model static. So the only data SearchResults ever saw was the initial object, which was empty.
I changed the line to the below, and updated SearchResult accordingly.
add(new SearchResults("searchResults", new Model<Result>(currentResult, "hits")));
If anyone can explain this further, or feel that I'm incorrect, please comment! In any case, I'm marking my own answer as correct as this solved the problem.