I am using suggest box for implementing autocomplete in GWT.
For retrieving data from entity i am using objectify and for mapping data to suggest box i have used MultiWordSuggestOracle.
On form load i am firing a query for retrieving data and passing it to MultiWordSuggestOracle. It is working fine.
For eg if i am loading customer data in suggestion it is working
But for eg if i have 5000 - 50000 customer records in my entity, so to retrieve all data and show it in suggestion could not be successful.
So is there any other technique for using autocomplete in gwt?
Thanks in advance
Instead of loading allt he customer records in on form load, dynamically filter the data on the backend based on what the user types into the SuggestBox. You can do this by implementing a custom SuggestOracle (maybe extending the MultiWordSuggestOracle).
public class ServerSuggestOracle extends SuggestOracle{
protected DataSource datasource;
protected int startQueryLength;
protected ArrayList<T> suggestions = new ArrayList<T>();
protected boolean isMoreSuggestions = false;
protected int previousQueryLength = 0;
public ServerSuggestOracle(DataSource datasource,int startQueryLength)
{
super();
this.datasource = datasource;
this.startQueryLength = startQueryLength;
}
#Override
public void requestSuggestions(final Request request, final Callback callback) {
// start the backend call only if the user types in more than startQueryLength characters.
if (request.getQuery().length() < startQueryLength)
return;
// if the user expands the search or a serach hasn't been carried out, call the backend. Otherwise filte the existing list
if (isMoreSuggestions || previousQueryLength > request.getQuery().length() || suggestions.size() == 0)
{
datasource.fetchDataFromBackend(request.getQuery(), new FetchDataFromBackendCallback() {
#Override
public void onFetchData(ArrayList<T> genes,Integer count,boolean isMore) {
suggestions.clear();
for (int i = 0;i<genes.size();i++) {
Suggestion suggestion = new Suggestion();
suggestions.add(suggestion);
}
SuggestOracle.Response response = new SuggestOracle.Response(suggestions);
isMoreSuggestions = isMore;
if (count != null)
response.setMoreSuggestionsCount(count);
else
response.setMoreSuggestions(isMore);
previousQueryLength = request.getQuery().length();
callback.onSuggestionsReady(request,response);
}
});
}
else
{
super.requestSuggestions(request,cabllack);
}
}
}
Related
I'm developing android chat application using QuickBlox.. My app will be like : The user logs in and chooses any another user to chat with.. (Not in the roster).. I managed to get users using the following code :
retrieveAllUsersFromPage(1);
private void retrieveAllUsersFromPage(int page){
QBPagedRequestBuilder pagedRequestBuilder = new QBPagedRequestBuilder();
pagedRequestBuilder.setPage(page);
pagedRequestBuilder.setPerPage(100);
QBUsers.getUsers(pagedRequestBuilder, this);
}
int userNumber = 1;
#Override
public void onSuccess(ArrayList<QBUser> users, Bundle params) {
for(QBUser user : users){
this.users.add(user);
userNumber ++;
}
int currentPage = params.getInt(Consts.CURR_PAGE);
int totalEntries = params.getInt(Consts.TOTAL_ENTRIES);
if(userNumber < totalEntries){
retrieveAllUsersFromPage(currentPage+1);
}
}
but I wanna filter them to add only the available(online) users.. I can't find a way to do that.. Any Idea ?
With no roster you can use next trick with user.lastRequestAt field
http://quickblox.com/developers/SimpleSample-users-android#Online.5COffline_status
I'm using the upload component of vaadin(7.1.9), now my trouble is that I'm not able to restrict what kind of files that can be sent with the upload component to the server, but I haven't found any API for that purpose. The only way is that of discarding file of wrong types after the upload.
public OutputStream receiveUpload(String filename, String mimeType) {
if(!checkIfAValidType(filename)){
upload.interruptUpload();
}
return out;
}
Is this a correct way?
No, its not the correct way. The fact is, Vaadin does provide many useful interfaces that you can use to monitor when the upload started, interrupted, finished or failed. Here is a list:
com.vaadin.ui.Upload.FailedListener;
com.vaadin.ui.Upload.FinishedListener;
com.vaadin.ui.Upload.ProgressListener;
com.vaadin.ui.Upload.Receiver;
com.vaadin.ui.Upload.StartedListener;
Here is a code snippet to give you an example:
#Override
public void uploadStarted(StartedEvent event) {
// TODO Auto-generated method stub
System.out.println("***Upload: uploadStarted()");
String contentType = event.getMIMEType();
boolean allowed = false;
for(int i=0;i<allowedMimeTypes.size();i++){
if(contentType.equalsIgnoreCase(allowedMimeTypes.get(i))){
allowed = true;
break;
}
}
if(allowed){
fileNameLabel.setValue(event.getFilename());
progressBar.setValue(0f);
progressBar.setVisible(true);
cancelButton.setVisible(true);
upload.setEnabled(false);
}else{
Notification.show("Error", "\nAllowed MIME: "+allowedMimeTypes, Type.ERROR_MESSAGE);
upload.interruptUpload();
}
}
Here, allowedMimeTypes is an array of mime-type strings.
ArrayList<String> allowedMimeTypes = new ArrayList<String>();
allowedMimeTypes.add("image/jpeg");
allowedMimeTypes.add("image/png");
I hope it helps you.
Can be done.
You can add this and it will work (all done by HTML 5 and most browsers now support accept attribute) - this is example for .csv files:
upload.setButtonCaption("Import");
JavaScript.getCurrent().execute("document.getElementsByClassName('gwt-FileUpload')[0].setAttribute('accept', '.csv')");
I think it's better to throw custom exception from Receiver's receiveUpload:
Upload upload = new Upload(null, new Upload.Receiver() {
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
boolean typeSupported = /* do your check*/;
if (!typeSupported) {
throw new UnsupportedImageTypeException();
}
// continue returning correct stream
}
});
The exception is just a simple custom exception:
public class UnsupportedImageTypeException extends RuntimeException {
}
Then you just simply add a listener if the upload fails and check whether the reason is your exception:
upload.addFailedListener(new Upload.FailedListener() {
#Override
public void uploadFailed(Upload.FailedEvent event) {
if (event.getReason() instanceof UnsupportedImageTypeException) {
// do your stuff but probably don't log it as an error since it's not 'real' error
// better would be to show sth like a notification to inform your user
} else {
LOGGER.error("Upload failed, source={}, component={}", event.getSource(), event.getComponent());
}
}
});
public static boolean checkFileType(String mimeTypeToCheck) {
ArrayList allowedMimeTypes = new ArrayList();
allowedMimeTypes.add("image/jpeg");
allowedMimeTypes.add("application/pdf");
allowedMimeTypes.add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
allowedMimeTypes.add("image/png");
allowedMimeTypes.add("application/vnd.openxmlformats-officedocument.presentationml.presentation");
allowedMimeTypes.add("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
for (int i = 0; i < allowedMimeTypes.size(); i++) {
String temp = allowedMimeTypes.get(i);
if (temp.equalsIgnoreCase(mimeTypeToCheck)) {
return true;
}
}
return false;
}
I am working with Vaadin 8 and I there is no change in Upload class.
FileUploader receiver = new FileUploader();
Upload upload = new Upload();
upload.setAcceptMimeTypes("application/json");
upload.setButtonCaption("Open");
upload.setReceiver(receiver);
upload.addSucceededListener(receiver);
FileUploader is the class that I created that handles the upload process. Let me know if you need to see the implementation.
So I am doing an edit profile feature with Play! Framework (2.2.0);
I have this code
public static Result doEditProfile(){
final User localUser = getLocalUser(session());
Form<User> formData = editProfileForm.bindFromRequest();
if (formData.hasErrors()) {
return badRequest(views.html.editprofile.render(localUser, editProfileForm));
} else {
localUser.firstName = formData.field("firstName").value();
localUser.lastName = formData.field("lastName").value();
localUser.locale = formData.field("locale").value();
localUser.gender = formData.field("gender").value();
localUser.country = formData.field("country").value();
localUser.save();
}
return redirect("/profile/edit");
}
It works. But I want to know is there a better way of doing this ?
I have tried this things:
1)
public static Result doEditProfile(){
final User localUser = getLocalUser(session());
Form<User> formData = editProfileForm.bindFromRequest();
if (formData.hasErrors()) {
return badRequest(views.html.editprofile.render(localUser, editProfileForm));
} else {
User localUser = formData.get();
localUser.save();
}
return redirect("/profile/edit");
}
but this says that variable localUser is already defined.
2) also, I tried this
public static Result doEditProfile(){
final User localUser = getLocalUser(session());
Form<User> formData = editProfileForm.bindFromRequest();
if (formData.hasErrors()) {
return badRequest(views.html.editprofile.render(localUser, editProfileForm));
} else {
User updatedUser = formData.get();
updatedUser.save();
}
return redirect("/profile/edit");
}
but this code is creating a new user in the database.
I am new to Play so I am waiting for any advice. Thanks and sorry for my english
Does your user have a unique id? If so, you could try the following:
updatedUser.setId(localUser.getId())
updatedUser.save()
Saw this example here:
How to update an existing object in playframework 2.0.2? aka CRUD in 1.2.x
... along the lines of what #mantithetical was saying. Better to have an update method in your User class:
public static Result update(Long id) {
Form<User> userForm = form(User.class).bindFromRequest();
if(userForm.hasErrors()) {
return badRequest(editForm.render(id, userForm));
}
userForm.get().update(id);
...
Just a matter of providing the unique id (note that also, we're relying on the id, rather than the entire user, when handling bad requests). You can do that by adding a parameter to your controller in the routes file:
POST /update/:id controllers.doEditProfile(id: Long)
Then when you direct to your controller method, you have to pass that unique id in.
My problem is annoying. My server side is generating 12 random numbers (double here).
My Client side received the correct data but nothing is displayed in my Chart. That worked fine with hardcoded data in the store but not with a REST call.
The transfer between my server and my client is that :
[{"key":"key0","value":0.47222548599297787},{"key":"key1","value":0.6009173797369691},{"key":"key2","value":0.13880104282435624},{"key":"key3","value":0.01804674319345545},{"key":"key4","value":0.5547733564202956},{"key":"key5","value":0.8229999661308851},{"key":"key6","value":0.8959346004391032},{"key":"key7","value":0.6848052288628435},{"key":"key8","value":0.10222856671111813},{"key":"key9","value":0.6931371931409103},{"key":"key10","value":0.2994297934549003},{"key":"key11","value":0.47566752196381334}]
Here my simple class used for my test. I am a newbie with GXT 3
public void onModuleLoad() {
final ListStore<JSOModel> store;
final ContentPanel panel = new FramedPanel();
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "/ws/DocumentService/v1/test");
builder.setHeader("Accept", "application/json");
HttpProxy proxy = new HttpProxy(builder);
final Loader<ListLoadConfig, ListLoadResult<JSOModel>> loader = new ListLoader<ListLoadConfig, ListLoadResult<JSOModel>>(proxy, new DataReader<ListLoadResult<JSOModel>, String>() {
#Override
public ListLoadResult<JSOModel> read(Object loadConfig, String data) {
List<JSOModel> jsoModels = new ArrayList<JSOModel>();
JsArray<JSOModel> jsoModelJsArray = JSOModel.arrayFromJson(data);
if(jsoModelJsArray != null) {
for(int i = 0; i < jsoModelJsArray.length(); i++) {
jsoModels.add(jsoModelJsArray.get(i));
}
}
return new ListLoadResultBean<JSOModel>(jsoModels);
}
});
store = new ListStore<JSOModel>(new ModelKeyProvider<JSOModel>() {
#Override
public String getKey(JSOModel item) {
return item.get("key");
}
});
loader.addLoadHandler(new LoadResultListStoreBinding<ListLoadConfig, JSOModel, ListLoadResult<JSOModel>>(store) {
#Override
public void onLoad(LoadEvent<ListLoadConfig, ListLoadResult<JSOModel>> event) {
ListLoadResult<JSOModel> loaded = event.getLoadResult();
if(loaded.getData() == null) {
store.replaceAll(new ArrayList<JSOModel>());
} else {
store.replaceAll(loaded.getData());
}
}
});
Chart<JSOModel> chart = new Chart<JSOModel>();
chart.setStore(store);
chart.setShadowChart(true);
NumericAxis<JSOModel> axis = new NumericAxis<JSOModel>();
axis.setPosition(Chart.Position.LEFT);
axis.addField(new ValueProvider<JSOModel, Number>() {
#Override
public Number getValue(JSOModel JSOModel) {
return JSOModel.getNumber("value");
}
#Override
public void setValue(JSOModel JSOModel, Number number) {
}
#Override
public String getPath() {
return "key";
}
});
axis.setTitleConfig(new TextSprite("Number of hits"));
axis.setWidth(50);
axis.setMinimum(0);
axis.setMaximum(100);
chart.addAxis(axis);
PathSprite odd = new PathSprite();
odd.setOpacity(1);
odd.setFill(new Color("#dff"));
odd.setStroke(new Color("#aaa"));
odd.setStrokeWidth(0.5);
axis.setGridOddConfig(odd);
CategoryAxis<JSOModel, String> horizontalAxis = new CategoryAxis<JSOModel, String>();
horizontalAxis.setPosition(Chart.Position.BOTTOM);
horizontalAxis.setField(new ValueProvider<JSOModel, String>() {
#Override
public String getValue(JSOModel JSOModel) {
return JSOModel.get("key");
}
#Override
public void setValue(JSOModel JSOModel, String s) {
}
#Override
public String getPath() {
return "key";
}
});
horizontalAxis.setTitleConfig(new TextSprite("month of year"));
chart.addAxis(horizontalAxis);
LineSeries<JSOModel> column = new LineSeries<JSOModel>();
column.setYAxisPosition(Chart.Position.LEFT);
column.setStroke(new RGB(148,174,10));
column.setHighlighting(true);
chart.addSeries(column);
axis.addField(column.getYField());
chart.addSeries(column);
chart.setHeight(100);
chart.setWidth(100);
Button b = new Button("ha");
b.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent clickEvent) {
loader.load();
}
});
RootPanel.get().add(b);
panel.setCollapsible(true);
panel.setHeadingText("Column Chart");
panel.setPixelSize(620, 500);
panel.setBodyBorder(true);
VerticalLayoutContainer layout = new VerticalLayoutContainer();
panel.add(layout);
chart.setLayoutData(new VerticalLayoutContainer.VerticalLayoutData(1,1));
layout.add(chart);
chart.setBackground(new Color("#dff"));
RootPanel.get().add(panel);
There are two ways to wire the chart into a store. One is to simply specify that the chart is using a store via setStore, as you have done:
chart.setStore(store);
When you do this, you must also inform the chart when it must redraw everything - you must call:
chart.redrawChart();
This call must be made shortly after the load is completed - consider doing it at the end of onLoad.
Why is this required? In some cases, developers want to make many changes to the store, one at a time, and if the chart automatically updated after each change, that would spawn many slow changes to the data model, and could end up looking strange. In a case like this, you would only call redrawChart() after all changes were complete.
There is another option however - instead of calling setStore, you can call bindStore, and ask the Chart to automatically update whenever any change occurs to the chart:
chart.bindStore(store);
In your case, this is likely the correct answer.
I need a wizard which second page content depends on the first page's selection. The first page asks the user the "kind" of filter he wants to create and the second one asks the user to create one filter instance of the selected "kind".
JFace's wizards pages contents (createControl(...) method) are all created when the wizard is open and not when a given page is displayed (this allow JFace to know the wizard size I guess ??).
Because of this, I have to create my second page content BEFORE the wizard is opened BUT I can't since the second page's content depends on the first page selection.
For now the cleaner solution I found consists in creating all (seconds) pages before the wizard is open (with their content) and override the getNextPage() method in the first page's implementation.
The main drawback of that solution is that it can be be expensive when there are many second pages to create.
What do you think about that solution ? How do you manage your wizard's pages ? Is there any cleaner solution I missed ?
The approach is right if you are several other pages which are
completely different one with another
depends on the previous choices made in a previous page
Then you can add the next page dynamically (also as described here)
But if you have just a next page with a dynamic content, you should be able to create that content in the onEnterPage() method
public void createControl(Composite parent)
{
//
// create the composite to hold the widgets
//
this.composite = new Composite(parent, SWT.NONE);
//
// create the desired layout for this wizard page
//
GridLayout layout = new GridLayout();
layout.numColumns = 4;
this.composite.setLayout(layout);
// set the composite as the control for this page
setControl(this.composite);
}
void onEnterPage()
{
final MacroModel model = ((MacroWizard) getWizard()).model;
String selectedKey = model.selectedKey;
String[] attrs = (String[]) model.macroMap.get(selectedKey);
for (int i = 0; i < attrs.length; i++)
{
String attr = attrs[i];
Label label = new Label(this.composite, SWT.NONE);
label.setText(attr + ":");
new Text(this.composite, SWT.NONE);
}
pack();
}
As shown in the eclipse corner article Creating JFace Wizards:
We can change the order of the wizard pages by overwriting the getNextPage method of any wizard page.Before leaving the page, we save in the model the values chosen by the user. In our example, depending on the choice of travel the user will next see either the page with flights or the page for travelling by car.
public IWizardPage getNextPage(){
saveDataToModel();
if (planeButton.getSelection()) {
PlanePage page = ((HolidayWizard)getWizard()).planePage;
page.onEnterPage();
return page;
}
// Returns the next page depending on the selected button
if (carButton.getSelection()) {
return ((HolidayWizard)getWizard()).carPage;
}
return null;
}
We define a method to do this initialization for the PlanePage, onEnterPage() and we invoke this method when moving to the PlanePage, that is in the getNextPage() method for the first page.
If you want to start a new wizard based on your selection on the first page, you can use the JFace base class org.eclipse.jface.wizard.WizardSelectionPage.
The example below shows a list of available wizards defined by an extension point.
When you press Next, the selected wizard is started.
public class ModelSetupWizardSelectionPage extends WizardSelectionPage {
private ComboViewer providerViewer;
private IConfigurationElement selectedProvider;
public ModelSetupWizardSelectionPage(String pageName) {
super(pageName);
}
private class WizardNode implements IWizardNode {
private IWizard wizard = null;
private IConfigurationElement configurationElement;
public WizardNode(IConfigurationElement c) {
this.configurationElement = c;
}
#Override
public void dispose() {
}
#Override
public Point getExtent() {
return new Point(-1, -1);
}
#Override
public IWizard getWizard() {
if (wizard == null) {
try {
wizard = (IWizard) configurationElement
.createExecutableExtension("wizardClass");
} catch (CoreException e) {
}
}
return wizard;
}
#Override
public boolean isContentCreated() {
// TODO Auto-generated method stub
return wizard != null;
}
}
#Override
public void createControl(Composite parent) {
setTitle("Select model provider");
Composite main = new Composite(parent, SWT.NONE);
GridLayout gd = new GridLayout(2, false);
main.setLayout(gd);
new Label(main, SWT.NONE).setText("Model provider");
Combo providerList = new Combo(main, SWT.NONE);
providerViewer = new ComboViewer(providerList);
providerViewer.setLabelProvider(new LabelProvider() {
#Override
public String getText(Object element) {
if (element instanceof IConfigurationElement) {
IConfigurationElement c = (IConfigurationElement) element;
String result = c.getAttribute("name");
if (result == null || result.length() == 0) {
result = c.getAttribute("class");
}
return result;
}
return super.getText(element);
}
});
providerViewer
.addSelectionChangedListener(new ISelectionChangedListener() {
#Override
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (!selection.isEmpty()
&& selection instanceof IStructuredSelection) {
Object o = ((IStructuredSelection) selection)
.getFirstElement();
if (o instanceof IConfigurationElement) {
selectedProvider = (IConfigurationElement) o;
setMessage(selectedProvider.getAttribute("description"));
setSelectedNode(new WizardNode(selectedProvider));
}
}
}
});
providerViewer.setContentProvider(new ArrayContentProvider());
List<IConfigurationElement> providers = new ArrayList<IConfigurationElement>();
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint extensionPoint = registry
.getExtensionPoint(<your extension point namespace>,<extension point name>);
if (extensionPoint != null) {
IExtension extensions[] = extensionPoint.getExtensions();
for (IExtension extension : extensions) {
IConfigurationElement configurationElements[] = extension
.getConfigurationElements();
for (IConfigurationElement c : configurationElements) {
providers.add(c);
}
}
}
providerViewer.setInput(providers);
setControl(main);
}
The corresponding wizard class looks like this:
public class ModelSetupWizard extends Wizard {
private ModelSetupWizardSelectionPage wizardSelectionPage;
public ModelSetupWizard() {
setForcePreviousAndNextButtons(true);
}
#Override
public boolean performFinish() {
// Do what you have to do to finish the wizard
return true;
}
#Override
public void addPages() {
wizardSelectionPage = new ModelSetupWizardSelectionPage("Select a wizard");
addPage(wizardSelectionPage);
}
}
Another alternative is to #Override setVisible. You can update page values or add additional widgets at that time.
I have a different solution.
If page depends on the result of page 1, create a variable and pass it into to first page, when that wizard page has the option from the user, then the last thing before the page is closed is to set the variable to the required value.
Then pass this variable to wizard, then pass it to the next wizard page. Then do a simple if statement and that way you get both choices together.
Remember that in most code there is only a small difference in the user options, so remember not to get bogged down in duplicating your code.