Using find method of org.apache.commons.collections4.CollectionUtils with Predicate - collections

I was using org.apache.commons.collections.CollectionUtils and for this version using find method was like this:
BeanPropertyValueEqualsPredicate objIdEqualsPredicate = new BeanPropertyValueEqualsPredicate("objId", objId);
myObj = (MyClass) CollectionUtils.find(myObjSet, objIdEqualsPredicate);
But with org.apache.commons.collections4.CollectionUtils, I don't know how to make it work.
Here what I do now but if there is a clear way of it, I will be glad to learn:
Predicate<MyClass> objIdEqualsPredicate = new Predicate<MyClass>() {
#Override
public boolean evaluate(MyClass obj) {
return obj.getObjId().equals(objId);
}
};
myObj = CollectionUtils.find(myObjSet, objIdEqualsPredicate);
Is there a way to filter some objects according to the their fields' values. If possible I don't want to use anonymous class for this.
Thanks.

As the common-beanutils still have commons-collections as dependency, you must implement the Predicate interface.
For example you can take the source code of BeanPropertyValueEqualsPredicate and refactor it, so your version implements the org.apache.commons.collections4.Predicate interface.
Or you write your own version. I would prefer not to use anonymous inner classes, because of the possibility to write unit tests for the predicate and reuse it.
Quick Example (not nullsafe,..)
#Test
public class CollectionsTest {
#Test
void test() {
Collection<Bean> col = new ArrayList<>();
col.add(new Bean("Foo"));
col.add(new Bean("Bar"));
Predicate<Bean> p = new FooPredicate("Bar");
Bean find = CollectionUtils.find(col, p);
Assert.assertNotNull(find);
Assert.assertEquals(find.getFoo(), "Bar");
}
private static final class FooPredicate implements Predicate<CollectionsTest.Bean> {
private String fieldValue;
public FooPredicate(final String fieldValue) {
super();
this.fieldValue = fieldValue;
}
#Override
public boolean evaluate(final Bean object) {
// return true for a match - false otherwise
return object.getFoo().equals(fieldValue);
}
}
public static class Bean {
private final String foo;
Bean(final String foo) {
super();
this.foo = foo;
}
public String getFoo() {
return foo;
}
}
}

Related

RestController JSON Response object format

I am using Spring Boot to return data from a Repository. I would like to format my JSON so that it plays nicely with ExtJS' ajax handling. Essentially I would like to include properties to handle success/failure, count, and errorMsg along with a List of data from the repository.
I have tried by creating a ResponseDTO object that I'm returning from my Rest Controller.
#RestController
public class AdminController {
private static final Logger logger = LogManager.getLogger(AdminController.class);
#Autowired
private UserService userService;
#Autowired
private SecurityService securityService;
#Autowired
private UserValidator userValidator;
#GetMapping("/searchUsers")
public ResponseDTO searchUsers(String name, String active) {
int activeFlag;
List<User> users;
ResponseDTO resp;
if(active.equals("true")) {
activeFlag = 1;
} else activeFlag=0;
if(StringUtils.isEmpty(name)) {
users= userService.findAllUsers(activeFlag);
} else {
users= userService.findByUsernameActive(name, activeFlag);
}
return new ResponseDTO(users, true);
}
}
Here's my DTO that I use in the controller:
public class ResponseDTO {
private boolean success;
private int count = 0;
private List<?> values;
public boolean getSuccess() {
return this.success;
}
public void setState(boolean st) {
this.success=st;
}
public int getCount() {
return this.count;
}
public void setCount(int cnt) {
this.count=cnt;
}
public List<?>getValues() {
return this.values;
}
public void setValues(List<?> vals) {
this.values = vals;
}
public ResponseDTO(List<?> items, boolean state) {
this.success = state;
values = items;
this.count = items.size();
}
}
Here's what the JSON I get back looks like:
{
"ResponseDTO": {
"success":true,
"count":2,
"values":[{obj1 } , { obj2}]
}
}
what I would like to get is something more like:
{
"success" : true,
"count" : 2,
"values" [{obj1},{obj2}]
}
I'm using Spring Boot and Jackson annotations. I have used an annotation to ignore individual fields in the objects in the results array, but I can't find a way to unwrap the ResponseDTO object to not include the class name.
When you serialize ResponseDTO POJO, you should not get 'ResponseDTO' in the response by default. Because, the root wrap feature is disabled by default. See the doc here. If you have the below code, please remove it.
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);

Reflection issue: NoSuchMethodException <init> ...specification.SearchCriteria, [Ljava.lang.String;)

Well, NoSuchMethodException is normally well self-explaining. Unfortunately, in my case, I couldn't even guess why I am getting such error.
I am taking care a code from other developer and I must maintain it. It was designed with specification pattern in mind. In order to make the search engine very generic, basically, any string passed from client to rest service is split in order to build the search criteria.
When executing "clazzSpec.getDeclaredConstructor(SearchCriteria.class, String[].class).newInstance(param);" I get
java.lang.NoSuchMethodException: br.com.mycompany.specification.SomethingSpecification.<init>(br.com.mycompany.specification.SearchCriteria, [Ljava.lang.String;)
Looking the image bellow, I can't see what is missed
SearchCriteria:
public class SearchCriteria {
private String key;
private String operation;
private Object value;
public SearchCriteria(String key, String operation, Object value) {
this.key = key;
this.operation = operation;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
SomethingSpecification
public class SomethingSpecification extends Specification<Something> {
public SomethingSpecification(SearchCriteria criteria) {
super(criteria);
}
#Override
public Predicate toPredicate(Root<Something> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
switch (criteria.getOperation()) {
case "=":
...
}
return super.toPredicate(root, query, builder);
}
}
The reflection code looks for a constructor with two arguments: SearchCriteria and a String[]. But the only constructor for SomethingSpecification only has one argument.

How do you abstract page session properties?

I was following this example
example code:
public class Global : HttpApplication
{
private Poster _posterDetails;
private Posting _postingDetails;
private Property _propertyDetails;
protected void Application_PostRequestHandlerExecute(object sender, EventArgs e)
{
if (HttpContext.Current.Session == null) return;
_posterDetails = HttpContext.Current.Session["Poster"] as Poster;
_postingDetails = HttpContext.Current.Session["Posting"] as Posting;
_propertyDetails = HttpContext.Current.Session["Property"] as Property;
}
}
these session variables are littered throughout the app and I need to abstract the retrieval of them. Say, later I get them from a db instead of the current session.
Session is baked into the Page or Context. How do I inject that dependency into the concrete implementation of a possible current property getter.
Create an abstraction around HttpContext:
public interface IHttpContextFactory
{
HttpContextBase Create();
}
public class HttpContextFactory
: IHttpContextFactory
{
public HttpContextBase Create()
{
return new HttpContextWrapper(HttpContext.Current);
}
}
Then inject it into a specialized service for these settings.
public interface ISettings
{
T GetValue<T>(string key);
void SetValue<T>(string key, T value);
}
public class ContextSettings
: ISettings
{
private readonly IHttpContextFactory httpContextFactory;
private HttpContextBase context;
public RequestCache(
IHttpContextFactory httpContextFactory
)
{
if (httpContextFactory == null)
throw new ArgumentNullException("httpContextFactory");
this.httpContextFactory = httpContextFactory;
}
protected HttpContextBase Context
{
get
{
if (this.context == null)
{
this.context = this.httpContextFactory.Create();
}
return context;
}
}
public virtual T GetValue<T>(string key)
{
if (this.Context.Session.Contains(key))
{
return (T)this.Context.Session[key];
}
return default(T);
}
public virtual void SetValue<T>(string key, T value)
{
this.Context.Session[key] = value;
}
}
It will later be possible to replace the service with another storage mechanism by implementing ISettings and providing different constructor dependencies. Note that changing the constructor signature does not require a different interface.
That said, you should provide another service (or perhaps more than one) that takes ISettings as a dependency so you can make explicit properties. You should aim to provide focused sets of related properties for specific purposes. Your application also shouldn't have to know the type of property in order to retrieve its value - it should just call a property that hides those details.
public class SomeSettingsService: ISomeSettingsService
{
private readonly ISettings settings;
public SomeSettingsService(ISettings settings)
{
if (settings == null)
throw new ArgumentNullException("settings");
this.settings = settings;
}
public Poster Poster
{
get { return this.settings.GetValue<Poster>("Poster"); }
set { this.settings.SetValue<Poster>("Poster", value); }
}
public Posting Posting
{
get { return this.settings.GetValue<Posting>("Posting"); }
set { this.settings.SetValue<Posting>("Posting", value); }
}
public Property Property
{
get { return this.settings.GetValue<Property>("Property"); }
set { this.settings.SetValue<Property>("Property", value); }
}
}
Not sure if this is what you are asking... What I often do is create a service:
public interface ISessionService
{
object Get(string key);
void Save(string key, object value);
}
And then I implement this, which calls HttpContext.Current.Session[key] and returns the value. It shouldn't be hard to create a Get<T>(string key) to return an object either. Break all of your dependencies to use this (which is the hard part).
There is no seamless way to break the dependency... it has to be through a manual change.

How to invoke an static method which contains generics types from an static generic class

I'm using Reflection to work out my project classes with the Generics from a third party, however, I keep getting the error "Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true." when I try to Invoke an static method from an static generic class which contains generics invocation.
Third Party code looks like this
public interface INestedGeneric<TResult>
{
INestedGeneric<TResult> DoSomethingElse();
}
public static class GenericClass<TResult> where TResult : new()
{
public static INestedGeneric<TResult> DoSomething()
{ return new NestedClass<TResult>(); }
}
public class NestedClass<TResult> : INestedGeneric<TResult>
{
public INestedGeneric<TResult> DoSomethingElse()
{ return new NestedClass<TResult>(); }
}
My code looks like:
public class Someone
{
private int _integerProperty;
private string _stringProperty;
public int IntegerProperty
{
get { return _integerProperty; }
set { _integerProperty = value; }
}
public string StringProperty
{
get { return _stringProperty; }
set { _stringProperty = value; }
}
}
static void Main(string[] args)
{
Type classType = typeof(Someone);
Type theclass = typeof(GenericClass<>); theclass.MakeGenericType(classType);
Type theinterface = typeof(INestedGeneric<>); theinterface.MakeGenericType(classType);
MethodInfo dosomething = theclass.GetMethod("DoSomething", BindingFlags.Public | BindingFlags.Static);
dosomething.Invoke(null, null);
dosomething = null;
}
Any idea how to invoke the method strictly in this scenario? I have read and try the help from other posts, but didn't work.
Thank you so much...
I already figure it out. The solution was to use the type provided by the MakeGenericType method.
Like this:
...
Type theclass = typeof(GenericClass<>).MakeGenericType(classType);
Type theinterface = typeof(INestedGeneric<>).MakeGenericType(classType);
MethodInfo dosomething = theclass.GetMethod("DoSomething", BindingFlags.Public | BindingFlags.Static);
dosomething.Invoke(null, null);
...

implementing singleton class for Actionscript

I know actionscript does not allowed private contstructor at any time and But if i want to write a sinlgleton class in action script So how to implement it in actionscript.
Can anyone provide an sample example of a singleton pattern in actionscript?
I use something like this:
package singletons
{
[Bindable]
public class MySingleton
{
private static var _instance:MySingleton;
public function MySingleton(e:Enforcer) {
if(e == null) {
throw new Error("Hey! You can't do that! Call getInstance() instead!");
}
}
public static function getInstance():MySingleton {
if(_instance == null) {
_instance = new MySingleton (new Enforcer);
}
return _instance;
}
}
}
// an empty, private class, used to prevent outside sources from instantiating this locator
// directly, without using the getInstance() function....
class Enforcer{}
You need to alter Alxx's answer slightly as it doesn't stop new Singleton() from working...
public class Singleton {
private static var _instance : Singleton;
public function Singleton( newBlocker : ClassLock ) {
}
public static function getInstance() : Singleton {
if ( _instance == null ) {
_instance = new Singleton( new ClassLock() );
}
return _instance;
}
}
class ClassLock{}
The private class is used by the Singleton to stop other classes simply doing new Singleton() initially and then getting a second instance by doing getInstance().
Note that this still isn't watertight... If someone is determined to break it, they can get access to the private class, but this is about the best option for Singletons.
basically, all answers are right, those of reid and gregor provide more compile time safety. I suppose, the best thing is however, to declare an interface for the singleton and a private implementor exposed through a static class:
package {
interface IFoo {
function foo():void;
}
}
and then:
package Foo {
private static var _instance:IFoo;
public static function getInstance():IFoo {
if (_instance == null) _instance = new Impl();
return _instance;
}
}
class Impl implements IFoo {
public function foo():void {
trace("fooooooooooooooooooo");
}
}
this doesn't rely on runtime errors for safety. Also, it lowers coupling.
greetz
back2dos
public class Singleton {
private static var _instance:Singleton;
public **static** function get instance():Singleton
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
public function Singleton()
{
if (_instance != null) throw new Error("You can't create Singleton twice!");
}
}
Runtime check in lack of private constructor.
I use this approach ...
package
{
public class Main
{
private static var _instance:Main;
private static var _singletonLock:Boolean = false;
/**
* Creates a new instance of the class.
*/
public function Main()
{
if (!_singletonLock) throw new SingletonException(this);
}
/**
* Returns the singleton instance of the class.
*/
public static function get instance():Main
{
if (_instance == null)
{
_singletonLock = true;
_instance = new Main();
_singletonLock = false;
}
return _instance;
}
}
}
... not as terse as some other methods but it's absolutely safe and there's no need for an empty package-level class. Also note the shortcut with SingletonException which is a class that extends the AS3 Error class and saves typing some code when using more than one Singleton ...
package
{
public class SingletonException extends Error
{
public function SingletonException(object:Object)
{
super("Tried to instantiate the singleton " + object + " through it's constructor."
+ " Use the 'instance' property to get an instance of this singleton.");
}
}
}

Resources