Formatting the value in the cell of a table - vaadin

I made a table and the corresponding SQLContainer. The table have a column with phone numbers. In db table type of the corresponding column is a int. I wish formatting values of Vaadin table, in such way that view phone numbers become without comas or dots like separator of thousand(8,888 -> 8888).
I have already made similar thing to the Table which data source is a JPAContainer on this way:
Table imenikTable = new Table("Imenik", imenikData){
/**
*
*/
private static final long serialVersionUID = 8213291207581835298L;
#Override
protected String formatPropertyValue(Object rowId,
Object colId, #SuppressWarnings("rawtypes") Property property) {
Object v = property.getValue();
if (v instanceof Integer) {
DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(getLocale());
df.applyLocalizedPattern("##00");
return df.format(v);
}
return super.formatPropertyValue(rowId, colId, property);
}
};
And everything works well. But when i made similar construction with SQLContiner instead of JPAContainer formatting is simply ignored. Affter that i try to change the way like this:
StringToIntegerConverter plainIntegerConverter = new StringToIntegerConverter(){
private static final long serialVersionUID = -7517984934588222147L;
protected NumberFormat getFormat(Locale locale){
NumberFormat format = super.getFormat(locale);
format.setGroupingUsed(false);
return format;
}
};
contaktListTable.setConverter("telbr", plainIntegerConverter);
But still my environment ignores me, even no error messages! What can be problem?

I think
Object v = property.getValue();
is not returning an Integer value when you use the SQLContainer and that's why you are not seeing any exceptions, the conditional block is not being executed.
Can you check that with a break point?

Related

Dart Object instantiating

I'm very new to programming and Dart. I was wondering why you put Response in front of the variable response. Also why do we use Datetime object in front of the variable 'now?' I believe when you want to instantiate, you write Datetime now = Datetime(); But it was written something else for the variable. What does it mean? Thank you very much in advance!
void getTime() async{
Response response = await get(Uri.parse('https://worldtimeapi.org/api/timezone/Europe/London'));
Map data = jsonDecode(response.body);
// get properties from data
String datetime = data['datetime'];
String offset = data['utc_offset'].substring(1,3);
//create DateTime object
DateTime now = DateTime.parse(datetime);
now = now.add(Duration(hours: int.parse(offset)));
print(now);
}
Ok, let's break this down:
Response response = await
get(Uri.parse('https://worldtimeapi.org/api/timezone/Europe/London'));
A variable declaration in Dart looks like this:
<Type> <name> [= <value>];
So in your case Response is the type of the variable, response is the name of the variable and get(Uri.parse('https://worldtimeapi.org/api/timezone/Europe/London')) is the value of the variable (actually get(...) is a future, and the future's response is the value, that's why the await keyword is there, but that's not important.)
Sidenote, you can actually use the var keyword to skip the <Type> part of the declaration:
int myFunction(a, b) => a+b;
int x = myFunction(1,2);
Above, we know myFunction returns an int, and the variable x is equal to the result of myFunction, so it must also be an int, we can use the var keyword to skip writing int then:
int myFunction(a, b) => a+b;
var x = myFunction(1,2);
Of course, here there isn't that big a difference between writing int and var, but when your type is something like List<Map<String, List<int>>> it is quite nice to be able to skip writing that over and over
Now for this line:
DateTime now = DateTime.parse(datetime);
We already know that the first DateTime tells us what type the variable is, and we know that now is the name of the variable, we also know that the variable's value is DateTime.parse(datetime) because it is what goes after the = sign, but we still don't know what DateTime.parse(datetime) means.
Classes can have static and non-static methods, a static method is a method that gets called on a class, while a non-static method gets called on an object. Most method calls ever are non-static, look at this example:
class Car {
void accelerate() {
// some method to increase the speed of the car
}
void decelerate() {
// some method to decrease the speed of the car
}
Car buyCar(int maxCost) {
// some method to buy a new car
}
}
void main() {
Car car = Car();
car.accelerate();
car.decelerate();
Car otherCar = car.buyCar(100000000);
}
Above, the method accelerate and decelerate are instance methods and that makes sense because they probably affect some statistics of the car (like current speed), buyCar is also an instance method, but if you think about it, it shouldn't be, it doesn't affect your current car if you buy a new one and also you shouldn't need to have a car object to buy another one in the first place. So let's make that last method static:
class Car {
void accelerate() {
// some method to increase the speed of the car
}
void decelerate() {
// some method to decrease the speed of the car
}
static Car buyCar(int maxCost) {
// some method to buy a new car
}
}
It is as simple as adding the static keyword, now instead of having to do this:
Car myOldCar = Car();
Car myNewCar = myOldCar.buyCar(100000000);
we can just do this:
Car myNewCar = Car.buyCar(100000000);
looks familiar?
That's right parse is a static method on DateTime class, it takes a string that looks like this: 2012-02-27 13:27:00.123456789z and returns a DateTime object.
So to recap:
Response response = await
get(Uri.parse('https://worldtimeapi.org/api/timezone/Europe/London'));
Response is the type of the variable, response is its name and get(Uri.parse('https://worldtimeapi.org/api/timezone/Europe/London')) is a method that returns a Response object.
DateTime now = DateTime.parse(datetime);
Similarly DateTime is the type, now is the name and DateTime.parse is a static method that parses a string and makes a DateTime object, in this case the string is datetime, which was declared as being equal to data['datetime'].
If you want to understand better how the parse method works, here is the DateTime parse documentation

Grails querying model containing an enum set

My domain class is
class RoomWantedAd{
Set<MateAgeRange> mateAgeRanges
static hasMany=[mateAgeRanges :MateAgeRange]
}
Her MateAgeRange is :
enum MateAgeRange {
TWENTIES('18-29')
,THIRTIES('30-39')
,FOURTIES("40-49")
,FIFTIES("50-59")
,SIXTIES("60+")
final String value
private MateAgeRange(String value) {
this.value = value
}
String toString() { value }
String getKey() { name() }
static belongsTo=[roomWanted:RoomWanted]
}
My problem is searching. In the search page, a person can select 0 or more values in [18-29, 30-39, 40-49, 50-59, 60+]. In the db, 0 or more values among [18-29, 30-39, 40-49, 50-59, 60+] are stored in field 'mateAgeRanges'.
Let db contains [30-39, 50-59] in 'mateAgeRange' field. Let in the search page, the user selects [18-29, 50-59, 60+]. Then the Ad corresponding to the above list must be returned. This is because at least one value in user's selection is present in the db list. How is it possible. Is it possible using an SQL query or grails GORM query.
you have to use exactly the same <g:select/> tag as you are using for create/update. Thus, you will see human readable values like THIRTIES in browser, but in the background the '30-39' values will be used.

Making a variable the key in a Map

I have two classes
class Phone extends Observable
{
#observable String type = '';
#observable String provider = '';
#observable String num = '';
Map<String, Map<String, String> map = {};
Phone() {}
Phone.build({ this.type,
this.provider,
this.num });
}
I have attempted to use the field values as the key in map like so
Phone phone = new Phone();
phone.map[phone.type] = {'type':'cell', 'provider':'Verizon', 'num':'1234567'};
but it does not work. How can I make the fields value the key for the map?
just remove the quotes
phone.map[phone.type] = {type:'cell', provider:'Verizon', num:'1234567'};
Because you are using strings in your example this may not apply but be aware that if you use instances of custom types as Map key...
The keys of a `HashMap` must have consistent [Object.operator==]
and [Object.hashCode] implementations. This means that the `==` operator
must define a stable equivalence relation on the keys (reflexive,
anti-symmetric, transitive, and consistent over time), and that `hashCode`
must be the same for objects that are considered equal by `==`.

C# Reflection PropertyInfo Nested Classes in MVC

Is there a generic way to retrieve PropertyInfo based on a string value alone, when deeper than one level.
I assume this is probably simple enough, but my search results are only as good as my search criteria, and I think I am having an issue articulating the proper keywords to get search results for what I am after.
I would like to be able to do something like the following (which works perfect if the key is for a direct property / one level - ie key = 'firstName'):
public static PropertyInfo (this HtmlHelper htmlHelper, string key) {
PropertyInfo pInfo = htmlHelper.ViewData.Model.GetType().GetProperty(key);
return pInfo;
}
But is there a way for me to return the PropertyInfo based on a string alone
when Key equals something more complex, such as nested classes, objects, lists, etc...:
key = "somelist[0].myproperty"
key = "Items[0].someotherlist[1].someproperty" (where Items is defined as List<Item> Items {get; set;}, someotherlist is defined similarly)
Can the method be generic enough to essentially drill down as many levels as needed (defined)?
So here is what I came up with... this is about to get wordy, and mostly 'stream of thought'
I have custom HtmlHelperExtension, and within it :
PropertyInfo[] pInfoArray = htmlHelper.ViewData.Model.GetType().GetProperties();
PropertyInfo pInfo = GetPropertyInfo(pInfoArray, key);
This GetPropertyInfo() method takes the key, and the PropertyInfo array, cycles through the properties, until the keypart (using regex to remove any indication of an array from the string, so I am left with only the property) matches the property name. On Match, determine if this is the first cycle in the loop, and if so assign the matched property to my Temp Type and PropertyInfo variables. If keyParts are remaining to loop through, subsequent loops now use previously set temp variables and the for loop index [i] to iterate / drill down the class structure. Each time setting the pInfoTemp variable, and then pTypeTemp so the next loop can use where it left off.
private static PropertyInfo GetPropertyInfo(PropertyInfo[] pInfoArray, string key)
{
PropertyInfo pInfo = null;
string[] keyParts = key.Split('.');
Regex arrayRgx = new Regex("\\[\\d*\\]");
PropertyInfo pInfoTemp = null;
Type pTypeTemp = null;
foreach (PropertyInfo prop in pInfoArray)
{
string keyPartsTrimmed = arrayRgx.Replace(keyParts[0], ""); // removes '[#]' from string
if (keyPartsTrimmed == prop.Name) // match property name
{
for (int i = 0; i < keyParts.Count(); i++)
{
if (i == 0) // initial item [0]
{
pTypeTemp = prop.PropertyType; // gets [0]'s type
pInfoTemp = prop; // assigns [0]'s property info
}
else
{
pInfoTemp = GetNestedPropertyInfo(pTypeTemp, arrayRgx.Replace(keyParts[i], "")); // gets [i]'s property info for return or next iteration
pTypeTemp = pInfoTemp.PropertyType; // gets [i]'s type for next iteration
}
}
pInfo = pInfoTemp;
break;
}
}
return pInfo;
}
This next method is invoked by the previous for grabbing nested property info, more importantly for detecting whether the passedItemType is a List (without this, it fails to work correctly as it is unable to find the property asked for in a List<> Type. I need to know what the List item Type is.
private static PropertyInfo GetNestedPropertyInfo(Type passedItemType, string passedProperty)
{
PropertyInfo pInfoOut = null;
if (passedItemType.IsGenericType && passedItemType.GetGenericTypeDefinition() == typeof(List<>))
{
Type itemType = passedItemType.GetGenericArguments()[0];
pInfoOut = itemType.GetProperty(passedProperty);
}
else
{
pInfoOut = passedItemType.GetProperty(passedProperty);
}
return pInfoOut;
}
This currently suits my requirements as they are today, and I have tested it with the following properties, lists, subclasses, subclasses with lists, etc.. to 4 levels deep, but should function properly no matter the depth:
firstName
lastName
Items[1].sprocket
subClass.subClassInt
subClass.mySubClassObj.sprocketObj
subClass.ItemsInMySubClass[1].sprocket
subClass.ItemsInMySubClass[0].mySubClassObj.widgetObj
subClass.ItemsInMySubClass[2].mySubClassObj.sprocketObj
If anyone has a better solution, or see any potential issues with what I have, I welcome the feedback.
The best way in your case is to make a parser that split that expression.

Object.ReferenceEquals returns incorrect results (in Silverlight 3 at least)

I just discovered a very strange behaviour. I have a class with a string property. In the setter of this property I compare the old value with the new value first and only change property if the values differ:
set
{
if ((object.ReferenceEquals(this.Identifier, value) != true))
{
this.Identifier = value;
this.RaisePropertyChanged("Identifier");
}
}
But this ReferenceEquals almost always returns false! Even if I call object.ReferenceEquals("test", "test") in Quick Watch I get false.
How is this possible?
That's because strings are immutable in C#:
The contents of a string object cannot
be changed after the object is
created, although the syntax makes it
appear as if you can do this.
Since you can't modify an existing string reference, there's no benefit in reusing them. The value passed to your property setter will always be a new string reference, except maybe if you do this.Identifier = this.Identifier;.
I'll try to clarify with an example:
string s = "Hello, "; // s contains a new string reference.
s += "world!"; // s now contains another string reference.

Resources