Inserting items in DynamoDB Range key - java

I have created a DynamoDB table with following details:
and I'm trying to insert items in my table:
public static void insertItems() {
AmazonDynamoDBClient ddb = UserPreferenceDemoActivity.clientManager
.ddb();
DynamoDBMapper mapper = new DynamoDBMapper(ddb);
try {
UserPreference userPreference = new UserPreference();
userPreference.setNavn("SalonSol");
for (int i = 800; i <= 1600; i = i + 50) {
userPreference.setTid(i);
userPreference.setMandag("Ledig");
userPreference.setTirsdag("Ledig");
userPreference.setOnsdag("Ledig");
userPreference.setTorsdag("Ledig");
userPreference.setFredag("Ledig");
userPreference.setLørdag("Ledig");
userPreference.setSøndag("Ledig");
Log.d(TAG, "Inserting Tid and Dage");
mapper.save(userPreference);
Log.d(TAG, "Tid and Dage inserted");
}
} catch (AmazonServiceException ex) {
Log.e(TAG, "Error inserting users");
UserPreferenceDemoActivity.clientManager
.wipeCredentialsOnAuthError(ex);
}
}
But AWS keeps returning following exception:
AmazonserviceException: The provided key element does not match the schema
Status Code: 400
I'm actually inserting a String value as a Hash Key and int values as range, so I don't really understand why I'm getting this exception.
My definition of UserPreference class:
#DynamoDBTable(tableName = Constants.TEST_TABLE_NAME)
public static class UserPreference {
private String Navn;
private int Tid;
private String Mandag;
private String Tirsdag;
private String Onsdag;
private String Torsdag;
private String Fredag;
private String Lørdag;
private String Søndag;
#DynamoDBHashKey(attributeName = "Navn")
public String getNavn() {
return Navn;
}
public void setNavn(String Navn) {
this.Navn = Navn;
}
#DynamoDBRangeKey(attributeName = "Tid")
public int getTid() {
return Tid;
}
public void setTid(int Tid) {
this.Tid = Tid;
}
#DynamoDBAttribute(attributeName = "Mandag")
public String getMandag() {
return Mandag;
}
public void setMandag(String Mandag) {
this.Mandag = Mandag;
}
#DynamoDBAttribute(attributeName = "Tirsdag")
public String getTirsdag() {
return Tirsdag;
}
public void setTirsdag(String Tirsdag) {
this.Tirsdag = Tirsdag;
}
#DynamoDBAttribute(attributeName = "Onsdag")
public String getOnsdag() {
return Onsdag;
}
public void setOnsdag(String Onsdag) {
this.Onsdag = Onsdag;
}
#DynamoDBAttribute(attributeName = "Torsdag")
public String getTorsdag() {
return Torsdag;
}
public void setTorsdag(String Torsdag) {
this.Torsdag = Torsdag;
}
#DynamoDBAttribute(attributeName = "Fredag")
public String getFredag() {
return Fredag;
}
public void setFredag(String Fredag) {
this.Fredag = Fredag;
}
#DynamoDBAttribute(attributeName = "Lørdag")
public String getLørdag() {
return Lørdag;
}
public void setLørdag(String Lørdag) {
this.Lørdag = Lørdag;
}
#DynamoDBAttribute(attributeName = "Søndag")
public String getSøndag() {
return Søndag;
}
public void setSøndag(String Søndag) {
this.Søndag = Søndag;
}
}
and the table name has following definition in the "Constants" class:
public static final String TEST_TABLE_NAME = "EkstraTable";

I tried to reproduce the problem by copying and pasting your code then change it to write to my own test table. The problem did not occur, I successfully put all items into the table as per your code:
http://i.imgur.com/lIPgn7P.png
I would suggest checking to make sure you have the newest version of the AWS Java SDK, and that the table was created correctly (I created mine through the console to be safe, you can try that if code still doesn't work after upgrading).

I found the issue. I did a huge mistake by importing:
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey
instead of:
com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBRangeKey
for #DynamoDBRangeKey annotation since I'm using Android mobile SDK. I found the issue by downloading and adding the DynamoDBMapper.jar for 2.1.8, and this version shows the
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey
as deprecated.

Related

How to get row from TableView?

I am creating a lobby application which will show all groups on a java tableview. Users are able to join groups that have space in them, else they will not be able to join.
I have been able to create this but I would like to be able to colour the row of the groups that have space in them in green and groups that are full will be coloured in red.
I will provide my code for this below. I am getting NullPointerException, which i dont know why. Thanks.
private void visualGroupAvailability() {
boolean isThereSpace;
for (currentGroupsModel o : groupsTable.getItems()) {
TableRow<currentGroupsModel> currentRow = getTableRow(o.getGroupID());
int limit = o.getNumberOfUsers();
isThereSpace = checkSpaceInGroup(o);
if(isThereSpace) {
currentRow.setStyle("-fx-background-color: #" + "388e3c ");
} else {
currentRow.setStyle("-fx-background-color: #" + "ffcdd2 ");
}
}
}
private TableRow<currentGroupsModel> getTableRow(int rowIndex) {
Set<Node> tableRowCell = groupsTable.lookupAll(".table-row-cell");
TableRow<currentGroupsModel> row = null;
for (Node tableRow : tableRowCell) {
TableRow<currentGroupsModel> r = (TableRow<currentGroupsModel>) tableRow;
row = r;
}
return row;
}
public class currentGroupsModel {
String groupName, groupDescription, hostName, groupType;
Integer numberOfUsers, groupID;
public currentGroupsModel(String gName, String gDesc, String hostName, String groupType, Integer numberOfUsers, Integer groupID){
this.groupName = gName;
this.groupDescription = gDesc;
this.hostName = hostName;
this.groupType = groupType;
this.numberOfUsers = numberOfUsers;
this.groupID = groupID;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getGroupDescription() {
return groupDescription;
}
public void setGroupDescription(String groupDescription) {
this.groupDescription = groupDescription;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getGroupType() {
return groupType;
}
public void setGroupType(String groupType) {
this.groupType = groupType;
}
public Integer getNumberOfUsers() {
return numberOfUsers;
}
public void setNumberOfUsers(int numberOfUsers) {
this.numberOfUsers = numberOfUsers;
}
public Integer getGroupID(){
return this.groupID;
}
public void setGroupID(Integer newID){
this.groupID = newID;
}
}
This question cannot really be answered with what you have given us. It is hard looking for a NullPointerException if there is a currentGroupModel we know nothing about and there are constant red hairings. For example why do you store something in limit, you never use it! Why do you pass getTableRow a rowIndex, that you are never using? As far as I get it your getTableRow returns the last TableRow in the table, not a specific one. Please consider fixing those problems first, before eventually providing some code to understand the inner workings of your currentGroupModel.

cannot fetch the exact dto returned from ejb to liferay controller

I am doing a liferay project which use ejb at back end. so my ejb method looks like this:-
#Override
public List<RmisPaymentDetailsDto> getEpaymentDetails(String ebpCode) {
Query q = entityManager.createQuery("select s from EpaymentBo s where s.ebpCode=:ebpcode")
.setParameter("ebpcode",ebpCode);
#SuppressWarnings("unchecked")
List<ProductBo> list = q.getResultList();
Iterator<ProductBo> i = list.iterator();
List<RmisPaymentDetailsDto> rList = new ArrayList<RmisPaymentDetailsDto>();
while(i.hasNext()){
EpaymentBo ep =(EpaymentBo) i.next();
RmisPaymentDetailsDto dto = new RmisPaymentDetailsDto();
dto.setAdvertisementcode(ep.getAdvertisementcode());
dto.setAmount(ep.getAmount());
dto.setStudentmasterid(ep.getStudentmasterid());
dto.setEbpgendate(ep.getEbp_gen_date());
dto.setEbpcode(ep.getEbpCode());
dto.setPaymentstatus(ep.getPaymentstatus());
dto.setCandidatenameinnepali(ep.getCandidatenameinnepali());
rList.add(dto);
}
return rList;
}
the above method successfully fetches data from database and sets it to my RmisPaymentDetailsDto.
like this:-
now i am calling same method from my liferay controlller.
PreExaminationRemote preRef = (PreExaminationRemote) jndiContext
.lookup("PreExamination/remote");
List<RmisPaymentDetailsDto> rDto = preRef.getEpaymentDetails(ebpCode);
I am wondering how my one property(candidatenameinnepali) is lost as i return same dto from my ejb.
My dto looks like this:-
public class RmisPaymentDetailsDto implements Serializable {
private static final long serialVersionUID = 1L;
private String advertisementcode;
private String ebpcode;
private String amount;
private String studentmasterid;
private Date ebpgendate;
private String paymentstatus;
private String candidatenameinnepali;
public String getCandidatenameinnepali() {
return candidatenameinnepali;
}
public void setCandidatenameinnepali(String candidatenameinnepali) {
this.candidatenameinnepali = candidatenameinnepali;
}
public String getAdvertisementcode() {
return advertisementcode;
}
public void setAdvertisementcode(String advertisementcode) {
this.advertisementcode = advertisementcode;
}
public String getEbpcode() {
return ebpcode;
}
public void setEbpcode(String ebpcode) {
this.ebpcode = ebpcode;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getStudentmasterid() {
return studentmasterid;
}
public void setStudentmasterid(String studentmasterid) {
this.studentmasterid = studentmasterid;
}
public Date getEbpgendate() {
return ebpgendate;
}
public void setEbpgendate(Date ebpgendate) {
this.ebpgendate = ebpgendate;
}
public String getPaymentstatus() {
return paymentstatus;
}
public void setPaymentstatus(String paymentstatus) {
this.paymentstatus = paymentstatus;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}

Room #Insert does not insert all records

I am running into an issue where only 1 record is being inserted into my Room SQLite DB.
When I perform a getAll(); the result only returns 1 record.
FOUND ISSUE: Genre[] genres = gson.fromJson(jsonArray.toString(), Genre[].class);
This line above is setting all "gid" values to 0, and I am not sure how to change that.
Genre.java
#Entity(indices = {#Index(value = {"id", "name"}, unique = true)})
public class Genre {
#PrimaryKey
private int gid;
//#ColumnInfo(name = "id") By Default - No need to annotate
#NonNull
private int id;
private String name;
public int getGid() {
return gid;
}
public void setGid(int gid) {
this.gid = gid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
GenreDao.java
#Dao
public interface GenreDao {
#Query("SELECT * FROM Genre")
LiveData<List<Genre>> getAll();
#Insert(onConflict = OnConflictStrategy.REPLACE) //If there is a conflict, replace the record.
void insertAll(Genre... genres);
}
GenreRepository.java
public class GenreRepository {
private final GenreDao genreDao;
public GenreRepository(GenreDao genreDao) {
this.genreDao = genreDao;
}
//Database Methods
public void insertAll(Genre... genres) {
AsyncTask.execute(() -> { //Same as new Runnable()
genreDao.insertAll(genres);
});
}
public LiveData<List<Genre>> getAll() {
return genreDao.getAll();
}
}
APIUtil.java - getGenres() Method
This class makes an API call, returns the proper results, converts the JSONArray to a Genre[]. I can successfully loop through the Genre[] and confirm 10+ results come back.
public static void getGenres(Context context) {
APIWrapper wrapper = new APIWrapper(context, API_KEY);
Parameters params = new Parameters();
params.addFields(GENRE_FIELDS);
params.addLimit("50");
wrapper.genres(params, new onSuccessCallback() {
#Override
public void onSuccess(JSONArray jsonArray) {
Gson gson = new Gson();
Genre[] genres = gson.fromJson(jsonArray.toString(), Genre[].class);
//Insert DB
AppDatabase db = AppDatabase.getAppDatabase(context);
GenreRepository genreRepository = new GenreRepository(db.genreDao());
genreRepository.insertAll(genres);
}
#Override
public void onError(VolleyError volleyError) {
Log.e("GENRES ERROR:", volleyError.toString());
}
});
}
GenreViewModel.java
public class GenreViewModel extends ViewModel {
private GenreRepository genreRepository;
public GenreViewModel(GenreRepository genreRepository) {
this.genreRepository = genreRepository;
}
public void insertAll(Genre... genres){
genreRepository.insertAll(genres);
}
public LiveData<List<Genre>> getAll(){
return genreRepository.getAll();
}
}
SearchFragment.java
This is where I am retrieving the database values. This for loop only returns 1 result.
AppDatabase db = AppDatabase.getAppDatabase(getActivity());
GenreRepository genreRepository = new GenreRepository(db.genreDao());
GenreViewModel genreViewModel = new GenreViewModel(genreRepository);
genreViewModel.getAll().observe(this, genres -> { //new Observer<List<Genre>>()
for(Genre g : genres){
Log.e("GENRE", g.getName());
}
});
public void insertAll(Genre... genres){
genreRepository.insertAll(genres);
}
here is your mistake , what you provide as method definition and what you provide at call. see you make some thing wrong.
Solution
void insertAll(List<T> obj);
you can try with convert your array to list and put above in definition
I had this problem too.
And Solved it this way.
The problem was that the id that comes from server was mongoId and String so I should create a int primary key and pass currentTime as value to it so the database can insert all of them not replace them.
But you should consider using System.nanoTime() method instead of System.currentTimeMillis() cause sometimes it generates same value and then room replace them instead of inserting each one of them.

Exception being thrown by hibernate in specifit request orders

I am experiencing strange behavior. I am using hibernate. I have two tables.
#Entity
public class Nemocnica implements java.io.Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="N_ID")
private BigDecimal NId;
#Column(name="adresa")
private String adresa;
#OneToMany
private Set sanitkas = new HashSet(0);
public Nemocnica() {
}
public Nemocnica( String adresa) {
this.NId = NId;
}
public Nemocnica(BigDecimal NId, String adresa) {
this.NId = NId;
this.adresa = adresa;
}
public Nemocnica(BigDecimal NId, String adresa, Set sanitkas) {
this.NId = NId;
this.adresa = adresa;
this.sanitkas = sanitkas;
}
public BigDecimal getNId() {
return this.NId;
}
public void setNId(BigDecimal NId) {
this.NId = NId;
}
public String getAdresa() {
return this.adresa;
}
public void setAdresa(String adresa) {
this.adresa = adresa;
}
public Set getSanitkas() {
return this.sanitkas;
}
public void setSanitkas(Set sanitkas) {
this.sanitkas = sanitkas;
}
}
and second
#Entity
public class Sanitka implements java.io.Serializable {
private BigDecimal sanitkaId;
private transient Nemocnica nemocnica;
private BigDecimal kapacita;
#ManyToOne
#JoinColumn(name="nemocnica_n_id")
private Set sanitaris = new HashSet(0);
public Sanitka() {
}
public Sanitka(BigDecimal sanitkaId, Nemocnica nemocnica, BigDecimal kapacita) {
this.sanitkaId = sanitkaId;
this.nemocnica = nemocnica;
this.kapacita = kapacita;
}
public Sanitka(BigDecimal sanitkaId, Nemocnica nemocnica, BigDecimal kapacita, Set sanitaris) {
this.sanitkaId = sanitkaId;
this.nemocnica = nemocnica;
this.kapacita = kapacita;
this.sanitaris = sanitaris;
}
public BigDecimal getSanitkaId() {
return this.sanitkaId;
}
public void setSanitkaId(BigDecimal sanitkaId) {
this.sanitkaId = sanitkaId;
}
#ManyToOne(cascade=CascadeType.ALL)
public Nemocnica getNemocnica() {
return this.nemocnica;
}
public void setNemocnica(Nemocnica nemocnica) {
this.nemocnica = nemocnica;
}
public BigDecimal getKapacita() {
return this.kapacita;
}
public void setKapacita(BigDecimal kapacita) {
this.kapacita = kapacita;
}
public Set getSanitaris() {
return this.sanitaris;
}
public void setSanitaris(Set sanitaris) {
this.sanitaris = sanitaris;
}
}
And routes that mannipulate with them.
nemocnicaRoute:
#Path("nemocnica")
public class nemocnicaRoute {
// private static final helper db = new helper();
#GET
#Path("all")
#Produces(MediaType.APPLICATION_JSON)
public String getName(){
List<Nemocnica> l = db.helper.getNemocnicas();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
//System.out.println( json );
//return l.toString();
return gson.toJson(l);
}
// another methods
}
sanitkaRoute
#Path("sanitka")
public class sanitkaRoute {
//private static final helper db = new helper();
#GET
#Path("all")
#Produces("text/plain")
public String getName(){
List<Sanitka> l = db.helper.getSanitkas();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
//System.out.println( json );
//return l.toString();
return gson.toJson(l);
}
// another methods
}
I am using these two getName() methods to retrieve all data from said tables.
This cause strange behavior , if i invoke get request on nemocnicaRoute first , it works very well as it should.
However when i invoke get requet on sanitkaRoute first , it works but after that when i want to invoke get request on nemocniceRoute it throws
java.lang.UnsupportedOperationException: Attempted to serialize
java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to
register a type adapter?
Which confuses me , bcs this does not happen when i invoke getRequest on nemocnicaRoute first.
How could i fix this strange behavior?
All help appreciated

Cannot Parse a JSON response that is received by RestTemplate

I need to parse a JSON response that I receive from a web service but I am receiving following error message, I puzzled with the this. I tried it without Results class as well to no avail. Any help would be appreciated.
The request sent by the client was syntactically incorrect.
Code
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new
MappingJackson2HttpMessageConverter());
ResponseEntity<Results> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi
/GetEvents?
username=username&
password=password&
userid=23",
Results.class);
System.err.println(">>" + responseEntity.getBody().getEvents().size());
Classes
Results
public class Results {
private List<Events> events;
getter and setter
}
Events
public class Event {
private long eventId;
private String name;
private String subTitle;
private String description;
private String localDate;
private String localDateFrom;
private String imageUrl;
private int venueId;
private String venue;
private int availableTickets;
private long performerId;
private String performer;
private String performerType;
private int subcategoryId;
private String urlCategoryName;
private String metaTitle;
private String metaDescription;
private String primeSportUrl;
private String sectionWiseView;
private String venueCity;
private String venueState;
private String snippetDate;
private int eiProductionId;
private boolean requireBillingAsShipping;
public long getEventId() {
return eventId;
}
public void setEventId(long eventId) {
this.eventId = eventId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLocalDate() {
return localDate;
}
public void setLocalDate(String localDate) {
this.localDate = localDate;
}
public String getLocalDateFrom() {
return localDateFrom;
}
public void setLocalDateFrom(String localDateFrom) {
this.localDateFrom = localDateFrom;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public int getVenueId() {
return venueId;
}
public void setVenueId(int venueId) {
this.venueId = venueId;
}
public String getVenue() {
return venue;
}
public void setVenue(String venue) {
this.venue = venue;
}
public int getAvailableTickets() {
return availableTickets;
}
public void setAvailableTickets(int availableTickets) {
this.availableTickets = availableTickets;
}
public long getPerformerId() {
return performerId;
}
public void setPerformerId(long performerId) {
this.performerId = performerId;
}
public String getPerformer() {
return performer;
}
public void setPerformer(String performer) {
this.performer = performer;
}
public String getPerformerType() {
return performerType;
}
public void setPerformerType(String performerType) {
this.performerType = performerType;
}
public int getSubcategoryId() {
return subcategoryId;
}
public void setSubcategoryId(int subcategoryId) {
this.subcategoryId = subcategoryId;
}
public String getUrlCategoryName() {
return urlCategoryName;
}
public void setUrlCategoryName(String urlCategoryName) {
this.urlCategoryName = urlCategoryName;
}
public String getMetaTitle() {
return metaTitle;
}
public void setMetaTitle(String metaTitle) {
this.metaTitle = metaTitle;
}
public String getMetaDescription() {
return metaDescription;
}
public void setMetaDescription(String metaDescription) {
this.metaDescription = metaDescription;
}
public String getPrimeSportUrl() {
return primeSportUrl;
}
public void setPrimeSportUrl(String primeSportUrl) {
this.primeSportUrl = primeSportUrl;
}
public String getSectionWiseView() {
return sectionWiseView;
}
public void setSectionWiseView(String sectionWiseView) {
this.sectionWiseView = sectionWiseView;
}
public String getVenueCity() {
return venueCity;
}
public void setVenueCity(String venueCity) {
this.venueCity = venueCity;
}
public String getVenueState() {
return venueState;
}
public void setVenueState(String venueState) {
this.venueState = venueState;
}
public String getSnippetDate() {
return snippetDate;
}
public void setSnippetDate(String snippetDate) {
this.snippetDate = snippetDate;
}
public int getEiProductionId() {
return eiProductionId;
}
public void setEiProductionId(int eiProductionId) {
this.eiProductionId = eiProductionId;
}
public boolean isRequireBillingAsShipping() {
return requireBillingAsShipping;
}
public void setRequireBillingAsShipping(boolean requireBillingAsShipping) {
this.requireBillingAsShipping = requireBillingAsShipping;
}
}
Partial Response
[{
"EventId":1000250537,
"Name":"US Open Golf",
"SubTitle":null,
"Description":"US Open Golf Tickets",
"Date":"\/Date(1434873560000)\/",
"LocalDate":"6/20/2015 11:59 PM",
"LocalDateFrom":null,
"ImageUrl":null,
"VenueId":146566,
"Venue":"Chambers Bay Golf Course",
"AvailableTickets":33,
"PerformerId":151551,
"Performer":"US Open Golf",
"PerformerType":"Golf",
"SubcategoryId":55,
"UrlCategoryName":"Sports",
"MetaTitle":null,
"MetaDescription":null,
"PrimeSportUrl":"http://primesport.sieenasoftware.com/e/sports/us-open-golf/chambers-bay-golf-course/",
"SectionWiseView":null,
"VenueCity":"UNIVERSITY PLACE",
"VenueState":"WA",
"SnippetDate":null,
"EIProductionId":99985,
"RequireBillingAsShipping":false},
{
"EventId":1000253479,
"Name":"Womens College World Series",
"SubTitle":null,
"Description": .....
UPDATE
I know JAXB can be used for both JSON and XML, I am trying to use it to see if it would help to solve the issue.
UPDATE
The code is returning following exception:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of com.myproject.myevent.Results out of START_ARRAY token
at [Source: java.io.PushbackInputStream#dedcd10; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.myproject.myevent.Results out of START_ARRAY token
at [Source: java.io.PushbackInputStream#dedcd10; line: 1, column: 1]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:208)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:200)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:97)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:809)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:793)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:576)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:529)
at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:261)
at com.myproject.service.TicketSeviceImpl.primeSport(TicketSeviceImpl.java:217)
at com.myproject.service.TicketSeviceImpl.findTicket(TicketSeviceImpl.java:45)
at com.myproject.web.TicketController.findTicket(TicketController.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
UPDATE
following code returns
Code
try {
System.err.println(">>> primeSport");
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(
new MappingJackson2HttpMessageConverter());
ResponseEntity<Event[]> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi/GetEvents?username=username&password=password&userid=23",
Event[].class);
System.err.println(">>" + responseEntity.getBody().length);
System.err.println(">>" + responseEntity.getBody()[0].getEventId());
System.err.println(">>" + responseEntity.getBody()[1].getEventId());
} catch (Exception e) {
e.printStackTrace();
}
Output
>1532
>0
>0
Can you try the following and see whether helps:
ResponseEntity<Events[]> responseEntity = restTemplate
.getForEntity(
"http://primesport.sieenasoftware.com/QryApi
/GetEvents?
username=username&
password=password&
userid=23",
Events[].class);
System.err.println(">>" + responseEntity.getBody().length);
For mapping the fields to the JSON members you can use Jackson annotation JSONProperty("EventId") can be used for the eventId field. Similarly for others.
#JsonProperty("EventId")
private long eventId;
#JsonProperty("Name")
private String name;
Have you tried to see the exact request getting generated? Let's say in a proxy software like fiddler/charles?
Sometimes I have experienced, the framework adds additional constructs(encoding, etc), before the requests actually really gets to the wire(or reaching the server endpoint).
Try this, to create the request. Even the documentation for RestTemplate suggests to avoid double encoding for URL. It may not be very apparent when looking in the IDE.
String url = "http://primesport.sieenasoftware.com/QryApi/GetEvents?";
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("username", "username");
params.add("password", "password");
params.add("userid", "23");
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).queryParams(params).build();
System.out.println(uriComponents.toUri());
Please let me know, how it works out.
Also, please let know, if you cant find steps to setup fiddler proxy. It quite a handy tool, while coding the service clients.
According to the json format, all you need is using the Event class instead of the Result class.
Or change the JSON result to this :
["events": {
"EventId":1000250537,
"Name":"US Open Golf",
"SubTitle":null,
"Description":"US Open Golf Tickets",
"Date":"\/Date(1434873560000)\/",
"LocalDate":"6/20/2015 11:59 PM",
"LocalDateFrom":null,
"ImageUrl":null,
"VenueId":146566,
"Venue":"Chambers Bay Golf Course",
"AvailableTickets":33,
"PerformerId":151551,
"Performer":"US Open Golf",
"PerformerType":"Golf",
"SubcategoryId":55,
"UrlCategoryName":"Sports",
"MetaTitle":null,
"MetaDescription":null,
"PrimeSportUrl":"http://primesport.sieenasoftware.com/e/sports/us-open-golf/chambers-bay-golf-course/",
"SectionWiseView":null,
"VenueCity":"UNIVERSITY PLACE",
"VenueState":"WA",
"SnippetDate":null,
"EIProductionId":99985,
"RequireBillingAsShipping":false},
{
"EventId":1000253479,
"Name":"Womens College World Series",
"SubTitle":null,
"Description": .....
You can try importing Jackson Jar or add dependency in pom.xml if you are using Maven.
ObjectMapper mapper = new ObjectMapper();
try
{
mapper.writeValue(new File("c://temp/employee.json"), Results);
}

Categories