Convert to class field from a string in Play template - scala

I have a model in play framework
public class XYZ extends Model
{
#Id
public int a;
public String field1;
public String field2;
}
In my index.scala.html I need to generate field1 and field2 dynamically.
I have an object xyz of XYZ class.
I need to get the value of xyz.field1.
I generate the string field1 dynamically in my code using "field".concat("1") and now I need to convert this string to a field so as to call xyz.field1.
I am not able to figure out how to do this conversion in my scala.html file.

You can use reflections to get a field by its name, even in a template.
#classof[XYZ].getField("field" + fieldNum).get(xyz)
If you have only a two fields, a simple if/else would probably a better way to get the fields values. If it's more complex create a method in your model and use some switch statement or a map, like Mikesname suggested.

Related

Is there a JPA annotation equivalent of jackson's #JsonAnyGetter/#JsonAnySetter?

With jackson, I can use #JsonAnyGetter and #JsonAnySetter to serialize/deserialize a Map<String, Object> into extra fields of a json object. Is there a JPA annotation that will do similar things with extra db column values being get/set from/into a member Map?
Specifically, I'd like to use jooq's .fetchInto(Pojo.class) to hydrate a java object. I can manually use .fetch(RecordMapper<Record, Pojo>) to get the results I want by hydrating the Map member from the Record fields manually, but wondering if there's a more automatic way of doing this. Pojo code could look something like the following (use lombok's #Data to make it concise):
#Data
public class Pojo {
#Column("field1")
private int field1;
#Column("field2")
private String field2;
#JsonAnyGetter // works for json serialization,
#JsonAnySetter // is there an equivalent for JPA?
private Map<String, Object> extraFields;
}
You can register a RecordMapperProvider with your jOOQ configuration in order to override how various methods, including fetchInto(Class) apply mapping:
https://www.jooq.org/doc/3.11/manual/sql-execution/fetching/pojos-with-recordmapper-provider/

how to use array of string as condition in Drools decision table?

I am new to drools decision table, so my question may be invalid.
In my decision table i am using "in" in condition column.
Exampe : i have class Student and there is another class UniversityConstant.
In UniversityConstant class there is array of string subject code : public static final String[] subjectCode ={"150","920","930","940","154"};
In this case my condition not working properly(Above picture: Not working). Instead of using string array constant of java class if i use direct subject code string than it is working(Below picture:working).
In my project there are lots of string array ,so it is not possible to copy paste them in decision table excel. Even in case i use string constant in UniversityConstant class which represent all subject code like public static final String subjectCodeStr1 ="\"155\",\"920\",\"930\",\"940\",\"154\"" OR
public static final String subjectCodeStr2 ="155,920,930,940,154"; than also it is not working. My question is there any way to use string array constant or simple string which represents array of string of java
in decision table .
You can declare the constant sets as
public static final List<String> subjectCodes =
Arrays.asList( "155","920","930","940","154" );
and use
...getPrimarySub() memberOf $param
...
UniversityConstamt.subjectCodes

Entity framework code first and data annotaions

I use code first approach in my project. In the prject I have classes with MetadataType attribute, which I don't use in my EF model. Class with metadata has some constant public fields (in addition to fields from main type). Now when I tried to query EF it threw exception that in metadata class there fields not mapped... se below in details
class M1
{
int Id;
string Name
}
class M2
{
int Id;
DateTime Date
}
[MetadataType(typeof(PageOFSRevenueMetadata))]
class NotRelatedToModel
{
int Prop1;
int Prop2;
}
class PageOFSRevenueMetadata
{
public const string RuleSet1 = "r1";
public const string RuleSet2 = "r2";
// Data Vaidation Attrs...
int Prop1;
int Prop2;
}
In my context I have mapping only for M1 and M2. In the DB exists table with name 'NotRelatedToModel', but I don't want to use it in my model. I use EF 6
Now when I try to make join query on M1 and M2 it threw below exception
'NotRelatedToModel' contains the following unknown properties or fields: RuleSet1, RuleSet2. Please make sure that the names of these members match the names of the properties on the main type
I can move this static fields to another place and it seems to work, but I would like to know why it is happend ? How the EF code first mapping works ?
Thanks in advance

Instruct XmlSerializer to process serialized/deserialized data?

I have an enum property. I want the serialized XML for this property to be the splitted camel-case string of the enum and vice versa.
I have two functions, one is ConcatCamelCase and the other is SplitCamelCase, I want the serializer to use them accordingly, is this possible by just decorating the field with an attribute?
If no, what are the other option without having to mess with all the other fields?
You'll have to do something like this:
public class SomeClass {
[XmlIgnore]
public MyEnum MyRealProperty {get;set;}
[XmlElement("MyRealProperty")]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string MyProxyProperty
{
get {return SplitCamelCase(MyRealProperty);}
set {MyRealProperty = ConcatCamelCase(value);}
}
}
You can explicitly set the name of everything that is serialized using the XMlSerialization attributes.
[XmlRoot("theNameYouWant")]
[XmlElement("theNameYouWant")]

NUnit TestCaseSource pass value to factory

I'm using the NUnit 2.5.3 TestCaseSource attribute and creating a factory to generate my tests. Something like this:
[Test, TestCaseSource(typeof(TestCaseFactories), "VariableString")]
public void Does_Pass_Standard_Description_Tests(string text)
{
Item obj = new Item();
obj.Description = text;
}
My source is this:
public static IEnumerable<TestCaseData> VariableString
{
get
{
yield return new TestCaseData(string.Empty).Throws(typeof(PreconditionException))
.SetName("Does_Reject_Empty_Text");
yield return new TestCaseData(null).Throws(typeof(PreconditionException))
.SetName("Does_Reject_Null_Text");
yield return new TestCaseData(" ").Throws(typeof(PreconditionException))
.SetName("Does_Reject_Whitespace_Text");
}
}
What I need to be able to do is to add a maximum length check to the Variable String, but this maximum length is defined in the contracts in the class under test. In our case its a simple public struct:
public struct ItemLengths
{
public const int Description = 255;
}
I can't find any way of passing a value to the test case generator. I've tried static shared values and these are not picked up. I don't want to save stuff to a file, as then I'd need to regenerate this file every time the code changed.
I want to add the following line to my testcase:
yield return new TestCaseData(new string('A', MAX_LENGTH_HERE + 1))
.Throws(typeof(PreconditionException));
Something fairly simple in concept, but something I'm finding impossible to do. Any suggestions?
Change the parameter of your test as class instead of a string. Like so:
public class StringTest {
public string testString;
public int maxLength;
}
Then construct this class to pass as an argument to TestCaseData constructor. That way you can pass the string and any other arguments you like.
Another option is to make the test have 2 arguments of string and int.
Then for the TestCaseData( "mystring", 255). Did you realize they can have multiple arguments?
Wayne
I faced a similar problem like yours and ended up writing a small NUnit addin and a custom attribute that extends the NUnit TestCaseSourceAttribute. In my particular case I wasn't interested in passing parameters to the factory method but you could easily use the same technique to achieve what you want.
It wasn't all that hard and only required me to write something like three small classes. You can read more about my solution at: blackbox testing with nunit using a custom testcasesource.
PS. In order to use this technique you have to use NUnit 2.5 (at least) Good luck.