in my code i have a tableview bound to a ListProperty.
I am able to retrieve all the data correctly but i need to apply a condition to this data set based on a specific property of each object in it.
Is it possible?
This is the model:
public class Ticket {
private String number;
private String sys_id;
private String short_description;
private String description;
private String opened_by;
private String assigned_to; // tabella esterna
private String assignment_group; // tabella esterna
private int incident_state; // 2: assigned - 3: wip - 4: hold
private String sys_created_on;
private Date sys_updated_on;
private int priority; // 1: critical
private boolean isVisible; // per nasconderlo nella tabella riassuntiva
private boolean isAlarmed; // per silenziare le notifiche
In the controller i have bound the tableview to a ListProperty (returned by ticketService.ticketsProperty()):
serviceNowTicket_tableView.itemsProperty().bindBidirectional(ticketService.ticketsProperty());
I just need to filter this by the ticket "isVisible" property.
Maybe via BooleanBinding?
I define an object like
public class DrivelogBean implements Serializable{
private String backInfoIdentify;
private DriVehNum driVehNum;
public static class TotalMileageIntd implements Serializable{
private static final long serialVersionUID = -3268743972404969523L;
private String totalMileage;
private String mileageTime;
public String getTotalMileage () {
return totalMileage;
}
public void setTotalMileage (String totalMileage) {
this.totalMileage = totalMileage;
}
public String getMileageTime () {
return mileageTime;
}
public void setMileageTime (String mileageTime) {
this.mileageTime = mileageTime;
}
}
}
and my controller is like:
#RequestMapping(value="saveDriveLog",method = RequestMethod.GET)
public #ResponseBody ResultBean saveDriveLog(DrivelogBean drivelogBean){
driveLogService.addDriveLog (drivelogBean);
ResultBean resultBean = new ResultBean();
resultBean.setRet (1);
resultBean.setDescripion (UsConstants.DRIVELOG_SAVE);
return resultBean;
}
I want request parameters convert to drivelogBean
and my url is like that:
http://127.0.0.1:8080//manage/drivelog/saveDriveLog/?backInfoIdentify=2&totalMileageIntd["driverNum%22]=1&totalMileageIntd["driveCode"]=2
but the page prompt
HTTP ERROR: 404 Problem accessing //manage/drivelog/saveDriveLog/error. Reason:Not Found
and i change the url like :
http://127.0.0.1:8080//manage/drivelog/saveDriveLog/?commendWord=2&totalMileageIntd.driverNum=1&totalMileageIntd.driveCode=2
but the drivelogBean parameter, the property driverNum of totalMileageIntd and the property driveCode of totalMileageIntd is null.
So how can I set the correct url pass parameter to the drivelogBean?
I don't know if binding inner static class works in spring.
Your parametter must match a setter
commendWord=2 => you must have setCommendWord on the class DrivelogBean
totalMileageIntd.driverNum=1 => you must have a setDriverNum() on and a getTotalMileageIntd
The class should look like this (I skipped getter and setter to save space but they must exists)
public class DrivelogBean implements Serializable{
private String backInfoIdentify;
private DriVehNum driVehNum;
private TotalMileageIntd totalMileageIntd ;
public static class TotalMileageIntd implements Serializable{
private static final long serialVersionUID = -3268743972404969523L;
private String totalMileage;
private String mileageTime;
}
}
In this case all the parametter you can use are :
backInfoIdentify=XXX
driVehNum=XXX
totalMileageIntd.totalMileage=XXX
totalMileageIntd.mileageTime=XXX
nothing else
I have a string with the below format. I would like to convert this string to array.But i don't know how to convert.
1395374478.195 {
Channel : 00000068
State : open
Exten : 100
}
I think Arrays are Collection of Homogeneous elements
and You are specified Elements having Different Data Types
Instead Arrays You can Use Class Or Structure.
But As per Naming Convention in c# Class or Structure Can't Have Name like 1395374478.195
EDIT:
class MyClass
{
private int Channel {get;set;}
private string State {get;set;}
// private bool State {get;set;} For Boolean
private int Exten {get;set;}
public void PerformAction()
{
/// Your actions on above properties ...ex.. ON Channel,State For Adding,removing,or Any
}
}
I'm new to Unity and I'm having a hard time trying to figure out how to expand Unity's concept of Auto Factory. Unity provides out of box the ability to create factories using Func in the place of the parameter itself. Like that:
public class Foo
{
private readonly Func<IBar> _barFactory;
public Foo(Func<IBar> barFactory)
{
_bar = barFactory;
}
}
The thing is, there are places where the class created by the factory needs some parameters and I'll only know those parameters in run time. Other than that, the number and type of those parameters varies from class to class.
What I'm looking for is something similar to Autofac DelegateFacotry, but I would like to keep the Unity's feeling. So, I want to make Unity to work like that:
public class Foo
{
private readonly Func<int, string, IBar> _barFactory;
public Foo(Func<int, string, IBar> barFactory)
{
_bar = barFactory;
}
}
The above code does not work, because Unity does work with that constructor, but it is exactly what I'm looking for.
I have tried use BuilderStrategy but it boils down to either Expression or IL generation. Before going down that path I would like to check for other options.
Is any one experienced enough with Unity who can help me with that?
Here are the constrains I have:
Keep Unity's concept of using Func
Do not need to register every single Func within the container
The constructor should accept Func from Func to Func (Func is handled already)
Changing the container is not an option
I hope I was clear enough. If I was not, please let me know.
Edit 1: I understand I can use abstract factories directly. But, the first goal is to keep Unity's feeling.
I don't like to answer my own questions, but I was able to somehow solve the problem and I believe the solution is good enough that others may be interested. I looked at Unity's source code and got the basic idea from there. I also read a couple of posts regarding Unity. Here it is:
First, I had to create a class that inherited from IBuildPlanPolicy. It is long because I left some supporting classes within the class itself:
public class AutomaticFactoryBuilderPolicy : IBuildPlanPolicy
{
private readonly Dictionary<Type, Type> _callables =
new Dictionary<Type, Type>
{
{typeof(Func<,>), typeof(CallableType<,>)},
{typeof(Func<,,>), typeof(CallableType<,,>)},
{typeof(Func<,,,>), typeof(CallableType<,,,>)},
{typeof(Func<,,,,>), typeof(CallableType<,,,,>)}
};
public void BuildUp(IBuilderContext context)
{
if (context.Existing == null)
{
var currentContainer = context.NewBuildUp<IUnityContainer>();
var buildKey = context.BuildKey;
string nameToBuild = buildKey.Name;
context.Existing = CreateResolver(currentContainer, buildKey.Type, nameToBuild);
}
}
private Delegate CreateResolver(IUnityContainer currentContainer,
Type typeToBuild, string nameToBuild)
{
Type[] delegateTypes = typeToBuild.GetGenericArguments();
Type func = typeToBuild.GetGenericTypeDefinition();
Type callable = _callables[func];
Type callableType = callable.MakeGenericType(delegateTypes);
Type delegateType = func.MakeGenericType(delegateTypes);
MethodInfo resolveMethod = callableType.GetMethod("Resolve");
object callableObject = Activator.CreateInstance(callableType, currentContainer, nameToBuild);
return Delegate.CreateDelegate(delegateType, callableObject, resolveMethod);
}
private class CallableType<T1, TResult>
{
private readonly IUnityContainer _container;
private readonly string _name;
public CallableType(IUnityContainer container, string name)
{
_container = container;
_name = name;
}
public TResult Resolve(T1 p1)
{
return _container.Resolve<TResult>(_name, new OrderedParametersOverride(new object[] { p1 }));
}
}
private class CallableType<T1, T2, TResult>
{
private readonly IUnityContainer _container;
private readonly string _name;
public CallableType(IUnityContainer container, string name)
{
_container = container;
_name = name;
}
public TResult Resolve(T1 p1, T2 p2)
{
return _container.Resolve<TResult>(_name, new OrderedParametersOverride(new object[] { p1, p2 }));
}
}
private class CallableType<T1, T2, T3, TResult>
{
private readonly IUnityContainer _container;
private readonly string _name;
public CallableType(IUnityContainer container, string name)
{
_container = container;
_name = name;
}
public TResult Resolve(T1 p1, T2 p2, T3 p3)
{
return _container.Resolve<TResult>(_name, new OrderedParametersOverride(new object[] { p1, p2, p3 }));
}
}
private class CallableType<T1, T2, T3, T4, TResult>
{
private readonly IUnityContainer _container;
private readonly string _name;
public CallableType(IUnityContainer container, string name)
{
_container = container;
_name = name;
}
public TResult Resolve(T1 p1, T2 p2, T3 p3, T4 p4)
{
return _container.Resolve<TResult>(_name, new OrderedParametersResolverOverride(new object[] { p1, p2, p3, p4 }));
}
}
}
It is pretty straightforward. The trick is to create one CallableType for each Func I want to handle. It is not as dynamic as I first wanted, but in order to make it more dynamic I believe I would have to deal with either IL or Expression Trees. The way I have it now is good enough for me.
Second, Unity handles parameters by name but I had to deal with them by order. That's where OrderedParametersResolverOverride comes into play (this class is used in the code above. Check CallableType classes):
public class OrderedParametersResolverOverride : ResolverOverride
{
private readonly Queue<InjectionParameterValue> _parameterValues;
public OrderedParametersResolverOverride(IEnumerable<object> parameterValues)
{
_parameterValues = new Queue<InjectionParameterValue>();
foreach (var parameterValue in parameterValues)
{
_parameterValues.Enqueue(InjectionParameterValue.ToParameter(parameterValue));
}
}
public override IDependencyResolverPolicy GetResolver(IBuilderContext context, Type dependencyType)
{
if (_parameterValues.Count < 1)
return null;
var value = _parameterValues.Dequeue();
return value.GetResolverPolicy(dependencyType);
}
}
Those two classes deal with Func creation. The next step is to add that builder to Unity's pipeline. We'll need to create a UnityContainerExtension:
public class AutomaticFactoryExtension: UnityContainerExtension
{
protected override void Initialize()
{
var automaticFactoryBuilderPolicy = new AutomaticFactoryBuilderPolicy();
Context.Policies.Set(typeof(Microsoft.Practices.ObjectBuilder2.IBuildPlanPolicy),
automaticFactoryBuilderPolicy,
new Microsoft.Practices.ObjectBuilder2.NamedTypeBuildKey(typeof(Func<,>)));
Context.Policies.Set(typeof(Microsoft.Practices.ObjectBuilder2.IBuildPlanPolicy),
automaticFactoryBuilderPolicy,
new Microsoft.Practices.ObjectBuilder2.NamedTypeBuildKey(typeof(Func<,,>)));
Context.Policies.Set(typeof(Microsoft.Practices.ObjectBuilder2.IBuildPlanPolicy),
automaticFactoryBuilderPolicy,
new Microsoft.Practices.ObjectBuilder2.NamedTypeBuildKey(typeof(Func<,,,>)));
Context.Policies.Set(typeof(Microsoft.Practices.ObjectBuilder2.IBuildPlanPolicy),
automaticFactoryBuilderPolicy,
new Microsoft.Practices.ObjectBuilder2.NamedTypeBuildKey(typeof(Func<,,,,>)));
}
}
The last piece is to actually add that class to Unity's pipeline:
IUnityContainer container = new UnityContainer();
container.AddExtension(new AutomaticFactoryExtension());
The rest of the registration is standard.
Now it is possible to have constructors from Func<> to Fun<,,,,>. The following constructor, for instance, is now handled (assuming it is possible to resolve IFoo):
public class Bar
{
private readonly Func<int, string, IFoo> _fooFactory;
public Bar(Func<int, string, IFoo> fooFactory)
{
_fooFactory = fooFactory;
}
}
Let me know if there are any question.
Hope this helps.
Have you thought about creating a delegate and registering and instance of that with Unity? That way you'd have named parameters and comments on those parameters, as well as the delegate itself. Then you wouldn't need to create build policies, and your code would be more readable.
My Grails application has a large number of enums that look like this:
public enum Rating {
BEST("be"), GOOD("go"), AVERAGE("av"), BAD("ba"), WORST("wo")
final String id
private RateType(String id) {
this.id = id
}
static public RateType getEnumFromId(String value) {
values().find {it.id == value }
}
}
If I have a command object such as this:
class MyCommand {
Rating rating
}
I would like to (for example) automatically convert a request parameter with value "wo" to Rating.WORST.
The procedure for defining custom converters is described here (in the context of converting Strings to Dates). Although this procedure works fine, I don't want to have to create a class implementing PropertyEditorSupport for each of my enums. Is there a better alternative?
I found a solution I'm pretty happy with.
Step 1: Create an implementation of PropertyEditorSupport to convert text to/from the relevant Enum
public class EnumEditor extends PropertyEditorSupport {
private Class<? extends Enum<?>> clazz
public EnumEditor(Class<? extends Enum<?>> clazz) {
this.clazz = clazz
}
public String getAsText() {
return value?.id
}
public void setAsText(String text) {
value = clazz.getEnumFromId(text)
}
}
Step 2: Define a class that registers EnumEditor as a converter for the various enum classes. To change the list of enum classes that are bindable by id, just modify BINDABLE_ENUMS
public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {
private static final String REQUIRED_METHOD_NAME = 'getEnumFromId'
// Add any enums that you want to bind to by ID into this list
private static final BINDABLE_ENUMS = [Rating, SomeOtherEnum, SomeOtherEnum2]
public void registerCustomEditors(PropertyEditorRegistry registry) {
BINDABLE_ENUMS.each {enumClass ->
registerEnum(registry, enumClass)
}
}
/**
* Register an enum to be bound by ID from a request parameter
* #param registry Registry of types eligible for data binding
* #param enumClass Class of the enum
*/
private registerEnum(PropertyEditorRegistry registry, Class<? extends Enum<?>> enumClass) {
boolean hasRequiredMethod = enumClass.metaClass.methods.any {MetaMethod method ->
method.isStatic() && method.name == REQUIRED_METHOD_NAME && method.parameterTypes.size() == 1
}
if (!hasRequiredMethod) {
throw new MissingMethodException(REQUIRED_METHOD_NAME, enumClass, [String].toArray())
}
registry.registerCustomEditor(enumClass, new EnumEditor(enumClass))
}
}
Step 3: Make Spring aware of the registry above by defining the following Spring bean in grails-app/conf/spring/resources.grooovy
customPropertyEditorRegistrar(CustomPropertyEditorRegistrar)
So the default Databinding binds on the Enum name and not a separately defined property of the Enum. You can either create your own PropertyEditor as you have mentioned or do a work-around similar to this:
class MyCommand {
String ratingId
Rating getRating() {
return Rating.getEnumFromId(this.ratingId)
}
static constraints = {
ratingId(validator:{val, obj -> Rating.getEnumFromId(val) != null })
}
}