Struts2 get object attribute from select tag - list

My problem is that I don't succeed in getting the attribute of the object of the list of my select tag.
I have a select tag in my .jsp like this :
<s:select list="listFonction" listKey="code" listValue="Libelle"
name="fonctionSelectionne" value="defaultFonction" />
and in my action, i declared an arraylist (with getter and setter) :
private ArrayList<Fonction> listFonction = new ArrayList<Fonction>();
I also have another class Fonction :
public class Fonction {
private int code;
private String libelle;
public Fonction(int code, String libelle)
{
this.code = code;
this.libelle =libelle;
}
public Fonction()
{
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
}
To get the selected value in my action i declared (whith getter and setter):
Private String fonctionSelectionne;
but i am just abbled to get the code (listkey) of my object with getFonctionSelectionne.
I want to get the code attribute (listkey) and the libelle attribute (listvalue).
Does anyone know how help me ?
thanks

2 points:
it should be libelle, not Libelle
<s:select list="listFonction" listKey="code" listValue="libelle"
name="fonctionSelectionne" value="defaultFonction" />
for list="listFunction", you need getter Collection getListFunction(){} in your action class
UPDATE
i'am not sure to this. but you can give a try.
here is the idea, don't deliver a list, but a map to select tag
Map getListFunction(){
Map<Object, String> map;
Function f = new Function(1, "test");
map.put(f, f.libelle);
return map;
}
then in the jsp:
<s:select list="listFonction" listKey="key" listValue="value"
name="fonctionSelectionne"/>

You should make the setter of the attribute listFonction on the ClassAction

Related

Mockito test when(repository.findById()).thenReturn(object with custom attributes)

So I was writing a couple of unit tests, some of them were made for testing missing attributes of Document. When using of when(repository.findOne(id)).thenReturn(DOCUMENT_WITHOUT_SOMETHING), those DOCUMENT_WITHOUT_SOMETHING were final objects with predefined attributes, depending on test cases.
Let's say, there could be a document without name, so when loading document by id the method was returning null with some log message. So I created a class of test data DocumentServiceTestData, where those necessary objects and attributes were declared. Is it a good approach or you suggest something more clear, without need of making new class?
I will try to write a simplified code of what I did.
Document
public class Document {
private String name;
private String applicant;
private String sign;
private boolean signed;
public boolean isSigned() {return signed;}
public String getApplicant() {return applicant;}
public String getName() {return name;}
public String getSign() {return sign;}
public void setSigned(boolean signed) {this.signed = signed;}
public void setApplicant(String applicant) {this.applicant = applicant;}
public void setName(String name) {this.name = name;}
public void setSign(String sign) {this.sign = sign;}
}
DocumentService
#Service
public class DocumentService {
private static final Logger LOG = LoggerFactory.getLogger(DocumentService.class);
private DocumentRepository documentRepository;
public Document loadDocument(Long docId) {
Document document = documentRepository.findByIdOrFail(docId);
if(document.getName() == null) {
LOG.info("There is no name for document, returning null");
return null;
}
if(document.getSign() == null) {
LOG.info("The document is not signed, returning null");
return null;
}
return document;
}
}
DocumentServiceTestData
public class DocumentServiceTestData {
public static final Long DOC_ID = 1L;
public static final String APPLICANT = "Applicant";
public static final String DOC_NAME = "Document";
public static final String SIGN = "Sign";
public static final Document DOCUMENT_WITHOUT_NAME;
public static final Document DOCUMENT_WITHOUT_SIGN;
static {
DOCUMENT_WITHOUT_NAME = makeDocument(null, APPLICANT, SIGN, true);
DOCUMENT_WITHOUT_SIGN = makeDocument(DOC_NAME, APPLICANT, null, false);
}
private static Document makeDocument(String name, String applicant, String sign, boolean signed) {
Document document = new Document();
document.setName(name);
document.setApplicant(applicant);
document.setSign(sign);
document.setSigned(signed);
return document;
}
}
DocumentServiceTest
#RunWith(MockitoJUnitRunner.class)
#Category(MockTest.class)
public class DocumentServiceUnitTest {
#InjectMocks
private DocumentService service;
#Mock
private DocumentRepository documentRepository;
#Test
public void testLoadDocument_notSigned(){
when(documentRepository.findByIdOrFail(DOC_ID)).thenReturn(DOCUMENT_WITHOUT_SIGN);
Document document = service.loadDocument(DOC_ID);
Assert.assertNull(document);
}
#Test
public void testLoadDocument_notNamed(){
when(documentRepository.findByIdOrFail(DOC_ID)).thenReturn(DOCUMENT_WITHOUT_NAME);
Document document = service.loadDocument(DOC_ID);
Assert.assertNull(document);
}
}
To sum up, I would like to know - if there is another way to test those cases, when I need to return specified objects while calling repository.findById(id).
PS: keep in mind that this is very simplified, those tests I've made were much more complex. If there is any information missing please let me know, I will try to clarify things. Thanks

How to parcel cascading classes with Parceler?

I can parcel some models using Parceler like this:
#Parcel(Serialization.BEAN)
public class PasswordSetModel {
private String mPassword;
private String mRepetition;
/* Getter & Setter */
...
But if this class is part of another class, the mechanism does not work. I am getting an NPE for mPasswordSetModel. Creating an instance in an constructor did not work, because the members mPassword and mRepetition were null after unparcelling.
#Parcel
public class RegistrationModel {
private PasswordSetModel mPasswordSetModel;
/* Getter & Setter */
...
So how can I parcel this using Parceler?
okay, the problem was that I uses "wrong" setter methods. In order to use fluent interface style I made it this way:
public String getPassword() {
return mPassword;
}
public PasswordSetModel setPassword(String password) {
mPassword = password;
return this;
}
public String getRepetition() {
return mRepetition;
}
public PasswordSetModel setRepetition(String repetition) {
mRepetition = repetition;
return this;
}
It seems that the setters were now found and therefor the model was NULL

How to combine PropertyData and AutoNSubstituteData attributes in xunit/autofixture?

I am using the [AutoNSubstituteData] attribute, which was posted here:
AutoFixture, xUnit.net, and Auto Mocking
I would like to combine this with the [PropertyData("")] attribute from xunit extensions.
This is my test:
public static IEnumerable<string[]> InvalidInvariant
{
get
{
yield return new string[] { null };
yield return new [] { string.Empty };
yield return new [] { " " };
}
}
[Theory, AutoNSubstituteData, PropertyData("InvalidInvariant")]
public void TestThatGuardsAreTriggeredWhenConnectionStringArgumentIsInvalid(
IDeal deal,
IDbConnection conn,
IDb db,
ISender sender,
string invalidConnString,
string query)
{
deal.Init.Group.Returns(Group.A);
deal.Aggr.Group.Returns(Group.A);
deal.Product.Commodity.Returns(Product.Commodity.E);
var sut = new Handler(db, sender);
Assert.Throws<ArgumentException>(() =>
sut.HandleDeal(deal, conn, invalidConnString, query));
}
Is there a way to combine these attributes or to get the desired functionality (mock everything, except for invalidConnstring, which should be filled with the property-data)?
There are two ways to do this:
Option 1 - Using AutoFixture.Xunit and the CompositeDataAttribute class:
internal class AutoNSubstituteDataAttribute : AutoDataAttribute
{
internal AutoNSubstituteDataAttribute()
: base(new Fixture().Customize(new AutoNSubstituteCustomization()))
{
}
}
internal class AutoNSubstitutePropertyDataAttribute : CompositeDataAttribute
{
internal AutoNSubstitutePropertyDataAttribute(string propertyName)
: base(
new DataAttribute[] {
new PropertyDataAttribute(propertyName),
new AutoNSubstituteDataAttribute() })
{
}
}
Define the test cases as below:
public class Scenario
{
public static IEnumerable<object[]> InvalidInvariantCase1
{
get
{
yield return new string[] { null };
}
}
public static IEnumerable<object[]> InvalidInvariantCase2
{
get
{
yield return new string[] { string.Empty };
}
}
public static IEnumerable<object[]> InvalidInvariantCase3
{
get
{
yield return new string[] { " " };
}
}
}
Then declare the parameterized test as:
public class Scenarios
{
[Theory]
[AutoNSubstitutePropertyData("InvalidInvariantCase1")]
[AutoNSubstitutePropertyData("InvalidInvariantCase2")]
[AutoNSubstitutePropertyData("InvalidInvariantCase3")]
public void AParameterizedTest(
string invalidConnString,
IDeal deal,
IDbConnection conn,
IDb db,
ISender sender,
string query)
{
}
}
Please note that the parameterized parameter invalidConnString have to be declared before the other parameters.
Option 2 - Using Exude:
public class Scenario
{
public void AParameterizedTest(
IDeal deal,
IDbConnection conn,
IDb db,
ISender sender,
string invalidConnString,
string query)
{
}
[FirstClassTests]
public static TestCase<Scenario>[] RunAParameterizedTest()
{
var testCases = new []
{
new
{
invalidConnString = (string)null
},
new
{
invalidConnString = string.Empty
},
new
{
invalidConnString = " "
}
};
var fixture = new Fixture()
.Customize(new AutoNSubstituteCustomization());
return testCases
.Select(tc =>
new TestCase<Scenario>(
s => s.AParameterizedTest(
fixture.Create<IDeal>(),
fixture.Create<IDbConnection>(),
fixture.Create<IDb>(),
fixture.Create<ISender>(),
tc.invalidConnString,
fixture.Create<string>())))
.ToArray();
}
}
The [Theory] attribute works by looking for one or more 'data source attributes'; for example
[InlineData]
[PropertyData]
[ClassData]
etc.
The [AutoData] attribute is just another such attribute, as is your derived [AutoNSubstituteData] attribute.
It's possible to add more than one 'data source attribute' to the same [Theory], as witnessed by the idiomatic use of the [InlineData] attribute:
[Theory]
[InlineData("foo")]
[InlineData("bar")]
[InlineData("baz")]
public void MyTest(string text)
This produces three test cases.
It's also possible to combine [PropertyData] and [AutoData], but it probably doesn't do what you want it to do. This:
[Theory]
[AutoNSubstituteData]
[PropertyData("InvalidInvariant")]
public void MyTest(/* parameters go here */)
will result in 1 + n test cases:
1 test case from [AutoNSubstituteData]
n test cases from the InvalidInvariant property
These two attributes know nothing about each other, so you can't combine them in the sense that they're aware of each other.
However, when you're implementing a property, you can write whatever code you'd like, including using a Fixture instance, so why not just do this?
public static IEnumerable<string[]> InvalidInvariant
{
get
{
var fixture = new Fixture().Customize(new MyConventions());
// use fixture to yield values...,
// using the occasional hard-coded test value
}
}
Another option is to use derive from the InlineAutoDataAttribute, which would enable you to write your test cases like this:
[Theory]
[MyInlineAutoData("foo")]
[MyInlineAutoData("bar")]
[MyInlineAutoData("baz")]
public void MyTest(string text, string someOtherText, int number, Guid id)
This would cause the first argument (text) to be populated with the constants from the attributes, while the remaining parameters are populated by AutoFixture.
Theoretically, you may also be able to combine the [AutoData] and [PropertyData] attributes using the CompositeDataAttribute, but it may not work the way you'd like.
Finally, you could consider using Exude for true first-class parameterized tests.
I have implemented an AutoPropertyDataAttribute that combines xUnit's PropertyDataAttribute with AutoFixture's AutoDataAttribute. I posted it as an answer here.
In your case you will need to inherit from the attribute in the same way as you would from an AutoDataAttribute, with the exception that you pass a fixture creation function instead of an instance:
public class AutoNSubPropertyDataAttribute : AutoPropertyDataAttribute
{
public AutoNSubPropertyDataAttribute(string propertyName)
: base(propertyName, () => new Fixture().Customize(new AutoNSubstituteCustomization()))
{
}
}

bada Programming - Call listview within a listview

I currently have a listview containing 4 items, in one of the listview item, I would like to implement another listview, do I have to do another form manager? Or how do I go about doing it? Also, how do I call one class's function in another class? Or do a reference (pointer) to pass information from one class to another?
Not sure I understand the question 100%.
In short, you would need pointer from one list view to another. If you are in a form then a local pointer to the list view may suffice.
Same applies with referencing class instances:
class Apple() {
private Basket* basket;
public Apple() {
basket = null;
}
public void setBasket(Basket* basket) {
this->basket = basket;
}
public Basket* getBasket() {
return this->basket;
}
}
class Basket() {
private Apple* apple;
public Basket() {
apple = null;
}
public setApple(Apple* apple) {
this->apple = apple;
this->apple->setBasket(this);
}
}
...
Apple* apple = new Apple();
Basket* basket = new Basket()
basket->setApple(apple);
Hope it helps a little.
Okay I am adding more code here to see if it helps It is not tested, written on the fly to show the principal:
FormA.h
class FormA :
public Osp::Ui::Controls::Form,
public Osp::Ui::IItemEventListener
{
// Other stuff including list
protected:
void OnItemStateChanged (const Osp::Ui::Control &source, int index, int itemId, Osp::Ui::ItemStatus status);
}
FormA.cpp
// Other stuff including constructor and list control creation/population
void FormA::OnItemStateChanged (const Osp::Ui::Control &source, int index, int itemId, Osp::Ui::ItemStatus status) {
// Construct and show other form
FormB* b = new FormB(itemId);
// Add to frame and set formb as current
}
FormB.h
class FormA :
public Osp::Ui::Controls::Form,
public Osp::Ui::IItemEventListener
{
private int itemId;
public:
FormA(int itemId);
}
FormB.cpp
FormA::FormA(int itemId) {
this->itemId = itemId;
}
// Now somewhere in your form initialization read the itemId
// value (this->itemId) and decide what you want to show in the form's list view

Is there any way to have a static regular expression class and use with attributes?

I would like to add a regular expression to a nattribute from a static class.
[RegularExpression(MyRegex.DecimalRegEx)]
from a class:
public static class MyRegex
{
public static string Decimal_Between_1_And_100
{
get
{
return (#"^\s*\d+(\.\d{1,2})?\s*$");
}
}
}
I know the attribute needs a const val - is there no way round this?
thanks
Davy
It is not possible to add an instance of Regex to an attribute because as you said, attribute arguments must be constant values. There is no way to work around this limitation as it's a limitation of the CLR / CLI.
The best you can do is take string values which are converted to Regex's under the hood inside the attribute constructor.
public class RegularExpressionAttribute : Attribute {
public readonly string StringValue;
public readonly Regex Regex;
public RegularExpressionAttribute(string str) {
StringValue = str;
Regex = new Regex(str);
}
}
You can assign the MyRegEx class type instead of the instance of the regex, here is the idea below.
public interface IRegexProvider
{
Regex Regex { get; }
}
public class RegularExpressionAttribute : Attribute
{
public readonly Type _factory;
public RegularExpressionAttribute(Type regexFactory)
{
_factory = regexFactory;
}
public Regex Regex
{
get
{
// you can cache this
var factory = (IRegexProvider)Activator.CreateInstance(_factory);
return factory.Regex;
}
}
}
// using
public class MyRegex : IRegexProvider
{
public Regex Regex
{
get
{
return new Regex(#"^\s*\d+(\.\d{1,2})?\s*$");
}
}
}
[RegularExpression(typeof(MyRegex))]