How to read and write Identified Data Serializable in Hazelcast - hazelcast

i have a problem and the documentations and github examples doesn't provide a clear example about how to do it....
i have this class
public class KeySerializable implements IdentifiedDataSerializable{
private String claveReq;
private int id_interno_pe;
private String cod_nrbe_en;
private int num_sec_ac;
public KeySerializable(String claveReq, int id_interno_pe, String cod_nrbe_en, int num_sec_ac) {
this.claveReq = claveReq;
this.id_interno_pe = id_interno_pe;
this.cod_nrbe_en = cod_nrbe_en;
this.num_sec_ac = num_sec_ac;
}
public KeySerializable() {
}
public void writeData(ObjectDataOutput out) throws IOException {
out.writeString(claveReq);
out.writeInt(id_interno_pe);
out.writeString(cod_nrbe_en);
out.writeInt(num_sec_ac);
}
public void readData(ObjectDataInput in) throws IOException {
this.claveReq = in.readString();
this.id_interno_pe = in.readInt();
this.cod_nrbe_en = in.readString();
this.num_sec_ac = in.readInt();
}
public int getFactoryId() {
return KeySerializableFactory.FACTORY_ID;
}
public int getClassId() {
return KeySerializableFactory.KEY_SERIALIZABLE_TYPE;
}
#Override
public String toString() {
return "KeySerializable [claveReq=" + claveReq + ", id_interno_pe=" + id_interno_pe + ", cod_nrbe_en="
+ cod_nrbe_en + ", num_sec_ac=" + num_sec_ac + "]";
}
}
and this class
public class ResponseSerializablePlus implements IdentifiedDataSerializable{
private int id_interno_pe;
private String cod_nrbe_en;
private int num_sec_ac;
private int statusCode;
private HashMap<String,List<String>> headers;
private byte[] content;
public ResponseSerializablePlus(int id_interno_pe, String cod_nrbe_en, int num_sec_ac, int statusCode,
HashMap<String, List<String>> headers, byte[] content) {
this.id_interno_pe = id_interno_pe;
this.cod_nrbe_en = cod_nrbe_en;
this.num_sec_ac = num_sec_ac;
this.statusCode = statusCode;
this.headers = headers;
this.content = content;
}
public ResponseSerializablePlus() {
}
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(id_interno_pe);
out.writeString(cod_nrbe_en);
out.writeInt(num_sec_ac);
out.write(statusCode);
out.writeObject(headers);
out.writeByteArray(content);
}
public void readData(ObjectDataInput in) throws IOException {
this.id_interno_pe = in.readInt();
this.cod_nrbe_en = in.readString();
this.num_sec_ac = in.readInt();
this.statusCode = in.readInt();
this.headers = in.readObject();
this.content = in.readByteArray();
}
public int getFactoryId() {
return ResponseSerializablePlusFactory.FACTORY_ID;
}
public int getClassId() {
return ResponseSerializablePlusFactory.RESPONSE_SERIALIZABLE_PLUS_CLASS;
}
#Override
public String toString() {
return "ResponseSerializablePlus [id_interno_pe=" + id_interno_pe + ", cod_nrbe_en=" + cod_nrbe_en
+ ", num_sec_ac=" + num_sec_ac + ", statusCode=" + statusCode + ", headers=" + headers + ", content="
+ Arrays.toString(content) + "]";
}
and this other class
public class ResponseSerializable implements IdentifiedDataSerializable{
private int statusCode;
private HashMap<String,List<String>> headers;
private byte[] content;
public ResponseSerializable(int statusCode, HashMap<String, List<String>> headers, byte[] content) {
this.statusCode = statusCode;
this.headers = headers;
this.content = content;
}
public ResponseSerializable() {
}
public void writeData(ObjectDataOutput out) throws IOException {
out.write(statusCode);
out.writeObject(headers);
out.writeByteArray(content);
}
public void readData(ObjectDataInput in) throws IOException {
this.statusCode = in.readInt();
this.headers = in.readObject();
this.content = in.readByteArray();
}
public int getFactoryId() {
return ResponseSerializableFactory.FACTORY_ID;
}
public int getClassId() {
return ResponseSerializableFactory.RESPONSE_TYPE;
}
#Override
public String toString() {
return "ResponseSerializable [statusCode=" + statusCode + ", headers=" + headers + ", content="
+ Arrays.toString(content) + "]";
}
}
and the factory it's always the same but with different classes
public class KeySerializableFactory implements DataSerializableFactory{
public static final int FACTORY_ID = 1;
public static final int KEY_SERIALIZABLE_TYPE = 1;
public IdentifiedDataSerializable create(int typeId) {
if ( typeId == KEY_SERIALIZABLE_TYPE ) {
return new KeySerializable();
} else {
return null;
}
}
}
and im always having this bunch errors
the documentation and the github examples from hazelcast doesn't provide a good example about how to use the getters and setters and i don't understand what to do here to write or read an object
any hint? can you help me?

You shouldn't be calling readData or writeData yourself. These methods are called by Hazelcast internally when the data is about to be serialized/deserialized.
On your side, you should only register the data serializable factories you have created to the Hazelcast.
Then, upon receiving an instance of a class that implements IdentifiedDataSerializable and has a factory registered for it, Hazelcast will call the methods I mentioned above in appropriate places and return you the object read.
From the code sample you shared, you need to drop the line starting with newResponse.writeData(..., and everything should be working, assuming you did the factory registration.
Also, please fix your ResponseSerializablePlus and ResponseSerializable classes: You need to use writeInt method to write the statusCode field. The readData and writeData methods should be consistent with each other.

Related

I Want To Itemonclicklister in Fragment on Spinner

This Is Main Fragment
Fragment:
private void getStock() {
dialog.show();
Retrofit retrofit = RetrofitClient.getRetrofitInstance();
apiInterface api = retrofit.create(apiInterface.class);
Call<List<Blocks>>call = api.getVaccineBlocks();
call.enqueue(new Callback<List<Blocks>>() {
#Override
public void onResponse(Call<List<Blocks>>call, Response<List<Blocks>> response) {
if (response.code() == 200) {
block = response.body();
spinnerada();
dialog.cancel();
}else{
dialog.cancel();
}
}
#Override
public void onFailure(Call<List<Blocks>> call, Throwable t) {
dialog.cancel();
}
});
}
private void spinnerada() {
String[] s = new String[block.size()];
for (int i = 0; i < block.size(); i++) {
s[i] = block.get(i).getBlockName();
final ArrayAdapter a = new ArrayAdapter(getContext(), android.R.layout.simple_spinner_item, s);
a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spinner.setAdapter(a);
}
}
This Is Blocks Model
model:
package com.smmtn.book.models;
import java.io.Serializable;
public class Blocks implements Serializable {
public String id;
public String blockName;
public String blockSlug;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBlockName() {
return blockName;
}
public void setBlockName(String blockName) {
this.blockName = blockName;
}
public String getBlockSlug() {
return blockSlug;
}
public void setBlockSlug(String blockSlug) {
this.blockSlug = blockSlug;
}
}
here i need onitemclick with blockslug please any one can help, am new to android so i need some example.when on click i want take blockslug and load another method with that blockslug,like will get data from u "http://example.com/block/"+blockslug
i want to get blockslug from selected block
i hope guys i will get help
and sorry for my bad English,
First of all, you need to implement setOnItemSelectedListener. Refer to this https://stackoverflow.com/a/20151596/9346054
Once you selected the item, you can call them by making a new method. Example like below
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
final String itemSelected = parent.getItemAtPosition(pos).toString();
showBlockSlug(itemSelected);
}
And then, at the method showBlockSlug() , you can call Retrofit.
private void showBlockSlug(final String blockslug){
final String url = "http://example.com/block/"+ blockslug;
//Do your stuff...
}

caling fragment method inside adapter but my value going null what should add?

This is my CartAdapter I called GetCart function in this adapter my function is calling successfully but my orgmst id and userid going null to database.
quantity.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
new GetUpdateQuantity().execute();
TwoFragment fragment = new TwoFragment();
fragment.Getcart();
if (quantity.length() == 0) {
} else {
quan = Double.parseDouble(quantity.getText().toString());
rate = Double.parseDouble(rate1.getText().toString());
total1 = Double.parseDouble(String.valueOf(rate * quan));
// convert double to string to get value
String show = Double.toString(total1);
//show in Textview
total.setText(show);
Log.d("<<<hcvyd", "" + show);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
----------
In myfragment i create method to send data to webservice this method i call in GetCart function then this function call inside adapter
MyFragment
'''GetCart Function'''
public void Getcart(){
String gh = orgmstid;
String hj = userid;
new GetCartItems().execute();
}
private class GetCartItems extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall("VIEW_CART", "F", "" + 'N' + "~" + orgmstid + "~" + userid);
Code for background CAll
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.os.AsyncTask;
import android.util.Log;
public class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... f_url) {
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
byte data[] = new byte[1024];
String file_string = "";
while ((count = input.read(data)) != -1) {
for (int i = 0; i < count; i++) {
file_string += (char) data[i];
}
}
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
// dismissDialog(progress_bar_type);
}
}
Code for calling
new DownloadFileFromURL().execute("URL");

issues with parcelable extension: getting unmarshalling unknown type code exception

long story short, I have one settlementItemeBase class as my father and two children. I want to make the father class parcelable so as extension happens, my two child classes be parcelable as well. I don't exactly know what I'm doing right or wrong. I searched little bit but nothing helped me.
here are my classes:
SettlementItemBase:
public class SettlementItemBase implements Parcelable{
public SettlementItemBase(){}
protected SettlementItemBase(Parcel in) {
}
public static final Creator<SettlementItemBase> CREATOR = new Creator<SettlementItemBase>() {
#Override
public SettlementItemBase createFromParcel(Parcel in) {
return new SettlementItemBase(in);
}
#Override
public SettlementItemBase[] newArray(int size) {
return new SettlementItemBase[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
}
}
first child class:
public class FirstClass extends SettlementItemBase {
private int id;
private int cardId;
private String cardNumber;
private String expDate;
private String currency;
private String url;
public FirstClass(){
id = 0;
cardId = 0;
cardNumber = "";
expDate = "";
currency = "";
url = "";
}
protected FirstClass(Parcel in) {
super(in);
id = in.readInt();
cardId = in.readInt();
cardNumber = in.readString();
expDate = in.readString();
currency = in.readString();
url = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeInt(cardId);
dest.writeString(cardNumber);
dest.writeString(expDate);
dest.writeString(currency);
dest.writeString(url);
}
public int getId() {
return id;
}
public int getCardId() {
return cardId;
}
public String getCardNumber() {
return cardNumber;
}
public String getExpDate() {
return expDate;
}
public String getCurrency() {
return currency;
}
public String getUrl() {
return url;
}
}
second child class:
public class SecondClass extends SettlementItemBase{
private int id;
private String currency;
private String accountNumber;
private String ibanNumber;
public SecondClass(int id, String currency,
String accountNumber, String ibanNumber){
this.id = id;
this.currency = currency;
this.accountNumber = accountNumber;
this.ibanNumber = ibanNumber;
}
protected SecondClass(Parcel in){
super(in);
id = in.readInt();
currency = in.readString();
accountNumber = in.readString();
ibanNumber = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(currency);
dest.writeString(accountNumber);
dest.writeString(ibanNumber);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCurrency() {
return currency;
}
public String getAccountNumber() {
return accountNumber;
}
public String getIbanNumber() {
return ibanNumber;
}
}
I'm passing and getting an ArrayList of both child class' items with intent putParcelableArrayListExtra and getParcelableArrayListExtra methods and get the following error:
Parcel android.os.Parcel#2d0fde33: Unmarshalling unknown type code 3276849 at offset 172
any help would be appreciated 3>
well I'm posting this for those who may run into the same problem as me.
the problem was solved after adding the Creator statement to the child classes.
for one of the child classes it would be like:
public static final Creator<FirstClass> CREATOR = new Creator<FirstClass>() {
#Override
public FirstClass createFromParcel(Parcel in) {
return new FirstClass(in);
}
#Override
public FirstClass[] newArray(int size) {
return new FirstClass[size];
}
};
hope this helps. 3>

Unmarshalling jaxB doesn't work, objects null

I have a problem with jaxB. There is no exception and here is my xml ;
<event>
<event_datetimeGMT>2015-02-27 17:00</event_datetimeGMT>
<gamenumber>443364144</gamenumber>
<sporttype>Basketball</sporttype>
<league>Adriatic</league>
<IsLive>No</IsLive>
<participants>
<participant>
<participant_name>Cedevita</participant_name>
<contestantnum>1001</contestantnum>
<rotnum>1001</rotnum>
<visiting_home_draw>Home</visiting_home_draw>
</participant>
<participant>
<participant_name>Mega Leks</participant_name>
<contestantnum>1002</contestantnum>
<rotnum>1002</rotnum>
<visiting_home_draw>Visiting</visiting_home_draw>
</participant>
</participants>
<periods>
<period>
<period_number>0</period_number>
<period_description>Game</period_description>
<periodcutoff_datetimeGMT>2015-02-27 17:00</periodcutoff_datetimeGMT>
<period_status>I</period_status>
<period_update>open</period_update>
<spread_maximum>500</spread_maximum>
<moneyline_maximum>500</moneyline_maximum>
<total_maximum>500</total_maximum>
<moneyline>
<moneyline_visiting>583</moneyline_visiting>
<moneyline_home>-720</moneyline_home>
</moneyline>
<spread>
<spread_visiting>12</spread_visiting>
<spread_adjust_visiting>-104</spread_adjust_visiting>
<spread_home>-12</spread_home>
<spread_adjust_home>-106</spread_adjust_home>
</spread>
<total>
<total_points>164</total_points>
<over_adjust>-101</over_adjust>
<under_adjust>-109</under_adjust>
</total>
</period>
</periods>
here is main class ;
#XmlRootElement (name = "pinnacle_line_feed")
public class PinnacleLineFeed {
private Long PinnacleFeedTime;
private Long lastContest;
private Long lastGame;
private List<Event> events;
#XmlAttribute(name = "PinnacleFeedTime")
public Long getPinnacleFeedTime() {
return PinnacleFeedTime;
}
public void setPinnacleFeedTime(Long pinnacleFeedTime) {
PinnacleFeedTime = pinnacleFeedTime;
}
#XmlAttribute (name = "lastContest")
public Long getLastContest() {
return lastContest;
}
public void setLastContest(Long lastContest) {
this.lastContest = lastContest;
}
#XmlAttribute (name = "lastGame")
public Long getLastGame() {
return lastGame;
}
public void setLastGame(Long lastGame) {
this.lastGame = lastGame;
}
#XmlElement (name = "events")
public List<Event> getEvents() {
return events;
}
public void setEvents(List<Event> events) {
this.events = events;
}
}
you can see full xml from the url which i shared at my first post
and here is my pojos ;
public class Event {
private String event_datetimeGMT;
private Long gamenumber;
private String sporttype;
private String league;
private String IsLive;
private List<Participant> participants;
private List<Period> periods;
#XmlAttribute (name = "event_datetimeGMT")
public String getEvent_datetimeGMT() {
return event_datetimeGMT;
}
public void setEvent_datetimeGMT(String event_datetimeGMT) {
this.event_datetimeGMT = event_datetimeGMT;
}
#XmlAttribute (name = "gamenumber")
public Long getGamenumber() {
return gamenumber;
}
public void setGamenumber(Long gamenumber) {
this.gamenumber = gamenumber;
}
#XmlAttribute (name = "sporttype")
public String getSporttype() {
return sporttype;
}
public void setSporttype(String sporttype) {
this.sporttype = sporttype;
}
#XmlAttribute (name = "league")
public String getLeague() {
return league;
}
public void setLeague(String league) {
this.league = league;
}
#XmlAttribute (name = "IsLive")
public String getIsLive() {
return IsLive;
}
public void setIsLive(String isLive) {
this.IsLive = isLive;
}
#XmlElement(name = "participant")
public List<Participant> getParticipants() {
return participants;
}
public void setParticipants(List<Participant> participants) {
this.participants = participants;
}
#XmlElement(name = "period")
public List<Period> getPeriods() {
return periods;
}
public void setPeriods(List<Period> periods) {
this.periods = periods;
}
}
public class Participants {
private List<Participant> participants;
#XmlElement(name = "participant")
public List<Participant> getParticipants() {
return participants;
}
public void setParticipants(List<Participant> participants) {
this.participants = participants;
}
}
public class Participant {
private String participant_name;
private Long contestantnum;
private Long rotnum;
private String visiting_home_draw;
#XmlAttribute(name = "participant_name")
public String getParticipant_name() {
return participant_name;
}
public void setParticipant_name(String participant_name) {
this.participant_name = participant_name;
}
#XmlAttribute (name = "contestantnum")
public Long getContestantnum() {
return contestantnum;
}
public void setContestantnum(Long contestantnum) {
this.contestantnum = contestantnum;
}
#XmlAttribute (name = "rotnum")
public Long getRotnum() {
return rotnum;
}
public void setRotnum(Long rotnum) {
this.rotnum = rotnum;
}
#XmlAttribute (name = "visiting_home_draw")
public String getVisiting_home_draw() {
return visiting_home_draw;
}
public void setVisiting_home_draw(String visiting_home_draw) {
this.visiting_home_draw = visiting_home_draw;
}
}
public class Periods {
private List<Period> periods;
#XmlElement(name = "period")
public List<Period> getPeriods() {
return periods;
}
public void setPeriods(List<Period> periods) {
this.periods = periods;
}
}
public class Period {
private int period_number;
private String period_description;
private String periodcutoff_datetimeGMT;
private String period_status;
private String period_update;
private int spread_maximum;
private int moneyline_maximum;
private int total_maximum;
private Moneyline moneyline;
private Spread spread;
private Total total;
#XmlAttribute(name = "period_number")
public int getPeriod_number() {
return period_number;
}
public void setPeriod_number(int period_number) {
this.period_number = period_number;
}
#XmlAttribute(name = "period_description")
public String getPeriod_description() {
return period_description;
}
public void setPeriod_description(String period_description) {
this.period_description = period_description;
}
#XmlAttribute(name = "periodcutoff_datetimeGMT")
public String getPeriodcutoff_datetimeGMT() {
return periodcutoff_datetimeGMT;
}
public void setPeriodcutoff_datetimeGMT(String periodcutoff_datetimeGMT) {
this.periodcutoff_datetimeGMT = periodcutoff_datetimeGMT;
}
#XmlAttribute(name = "period_status")
public String getPeriod_status() {
return period_status;
}
public void setPeriod_status(String period_status) {
this.period_status = period_status;
}
#XmlAttribute(name = "period_update")
public String getPeriod_update() {
return period_update;
}
public void setPeriod_update(String period_update) {
this.period_update = period_update;
}
#XmlAttribute(name = "spread_maximum")
public int getSpread_maximum() {
return spread_maximum;
}
public void setSpread_maximum(int spread_maximum) {
this.spread_maximum = spread_maximum;
}
#XmlAttribute(name = "moneyline_maximum")
public int getMoneyline_maximum() {
return moneyline_maximum;
}
public void setMoneyline_maximum(int moneyline_maximum) {
this.moneyline_maximum = moneyline_maximum;
}
#XmlAttribute(name = "total_maximum")
public int getTotal_maximum() {
return total_maximum;
}
public void setTotal_maximum(int total_maximum) {
this.total_maximum = total_maximum;
}
#XmlElement (name = "moneyline")
public Moneyline getMoneyline() {
return moneyline;
}
public void setMoneyline(Moneyline moneyline) {
this.moneyline = moneyline;
}
#XmlElement (name = "spread")
public Spread getSpread() {
return spread;
}
public void setSpread(Spread spread) {
this.spread = spread;
}
#XmlElement (name = "total")
public Total getTotal() {
return total;
}
public void setTotal(Total total) {
this.total = total;
}
}
public class Moneyline {
private int moneyline_visiting;
private int moneyline_home;
#XmlAttribute(name = "moneyline_visiting")
public int getMoneyline_visiting() {
return moneyline_visiting;
}
public void setMoneyline_visiting(int moneyline_visiting) {
this.moneyline_visiting = moneyline_visiting;
}
#XmlAttribute(name = "moneyline_home")
public int getMoneyline_home() {
return moneyline_home;
}
public void setMoneyline_home(int moneyline_home) {
this.moneyline_home = moneyline_home;
}
}
public class Spread {
private int spread_visiting;
private int spread_adjust_visiting;
private int spread_home;
private int spread_adjust_home;
#XmlAttribute(name = "spread_visiting")
public int getSpread_visiting() {
return spread_visiting;
}
public void setSpread_visiting(int spread_visiting) {
this.spread_visiting = spread_visiting;
}
#XmlAttribute(name = "spread_adjust_visiting")
public int getSpread_adjust_visiting() {
return spread_adjust_visiting;
}
public void setSpread_adjust_visiting(int spread_adjust_visiting) {
this.spread_adjust_visiting = spread_adjust_visiting;
}
#XmlAttribute(name = "spread_home")
public int getSpread_home() {
return spread_home;
}
public void setSpread_home(int spread_home) {
this.spread_home = spread_home;
}
#XmlAttribute(name = "spread_adjust_home")
public int getSpread_adjust_home() {
return spread_adjust_home;
}
public void setSpread_adjust_home(int spread_adjust_home) {
this.spread_adjust_home = spread_adjust_home;
}
}
public class Total {
private int total_points;
private int over_adjust;
private int under_adjust;
#XmlAttribute(name = "total_points")
public int getTotal_points() {
return total_points;
}
public void setTotal_points(int total_points) {
this.total_points = total_points;
}
#XmlAttribute(name = "over_adjust")
public int getOver_adjust() {
return over_adjust;
}
public void setOver_adjust(int over_adjust) {
this.over_adjust = over_adjust;
}
#XmlAttribute(name = "under_adjust")
public int getUnder_adjust() {
return under_adjust;
}
public void setUnder_adjust(int under_adjust) {
this.under_adjust = under_adjust;
}
}
and my test method ;
private static void unmarshall() {
try {
JAXBContext jc = JAXBContext.newInstance(PinnacleLineFeed.class);
URL url = new URL("http://xml.pinnaclesports.com/pinnacleFeed.aspx?");
Unmarshaller unmarshaller = jc.createUnmarshaller();
PinnacleLineFeed pinnacleLineFeed = (PinnacleLineFeed) unmarshaller.unmarshal(url);
System.out.println("bakıcez");
} catch (Exception ex) {
ex.printStackTrace();
}
}
When i try to unmarshall this xml, all fields are null. And there is no exception. Can anyone help ?

PickList PrimeFaces not working

I try to use the pickList component of Primefaces. My converter does not work properly and I don't know why.
This is my ManagedBean:
#ManagedBean(name = "comMB")
#SessionScoped
public class TeamCompetitionBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private DualListModel<Team> teams;
List<Team> source;
List<Team> source1;
List<Team> target;
#ManagedProperty("#{team}")
private TeamServiceI teamService;
List<String> teamNameList ;
// public TeamCompetitionBean() {
public DualListModel<Team> getTeams() {
// Players
teamNameList = new ArrayList<String>();
source = new ArrayList<Team>();
target = new ArrayList<Team>();
source.addAll(getTeamService().getTeam());
teams = new DualListModel<Team>(source, target);
return teams;
}
public void setTeams(DualListModel<Team> teams) {
this.teams = teams;
}
public void onTransfer(TransferEvent event) {
StringBuilder builder = new StringBuilder();
for (Object item : event.getItems()) {
builder.append(((Team) item).getTeamName()).append("<br />");
}
FacesMessage msg = new FacesMessage();
msg.setSeverity(FacesMessage.SEVERITY_INFO);
msg.setSummary("Items Transferred");
msg.setDetail(builder.toString());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public TeamServiceI getTeamService() {
return teamService;
}
public void setTeamService(TeamServiceI teamService) {
this.teamService = teamService;
}
public List<Team> getSource() {
return source;
}
public void setSource(List<Team> source) {
this.source = source;
}
public List<Team> getTarget() {
return target;
}
public void setTarget(List<Team> target) {
this.target = target;
}
public void afficher(){
System.out.println(target);
System.out.println(source);
}
}
and this is my entity class that I would like to load in my pickList:
#Entity
#Table(name = "team", catalog = "competition_manager")
public class Team implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer idTeam;
private Stadium stadium;
private League league;
private String teamName;
// getters and setters
#Override
public String toString() {
return teamName.toString();
}
#Override
public boolean equals(Object obj) {
if (!(obj instanceof Team)) {
return false;
}
Team f = (Team) obj;
return (this.idTeam == f.getIdTeam());
}
Now, this is my custom Converter:
#FacesConverter(forClass = Team.class, value = "teamConverter")
public class TeamConverter implements Converter {
Team team;
public Object getAsObject(FacesContext facesContext, UIComponent component,
String value) {
System.out.println("hello object");
if (value == null || value.length() == 0) {
return null;
}
ApplicationContext ctx = FacesContextUtils
.getWebApplicationContext(FacesContext.getCurrentInstance());
TeamBean controller = (TeamBean) ctx.getBean("teamMB");
List<Team> liststagiaire = controller.getTeamList();
for (int i = 0; i < liststagiaire.size(); i++)
{
team = liststagiaire.get(i);
if (team.getIdTeam() == getKey(value)) {
break;
}
}
return team;
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component,
Object object) {
System.out.println("hello string");
if (object == null) {
System.out.println("hello string null");
return null;
}
if (object instanceof Team) {
System.out.println("hello string intance of");
Team o = (Team) object;
String i = getStringKey(o.getIdTeam());
return i;
} else {
System.out.println("hello throw");
throw new IllegalArgumentException("object " + object
+ " is of type " + object.getClass().getName()
+ "; expected type: " + Team.class.getName());
}
}
}
And finally this is my XHTML page:
<p:pickList id="teamPickList" value="#{comMB.teams}" var="team"
itemValue="#{team}" itemLabel="#{team}" converter="teamConverter">
</p:pickList>
Your problem is comming from this line (in your class TeamConverter) :
if (team.getIdTeam() == getKey(value)) {
You can't compare Integer objects like that, because doing like this you are comparing reference. You should replace this line by
if (team.getIdTeam().intValue() == getKey(value).intValue()) {
You have the same problem in your class Team :
return (this.idTeam == f.getIdTeam());
should be replaced by :
return (this.idTeam.intValue() == f.getIdTeam().intValue());
Not related :
You don't need to use getKey and getStringKey, you could replace them simply like this :
getKey(value) // this
Integer.valueOf(value) // by this
and
getStringKey(o.getIdTeam()) // this
o.getIdTeam().toString() // by this
Also you should replace itemLabel="#{team}" by itemLabel="#{team.teamName}" in your view.

Resources