Since Codename One supports a subset of base Java Object Functionality, I can't use Vector.sort() to sort my data before adding it into a DefaultListModel. so Looking for other sorting options in Codename One, I found the FilterProxyListModel.
I can't find an example of how to properly initialize the FilterProxyListModel as it's using an interesting but tricky "Proxy" design pattern that I'm unfamiliar with. Here's how I've implemented it so far, but the component doesn't show any elements in the simulator when I do it this way. This is in the "initListModel..." method for my List from the GUI Builder:
protected boolean initListModelLearnableTopicsList(List cmp){
Vector learnableListModel = new Vector;
//omitting initialization of learnableListModel as a Vector of HashTables with key/value pairs to display
...
FilterProxyListModel<DefaultListModel> fpListModel = new FilterProxyListModel<DefaultListModel>(new DefaultListModel(learnableListModel)) {
#Override
protected int compare(Object a, Object b, boolean ascending) {
//details omitted... uses data in the LearnableListModel to provide sort order
}
#Override
protected boolean check(Object o, String str) {
//force all results to pass filter since original method fails when a Map object without a key of "name" is in the list
return true;
}
};
fpListModel.sort(true);
cmp.setModel(fpListModel);
}
Am I doing something wrong here? is there an example somewhere I should be using as a guide to doing this properly?
You can use Collections.sort(vector); the filter model is for list classes which we don't really recommend as much https://www.codenameone.com/blog/avoiding-lists.html
Related
I implemented my custom ArrayList using a resizeable Array, and I would like to unit test my add method to check if the right value getting inserted to the right position. My add method looks like this:
public class MyArrayList<T> implements ArrayListInterface {
private int max=20;
private int index = 0;
private int[] a = new int[max];
#Override
public void add(int value) {
if(index>max-1) {
resize();
}
a[index] = value;
index++;
}
I am aware, I could just make my method boolean and check what the method returns, but I would like to check that the right value added to the right position. My problem is that my Array is private, and that way it is only possible to reach its value through a getter. Is it a good solution to make a getter for my Array, and compare that to the actual result of the test, or what would be the best solution to test this method?
I have checked couple of other stackoverflow questions in the same topic, but I couldn't find any solution for my problem.
Add a get() (get(position), getLast(), etc.) method to your class and test using this method. Unit tests should exercise the class through its interfaces, without caring about the internal implementation. Any other class that will interact with your MyArrayList will do so through add() and get().
As SpringEl doc. indicates, there is el syntax for creating a list which then allows me setting it into the context as below:
List numbers = (List) parser.parseExpression("map['innermap']['newProperty']={1,2,3,4}").getValue(context);
However, I am not able to find a way of doing the same thing for Map nor I can find it in the document.
Is there a short hand way of creating a map and then setting it to context? if not, how can we go about it.
If possible a code snippet will be helpful.
Thanks in advance.
It's now possible (since 4.1, I think):
{key:value, key:value}
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html#expressions-inline-maps
No, it isn't possible yet: https://jira.spring.io/browse/SPR-9472
But you can do it with some util method, which should be registered as SpEL-function:
parser.parseExpression("#inlineMap('key1: value1, key2:' + value2)");
Where you have to parse the String arg to the Map.
UPDATE
Please, read this paragraph: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html#expressions-ref-functions.
From big height it should be like this:
public abstract class StringUtils {
public static Map<String, Object> inlineMap(String input) {
// Here is a code to parse 'input' string and build a Map
}
}
context.registerFunction("inlineMap",
StringUtils.class.getDeclaredMethod("inlineMap", new Class[] { String.class }));
parser.parseExpression("#inlineMap('key1: value1, key2:' + value2)")
.getValue(context, rootObject);
I'm not sure if this is possible at all, but is there a way to override the Comparable used by a Google App Engine property when used in a query? For example, there is a property type PhoneNumber (basically a String) that in the docs has a method:
public int compareTo(PhoneNumber o)
Specified by:
compareTo in interface java.lang.Comparable<PhoneNumber>
The exact workings of how it compares I haven't been able to find. Is there a way to override that Comparable so that it compares it in a way I choose?
Thanks
No. But you can sort any collection any way you want. Since you tagged this with objectify:
#Entity
public class Thing {
private static final Comparator<PhoneNumber> SPECIAL_COMPARATOR = // make one
// ... id, etc
SortedSet<PhoneNumber> phoneNumbers = new TreeSet<>(SPECIAL_COMPARATOR);
}
This won't help you if you need the phone numbers indexed in a particular way (although collection property index sorting would be very strange anyways). If you have a single indexed phone number property and you want to control index ordering, you need to create your own PhoneNumber that translates to a correctly-sorted String representation. You'll need to register your own PhoneNumberTranslatorFactory with Objectify. This is not hard; look at the source code for examples.
I have recently started evaluating Dapper as a potential replacement for EF, since I was not too pleased with the SQL that was being generated and wanted more control over it. I have a question regarding mapping a complex object in my domain model. Let's say I have an object called Provider, Provider can contain several properties of type IEnumerable that should only be accessed by going through the parent provider object (i.e. aggregate root). I have seen similar posts that have explained using the QueryMultiple and a Map extension method but was wondering how if I wanted to write a method that would bring back the entire object graph eager loaded, if Dapper would be able to do this in one fell swoop or if it needed to be done piece-meal. As an example lets say that my object looked something like the following:
public AggregateRoot
{
public int Id {get;set;}
...//simple properties
public IEnumerable<Foo> Foos
public IEnumerable<Bar> Bars
public IEnumerable<FooBar> FooBars
public SomeOtherEntity Entity
...
}
Is there a straightforward way of populating the entire object graph using Dapper?
I have a similar situation. I made my sql return flat, so that all the sub objects come back. Then I use the Query<> to map the full set. I'm not sure how big your sets are.
So something like this:
var cnn = sqlconnection();
var results = cnn.Query<AggregateRoot,Foo,Bars,FooBar,someOtherEntity,AggregateRoot>("sqlsomething"
(ar,f,b,fb,soe)=>{
ar.Foo = f;
ar.Bars = b;
ar.FooBar = fb;
ar.someotherentity = soe;
return ar;
},.....,spliton:"").FirstOrDefault();
So the last object in the Query tag is the return object. For the SplitOn, you have to think of the return as a flat array that the mapping will run though. You would pick the first return value for each new object so that the new mapping would start there.
example:
select ID,fooid, foo1,foo2,BarName,barsomething,foobarid foobaritem1,foobaritem2 from blah
The spliton would be "ID,fooid,BarName,foobarid". As it ran over the return set, it will map the properties that it can find in each object.
I hope that this helps, and that your return set is not too big to return flat.
I would like to create a new array with a given type from a class object in GWT.
What I mean is I would like to emulate the functionality of
java.lang.reflect.Array.newInstance(Class<?> componentClass, int size)
The reason I need this to occur is that I have a library which occasionally needs to do the following:
Class<?> cls = array.getClass();
Class<?> cmp = cls.getComponentType();
This works if I pass it an array class normally, but I can't dynamically create a new array from some arbitrary component type.
I am well aware of GWT's lack of reflection; I understand this. However, this seems feasible even given GWT's limited reflection. The reason I believe this is that in the implementation, there exists an inaccessible static method for creating a class object for an array.
Similarly, I understand the array methods to just be type-safe wrappers around JavaScript arrays, and so should be easily hackable, even if JSNI is required.
In reality, the more important thing would be getting the class object, I can work around not being able to make new arrays.
If you are cool with creating a seed array of the correct type, you can use jsni along with some knowledge of super-super-source to create arrays WITHOUT copying through ArrayList (I avoid java.util overhead like the plague):
public static native <T> T[] newArray(T[] seed, int length)
/*-{
return #com.google.gwt.lang.Array::createFrom([Ljava/lang/Object;I)(seed, length);
}-*/;
Where seed is a zero-length array of the correct type you want, and length is the length you want (although, in production mode, arrays don't really have upper bounds, it makes the [].length field work correctly).
The com.google.gwt.lang package is a set of core utilities used in the compiler for base emulation, and can be found in gwt-dev!com/google/gwt/dev/jjs/intrinsic/com/google/gwt/lang.
You can only use these classes through jsni calls, and only in production gwt code (use if GWT.isProdMode()). In general, if you only access the com.google.gwt.lang classes in super-source code, you are guaranteed to never leak references to classes that only exist in compiled javascript.
if (GWT.isProdMode()){
return newArray(seed, length);
}else{
return Array.newInstance(seed.getComponentType(), length);
}
Note, you'll probably need to super-source the java.lang.reflect.Array class to avoid gwt compiler error, which suggests you'll want to put your native helper method there. However, I can't help you more than this, as it would overstep the bounds of my work contract.
The way that I did a similar thing was to pass an empty, 0 length array to the constructor of the object that will want to create the array from.
public class Foo extends Bar<Baz> {
public Foo()
{
super(new Baz[0]);
}
...
}
Baz:
public abstract class Baz<T>
{
private T[] emptyArray;
public Baz(T[] emptyArray)
{
this.emptyArray = emptyArray;
}
...
}
In this case the Bar class can't directly create new T[10], but we can do this:
ArrayList<T> al = new ArrayList<T>();
// add the items you want etc
T[] theArray = al.toArray(emptyArray);
And you get your array in a typesafe way (otherwise in your call super(new Baz[0]); will cause a compiler error).
I had to do something similar, I found it was possible using the Guava library's ObjectArrays class. Instead of the class object it requires a reference to an existing array.
T[] newArray = ObjectArrays.newArray(oldArray, oldArray.length);
For implementing an array concatenation method, I also stepped into the issue of missing Array.newInstance-method.
It's still not implemented, but if you have an existing array you can use
Arrays.copyOf(T[] original, int newLength)
instead.