Using is method instead of a getter method - supercsv

can I tell supercsv that the class has an is method instead of a getter?
public class Decision {
private boolean isAccepcted;
public boolean isAccepcted() {
return isAccepcted;
}
public boolean getIsAccepted() {
return isAccepcted;
}
}
Here a part as the class tried to read the values.
private static final String[] NAME_MAPPING = new String[]{
"isAccepcted"
};
private static final CellProcessor[] PROCESSORS = new CellProcessor[] {
new org.supercsv.cellprocessor.ConvertNullTo(DEFAULT_NULL_VALUE)
};
private final CsvBeanWriter csvWriter;
csvWriter.write(consent, NAME_MAPPING, PROCESSORS);
With out the method getIsAccepted the lib won't find the method.
Any idea how I can call only isAccepted?
Thanks a lot,
Markus

Related

Get properties from subclass object using BeanWrapperFieldExtractor

In my Spring batch application I have the following POJO classes:
public class School {
private String schoolName;
private String schoolAddress;
private ClassDetails classDetails;
}
public class ClassDetails {
private String className;
private String totalCountStudents;
private SectionDetails sectionDetails;
}
public class SectionDetails {
private String sectionName;
private String totalSubjects;
}
I have written the following FlatFileItemWriter to get the properties from School object.
public FlatFileItemWriter<School> write() throws Exception {
FlatFileItemWriter<School> flatFileWriter = new FlatFileItemWriter<School>();
flatFileWriter.setResource(new FileSystemResource("C:\\u01\\SchoolDetails.txt"));
flatFileWriter.setName("School-File-Writer");
flatFileWriter.setAppendAllowed(true);
flatFileWriter.setLineSeparator("\n");
flatFileWriter.setHeaderCallback(writer -> writer.write(columnHeaders()));
flatFileWriter.setLineAggregator(new DelimitedLineAggregator<School>() {
{
setDelimiter("^");
setFieldExtractor((FieldExtractor<School>) schoolFieldExtractor());
}
});
return flatFileWriter;
}
private BeanWrapperFieldExtractor<School> schoolFieldExtractor() {
return new BeanWrapperFieldExtractor<School>() {
{
String[] columnValuesMapper = new String[] {
"schoolName", "schoolAddress"
};
setNames(columnValuesMapper);
}
};
}
Currently the file I am sending out has schoolName, schoolAddress. But I want to get all the properties from subclasses along wth school object in BeanWrapperFieldExtractor. The final output file that I will be sending out should have schoolName, schoolAddress, className, totalCountStudents, sectionName, totalSubjects.
I am not sure on how to do that. Any help would be appreciated. Thanks in advance!
The BeanWrapperFieldExtractor supports the dotted notation for nested properties, so you can define your schoolFieldExtractor as follow:
private BeanWrapperFieldExtractor<School> schoolFieldExtractor() {
return new BeanWrapperFieldExtractor<School>() {
{
String[] columnValuesMapper = new String[] {
"schoolName", "schoolAddress",
"classDetails.className", "classDetails.totalCountStudents",
"classDetails.sectionDetails.sectionName", "classDetails.sectionDetails.totalSubjects",
};
setNames(columnValuesMapper);
}
};
}

Sonarqube not finding possible null pointer exception

In the below code, Why sonarqube is not finding possible null pointer exception in "updateData" method?
public class PropertyObject extends LinkedHashMap<String, Object> {
/**
* Unique serialization id.
*/
private static final long serialVersionUID = 4789053897514939L;
}
public class BaseObject extends PropertyObject {
#JsonProperty("_id")
public String getId() {
return String.valueOf(this.get("_id"));
}
#JsonProperty("_id")
public void setId(Object id) {
this.put("_id", String.valueOf(id));
}
public String getName() {
return (String) this.get("name");
}
public void setName(String name) {
this.put("name", name);
}
}
private void updateData(BaseObject baseObject) {
List<Map<String, String>> link = (List<Map<String, String>>) baseObject.get("ratioMap");
for (Map<String, String> linkmap : link) {
}
}
}
I can see potential null pointer exception in updateData method in line number 2.
Is there any way by which I can make sonarqube to find these issues by itself?
First of all Sonar is a static code analysis tool. It depends on simple declarations to look for possible NPEs. Second I assume that you have an active rule for detecting possible NullPointer dereferences.
Last but not least I think that it would not detect NPEs in private methods which is not called...

How to properly implement a Spring Converter?

I have a Money class with factory methods for numeric and String values. I would like to use it as a property of my input Pojos.
I created some Converters for it, this is the String one:
#Component
public class StringMoneyConverter implements Converter<String, Money> {
#Override
public Money convert(String source) {
return Money.from(source);
}
}
My testing Pojo is very simple:
public class MoneyTestPojo {
private Money value;
//getter and setter ommited
}
I have an endpoint which expects a Pojo:
#PostMapping("/pojo")
public String savePojo(#RequestBody MoneyTestPojo pojo) {
//...
}
Finally, this is the request body:
{
value: "100"
}
I have the following error when I try this request:
JSON parse error: Cannot construct instance of
br.marcellorvalle.Money (although at least one Creator
exists): no String-argument constructor/factory method to deserialize
from String value ('100'); nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
construct instance of br.marcellorvalle.Money (although at
least one Creator exists): no String-argument constructor/factory
method to deserialize from String value ('100')\n at [Source:
(PushbackInputStream); line: 8, column: 19] (through reference chain:
br.marcellorvalle.MoneytestPojo[\"value\"])",
If I change Money and add a constructor which receives a String this request works but I really need a factory method as I have to deliver special instances of Money on specific cases (zeros, nulls and empty strings).
Am I missing something?
Edit: As asked, here goes the Money class:
public class Money {
public static final Money ZERO = new Money(BigDecimal.ZERO);
private static final int PRECISION = 2;
private static final int EXTENDED_PRECISION = 16;
private static final RoundingMode ROUNDING = RoundingMode.HALF_EVEN;
private final BigDecimal amount;
private Money(BigDecimal amount) {
this.amount = amount;
}
public static Money from(float value) {
return Money.from(BigDecimal.valueOf(value));
}
public static Money from(double value) {
return Money.from(BigDecimal.valueOf(value));
}
public static Money from(String value) {
if (Objects.isNull(value) || "".equals(value)) {
return null;
}
return Money.from(new BigDecimal(value));
}
public static Money from(BigDecimal value) {
if (Objects.requireNonNull(value).equals(BigDecimal.ZERO)) {
return Money.ZERO;
}
return new Money(value);
}
//(...)
}
Annotating your factory method with #JsonCreator (from the com.fasterxml.jackson.annotation package) will resolve the issue:
#JsonCreator
public static Money from(String value) {
if (Objects.isNull(value) || "".equals(value)) {
return null;
}
return Money.from(new BigDecimal(value));
}
I just tested it, and it worked for me. Rest of your code looks fine except for the sample request (value should be in quotes), but I guess that's just a typo.
Update 1:
If you're unable to make changes to the Money class, I can think of another option - a custom Jackson deserializer:
public class MoneyDeserializer extends StdDeserializer<Money> {
private static final long serialVersionUID = 0L;
public MoneyDeserializer() {
this(null);
}
public MoneyDeserializer(Class<?> vc) {
super(vc);
}
#Override
public Money deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
String value = node.textValue();
return Money.from(value);
}
}
Just register it with your ObjectMapper.
It seems that using the org.springframework.core.convert.converter.Converter only works if the Money class is a "#PathVariable" in the controller.
I finally solved it using the com.fasterxml.jackson.databind.util.StdConverter class:
I created the following Converter classes:
public class MoneyJsonConverters {
public static class FromString extends StdConverter<String, Money> {
#Override
public Money convert(String value) {
return Money.from(value);
}
}
public static class ToString extends StdConverter<Money, String> {
#Override
public String convert(Money value) {
return value.toString();
}
}
}
Then I annotated the Pojo with #JsonDeserialize #JsonSerialize accordingly:
public class MoneyTestPojo {
#JsonSerialize(converter = MoneyJsonConverters.ToString.class)
#JsonDeserialize(converter = MoneyJsonConverters.FromString.class)
private Money value;
//getter and setter ommited
}

Spring MVC Generics Object Binding/Type Conversion

I'm looking for a way to wrap my models or DTOs with a generic class to add a 'selected' Boolean property and be able to bind the object in my POST method controller.
Like this:
public class RowForm<T> implements Serializable {
private static final long serialVersionUID = 1L;
private T model;
private Boolean selected=false;
public RowForm() {
super();
}
public RowForm(T model) {
super();
this.model = model;
}
public T getModel() {
return model;
}
public void setModel(T model) {
this.model = model;
}
public Boolean getSelected() {
return selected;
}
public void setSelected(Boolean selected) {
this.selected = selected;
}
}
public class ProductsForm implements Serializable{
private static final long serialVersionUID = 1L;
private RowForm<Product> row;
//...other stuff and getters/setters
}
and use it like this:
#PostMapping ("/postProduct")
public String POSTproduct(Model model, #ModelAttribute ProductsForm pf)
{
....
}
But I'm stuck with the conversion...
When I call pf.getRow() it returns a plain Object, not a RowForm<Product>.
How can I implement a ConversionService/PropertyEditor to bind my posted data to my extended generic object?
Why not use a abstract base class with the selected property, and extend it for your DTOs?

Generate static map from database using a singleton class also using spring configuration #Autowired

I need to create an unmodifiable map generated from data obtained by querying a database. How, or can I, or is there a better way to do this using spring annotations?
I ran into a problem when creating a singleton for my Regions class and then trying to #Autowire in a RegionService to grab the object from the DAO. The problem is that spring can't instantiate the RegionService because it needs to instantiate the static singleton class Regions which needs to get data from the database as shown below in the constructor.
Please see me classes below (I've removed multiple unneeded methods that don't pertain to this question):
public final class Region {
private static final String DEFAULT_SEPERATOR = "-";
private final Integer key;
private final String description;
public Region(Integer pKey, String pDescription) {
this.key = pKey;
this.description = pDescription;
}
public Integer getKey() {
return this.key;
}
public String getValue() {
return this.description;
}
}
Here is my singleton:
public final class Regions {
private static Regions regionsInstance = null;
#Autowired
private RegionService regionService;
static Map<Integer, Region> regions;
private Regions() {
final Map<Integer, Region> tempRegions = new HashMap<Integer, Region>();
for (final Region region : this.regionService.retrieveAll()) {
tempRegions.put(region.getKey(), region);
}
regions = Collections.unmodifiableMap(tempRegions);
}
public static synchronized Regions getRegionsInstance() {
if (regionsInstance == null) {
regionsInstance = new Regions();
}
return regionsInstance;
}
public Region getRegion(final Integer pKey) {
return regions.get(pKey);
}
public List<Region> getRegions() {
return (List<Region>) regions.values();
}
}
My DAO and Service are just interfaces, no need to post those, here are my Impls:
#Service
public class RegionServiceImpl implements RegionService {
#Autowired
private RegionDAO regionDao;
#Override
public List<Region> retrieveAll() {
return this.regionDao.retrieveAll();
}
}
My DAOImpl (tested and works, just posting to give you the full picture):
#Repository
public class RegionDAOImpl implements RegionDAO {
private static final String SQL_RETRIEVE_REGIONS = "some random SQL";
#Autowired
private JdbcTemplate jdbcTemplate;
#Override
public List<Region> retrieveAll() {
try {
return this.jdbcTemplate.query(SQL_RETRIEVE_REGIONS, new ResultSetExtractor<List<Region>>() {
#Override
public List<Region> extractData(ResultSet rs) throws SQLException, DataAccessException {
return RegionDAOImpl.this.mapRegionData(rs);
}
});
} catch (final DataAccessException dae) {
throw new DaoException("Could not retrieve regionList from database. " + dae);
}
}
protected final List<Region> mapRegionData(ResultSet rs) throws SQLException {
final List<Region> regionList = new ArrayList<Region>();
while (rs.next()) {
regionList.add(new Region(rs.getInt("REGION_CD"), rs.getString("REGION_TXT")));
}
return Collections.unmodifiableList(regionList);
}
}
Then I run my test(I took out unneeded crap):
#..annotated with things you don't need to know
public class RetrieveRegionsTest {
#Autowired
private Regions r;
#Test
public void getAndLogRegion() {
final List<Region> regionDescriptions = new ArrayList<Region>(this.r.getRegions());
for (final Region region : regionDescriptions) {
LOGGER.info(region.getValue());
}
}
Yes my configuration and classpaths are set up properly. I can get this to work other ways, just not by accessing the Regions singleton which is what I want. Now I know I could take off the #Autowired on the RegionService in my Regions singleton and just create a new instance of RegionService, but that would defeat the purpose of springs #Autowired feature.
Any thoughts, ideas, comments?

Resources