Junit testing for exceptions in a constructor? - java

In the following test I am trying to test if an exception has been thrown by the constructor when it is passed illegal arguments when trying to create the object, I have added validation in the setters of each instance variable that when they are passed invalid data they throw an exception.
// test for invalid const
#Test(expected = IllegalArgumentException.class)
public void testInvalidBookStringStringStringInt() {
// create a new book
Book b = new Book(invalidISBN, invalidAuthor, invalidTitle,
invalidRating1);
}
The test is currently failing at the minute, what am i doing wrong?
Book class:
package practice;
/**
* Class that creates a Book
*
* #author Ross Young
*
*/
public class Book {
// declaring instance variables
/**
* Book's ISBN
*/
private String ISBN;
/**
* Book's Author
*/
private String author;
/**
* Book's Title
*/
private String title;
/**
* Book's rating
*/
private int rating;
/**
* Default constructor
*/
public Book() {
}
/**
* Constructor with Args
*
* #param ISBN
* #param author
* #param title
* #param rating
*/
public Book(String ISBN, String author, String title, int rating) {
this.ISBN = ISBN;
this.author = author;
this.title = title;
this.rating = rating;
}
/**
* Gets ISBN
*
* #return ISBN
*/
public String getISBN() {
return ISBN;
}
/**
* Sets ISBN
*
* #param iSBN
*/
public void setISBN(String iSBN) {
if((iSBN.length()!=9)||(iSBN.length()!=12)){
throw new IllegalArgumentException("Invalid ISBN length");
}else{
this.ISBN=iSBN;
}
}
/**
* Gets Author
*
* #return author
*/
public String getAuthor() {
return author;
}
/**
* Sets author
*
* #param author
*/
public void setAuthor(String author) {
if ((author.length() < 0) || (author.length() > 20)) {
throw new IllegalArgumentException("Invalid author Length");
} else {
this.author = author;
}
}
/**
* gets title
*
* #return title
*/
public String getTitle() {
return title;
}
/**
* Sets title
*
* #param title
*/
public void setTitle(String title) {
if ((title.length() < 0) || (title.length() > 20)) {
throw new IllegalArgumentException("Invalid title Length");
} else {
this.title = title;
}
}
/**
* Gets rating
*
* #return rating
*/
public int getRating() {
return rating;
}
/**
* Sets rating
*
* #param rating
*/
public void setRating(int rating) {
if((rating>5)|| (rating<1)){
throw new IllegalArgumentException("Rating invalid");
}
this.rating = rating;
}
}

Your constructor doesn't perform any of the checks that your setters check, so it won't ever throw any exceptions. Setters aren't called when you directly assign an instance variable; they're only called explicitly.
Either have your constructor call your setters, or implement the validation in your constructor.

You need to call the setX methods from your constructor. Also change setISBN to :
if((iSBN.length()!=9) && (iSBN.length()!=12)) {
throw new IllegalArgumentException("Invalid ISBN length");

Your constructor is setting the private variables and not using the public setters that contain the validation.

Related

Attempting to generate javadoc in Eclipse but getting "Error=193, %1 is not a valid Win32 application"

I'm working on an assignment and having trouble generating a javadoc html file for this class I've made. I've clicked Project > Generate Java Doc > Javadoc command auto filled to C:\Users\Evanl\workspace\CSC - Car Class\bin\Main\Car.class > click Next > name the document "Car javadoc" > click FInish and get error Error 193
Any ideas on how to fix this?
Main that runs my program:
package Main;
public class CarMain {
public static void main(String[] args) {
Car car1 = new Car("Honda", "Civic", "Black", 2020);
System.out.println(car1.toString() +"\n"+car1.ageOfCar()+"\n");
// TODO (Optional)
// Create another Car object named car2 and input your own values :)
// And then output its values like I did in line 5
// This is completely optional
Car myCar = new Car("Jeep", "Wrangler", "Black", 2023);
System.out.println(myCar.toString() +"\n"+myCar.ageOfCar()+"\n");
}
}
Car class:
package Main;
/**
* #author Evan Cammack
* #version 1.0
* created on 2/15/2023
* this is a template for a software car object
*/
import java.util.Calendar;
public class Car {
//private fields
private String make;
private String model;
private String color;
private int year;
private double mileage;
//default constructor sets all fields to default blank values
public Car(){
make = "";
model = "";
color = "";
year = 0;
mileage = 0;
}
//custom constructor
//"this" refers to current object
/**
* #param make String parameter representing make of car
* #param model String parameter representing model of car
* #param color String parameter representing color of car
* #param year int parameter representing year of car
* #throws IllegalArgumentException if year equals "0000"
*/
public Car(String make, String model, String color, int year){
this.make = make;
this.model = model;
this.color = color;
if (year <= 0000)
throw new IllegalArgumentException();
this.year = year;
mileage = 0;
}
//getters
/**
* #return make - the make of the car
*/
public String getMake(){
return this.make;
}
/**
* #return model - the model of the car
*/
public String getModel(){
return this.model;
}
/**
* #return color - the color of the car
*/
public String getColor(){
return this.color;
}
/**
* #return year - the year of the car
*/
public int getYear(){
return this.year;
}
//setters
/**
* #param make changes to the make of the car to given input String
*/
public void setMake(String make){
this.make = make;
}
/**
* #param make changes to the model of the car to given input String
*/
public void setModel(String model){
this.model = model;
}
/**
* #param make changes to the color of the car to given input String
*/
public void setColor(String color){
this.color = color;
}
/**
* #param make changes to the year of the car to given input String
*/
public void setYear(int year){
this.year = year;
}
/**
* #return ageOfCar - how old the car is
*/
public String ageOfCar() {
Calendar cal = Calendar.getInstance();
int ageOfCar = cal.get(Calendar.YEAR) - this.year;
return "This car is "+ageOfCar+" years old.";
}
/**
* #return make, model, color, year - returns make, model, color, and year in a string
*/
public String toString() {
return "Make: " +this.make+" Model: "+this.model+" Color: "+this.color+" Year: "+this.year;
}
}
I've tried googling and youtubing this specific error message but there's no guides to help fix it.

Deserialize Array Of Objects with the first item being the counter of the elements

Hello i was trying to deserialize the following JSON response from a Web Api:
{
"response": [
370968,
{
"aid": 65843156,
"owner_id": 17519165,
"artist": "Bass Test",
"title": "дурной басс!",
"duration": 238,
"url": "http://cs6-10v4.vk-cdn.net/p22/c412a04df93035.mp3?extra=9YguhLftfZDDwo4JKBVwvlx_V1vwlu5pNU4-WremEqM9bL8eN2vh3_qu7bAg9EgNCj0ztEcMurarC499x8X2MpUaipykG2LDueWe0QQMrIPplkxKdV1xcQp35baDwA84l-luVxai9maX",
"lyrics_id": "6214304"
},
{
"aid": 207425918,
"owner_id": 96085484,
"artist": "► DJ Pleased",
"title": "Bass Test № 04 (New 2013)",
"duration": 328,
"url": "http://cs6-7v4.vk-cdn.net/p23/6d7071221fb912.mp3?extra=O5ih5W5YkaEkXhHQSOKeDzvtr0V8xyS1WhIgjYLROFOMcW__FpU3mSf5udwdEAq6kkcz7QSy5jB57rTgSxnRJXCySZy2b0J_a2DvzFUBqVX6lcKqlarTryP_loQyk-SYPbFLh-9mSzm_iA",
"lyrics_id": "86651563",
"genre": 10
}
]
}
My intention is to build a class to get the items in the response and use them in my Java Android application. The problem is that the first item of the response array is a number and not an object like the next items. So when I parse it with Gson it gives me the error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 20 path $.response[0]
I used the retrofit android library with the following POJO class (witch works if i don't have the counter in the response):
import java.util.HashMap;
import java.util.Map;
public class Response {
private Integer aid;
private Integer ownerId;
private String artist;
private String title;
private Integer duration;
private String url;
private String lyricsId;
private Integer genre;
private String album;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The aid
*/
public Integer getAid() {
return aid;
}
/**
*
* #param aid
* The aid
*/
public void setAid(Integer aid) {
this.aid = aid;
}
/**
*
* #return
* The ownerId
*/
public Integer getOwnerId() {
return ownerId;
}
/**
*
* #param ownerId
* The owner_id
*/
public void setOwnerId(Integer ownerId) {
this.ownerId = ownerId;
}
/**
*
* #return
* The artist
*/
public String getArtist() {
return artist;
}
/**
*
* #param artist
* The artist
*/
public void setArtist(String artist) {
this.artist = artist;
}
/**
*
* #return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* #param title
* The title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* #return
* The duration
*/
public Integer getDuration() {
return duration;
}
/**
*
* #param duration
* The duration
*/
public void setDuration(Integer duration) {
this.duration = duration;
}
/**
*
* #return
* The url
*/
public String getUrl() {
return url;
}
/**
*
* #param url
* The url
*/
public void setUrl(String url) {
this.url = url;
}
/**
*
* #return
* The lyricsId
*/
public String getLyricsId() {
return lyricsId;
}
/**
*
* #param lyricsId
* The lyrics_id
*/
public void setLyricsId(String lyricsId) {
this.lyricsId = lyricsId;
}
/**
*
* #return
* The genre
*/
public Integer getGenre() {
return genre;
}
/**
*
* #param genre
* The genre
*/
public void setGenre(Integer genre) {
this.genre = genre;
}
/**
*
* #return
* The album
*/
public String getAlbum() {
return album;
}
/**
*
* #param album
* The album
*/
public void setAlbum(String album) {
this.album = album;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
Is there any way to make it work? I don't have access to the API server so i cant change how the result is displayed. To generate the class i used http://www.jsonschema2pojo.org/ but i was able to generate it only by removing the counter from the response.
The wrapper class VKSongApi:
public class VKSongApi {
private List<Response> response = new ArrayList<Response>();
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The response
*/
public List<Response> getResponse() {
return response;
}
/**
*
* #param response
* The response
*/
public void setResponse(List<Response> response) {
this.response = response;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
The retrofit interface class is:
public interface VKApi {
#GET("/method/audio.search")
Call<VKSongApi> search(#Query("q") String query, #Query("access_token") String token);
}
Then in the MainActivity i do:
public static final String BASE_URL = "https://api.vk.com/method/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
VKApi apiService =
retrofit.create(VKApi.class);
And call the method from the MainActivity with:
Call<VKSongApi> call = apiService.search("test","fff9ef502df4bb10d9bf50dcd62170a24c69e98e4d847d9798d63dacf474b674f9a512b2b3f7e8ebf1d69");
call.enqueue(new Callback<VKSongApi>() {
#Override
public void onResponse(Call<VKSongApi> call, Response<VKSongApi> response) {
int statusCode = response.code();
VKSongApi song = response.body();
Log.d(TAG,response.message());
}
#Override
public void onFailure(Call<VKSongApi> call, Throwable t) {
//Here the error occurs com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 20 path $.response[0]
Log.d(TAG,"Failure");
}
});
I solved by parsing manually the response using a custom deserializer class

Retrofit 2 (in Android) after implementation, Where are my JSON elements?

I'm implementing a retrofit 2 interface to parse JSON elements (video urls, thumbnails, title etc.)
JSONschema2Pojo resulted in 4 pojo classes, but the main/root one is VideoInfo (never mind implements Parcelable, I'm not yet doing anything with it)
Is the lack of #SerializedName("....") affects anything, knowing that this was automatically generated by jsonschema2pojo ? UPDATE : generated new pojo classes, this time with Gson annotations (#SerializedName("") and #Expose) but still having the same problem.
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
public class VideoInfo implements Parcelable {
private List<Item> items = new ArrayList<Item>();
private int pageNumber;
private int pageSize;
private int totalCount;
/**
* No args constructor for use in serialization
*
*/
public VideoInfo() {
}
/**
*
* #param totalCount
* #param items
* #param pageSize
* #param pageNumber
*/
public VideoInfo(List<Item> items, int pageNumber, int pageSize, int totalCount) {
this.items = items;
this.pageNumber = pageNumber;
this.pageSize = pageSize;
this.totalCount = totalCount;
}
/**
*
* #return
* The items
*/
public List<Item> getItems() {
return items;
}
/**
*
* #param items
* The items
*/
public void setItems(List<Item> items) {
this.items = items;
}
/**
*
* #return
* The pageNumber
*/
public int getPageNumber() {
return pageNumber;
}
/**
*
* #param pageNumber
* The page_number
*/
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
/**
*
* #return
* The pageSize
*/
public int getPageSize() {
return pageSize;
}
/**
*
* #param pageSize
* The page_size
*/
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
/**
*
* #return
* The totalCount
*/
public int getTotalCount() {
return totalCount;
}
/**
*
* #param totalCount
* The total_count
*/
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
}
}
UPDATE: in the class VideoInfo above you can see private List<Item> items = new ArrayList<Item>(); this is because there's another pojo class that has a list of tiems, as follows:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class Item {
#SerializedName("id")
#Expose
private int id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("shortDescription")
#Expose
private String shortDescription;
#SerializedName("creationDate")
#Expose
private String creationDate;
#SerializedName("publishedDate")
#Expose
private String publishedDate;
#SerializedName("linkURL")
#Expose
private String linkURL;
#SerializedName("linkText")
#Expose
private String linkText;
#SerializedName("tags")
#Expose
private List<String> tags = new ArrayList<String>();
#SerializedName("videoStillURL")
#Expose
private String videoStillURL;
#SerializedName("thumbnailURL")
#Expose
private String thumbnailURL;
#SerializedName("length")
#Expose
private int length;
#SerializedName("renditions")
#Expose
private List<Rendition> renditions = new ArrayList<Rendition>();
#SerializedName("IOSRenditions")
#Expose
private List<IOSRendition> IOSRenditions = new ArrayList<IOSRendition>();
#SerializedName("HDSRenditions")
#Expose
private List<Object> HDSRenditions = new ArrayList<Object>();
/**
* No args constructor for use in serialization
*
*/
public Item() {
}
/**
*
* #param tags
* #param videoStillURL
* #param HDSRenditions
* #param id
* #param creationDate
* #param IOSRenditions
* #param linkText
* #param shortDescription
* #param renditions
* #param name
* #param linkURL
* #param length
* #param publishedDate
* #param thumbnailURL
*/
public Item(int id, String name, String shortDescription, String creationDate, String publishedDate, String linkURL, String linkText, List<String> tags, String videoStillURL, String thumbnailURL, int length, List<Rendition> renditions, List<IOSRendition> IOSRenditions, List<Object> HDSRenditions) {
this.id = id;
this.name = name;
this.shortDescription = shortDescription;
this.creationDate = creationDate;
this.publishedDate = publishedDate;
this.linkURL = linkURL;
this.linkText = linkText;
this.tags = tags;
this.videoStillURL = videoStillURL;
this.thumbnailURL = thumbnailURL;
this.length = length;
this.renditions = renditions;
this.IOSRenditions = IOSRenditions;
this.HDSRenditions = HDSRenditions;
}
/**
*
* #return
* The id
*/
public int getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(int id) {
this.id = id;
}
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The shortDescription
*/
public String getShortDescription() {
return shortDescription;
}
/**
*
* #param shortDescription
* The shortDescription
*/
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
/**
*
* #return
* The creationDate
*/
public String getCreationDate() {
return creationDate;
}
/**
*
* #param creationDate
* The creationDate
*/
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
/**
*
* #return
* The publishedDate
*/
public String getPublishedDate() {
return publishedDate;
}
/**
*
* #param publishedDate
* The publishedDate
*/
public void setPublishedDate(String publishedDate) {
this.publishedDate = publishedDate;
}
/**
*
* #return
* The linkURL
*/
public String getLinkURL() {
return linkURL;
}
/**
*
* #param linkURL
* The linkURL
*/
public void setLinkURL(String linkURL) {
this.linkURL = linkURL;
}
/**
*
* #return
* The linkText
*/
public String getLinkText() {
return linkText;
}
/**
*
* #param linkText
* The linkText
*/
public void setLinkText(String linkText) {
this.linkText = linkText;
}
/**
*
* #return
* The tags
*/
public List<String> getTags() {
return tags;
}
/**
*
* #param tags
* The tags
*/
public void setTags(List<String> tags) {
this.tags = tags;
}
/**
*
* #return
* The videoStillURL
*/
public String getVideoStillURL() {
return videoStillURL;
}
/**
*
* #param videoStillURL
* The videoStillURL
*/
public void setVideoStillURL(String videoStillURL) {
this.videoStillURL = videoStillURL;
}
/**
*
* #return
* The thumbnailURL
*/
public String getThumbnailURL() {
return thumbnailURL;
}
/**
*
* #param thumbnailURL
* The thumbnailURL
*/
public void setThumbnailURL(String thumbnailURL) {
this.thumbnailURL = thumbnailURL;
}
/**
*
* #return
* The length
*/
public int getLength() {
return length;
}
/**
*
* #param length
* The length
*/
public void setLength(int length) {
this.length = length;
}
/**
*
* #return
* The renditions
*/
public List<Rendition> getRenditions() {
return renditions;
}
/**
*
* #param renditions
* The renditions
*/
public void setRenditions(List<Rendition> renditions) {
this.renditions = renditions;
}
/**
*
* #return
* The IOSRenditions
*/
public List<IOSRendition> getIOSRenditions() {
return IOSRenditions;
}
/**
*
* #param IOSRenditions
* The IOSRenditions
*/
public void setIOSRenditions(List<IOSRendition> IOSRenditions) {
this.IOSRenditions = IOSRenditions;
}
/**
*
* #return
* The HDSRenditions
*/
public List<Object> getHDSRenditions() {
return HDSRenditions;
}
/**
*
* #param HDSRenditions
* The HDSRenditions
*/
public void setHDSRenditions(List<Object> HDSRenditions) {
this.HDSRenditions = HDSRenditions;
}
}
UPDATE: So above you can see that we have defined private List<Rendition> renditions = new ArrayList<Rendition>(); that is defined in another pojo classes Rendition.class:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Rendition {
#SerializedName("audioOnly")
#Expose
private boolean audioOnly;
#SerializedName("controllerType")
#Expose
private String controllerType;
#SerializedName("displayName")
#Expose
private String displayName;
#SerializedName("encodingRate")
#Expose
private int encodingRate;
#SerializedName("frameHeight")
#Expose
private int frameHeight;
#SerializedName("frameWidth")
#Expose
private int frameWidth;
#SerializedName("id")
#Expose
private int id;
#SerializedName("referenceId")
#Expose
private Object referenceId;
#SerializedName("remoteStreamName")
#Expose
private Object remoteStreamName;
#SerializedName("remoteUrl")
#Expose
private Object remoteUrl;
#SerializedName("size")
#Expose
private int size;
#SerializedName("uploadTimestampMillis")
#Expose
private int uploadTimestampMillis;
#SerializedName("url")
#Expose
private String url;
#SerializedName("videoCodec")
#Expose
private String videoCodec;
#SerializedName("videoContainer")
#Expose
private String videoContainer;
#SerializedName("videoDuration")
#Expose
private int videoDuration;
/**
* No args constructor for use in serialization
*
*/
public Rendition() {
}
/**
*
* #param controllerType
* #param encodingRate
* #param referenceId
* #param url
* #param size
* #param id
* #param uploadTimestampMillis
* #param frameWidth
* #param remoteUrl
* #param videoContainer
* #param remoteStreamName
* #param displayName
* #param videoCodec
* #param videoDuration
* #param audioOnly
* #param frameHeight
*/
public Rendition(boolean audioOnly, String controllerType, String displayName, int encodingRate, int frameHeight, int frameWidth, int id, Object referenceId, Object remoteStreamName, Object remoteUrl, int size, int uploadTimestampMillis, String url, String videoCodec, String videoContainer, int videoDuration) {
this.audioOnly = audioOnly;
this.controllerType = controllerType;
this.displayName = displayName;
this.encodingRate = encodingRate;
this.frameHeight = frameHeight;
this.frameWidth = frameWidth;
this.id = id;
this.referenceId = referenceId;
this.remoteStreamName = remoteStreamName;
this.remoteUrl = remoteUrl;
this.size = size;
this.uploadTimestampMillis = uploadTimestampMillis;
this.url = url;
this.videoCodec = videoCodec;
this.videoContainer = videoContainer;
this.videoDuration = videoDuration;
}
/**
*
* #return
* The audioOnly
*/
public boolean isAudioOnly() {
return audioOnly;
}
/**
*
* #param audioOnly
* The audioOnly
*/
public void setAudioOnly(boolean audioOnly) {
this.audioOnly = audioOnly;
}
/**
*
* #return
* The controllerType
*/
public String getControllerType() {
return controllerType;
}
/**
*
* #param controllerType
* The controllerType
*/
public void setControllerType(String controllerType) {
this.controllerType = controllerType;
}
/**
*
* #return
* The displayName
*/
public String getDisplayName() {
return displayName;
}
/**
*
* #param displayName
* The displayName
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
*
* #return
* The encodingRate
*/
public int getEncodingRate() {
return encodingRate;
}
/**
*
* #param encodingRate
* The encodingRate
*/
public void setEncodingRate(int encodingRate) {
this.encodingRate = encodingRate;
}
/**
*
* #return
* The frameHeight
*/
public int getFrameHeight() {
return frameHeight;
}
/**
*
* #param frameHeight
* The frameHeight
*/
public void setFrameHeight(int frameHeight) {
this.frameHeight = frameHeight;
}
/**
*
* #return
* The frameWidth
*/
public int getFrameWidth() {
return frameWidth;
}
/**
*
* #param frameWidth
* The frameWidth
*/
public void setFrameWidth(int frameWidth) {
this.frameWidth = frameWidth;
}
/**
*
* #return
* The id
*/
public int getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(int id) {
this.id = id;
}
/**
*
* #return
* The referenceId
*/
public Object getReferenceId() {
return referenceId;
}
/**
*
* #param referenceId
* The referenceId
*/
public void setReferenceId(Object referenceId) {
this.referenceId = referenceId;
}
/**
*
* #return
* The remoteStreamName
*/
public Object getRemoteStreamName() {
return remoteStreamName;
}
/**
*
* #param remoteStreamName
* The remoteStreamName
*/
public void setRemoteStreamName(Object remoteStreamName) {
this.remoteStreamName = remoteStreamName;
}
/**
*
* #return
* The remoteUrl
*/
public Object getRemoteUrl() {
return remoteUrl;
}
/**
*
* #param remoteUrl
* The remoteUrl
*/
public void setRemoteUrl(Object remoteUrl) {
this.remoteUrl = remoteUrl;
}
/**
*
* #return
* The size
*/
public int getSize() {
return size;
}
/**
*
* #param size
* The size
*/
public void setSize(int size) {
this.size = size;
}
/**
*
* #return
* The uploadTimestampMillis
*/
public int getUploadTimestampMillis() {
return uploadTimestampMillis;
}
/**
*
* #param uploadTimestampMillis
* The uploadTimestampMillis
*/
public void setUploadTimestampMillis(int uploadTimestampMillis) {
this.uploadTimestampMillis = uploadTimestampMillis;
}
/**
*
* #return
* The url
*/
public String getUrl() {
return url;
}
/**
*
* #param url
* The url
*/
public void setUrl(String url) {
this.url = url;
}
/**
*
* #return
* The videoCodec
*/
public String getVideoCodec() {
return videoCodec;
}
/**
*
* #param videoCodec
* The videoCodec
*/
public void setVideoCodec(String videoCodec) {
this.videoCodec = videoCodec;
}
/**
*
* #return
* The videoContainer
*/
public String getVideoContainer() {
return videoContainer;
}
/**
*
* #param videoContainer
* The videoContainer
*/
public void setVideoContainer(String videoContainer) {
this.videoContainer = videoContainer;
}
/**
*
* #return
* The videoDuration
*/
public int getVideoDuration() {
return videoDuration;
}
/**
*
* #param videoDuration
* The videoDuration
*/
public void setVideoDuration(int videoDuration) {
this.videoDuration = videoDuration;
}
}
I have created a retrofit interface VideoInterface.class
import retrofit2.Call;
import retrofit2.http.GET;
/**
* retrofit 2 interface
*/
public interface VideoInterface {
String apiURL = ".....";
#GET(apiURL)
public Call<VideosResponse> listVideos();
}
I have created a response/parse class VideosResponse.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.ArrayList;
import java.util.List;
/**
*/
public class VideosResponse {
//initalizing the collection
List<VideoInfo> videos;
public VideosResponse() {
videos = new ArrayList<VideoInfo>();
}
//parsing the response
public static VideosResponse parseJSON(String response) {
Gson gson = new GsonBuilder().create();
VideosResponse videosResponse = gson.fromJson(response, VideosResponse.class);
return videosResponse;
}
}
UPDATED :Finally I'm calling the API , but not able to get the individual elements
I know I should be able to do something like response.body().getItem().getID().getRendition().getUrl() for example, but I don't see it in the auto complete and if I write it I get errors.
This code is in my onResume() method , the reason why I've commented out public static below is because it's not allowed within the onResume()
// Creating a simple REST adapter which points the API
// public static
final String BASE_URL = "http://api......";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
// Creating an instance of our API interface.
VideoInterface service = retrofit.create(VideoInterface.class);
Call<VideosResponse> call = service.listVideos();
call.enqueue(new Callback<VideosResponse>() {
#Override
public void onResponse(Call<VideosResponse> call, Response<VideosResponse> response) {
VideosResponse videoResponse = response.body();
}
#Override
public void onFailure(Call<VideosResponse> call, Throwable t) {
}});
Everything to the last step seems be alright (no errors), the following logs gives me:
Log.d("Videos ", response.message()); //OK
Log.d("Videos ", String.valueOf(response.isSuccess())); //TRUE
Log.d("Videos ", String.valueOf(response.code())); //200
but I'm still not able to get the strings I need. When I print the log for the response show the response VideosResponse videoResponse = response.body(); I get : VideosResponse#3b8bfaa4 , is this normal? how can I use this?
Is using parcelable advised? will it change anything?
You need to show us the json response or you can figure out on your own also. Basically the object attributes name must match the json attributes, you can debug to see whether the elements are receiving the value or not, in case they are not then add the SerializedName annotation to it. From there onwards there are two possibilities either you have an object or an array. For which you can further create a POJO or create a attribute of type List.
I know I should be able to do something like response.body().item.getID() for example
Um, no, not based on the code as I understand it.
response here would appear to be Response<VideosResponse> response
response.body() therefore would be a VideosResponse
response.body().item will fail, as VideosResponse does not have an item field
When I print the log for the response show the response VideosResponse videoResponse = response.body(); I get : VideosResponse#3b8bfaa4 , is this normal?
Yes. That is the default toString() output for a Java object that has not overridden toString(). This shows that response.body() is a VideosResponse.
I have created a response/parse class VideosResponse.java
Then you know that VideosResponse does not have anything named item. Gson does not add methods to your classes; it only populates instances of those classes, based on parsing some JSON.
If you are expecting VideosResponse to have an item field, make sure that exists in your JSON, and then edit VideosResponse to have an item field.
add a toString() to your VideoInfo class and then onResponse you can log the single object of the returned list with something like
for (VideoInfo videoInfo : videoResponses)
Log.d(LOG_TAG, "VideoInfo: " + videoInfo.toString());

Hibernate error reading data from database

I have created an application using Spring MVC 3, Hibernate and Ext Js 4. The problem is that when I start the application the data is not readed from the database.
BookController.java:
#Controller
public class BookController {
private BookService bookService;
#RequestMapping(value="/books/view.action")
public #ResponseBody Map<String,? extends Object> view(#RequestParam int start, #RequestParam int limit) throws Exception {
try{
List<Book> books = bookService.getBookList(start,limit);
int total = bookService.getTotalBooks();
return ExtJSReturn.mapOK(books, total);
} catch (Exception e) {
return ExtJSReturn.mapError("Error retrieving books from database.");
}
}
BookService.java:
#Service
public class BookService {
private BookDAO bookDAO;
/**
* Get all books
* #return
*/
#Transactional(readOnly=true)
public List<Book> getBookList(int start, int limit){
return bookDAO.getBooks(start, limit);
}
public int getTotalBooks(){
return bookDAO.getTotalBooks();
}
BookDAO.java:
#SuppressWarnings("unchecked")
public List<Book> getBooks(int start, int limit) {
DetachedCriteria criteria = DetachedCriteria.forClass(Book.class);
return hibernateTemplate.findByCriteria(criteria, start, limit);
}
public int getTotalBooks(){
return DataAccessUtils.intResult(hibernateTemplate.find("SELECT COUNT(*) FROM books"));
}
Book.java:
#JsonAutoDetect
#Entity
#Table(name="books")
public class Book {
#Id
#GeneratedValue
#Column(name="id")
private int id;
#Column(name="title", nullable=false)
private String title;
#Column(name="author", nullable=false)
private String author;
#Column(name="publisher", nullable=false)
private String publisher;
#Column(name="isbn", nullable=false)
private String isbn;
#Column(name="pages", nullable=false)
private int pages;
#Column(name="category", nullable=false)
private String category;
#Column(name="qty", nullable=false)
private int qty;
/**
* #return the title
*/
public String getTitle() {
return title;
}
/**
* #param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* #return the author
*/
public String getAuthor() {
return author;
}
/**
* #param author the author to set
*/
public void setAuthor(String author) {
this.author = author;
}
/**
* #return the publisher
*/
public String getPublisher() {
return publisher;
}
/**
* #param publisher the publisher to set
*/
public void setPublisher(String publisher) {
this.publisher = publisher;
}
/**
* #return the isbn
*/
public String getIsbn() {
return isbn;
}
/**
* #param isbn the isbn to set
*/
public void setIsbn(String isbn) {
this.isbn = isbn;
}
/**
* #return the pages
*/
public int getPages() {
return pages;
}
/**
* #param pages the pages to set
*/
public void setPages(int pages) {
this.pages = pages;
}
/**
* #return the category
*/
public String getCategory() {
return category;
}
/**
* #param category the category to set
*/
public void setCategory(String category) {
this.category = category;
}
/**
* #return the qty
*/
public int getQty() {
return qty;
}
/**
* #param qty the qty to set
*/
public void setQty(int qty) {
this.qty = qty;
}
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
}
ExtJsReturn.java:
#Component
public class ExtJSReturn {
/**
* Generates modelMap to return in the modelAndView
* #param books
* #return
*/
public static Map<String,Object> mapOK(List<Book> books){
Map<String,Object> modelMap = new HashMap<String,Object>(3);
modelMap.put("total", books.size());
modelMap.put("data", books);
modelMap.put("success", true);
return modelMap;
}
/**
* Generates modelMap to return in the modelAndView
* #param books
* #return
*/
public static Map<String,Object> mapOK(List<Book> books, int total){
Map<String,Object> modelMap = new HashMap<String,Object>(3);
modelMap.put("total", total);
modelMap.put("data", books);
modelMap.put("success", true);
return modelMap;
}
/**
* Generates modelMap to return in the modelAndView in case
* of exception
* #param msg message
* #return
*/
public static Map<String,Object> mapError(String msg){
Map<String,Object> modelMap = new HashMap<String,Object>(2);
modelMap.put("message", msg);
modelMap.put("success", false);
return modelMap;
}
}
The error is raised from the controller: Error retrieving books from database.
Do you have any ideea what can be the problem?
See here the Console output: http://pastebin.com/jMQKS31P
FIXED!!!
https://stackoverflow.com/a/14447201/1564840
You're passing a SQL request, using tables and column names, to a method which expects an HQL request, using entities, mapped fields and associations. SQL and HQL are two different query languages.
The HQL query should be
select count(book.id) from Book book
If you don't know about HQL, then you really need to read the documentation. Using Hibernate without knowing HQL is like using JDBC without knowing SQL.

org.hibernate.QueryException: could not resolve property

This is the first time that I use JPA. I write the code with Java and JPA. My code is below.
String queryStr = "SELECT m.title, b.isbn, b.authors";
queryStr += " FROM Book b, Media m";
queryStr += " WHERE m.MediaID = b.MediaID";
queryStr += " AND b.isbn = '" + isbn + "' AND m.title = '%" + title +"%'";
Query query = em.createQuery(queryStr);
From my code, Class Book extends class Media.
But I got the error which is
org.hibernate.QueryException: could not resolve property: MediaID of: mediaManagement.Media [SELECT m.title, b.isbn, b.authors FROM mediaManagement.Book b, mediaManagement.Media m WHERE m.MediaID = b.MediaID ]
This is the Media class.
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
#Table(name = "Media")
#NamedQuery(name = "findAllMedias", query = "select b from Media b")
public class Media {
#Id
#Column(name = "MediaID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int mediaID;
/**
* Getter of the property <tt>mediaID</tt>
*
* #return Returns the mediaID.
* #uml.property name="mediaID"
*/
public int getMediaID() {
return mediaID;
}
/**
* Setter of the property <tt>mediaID</tt>
*
* #param mediaID
* The mediaID to set.
* #uml.property name="mediaID"
*/
public void setMediaID(int mediaID) {
this.mediaID = mediaID;
}
/**
* #uml.property name="title"
*/
#Column(name = "title")
private String title;
/**
* Getter of the property <tt>title</tt>
*
* #return Returns the title.
* #uml.property name="title"
*/
public String getTitle() {
return title;
}
/**
* Setter of the property <tt>title</tt>
*
* #param title
* The title to set.
* #uml.property name="title"
*/
public void setTitle(String title) {
this.title = title;
}
/**
* #uml.property name="editionDate"
*/
private Calendar editionDate;
/**
* Getter of the property <tt>editionDate</tt>
*
* #return Returns the editionDate.
* #uml.property name="editionDate"
*/
public Calendar getEditionDate() {
return editionDate;
}
/**
* Setter of the property <tt>editionDate</tt>
*
* #param editionDate
* The editionDate to set.
* #uml.property name="editionDate"
*/
public void setEditionDate(Calendar editionDate) {
this.editionDate = editionDate;
}
/*
* Two medias are equal if their mediaID is the same
*/
#Override
public boolean equals(Object media) {
if (media == null)
return false;
Media b = (Media) media;
if (b.mediaID == mediaID)
return true;
return false;
}
public Media() {
};
/**
* Creates a media All parameters should be given
*
* #param title
* the title of the media
*
* #param editionDate
* date of the edition of the media
*
* #throws BadParametersException
*/
public Media(String title, Calendar editionDate)
throws BadParametersException {
if ((title == null) || (editionDate == null))
throw new BadParametersException();
this.title = title;
this.editionDate = editionDate;
}
/**
* Returns a description of the media
*/
public String toString() {
return this.title + " " + String.valueOf(this.title);
}
/**
* #uml.property name="copies"
* #uml.associationEnd multiplicity="(0 -1)" inverse="media:copyManagement.Copy"
*/
#OneToMany(mappedBy="mediaRef") protected Set<Copy> copies;
public void addCopy(Copy copy) {
copies.add(copy);
}
/**
* Getter of the property <tt>copies</tt>
* #return Returns the copies.
* #uml.property name="copies"
*/
public Set<Copy> getCopies() {
return copies;
}
/**
* Setter of the property <tt>copies</tt>
* #param editionDate The copies to set.
* #uml.property name="copies"
*/
public void setCopies(Set<Copy> copies) {
this.copies = copies;
}
And this is Book class.
#Entity
#Table(name = "Book")
#NamedQuery(name = "findAllBooks", query = "select b from Book b")
public class Book extends Media {
/**
* #uml.property name="authors"
*/
#Column(name = "authors")
private ArrayList<String> authors;
/**
* Getter of the property <tt>authors</tt>
*
* #return Returns the authors.
* #uml.property name="authors"
*/
public ArrayList<String> getAuthors() {
return authors;
}
/**
* Setter of the property <tt>authors</tt>
*
* #param authors
* The authors to set.
* #uml.property name="authors"
*/
public void setAuthors(ArrayList<String> authors) {
this.authors = authors;
}
/**
* #uml.property name="isbn"
*/
#Column(name = "isbn")
private String isbn;
/**
* Getter of the property <tt>isbn</tt>
*
* #return Returns the isbn.
* #uml.property name="isbn"
*/
public String getisbn() {
return isbn;
}
/**
* Setter of the property <tt>isbn</tt>
*
* #param isbn
* The isbn to set.
* #uml.property name="isbn"
*/
public void setisbn(String isbn) {
this.isbn = isbn;
}
public Book() {
// TODO Auto-generated constructor stub
}
public Book(String title, Calendar editionDate, ArrayList<String> authors,
String isbn) throws BadParametersException {
super(title, editionDate);
this.authors = authors;
this.isbn = isbn;
// TODO Auto-generated constructor stub
}
}
Anyone can help?
If book extends media, why are you joining with the Media table? (though it would be easier with the Book and Media classes and mappings)
Querying the "Book" object should be enough. Also perhaps "MediaId" should be "mediaId". Hibernate is case sensitive on it's property names.

Categories

Resources