I need to save a java object in mongodb database. This object has an other object into it. When I try to save, I receive the error message on console:
org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class Item.
The problem is that I created the codec for class Item, but, it can't work even registering it. See the classes for best understanding.
Models
public class Card(){
public Card(){
itens = new ArrayList<Item>()
}
String id;
String description;
List<Item> itens;
.
.
.
}
public class Item(){
String id;
String name;
.
.
.
}
CardCodec
public class CardCodec implements CollectibleCodec<Card>{
private final Codec<Document> documentCodec;
public CardCodec() {
this.documentCodec = new DocumentCodec();
}
#Override
public void encode(BsonWriter writer, Card card, EncoderContext encoderContext) {
Document cardDoc = new Document();
String id = card.getId();
String description = card.getDescription();
List<Item> itens = card.getItens();
if(id != null) {
cardDoc.put("_id", new ObjectId(id));
}
if(description != null){
cardDoc.put("description", card.getDescription);
}
if(Itens != null){
cardDoc.put("itens", card.getItens());
}
this.documentCodec.encode(writer, cardDoc, encoderContext);
}
#Override
public Class<Card> getEncoderClass() {
return Card.class;
}
#Override
public Card decode(BsonReader reader, DecoderContext decoderContext) {
Document cardDoc = this.documentCodec.decode(reader, decoderContext);
Card card= new Card();
card.setId(cardDoc .getObjectId("_id").toHexString());
card.setDescription(cardDoc .getString("description"));
List<Document> itensDoc = cardDoc.getList("itens", Document.class);
List<Item> itens = new ItemConverter().convertToListItem(itensDoc);
card.setItens(itens);
return card;
}
#Override
public Card generateIdIfAbsentFromDocument(Card card) {
if( !documentHasId(card) ) {
card.setId(new ObjectId().toHexString());
}
return card;
}
#Override
public boolean documentHasId(Card card) {
return null != card.getId();
}
#Override
public BsonValue getDocumentId(Card card) {
if(!documentHasId(card)) {
throw new IllegalStateException("Esse documento não tem um _id");
}
return new BsonString(card.getId());
}
}
Converter
public class ItemConverter {
public Item convert(Document doc) {
Item item = new Item();
String id = doc.getObjectId("_id").toHexString();
String description = doc.getString("description");
item.setId(id);
item.setName(description);
return item;
}
public List<Item> convertToListItem(List<Document> ItensDocs){
List<Item> itens = new ArrayList<Item>();
if(ItensDocs== null) {
return Collections.emptyList();
}
for(Document doc: ItensDocs) {
itens.add( this.convert(doc) );
}
return itens;
}
}
ItemCodec
public class ItemCodec implements CollectibleCodec<Item>{
private final Codec<Document> documentCodec;
public ItemCodec() {
this.documentCodec = new DocumentCodec();
}
#Override
public void encode(BsonWriter writer, Item value, EncoderContext encoderContext) {
Document itemDoc = new Document();
String id = value.getId();
String name = value.getName();
if(id != null) {
itemDoc.put("_id", new ObjectId(id));
}
if(name != null) {
itemDoc.put("name", value.getName());
}
documentCodec.encode(writer, itemDoc, encoderContext);
}
#Override
public Class<Item> getEncoderClass() {
return Item.class;
}
#Override
public Item decode(BsonReader reader, DecoderContext decoderContext) {
Document document = documentCodec.decode(reader, decoderContext);
return new ItemConverter().convert(document);
}
#Override
public Item generateIdIfAbsentFromDocument(Item item) {
if(!this.documentHasId(item)) {
item.setId(new ObjectId().toHexString());
}
return item;
}
#Override
public boolean documentHasId(Item item) {
return null != item.getId();
}
#Override
public BsonValue getDocumentId(Item item) {
if(!documentHasId(item)) {
throw new IllegalStateException("Esse documento não tem um _id");
}
return new BsonString(item.getId());
}
}
Now, how I registry the codecs
...
CardCodec cardCodec = new CardCodec();
ItemCodec itemCodec = new ItemCodec();
this.codecRegistry = CodecRegistries.fromRegistries(
MongoClientSettings.getDefaultCodecRegistry(),
CodecRegistries.fromCodecs(cardCodec, itemCodec)
);
this.cardCollection = this.mongoDatabase.getCollection("cards", Card.class).withCodecRegistry(this.codecRegistry);
...
When I try to execute an insert:
this.cardCollection.insertOne(card);
I receive:
org.bson.codecs.configuration.CodecConfigurationException
It's tricky to write correct and efficient POJO Codec implementations by hand. In this case the problem is that the DocumentCodec that you instantiate within the CardCodec is not configured with a CodecRegistry that contains the ItemCodec, so it is unable to find the ItemCodec.
There are ways that you can fix your Codec implementations, but I'm not clear why you want to roll your own when the driver has a general solution for this. See POJO Support for details.
Simply create your CodecRegistry like this:
CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
MongoClientSettings.getDefaultCodecRegistry(),
CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build())
);
This code:
#Override
public List<FactCodeDto> getAllFactsWithoutParentsAsFactDto() {
String completeQuery = FactCodeQueries.SELECT_DTO_FROM_FACT_WITH_NO_PARENTS;
Query query = createHibernateQueryForUnmappedTypeFactDto(completeQuery);
List<FactCodeDto> factDtoList = query.list(); //line 133
return factDtoList;
}
calling this method:
private Query createHibernateQueryForUnmappedTypeFactDto(String sqlQuery) throws HibernateException {
return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(Transformers.aliasToBean(FactCodeDto.class));
}
gives me a ClassCastException -> part of the trace:
Caused by: java.lang.ClassCastException: org.bamboomy.cjr.dto.FactCodeDto cannot be cast to java.util.Map
at org.hibernate.property.access.internal.PropertyAccessMapImpl$SetterImpl.set(PropertyAccessMapImpl.java:102)
at org.hibernate.transform.AliasToBeanResultTransformer.transformTuple(AliasToBeanResultTransformer.java:78)
at org.hibernate.hql.internal.HolderInstantiator.instantiate(HolderInstantiator.java:75)
at org.hibernate.loader.custom.CustomLoader.getResultList(CustomLoader.java:435)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2423)
at org.hibernate.loader.Loader.list(Loader.java:2418)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:336)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1898)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:318)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125)
at org.bamboomy.cjr.dao.factcode.FactCodeDAOImpl.getAllFactsWithoutParentsAsFactDto(FactCodeDAOImpl.java:133)
Which is pretty strange because, indeed, if you look up the source code of Hibernate it tries to do this:
#Override
#SuppressWarnings("unchecked")
public void set(Object target, Object value, SessionFactoryImplementor factory) {
( (Map) target ).put( propertyName, value ); //line 102
}
Which doesn't make any sense...
target is of type Class and this code tries to cast it to Map,
why does it try to do that???
any pointers are more than welcome...
I'm using Hibernate 5 (and am upgrading from 3)...
edit: I also use Spring (4.2.1.RELEASE; also upgrading) which calls these methods upon deploy, any debugging pointers are most welcome as well...
edit 2: (the whole FactCodeDto class, as requested)
package org.bamboomy.cjr.dto;
import org.bamboomy.cjr.model.FactCode;
import org.bamboomy.cjr.model.FactCodeType;
import org.bamboomy.cjr.utility.FullDateUtil;
import org.bamboomy.cjr.utility.Locales;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.util.Assert;
import java.util.*;
#Getter
#Setter
#ToString
public class FactCodeDto extends TreeNodeValue {
private String cdFact;
private String cdFactSuffix;
private Boolean isSupplementCode;
private Boolean isTitleCode;
private Boolean mustBeFollowed;
private Date activeFrom;
private Date activeTo;
private Boolean isCode;
private Long idFact;
private Long idParent;
private String type;
Map<Locale, String> description = new HashMap<Locale, String>(3);
public FactCodeDto() {
}
public FactCodeDto(String prefix, String suffix) {
super();
this.cdFact = prefix;
this.cdFactSuffix = suffix;
}
public FactCodeDto(String cdFact, String cdFactSuffix, Boolean isSupplementCode, Boolean mustBeFollowed) {
super();
this.cdFact = cdFact;
this.cdFactSuffix = cdFactSuffix;
this.isSupplementCode = isSupplementCode;
this.mustBeFollowed = mustBeFollowed;
}
public FactCodeDto(String cdFact, String cdFactSuffix, Boolean isSupplementCode, Boolean mustBeFollowed, Long idFact, Long idParent, Boolean isCode, Boolean isTitleCode, Date from, Date to, Map<Locale, String> descriptions,String type) {
super();
this.cdFact = cdFact;
this.cdFactSuffix = cdFactSuffix;
this.isSupplementCode = isSupplementCode;
this.mustBeFollowed = mustBeFollowed;
this.idFact = idFact;
this.idParent = idParent;
this.isCode = isCode;
this.isTitleCode = isTitleCode;
this.activeFrom = from;
this.activeTo = to;
if (descriptions != null) {
this.description = descriptions;
}
this.type = type;
}
public FactCodeDto(FactCode fc) {
this(fc.getPrefix(), fc.getSuffix(), fc.isSupplementCode(), fc.isHasMandatorySupplCodes(), fc.getId(), fc.getParent(), fc.isActualCode(), fc.isTitleCode(), fc.getActiveFrom(), fc.getActiveTo(), fc.getAllDesc(),fc.getType().getCode());
}
public String formatCode() {
return FactCode.formatCode(cdFact, cdFactSuffix);
}
public boolean isActive() {
Date now = new Date(System.currentTimeMillis());
return FullDateUtil.isBetweenDates(now, this.activeFrom, this.activeTo);
}
public void setDescFr(String s) {
description.put(Locales.FRENCH, s);
}
public void setDescNl(String s) {
description.put(Locales.DUTCH, s);
}
public void setDescDe(String s) {
description.put(Locales.GERMAN, s);
}
/**
* public String toString() {
* StringBuilder sb = new StringBuilder();
* sb.append(getIdFact() + ": ")
* .append(getIdParent() + ": ")
* .append(" " + cdFact + cdFactSuffix + ": " + (isSupplementCode ? "NO Principal " : " Principal "))
* .append((mustBeFollowed ? " Must Be Followed " : "NOT Must Be Followed "));
* return sb.toString();
* }
*/
public Map<Locale, String> getDescription() {
return description;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
String fullCode = formatCode();
result = prime * result + ((fullCode == null) ? 0 : fullCode.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
FactCodeDto other = (FactCodeDto) obj;
return formatCode().equals(other.formatCode());
}
#Override
public boolean isChildOf(TreeNodeValue value) {
Assert.notNull(value);
boolean isChild = false;
if (value instanceof FactCodeDto) {
if (this.getIdParent() != null) {
isChild = this.getIdParent().equals(((FactCodeDto) value).getIdFact());
}
}
return isChild;
}
#Override
public boolean isBrotherOf(TreeNodeValue value) {
Assert.notNull(value);
boolean isBrother = false;
if (value instanceof FactCodeDto) {
if (this.getIdParent() != null) {
isBrother = this.getIdParent().equals(((FactCodeDto) value).getIdParent());
}
}
return isBrother;
}
#Override
public boolean isParentOf(TreeNodeValue value) {
Assert.notNull(value);
boolean isParent = false;
if (value instanceof FactCodeDto) {
isParent = this.getIdFact().equals(((FactCodeDto) value).getIdParent());
}
return isParent;
}
#Override
public int compareTo(TreeNodeValue to) {
if (to instanceof FactCodeDto) {
return formatCode().compareTo(((FactCodeDto) to).formatCode());
} else return 1;
}
public String getCode() {
return formatCode();
}
}
I found that AliasToBean has changed in Hibernate 5. For me adding getter for my field fixed the problem.
This exception occurs when the setters and getters are not mapped correctly to the column names.
Make sure you have the correct getters and setters for the query(Correct names and correct datatypes).
Read more about it here:
http://javahonk.com/java-lang-classcastexception-com-wfs-otc-datamodels-imagineexpirymodel-cannot-cast-java-util-map/
I do some investigation on this question. The problem is that Hibernate converts aliases for column names to upper case — cdFact becomesCDFACT.
Read for a more deeply explanation and workaround here:
mapping Hibernate query results to custom class?
In the end it wasn't so hard to find a solution,
I just created my own (custom) ResultTransformer and specified that in the setResultTransformer method:
private Query createHibernateQueryForUnmappedTypeFactDto(String sqlQuery) throws HibernateException {
return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(new FactCodeDtoResultTransformer());
//return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(Transformers.aliasToBean(FactCodeDto.class));
}
the code of the custom result transformer:
package org.bamboomy.cjr.dao.factcode;
import org.bamboomy.cjr.dto.FactCodeDto;
import java.util.Date;
import java.util.List;
/**
* Created by a162299 on 3-11-2015.
*/
public class FactCodeDtoResultTransformer implements org.hibernate.transform.ResultTransformer {
#Override
public Object transformTuple(Object[] objects, String[] strings) {
FactCodeDto result = new FactCodeDto();
for (int i = 0; i < objects.length; i++) {
setField(result, strings[i], objects[i]);
}
return result;
}
private void setField(FactCodeDto result, String string, Object object) {
if (string.equalsIgnoreCase("cdFact")) {
result.setCdFact((String) object);
} else if (string.equalsIgnoreCase("cdFactSuffix")) {
result.setCdFactSuffix((String) object);
} else if (string.equalsIgnoreCase("isSupplementCode")) {
result.setIsSupplementCode((Boolean) object);
} else if (string.equalsIgnoreCase("isTitleCode")) {
result.setIsTitleCode((Boolean) object);
} else if (string.equalsIgnoreCase("mustBeFollowed")) {
result.setMustBeFollowed((Boolean) object);
} else if (string.equalsIgnoreCase("activeFrom")) {
result.setActiveFrom((Date) object);
} else if (string.equalsIgnoreCase("activeTo")) {
result.setActiveTo((Date) object);
} else if (string.equalsIgnoreCase("descFr")) {
result.setDescFr((String) object);
} else if (string.equalsIgnoreCase("descNl")) {
result.setDescNl((String) object);
} else if (string.equalsIgnoreCase("descDe")) {
result.setDescDe((String) object);
} else if (string.equalsIgnoreCase("type")) {
result.setType((String) object);
} else if (string.equalsIgnoreCase("idFact")) {
result.setIdFact((Long) object);
} else if (string.equalsIgnoreCase("idParent")) {
result.setIdParent((Long) object);
} else if (string.equalsIgnoreCase("isCode")) {
result.setIsCode((Boolean) object);
} else {
throw new RuntimeException("unknown field");
}
}
#Override
public List transformList(List list) {
return list;
}
}
in hibernate 3 you could set Aliasses to queries but you can't do that anymore in hibernate 5 (correct me if I'm wrong) hence the aliasToBean is something you only can use when actually using aliasses; which I didn't, hence the exception.
Im my case :
=> write sql query and try to map result to Class List
=> Use "Transformers.aliasToBean"
=> get Error "cannot be cast to java.util.Map"
Solution :
=> just put \" before and after query aliases
ex:
"select first_name as \"firstName\" from test"
The problem is that Hibernate converts aliases for column names to upper case or lower case
I solved it by defining my own custom transformer as given below -
import org.hibernate.transform.BasicTransformerAdapter;
public class FluentHibernateResultTransformer extends BasicTransformerAdapter {
private static final long serialVersionUID = 6825154815776629666L;
private final Class<?> resultClass;
private NestedSetter[] setters;
public FluentHibernateResultTransformer(Class<?> resultClass) {
this.resultClass = resultClass;
}
#Override
public Object transformTuple(Object[] tuple, String[] aliases) {
createCachedSetters(resultClass, aliases);
Object result = ClassUtils.newInstance(resultClass);
for (int i = 0; i < aliases.length; i++) {
setters[i].set(result, tuple[i]);
}
return result;
}
private void createCachedSetters(Class<?> resultClass, String[] aliases) {
if (setters == null) {
setters = createSetters(resultClass, aliases);
}
}
private static NestedSetter[] createSetters(Class<?> resultClass, String[] aliases) {
NestedSetter[] result = new NestedSetter[aliases.length];
for (int i = 0; i < aliases.length; i++) {
result[i] = NestedSetter.create(resultClass, aliases[i]);
}
return result;
}
}
And used this way inside the repository method -
#Override
public List<WalletVO> getWalletRelatedData(WalletRequest walletRequest,
Set<String> requiredVariablesSet) throws GenericBusinessException {
String query = getWalletQuery(requiredVariablesSet);
try {
if (query != null && !query.isEmpty()) {
SQLQuery sqlQuery = mEntityManager.unwrap(Session.class).createSQLQuery(query);
return sqlQuery.setResultTransformer(new FluentHibernateResultTransformer(WalletVO.class))
.list();
}
} catch (Exception ex) {
exceptionThrower.throwDatabaseException(null, false);
}
return Collections.emptyList();
}
It worked perfectly !!!
Try putting Column names and field names both in capital letters.
This exception occurs when the class that you specified in the AliasToBeanResultTransformer does not have getter for the corresponding columns. Although the exception details from the hibernate are misleading.
I've this kind of json response:
{
error: false
stats: {
punti: 150
punti2: 200
}-
}
I created a StatsReceiver class:
public class StatsReceiver {
Boolean error;
Stats stat;
public Boolean isError() {
if (error == null)
return true;
else
return error;
}
public int getPunti() {
if (stat == null)
return -1;
else
return stat.getPunti();
}
private class Stats {
private int punti = 0;
public int getPunti() {
return punti;
}
public void setPunti(int punti) {
this.punti = punti;
}
public int getPunti2() {
return punti2;
}
public void setPunti2(int punti2) {
this.punti2 = punti2;
}
private int punti2 = 0;
public Stats(int punti, int punti2) {
this.punti = punti;
this.punti2 = punti2;
}
}
}
Next:
#GET("/v1/stats")
void stats(#Header("Auth") String code,
Callback<StatsReceiver> object);
Now when I do:
apiServiceUsers.stats(apiKey, new Callback<StatsReceiver>() {
#Override
public void success(StatsReceiver statsReceiver, Response response) {
if (statsReceiver.isError()) {
Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, statsReceiver.getPunti(), Toast.LENGTH_LONG).show();
}
}
Error is false as expected, but getPunti() return always -1, so stat object is always null.
What's wrong?
P.S in the Log console, there is:
{"error":false,"stats":{"punti":150,"punti2":200}}
In your JSON example the key is stats; but in your Java class the member variable is called stat. For Gson to work, these must be either exactly the same, or you must use #SerializedName to tell Gson which JSON key corresponds to which variable:
#SerializedName("stats")
Stats statOrSomethingElseEntirely;
I would like to create that object same for java. Is it possible to create it?
How it works :
you can find more informaiton how I used it.
using System;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using Common.Models;
using System.Text;
namespace Common.Utilities.Helpers
{
public partial class CommareaHelper
{
public static T StringToObject<T>(string buffer)
{
IntPtr pBuf = IntPtr.Zero;
try
{
pBuf = Marshal.StringToBSTR(buffer);
return (T)Marshal.PtrToStructure(pBuf, typeof(T));
}
catch
{
throw;
}
finally
{
pBuf = IntPtr.Zero;
}
}
public static string ObjectToString(Object conversionObject)
{
int size = 0;
IntPtr pBuf = IntPtr.Zero;
try
{
size = Marshal.SizeOf(conversionObject);
pBuf = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(conversionObject, pBuf, false);
return Marshal.PtrToStringAuto(pBuf, size).Substring(0, size/2);
}
catch
{
throw;
}
finally
{
Marshal.FreeHGlobal(pBuf);
}
}
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class Comarea
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)]
private string status;
public string Status
{
get
{
return new string(status).Trim();
}
set
{
status = value.ToFixedCharArray(1, true);
}
}
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 5)]
private string operationName;
public string OperationName
{
get
{
return new string(operationName).Trim();
}
set
{
operationName = value.ToFixedCharArray(5, true);
}
}
}
I can fill any object using single line of string and opposite of that operation
string commareaStr = "0TR231";
Commarea commarea = CommareaHelper.StringToObject<Commarea>(commareaStr);
I'm trying to populate a bean with some table driven attribute:value pairs. I retrieve them from a MySQL table, and populate a hashmap just fine. I iterate through the hashmap, and if I use PropertyUtils.setProperty() I get a "Class does not have setter for *" error. If I use BeanUtils.setProperty() the bean never gets populated. Here's the sample:
public class DBDrivenPayloadHandler extends GDE{
DbDrivenPayloadHandlerBean bean;
#SuppressWarnings("rawtypes")
public void populateBean() throws Exception {
ITransaction trans = new MySQLTransaction();
IAdapterDataMapDAO adapterDataMap = new MySQLAdapterDataMapDAO();
adapterDataMap.setTransaction(trans);
HashMap<String, String> values = adapterDataMap.getHashMap(super.getCurrentAccountId());
//hashmap gets populated correctly with correct variable names and values != "-1";
DbDrivenPayloadHandlerBean bean = new DbDrivenPayloadHandlerBean();
//We have a bean with all the intialized variable values
Iterator it = values.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
try {
PropertyUtils.setProperty(bean, (String) entry.getKey(), entry.getValue());
//PropertyUtils will give a setter not found error. BeanUtils never sets the values.
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void getInfo(String fileName) {
try {
populateBean();
} catch (Exception e) {
e.printStackTrace();
}
APPTS_FULLNAME_POS = bean.getAPPTS_FULLNAME_POS();
APPTS_DATETIME_POS = bean.getAPPTS_DATETIME_POS();
//Both still -1;
super.getInfo(filename);
}
And here's the Bean (or at least some of it):
public class DbDrivenPayloadHandlerBean {
int APPTS_FULLNAME_POS = -1;
int APPTS_DATETIME_POS = -1;
public DbDrivenPayloadHandlerBean() {
super();
}
public int getAPPTS_FULLNAME_POS() {
return APPTS_FULLNAME_POS;
}
public void setAPPTS_FULLNAME_POS(String APPTS_FULLNAME_POS) {
this.APPTS_FULLNAME_POS = Integer.parseInt(APPTS_FULLNAME_POS);
}
public int getAPPTS_DATETIME_POS() {
return APPTS_DATETIME_POS;
}
public void setAPPTS_DATETIME_POS(String APPTS_DATETIME_POS) {
this.APPTS_DATETIME_POS = Integer.parseInt(APPTS_DATETIME_POS);
}
Sorry guys, BeanUtils does the trick. I just don't want to be allowing setters that take Strings. I guess reflection does the casting for you. Apologies.
Solution as stated above: don't try to cast for BeanUtils.
public class DBDrivenPayloadHandler extends GDE{
DbDrivenPayloadHandlerBean bean;
#SuppressWarnings("rawtypes")
public void populateBean() throws Exception {
ITransaction trans = new MySQLTransaction();
IAdapterDataMapDAO adapterDataMap = new MySQLAdapterDataMapDAO();
adapterDataMap.setTransaction(trans);
HashMap<String, String> values = adapterDataMap.getHashMap(super.getCurrentAccountId());
this.bean = new DbDrivenPayloadHandlerBean();
Iterator it = values.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
try {
BeanUtils.setProperty(bean, (String) entry.getKey(), entry.getValue());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void getInfo(String fileName) {
try {
populateBean();
} catch (Exception e) {
e.printStackTrace();
}
APPTS_FULLNAME_POS = bean.getAPPTS_FULLNAME_POS();
APPTS_DATETIME_POS = bean.getAPPTS_DATETIME_POS();
//Both still -1;
super.getInfo(filename);
}
Bean
public class DbDrivenPayloadHandlerBean {
int APPTS_FULLNAME_POS = -1;
int APPTS_DATETIME_POS = -1;
public DbDrivenPayloadHandlerBean() {
super();
}
public int getAPPTS_FULLNAME_POS() {
return APPTS_FULLNAME_POS;
}
public void setAPPTS_FULLNAME_POS(int APPTS_FULLNAME_POS) {
this.APPTS_FULLNAME_POS = APPTS_FULLNAME_POS;
}
public int getAPPTS_DATETIME_POS() {
return APPTS_DATETIME_POS;
}
public void setAPPTS_DATETIME_POS(String APPTS_DATETIME_POS) {
this.APPTS_DATETIME_POS = APPTS_DATETIME_POS;
}