I am trying to do multiple columns sorting in my application .
Like i have firstname , last name columns
Right now , when i click on firstname header , it sorts as per firstname , when i click on lastname column it sorts as per lastname column..
what i need is when i click on firstname header it should sort on the basis of firstname and then if i click on lastname(with shift or any other option) header it should sort on the basis of both firstname and lastname , firstname as primary column and last name as sub sorting column
here is what i have now
private void sortTableUsers(List<UserDTO> userList){
ListDataProvider<UserDTO> dataProvider = new ListDataProvider<UserDTO>();
dataProvider.addDataDisplay(usersTable);
List<UserDTO> list = dataProvider.getList();
for (UserDTO UserDTO : userList) {
list.add(UserDTO);
}
final ListHandler<UserDTO> columnSortHandler = new ListHandler<UserDTO>(list);
columnSortHandler.setComparator(firstNameColumn,new Comparator<UserDTO>() {
public int compare(UserDTO o1,UserDTO o2) {
if (o1 == o2) {
return 0;
}
// Compare the firstname columns.
if (o1 != null) {
return (o2 != null) ? o1.getUser().getFirstName().compareTo(o2.getUser().getFirstName()) : 1;
}
return -1;
}
});
columnSortHandler.setComparator(lastNameColumn,new Comparator<UserDTO>() {
public int compare(UserDTO o1,UserDTO o2) {
if (o1 == o2) {
return 0;
}
// Compare the lastname columns.
if (o1 != null) {
return (o2 != null) ? o1.getUser().getLastName().compareTo(o2.getUser().getLastName()) : 1;
}
return -1;
}
});
usersTable.getColumnSortList().push(firstNameColumn);
usersTable.getColumnSortList().push(middleNameColumn);
}
Well, you need a different comparator for each column, the second comparator is the one that you need to change.
First it must sort for FirstName,and if the firstnames are equal, then go on and compare the last names too.
I'm not using your DTO, and i don't check for nulls, but it's the same thing, you get the idea
ArrayList<Map> list = new ArrayList<Map>();
ListHandler<Map> _sortHandler = new ListHandler<Map>(list);
Column columnDefinitionFirstName = null; // create your column first name
columnDefinitionFirstName.setSortable(true);
//
_sortHandler.setComparator(columnDefinitionFirstName, new Comparator<Map>()
{
public int compare(Map o1, Map o2)
{
int res = 0;
String object1 = (String) o1.get("FIRST_NAME");
String object2 = (String) o2.get("FIRST_NAME");
res = object1.compareTo(object2);
return res;
}
});
Column columnDefinitionLastName = null; // create your column last name
columnDefinitionLastName.setSortable(true);
_sortHandler.setComparator(columnDefinitionLastName, new Comparator<Map>()
{
public int compare(Map o1, Map o2)
{
int res = 0;
String object1 = (String) o1.get("FIRST_NAME");
String object2 = (String) o2.get("FIRST_NAME");
res = object1.compareTo(object2);
if(res == 0)
{
String object11 = (String) o1.get("LAST_NAME");
String object22 = (String) o2.get("LAST_NAME");
res = object11.compareTo(object22);
}
return res;
}
});
Related
I am trying to write a generic way to provide pagination on my Link query to my MySQL database. However this required me to have a generic way to where, as the field used may differ from table to table. The issue i am facing it that Linq can't translate my generic types. Are there a way to do this that would work with Linq?
public static class PaginationExtentions {
public static async Task<PaginationResult<T>> Pagination<T, J>(this DbSet<J> dbSet, Pagination pagination, Func<IQueryable<J>, IQueryable<T>>? select) where J : class {
bool previousPage = false;
bool nextPage = false;
string startCursor = null;
string endCursor = null;
var property = typeof(J).GetProperty(pagination.SortBy);
string after = pagination.After != null ? Base64Decode(pagination.After) : null;
bool backwardMode = after != null && after.ToLower().StartsWith("prev__");
string cursor = after != null ? after.Split("__", 2).Last() : null;
List<J> items;
if (cursor == null) {
items = await (from s in dbSet
orderby GetPropertyValue<J, string>(s, pagination.SortBy) ascending
select s).Take(pagination.First)
.ToListAsync();
}
else if (backwardMode) {
items = await (from subject in (
from s in dbSet
where string.Compare( (string?)property.GetValue(s), cursor) < 0
orderby (string?)property.GetValue(s) descending
select s).Take(pagination.First)
orderby (string?)property.GetValue(subject) ascending
select subject).ToListAsync();
}
else {
items = await (from s in dbSet
where string.Compare((string?)property.GetValue(s), cursor) > 0
orderby GetPropertyValue<J, string>(s, pagination.SortBy) ascending
select s).Take(pagination.First)
.ToListAsync();
}
previousPage = await dbSet.Where(s => string.Compare((string?)property.GetValue(s), cursor) < 0).AnyAsync();
nextPage = items.Count == 0 ? false : await dbSet.Where(s => string.Compare((string?)property.GetValue(s), (string?)property.GetValue(items.Last())) > 0).AnyAsync();
var backwardsCursor = !previousPage ? null : "prev__" + cursor;
var forwardsCursor = !nextPage ? null : items.Count > 0 ? "next__" + (string?)property.GetValue(items.Last()) : null;
return new PaginationResult<T>() {
Items = select(items.AsQueryable()).ToList(),
TotalCount = await dbSet.CountAsync(),
HasPreviousPage = previousPage,
HasNextPage = nextPage,
StartCusor = Base64Encode(backwardsCursor),
EndCursor = Base64Encode(forwardsCursor)
};
}
private static U GetPropertyValue<T, U>(T obj, string propertyName) {
return (U)obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}
public static string Base64Encode(string plainText) {
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public static string Base64Decode(string base64EncodedData) {
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
}
I have these parameters in a class:
public class UserParams
{
public string Gender {get; set;}
public int MinAge {get; set;} = 1;
public int MaxAge {get; set;} = 19;
}
The query is done in the repository as shown below. First is to query for the child sex or gender and the second is to query for the child sex or gender
var query = _context.Children.AsQueryable();
query = query.Where(c => c.Sex == userParams.Gender);
var minchildDob = DateTime.Today.AddYears(-userParams.MaxAge - 1);
var maxchildDob = DateTime.Today.AddYears(-userParams.MinAge);
query = query.Where(u => u.DateOfBirth >= minchildDob && u.DateOfBirth <= maxchildDob);
return await PagedList<Child>.CreateAsync(query.AsNoTracking(), userParams.PageNumber, userParams.PageSize);
The gender filter returns empty array of children and the minchildDob and maxchildDob too not working
if (!string.IsNullOrEmpty(temp.Gender))
{
all = all.Where(u => new[] { "men", "women" }.Contains(u.sex));
//all = all.Where(t => t.sex == temp.Gender);
}
=======================Update=======================
var temp = new UserParams();
temp.Gender = "men";
var minchildDob = DateTime.Today.AddYears(-temp.MaxAge - 1);
var maxchildDob = DateTime.Today.AddYears(-temp.MinAge);
IEnumerable<Table> all = from m in _context.data
select m;
_logger.LogError("all data");
foreach (var item in all)
{
_logger.LogError(item.name);
}
_logger.LogError("============================================");
if (!string.IsNullOrEmpty(temp.Gender)) {
all = all.Where(t => t.sex == temp.Gender);
}
_logger.LogError("filter gender");
foreach (var item in all) {
_logger.LogError(item.name);
}
_logger.LogError("============================================");
if (temp.MaxAge > 0) {
all = all.Where(t => t.birthday >= minchildDob && t.birthday <= maxchildDob);
}
_logger.LogError("filter age");
foreach (var item in all)
{
_logger.LogError(item.name);
}
_logger.LogError("============================================");
i am quite new to Javafx, and would like your help in solving the below:
I have two tableviews, and i would like to compare the column values between the two and highlight the cell of one of the tables, if the values are different.
(Assumption - both tables have same number of columns, restricting rows to the minimum content among tables)
ex:
table 1 has
column1 column2 column3
1 America Newyork
table 2 has
column1 column2 column3
1 America Washington
The second table last column should be highlighted with a textfill
I have this pseudo code, doesnt seem to work though
int colsize1= tableview1.getColumns().size();
int colsize2= tableview2.getColumns().size();
if(colsize1 != colsize2) {
alert("number of columns do not match, cannot be validated");
return;
}
ObservableList<ObservableList<String>> da1 = FXCollections.observableArrayList();
ObservableList<ObservableList<String>> da2 = FXCollections.observableArrayList();
da1.addAll(tableview1.getItems());
da2.addAll(tableview2.getItems());
int size = Math.min(da1.size(), da2.size());
for(int i = 0; i < size; i++) {
for (int j = 0; j < colsize1; j++) {
if(!(tableview1.getItems().get(i).get(j).equals(tableview2.getItems().get(i).get(j)))) {
String value = tableview1.getItems().get(i).get(j);
String value2 = tableview2.getItems().get(i).get(j);
int currentrow = i;
TableColumn<TableView<ObservableList<String>>, String> columns = (TableColumn) tableview2.getColumns().get(j);
columns.setCellFactory(column -> {
return new TableCell<TableView<ObservableList<String>>, String>() {
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
System.out.println("item is " + item + " empty is " + empty);
if(empty){
if(value != value2){
this.setStyle("-fx-background-color : yellow");
}
}
if (!empty) {
if((value != item) && currentrow == getTableRow().getIndex()) {
// int rowindex = getTableRow().getIndex();
System.out.println(" item is " + item);
this.setText(item);
this.setTextFill(Color.RED);
this.setStyle("-fx-background-color : yellow");
}else {
this.setText(item);
}
}
}
};
});
}
}
}
}
I found a solution to the given problem.
#FXML
public void onvalidatebutton() {
int colsize1 = tableview1.getColumns().size();
int colsize2 = tableview2.getColumns().size();
if (colsize1 != colsize2) {
alert("number of columns do not match, cannot be validated");
return;
}
int size = tableview1.getItems().size();
for (int i = 0; i < size; i++) {
for (int j = 0; j < colsize1; j++) {
TableColumn columns2 = tableview2.getColumns().get(j);
// String value = tableview1.getItems().get(currentrow).get(j);
settingcell(columns2);
}
}
}
private void settingcell(TableColumn<ObservableList<String>,String> column) {
column.setCellFactory(col -> {
return new TableCell<ObservableList<String>, String>() {
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
int ind = getTableView().getVisibleLeafIndex(column);
// System.out.println(" ind is " + ind);
String value = tableview1.getItems().get(this.getIndex()).get(ind);
// System.out.println(" value is " + value + " & item is "+ item);
if (!(StringUtils.equals(value,item))) {
this.setText(item);
this.setTextFill(Color.RED);
this.setStyle("-fx-background-color : yellow");
} else {
this.setText(item);
}
}
else{
this.setText("");
}
}
};
});
}
I've Been Trying to change the order of nodes through quickfix, but something is wrong.
Here's my code in xtend:
#Fix(org.xtext.custom.conventions.validation.ConventionsValidator::CONVENTION_NOT_ORDERED)
def fixFeatureName( Issue issue, IssueResolutionAcceptor acceptor){
acceptor.accept(issue, 'Sort', "Sort '" + issue.data.head + "'", null)[
element, context |
var gr=(element as Greeting)
if (gr.name === null || gr.name.length === 0)
return;
var econt=gr.eContainer.eContents
var comparator = [ EObject obj1, EObject obj2 |
var o1 = (obj1 as Greeting)
var o2 = (obj2 as Greeting)
return o1.name.compareTo(o2.name)
]
ECollections::sort(econt, comparator)
]
}
No exception is being thrown to console, in debug I found an UnsupportedOperationException is thrown and handled by xtext.
I suspect that EList is immutable.
So how can I sort the AST?
(Here is the generated code: )
#Fix(ConventionsValidator.CONVENTION_NOT_ORDERED)
public void fixFeatureName(final Issue issue, final IssueResolutionAcceptor acceptor) {
String[] _data = issue.getData();
String _head = IterableExtensions.<String>head(((Iterable<String>)Conversions.doWrapArray(_data)));
String _plus = ("Sort \'" + _head);
String _plus_1 = (_plus + "\'");
final ISemanticModification _function = new ISemanticModification() {
public void apply(final EObject element, final IModificationContext context) throws Exception {
Greeting gr = ((Greeting) element);
boolean _or = false;
String _name = gr.getName();
boolean _tripleEquals = (_name == null);
if (_tripleEquals) {
_or = true;
} else {
String _name_1 = gr.getName();
int _length = _name_1.length();
boolean _tripleEquals_1 = (Integer.valueOf(_length) == Integer.valueOf(0));
_or = (_tripleEquals || _tripleEquals_1);
}
if (_or) {
return;
}
EObject _eContainer = gr.eContainer();
EList<EObject> econt = _eContainer.eContents();
final Function2<EObject,EObject,Integer> _function = new Function2<EObject,EObject,Integer>() {
public Integer apply(final EObject obj1, final EObject obj2) {
Greeting o1 = ((Greeting) obj1);
Greeting o2 = ((Greeting) obj2);
String _name = o1.getName();
String _name_1 = o2.getName();
return _name.compareTo(_name_1);
}
};
Function2<EObject,EObject,Integer> comparator = _function;
final Function2<EObject,EObject,Integer> _converted_comparator = (Function2<EObject,EObject,Integer>)comparator;
ECollections.<EObject>sort(econt, new Comparator<EObject>() {
public int compare(EObject o1,EObject o2) {
return _converted_comparator.apply(o1,o2);
}
});
}
};
acceptor.accept(issue, "Sort", _plus_1, null, _function);
}
thanks!
Sorting a temporary collection which will then replace econt didn't work. but I managed to solve it in a different way.
so one solution was to force a cast of eContainer as it's runtime element (which is Model), and then getting a list with it's getGreetings getter, and with that element the sorting works, but I didn't want to involve non-generic code, for technical reasons.
So after a lot of experiments I finally found that element without involving any other elements or keywords from the grammar:
var econt = (gr.eContainer.eGet(gr.eContainingFeature) as EObjectContainmentEList<Greeting>)
and that is exactly what was looking for. Sorting is successful!
Here's the resulting Xtend code (got rid of casing in the comperator as well):
#Fix(ConventionsValidator::CONVENTION_NOT_ORDERED)
def fixFeatureName(Issue issue, IssueResolutionAcceptor acceptor) {
acceptor.accept(issue, 'Sort', "Sort '" + issue.data.head + "'", null) [
element, context |
var gr = (element as Greeting)
if (gr.name === null || gr.name.length === 0)
return;
var econt = (gr.eContainer.eGet(gr.eContainingFeature) as EObjectContainmentEList<Greeting>)
var comparator = [ Greeting o1, Greeting o2 |
return o1.name.compareTo(o2.name)
]
ECollections::sort(econt, comparator)
]
}
and the generated java:
#Fix(ConventionsValidator.CONVENTION_NOT_ORDERED)
public void fixFeatureName(final Issue issue, final IssueResolutionAcceptor acceptor) {
String[] _data = issue.getData();
String _head = IterableExtensions.<String>head(((Iterable<String>)Conversions.doWrapArray(_data)));
String _plus = ("Sort \'" + _head);
String _plus_1 = (_plus + "\'");
final ISemanticModification _function = new ISemanticModification() {
public void apply(final EObject element, final IModificationContext context) throws Exception {
Greeting gr = ((Greeting) element);
boolean _or = false;
String _name = gr.getName();
boolean _tripleEquals = (_name == null);
if (_tripleEquals) {
_or = true;
} else {
String _name_1 = gr.getName();
int _length = _name_1.length();
boolean _tripleEquals_1 = (Integer.valueOf(_length) == Integer.valueOf(0));
_or = (_tripleEquals || _tripleEquals_1);
}
if (_or) {
return;
}
EObject _eContainer = gr.eContainer();
EStructuralFeature _eContainingFeature = gr.eContainingFeature();
Object _eGet = _eContainer.eGet(_eContainingFeature);
EObjectContainmentEList<Greeting> econt = ((EObjectContainmentEList<Greeting>) _eGet);
final Function2<Greeting,Greeting,Integer> _function = new Function2<Greeting,Greeting,Integer>() {
public Integer apply(final Greeting o1, final Greeting o2) {
String _name = o1.getName();
String _name_1 = o2.getName();
return _name.compareTo(_name_1);
}
};
Function2<Greeting,Greeting,Integer> comparator = _function;
final Function2<Greeting,Greeting,Integer> _converted_comparator = (Function2<Greeting,Greeting,Integer>)comparator;
ECollections.<Greeting>sort(econt, new Comparator<Greeting>() {
public int compare(Greeting o1,Greeting o2) {
return _converted_comparator.apply(o1,o2);
}
});
}
};
acceptor.accept(issue, "Sort", _plus_1, null, _function);
}
I am using JPA named queries for Loading a Lazy Loaded DataTable. and setting first and Max results as shown below.
Query query = entityManager.createNamedQuery("StudyplanCategory.findByStatusAndLimit");
int end=(start*pageNumber);
query.setParameter("status", status);
query.setParameter("start", start);
query.setParameter("end", end);
query.setMaxResults(end - start);
The load method is given below:
public List<StudyplanCategory> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {
List<StudyplanCategory> data = new ArrayList<StudyplanCategory>();
//System.out.println("Page First Value:"+first+"PageSize Value:"+pageSize);
datasource=categoryService.findDynaEditStudyPlan("NOT_USER_SPECIFIC",first,pageSize);
//filter
for(StudyplanCategory studyplanCategory : datasource) {
boolean match = true;
for(Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {
try {
String filterProperty = it.next();
String filterValue = filters.get(filterProperty).toLowerCase();
String fieldValue = String.valueOf(studyplanCategory.getClass().getDeclaredField(filterProperty).get(studyplanCategory)).toLowerCase();
//System.out.println("fieldValue............."+fieldValue);
if(filterValue == null || fieldValue.startsWith(filterValue)) {
match = true;
}
else {
match = false;
break;
}
} catch(Exception e) {
match = false;
System.out.println("The Exception occured at"+e);
}
}
if(match) {
data.add(studyplanCategory);
}
}
//sort
if(sortField != null) {
Collections.sort(data, new LazySorter(sortField, sortOrder));
}
//rowCount
int dataSize = data.size();
this.setRowCount(dataSize);
//paginate
if(dataSize > pageSize) {
try {
return data.subList(first, first + pageSize);
}
catch(IndexOutOfBoundsException e) {
return data.subList(first, first + (dataSize % pageSize));
}
}
else {
return data;
}
}
But when the table is loaded Next Buttons are not active because I am loading only those data required to load the first page. How can I Solve this.
You need to fire another query which sets the total rowcount. Basically, in LazyDataModel#load():
public List<StudyplanCategory> load(...) {
setRowCount(studyplanCategoryService.count());
return studyplanCategoryService.list(...);
}
Unrelated to the concrete problem, you should actually be using Query#setFirstResult() to set the first record index.