How to make a JAVADOC of my program? - java

This is my code:
public class Client
{
protected int cod;
protected String name;
public void setCod(int cod) throws Exception
{
if(cod==null)
throw new Exception("Invalid code!");
this.cod = cod;
}
public int getCod()
{
return this.cod;
}
public void setName(String name) throws Exception
{
if(name==null || name.equals("")
throw new Exception("Invalid name!");
this.name = name;
}
public String getName()
{
return this.name;
}
public Client(int cod, String name) throws Exception
{
this.setCod(cod);
this.setName(name);
}
public boolean equals(Object obj)
{
if(this==obj)
return true;
if(obj==null)
return false;
if(!(obj instanceof Client))
return false;
Client client = (Client)obj;
if(this.cod!=client.cod)
return false;
if(this.name!=client.name)
return false;
return true;
}
public String toString()
{
return "Code: " + this.cod + "\n" +
"Name: " + this.name;
}
public int hashCode()
{
int ret = 444;
ret += ret*7 + new Integer (this.cod).hashCode();
ret += ret*7 + (this.name).hashCode();
return ret;
}
public Object clone()
{
Client ret = null;
try
{
ret = new Client(this);
}
catch(Exception error)
{
// this is never null
}
return ret;
}
public Client(Client model) throws Exception
{
if(model==null)
throw new Exception("Inexistent model!");
this.cod = model.cod;
this.name = model.name;
}
}
I know that, to make a comment, you'll have to put "//" or " /* " and " */ ". But how can I comment following the JAVADOC rule?
If you know how, can you copy my code and put it in your answer, with the JAVADOC? Thanks :)
And please tell me, what is a JAVADOC, and what is it for? Is there any simple way to make it?

Javadoc is a kind of comment that you use in your program, to organize it, to make the program more friendly and to create a page HTML with everything you commented, like this:
So, to create a javadoc, you'll have top put /** in place of /*.
There is types of commands that you need to know when you're creating the javadoc.
#author - who created the program
#throws - for exceptions
#param - the method parameters
#return - what the method returns
So, your code with javadoc will be like this:
/**
* #author IncredibleCoding
*/
public class Client
{
protected int cod;
protected String name;
/**
* instance the code passed
*/
public void setCod(int cod) throws Exception
{
if(cod==null)
throw new Exception("Invalid code!");
this.cod = cod;
}
/**
* #returns the code
*/
public int getCod()
{
return this.cod;
}
/**
* instance the name passed
* #param name, that is the name passed
* #throws Exception, if the name is in invalid format
*/
public void setName(String name) throws Exception
{
if(name==null || name.equals("")
throw new Exception("Invalid name!");
this.name = name;
}
/**
* #returns the name
*/
public String getName()
{
return this.name;
}
/**
* the constructor
* #param cod, that is the code passed
* #param name, that is the name passed
*/
public Client(int cod, String name) throws Exception
{
this.setCod(cod);
this.setName(name);
}
/**
* #param obj, that is the object that will be compared
* #returns true if the object is equal to this, false if the object isn't equal
*/
public boolean equals(Object obj)
{
if(this==obj)
return true;
if(obj==null)
return false;
if(!(obj instanceof Client))
return false;
Client client = (Client)obj;
if(this.cod!=client.cod)
return false;
if(this.name!=client.name)
return false;
return true;
}
/**
* returns the formatted variable like String
*/
public String toString()
{
return "Code: " + this.cod + "\n" +
"Name: " + this.name;
}
/**
* returns the hashCode of a variable
*/
public int hashCode()
{
int ret = 444;
ret += ret*7 + new Integer (this.cod).hashCode();
ret += ret*7 + (this.name).hashCode();
return ret;
}
/**
* clone the object
*/
public Object clone()
{
Client ret = null;
try
{
ret = new Client(this);
}
catch(Exception error)
{
// this is never null
}
return ret;
}
/**
* "copy" the variables
* #param model, that is the object that will be copied
* #throws Exception, if the model is inexistent
*/
public Client(Client model) throws Exception
{
if(model==null)
throw new Exception("Inexistent model!");
this.cod = model.cod;
this.name = model.name;
}
}
You should consider take a look in this ORACLE's page, this will help you too:
https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html

Related

Retrofit Error: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $ [duplicate]

This question already has answers here:
Retrofit Expected BEGIN_OBJECT but was BEGIN_ARRAY
(7 answers)
Closed 6 years ago.
Learning how to use Retrofit in my Android App, getting following error:
Please help if you can. Thank you,
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
here is my code: Please help if your able too:
public void clickButton(View view){
button = (Button) findViewById(R.id.button);
drawDate = (TextView)findViewById(R.id.drawDate);
LotteryAPI.Factory.getIstance().getLottery().enqueue(new Callback<Lottery>() {
#Override
public void onResponse(Call<Lottery> call, Response<Lottery> response) {
Log.d(TAG, "getting Draw Date");
Log.d(TAG, "Draw Date is: " + response.body().getDrawDate());
String DRAW_DATE = response.body().getDrawDate();
drawDate.setText("DRAW_DATE");
Log.d(TAG, "done setting Draw Date");
}
#Override
public void onFailure(Call<Lottery> call, Throwable t) {
Log.e("Failed", t.getMessage());
Log.d(TAG, "At onFailure - Something Failed!!");
Log.d(TAG, "error is: " + t.getCause());
}
});
}
Here is my interface:
String BASE_URL = "https://data.ny.gov/resource/h6w8-42p9.json/";
#GET("?$$app_token=xxxxxxGtxKw3s6gurSxxxxxx")
Call<Lottery> getLottery();
class Factory {
public static LotteryAPI service;
public static LotteryAPI getIstance() {
if (service == null) {
Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(BASE_URL).build();
service = retrofit.create(LotteryAPI.class);
return service;
} else {
return service;
}
}
}
Here is my POJO:
#Generated("org.jsonschema2pojo")
public class Lottery {
#SerializedName("draw_date")
#Expose
private String drawDate;
#SerializedName("mega_ball")
#Expose
private String megaBall;
#SerializedName("multiplier")
#Expose
private String multiplier;
#SerializedName("winning_numbers")
#Expose
private String winningNumbers;
/**
*
* #return
* The drawDate
*/
public String getDrawDate() {
return drawDate;
}
/**
*
* #param drawDate
* The draw_date
*/
public void setDrawDate(String drawDate) {
this.drawDate = drawDate;
}
/**
*
* #return
* The megaBall
*/
public String getMegaBall() {
return megaBall;
}
/**
*
* #param megaBall
* The mega_ball
*/
public void setMegaBall(String megaBall) {
this.megaBall = megaBall;
}
/**
*
* #return
* The multiplier
*/
public String getMultiplier() {
return multiplier;
}
/**
*
* #param multiplier
* The multiplier
*/
public void setMultiplier(String multiplier) {
this.multiplier = multiplier;
}
/**
*
* #return
* The winningNumbers
*/
public String getWinningNumbers() {
return winningNumbers;
}
/**
*
* #param winningNumbers
* The winning_numbers
*/
public void setWinningNumbers(String winningNumbers) {
this.winningNumbers = winningNumbers;
}
}
The problem is that the endpoint is returning a list of your Lottery class items and you are asking Retrofit to map the response to a single Lottery item.
Try changing Call<Lottery> getLottery(); to Call<List<Lottery>> getLottery();. You will also need to change it in your Retrofit call definition.
You should change the structure of POJO class structure, because as i can see your json string is an array which contain objects. You have to make to POJO classes:
class Lottery {
private String draw_date, mega_ball, multiplier, winning_numbers;
public Lottery() {}
public String getDraw_date() {
return draw_date;
}
public void setDraw_date(String draw_date) {
this.draw_date = draw_date;
}
public String getWinning_numbers() {
return winning_numbers;
}
public void setWinning_numbers(String winning_numbers) {
this.winning_numbers = winning_numbers;
}
public String getMega_ball() {
return mega_ball;
}
public void setMega_ball(String mega_ball) {
this.mega_ball = mega_ball;
}
public String getMultiplier() {
return multiplier;
}
public void setMultiplier(String multiplier) {
this.multiplier = multiplier;
}
}
You also have to change the following line into LotteryAPI interface from
Call<Lottery> getLottery();
to
Call<List<Lottery>> getLottery();
Then inside onResponse() callback you should iterate through the LotteryObj list
public void clickButton(View view){
button = (Button) findViewById(R.id.button);
drawDate = (TextView)findViewById(R.id.drawDate);
LotteryAPI.Factory.getIstance().getLottery().enqueue(new Callback<List<Lottery>>() {
#Override
public void onResponse(Response<List<Lottery>> response, Retrofit retrofit) {
Log.e(TAG, response.body()+"");
for (Lottery lt : response.body()) {
Log.e(TAG, lt.getDraw_date());
Log.e(TAG, lt.getMega_ball());
if (lt.getMultiplier() != null) Log.e(TAG, lt.getMultiplier());
Log.e(TAG, lt.getWinning_numbers());
}
Log.d(TAG, "getting Draw Date");
// Log.d(TAG, "Draw Date is: " + response.body().getDrawDate());
// String DRAW_DATE = response.body().getDrawDate();
drawDate.setText("DRAW_DATE");
Log.d(TAG, "done setting Draw Date");
}
#Override
public void onFailure(Throwable t) {
Log.e("Failed", t.getMessage());
Log.d(TAG, "At onFailure - Something Failed!!");
Log.d(TAG, "error is: " + t.getCause());
}
});
}

Microsoft Cognitive Speech Service - Android

I am using Microsoft Cognitive Services - Speech Recognition on an Android application. Everything works fine when the code is in my main activity, but when I want to move the part corresponding to speech recognition to a new class, it throws an error.
Here are the code samples:
In the main activity
int m_waitSeconds = 0;
MicrophoneRecognitionClient micClient = null;
FinalResponseStatus isReceivedResponse = FinalResponseStatus.NotReceived;
Boolean speechIntent = false;
SpeechRecognitionMode speechMode = SpeechRecognitionMode.ShortPhrase;
public enum FinalResponseStatus { NotReceived, OK }
/**
* Gets the primary subscription key
*/
public String getPrimaryKey() {
return this.getString(R.string.primaryKey);
}
/**
* Gets the secondary subscription key
*/
public String getSecondaryKey() {
return this.getString(R.string.secondaryKey);
}
/**
* Gets the LUIS application identifier.
* #return The LUIS application identifier.
*/
private String getLuisAppId() {
return this.getString(R.string.luisAppID);
}
/**
* Gets the LUIS subscription identifier.
* #return The LUIS subscription identifier.
*/
private String getLuisSubscriptionID() {
return this.getString(R.string.luisSubscriptionID);
}
/**
* Gets the default locale.
* #return The default locale.
*/
private String getDefaultLocale() {
return "en-us";
}
/**
* Handles the Click event of the _startButton control.
*/
private void StartButton_Click(View v) {
this.m_waitSeconds = this.speechMode == SpeechRecognitionMode.ShortPhrase ? 20 : 200;
if (this.micClient == null) {
if (this.speechIntent) {
this.WriteLine("--- Start microphone dictation with Intent detection ----");
this.micClient = SpeechRecognitionServiceFactory.createMicrophoneClientWithIntent(
this,
this.getDefaultLocale(),
this,
this.getPrimaryKey(),
this.getSecondaryKey(),
this.getLuisAppId(),
this.getLuisSubscriptionID());
}
else
{
this.micClient = SpeechRecognitionServiceFactory.createMicrophoneClient(
this,
this.speechMode,
this.getDefaultLocale(),
this,
this.getPrimaryKey(),
this.getSecondaryKey());
}
}
this.micClient.startMicAndRecognition();
}
public void onFinalResponseReceived(final RecognitionResult response) {
boolean isFinalDicationMessage = this.speechMode == SpeechRecognitionMode.LongDictation &&
(response.RecognitionStatus == RecognitionStatus.EndOfDictation ||
response.RecognitionStatus == RecognitionStatus.DictationEndSilenceTimeout);
if (null != this.micClient && ((this.speechMode == SpeechRecognitionMode.ShortPhrase) || isFinalDicationMessage)) {
// we got the final result, so it we can end the mic reco. No need to do this
// for dataReco, since we already called endAudio() on it as soon as we were done
// sending all the data.
this.micClient.endMicAndRecognition();
}
if (isFinalDicationMessage) {
this.isReceivedResponse = FinalResponseStatus.OK;
}
Confidence cMax = Confidence.Low;
int iMax = 0;
if (!isFinalDicationMessage && response.Results.length != 0) {
for (int i = 0; i < response.Results.length; i++) {
//get the text with highest confidence:
if(response.Results[i].Confidence.getValue() > cMax.getValue()){
cMax = response.Results[i].Confidence;
iMax = i;
}
}
this.WriteLine(response.Results[iMax].DisplayText);
}
}
/**
* Called when a final response is received and its intent is parsed
*/
public void onIntentReceived(final String payload) {
this.WriteLine("--- Intent received by onIntentReceived() ---");
this.WriteLine(payload);
this.WriteLine();
}
public void onPartialResponseReceived(final String response) {
this.WriteLine("--- Partial result received by onPartialResponseReceived() ---");
this.WriteLine(response);
this.WriteLine();
}
public void onError(final int errorCode, final String response) {
this.WriteLine("--- Error received by onError() ---");
this.WriteLine("Error code: " + SpeechClientStatus.fromInt(errorCode) + " " + errorCode);
this.WriteLine("Error text: " + response);
this.WriteLine();
}
/**
* Called when the microphone status has changed.
* #param recording The current recording state
*/
public void onAudioEvent(boolean recording) {
if (!recording) {
this.micClient.endMicAndRecognition();
}
}
/**
* Writes the line.
*/
private void WriteLine() {
this.WriteLine("");
}
/**
* Writes the line.
* #param text The line to write.
*/
private void WriteLine(String text) {
System.out.println(text);
}
In a separate class
public class SpeechRecognition implements ISpeechRecognitionServerEvents
{
int m_waitSeconds = 0;
private MicrophoneRecognitionClient micClient = null;
private FinalResponseStatus isReceivedResponse =FinalResponseStatus.NotReceived;
private Boolean speechIntent = false;
private SpeechRecognitionMode speechMode=SpeechRecognitionMode.ShortPhrase;
public enum FinalResponseStatus { NotReceived, OK }
/**
* Gets the primary subscription key
*/
public String getPrimaryKey() {
return Integer.toString(R.string.primaryKey);
}
/**
* Gets the secondary subscription key
*/
public String getSecondaryKey() {
return Integer.toString(R.string.secondaryKey);
}
/**
* Gets the LUIS application identifier.
* #return The LUIS application identifier.
*/
private String getLuisAppId() {
return Integer.toString(R.string.luisAppID);
}
/**
* Gets the LUIS subscription identifier.
* #return The LUIS subscription identifier.
*/
private String getLuisSubscriptionID() {
return Integer.toString(R.string.luisSubscriptionID);
}
/**
* Gets the default locale.
* #return The default locale.
*/
private String getDefaultLocale() {
return "en-us";
}
public void startSpeechRecognition() {
this.m_waitSeconds = this.speechMode == SpeechRecognitionMode.ShortPhrase ? 20 : 200;
if (this.micClient == null) {
if (this.speechIntent) {
this.micClient = SpeechRecognitionServiceFactory.createMicrophoneClientWithIntent(
this.getDefaultLocale(),
this,
this.getPrimaryKey(),
this.getSecondaryKey(),
this.getLuisAppId(),
this.getLuisSubscriptionID());
}
else
{
this.micClient = SpeechRecognitionServiceFactory.createMicrophoneClient(
this.speechMode,
this.getDefaultLocale(),
this,
this.getPrimaryKey(),
this.getSecondaryKey());
}
}
this.micClient.startMicAndRecognition();
}
public void endSpeechRecognition(){
this.micClient.endMicAndRecognition();
}
public void onFinalResponseReceived(final RecognitionResult response) {
boolean isFinalDicationMessage = this.speechMode == SpeechRecognitionMode.LongDictation &&
(response.RecognitionStatus == RecognitionStatus.EndOfDictation ||
response.RecognitionStatus == RecognitionStatus.DictationEndSilenceTimeout);
if (null != this.micClient && ((this.speechMode == SpeechRecognitionMode.ShortPhrase) || isFinalDicationMessage)) {
// we got the final result, so it we can end the mic reco. No need to do this
// for dataReco, since we already called endAudio() on it as soon as we were done
// sending all the data.
this.micClient.endMicAndRecognition();
}
if (isFinalDicationMessage) {
this.isReceivedResponse = FinalResponseStatus.OK;
}
Confidence cMax = Confidence.Low;
int iMax = 0;
if (!isFinalDicationMessage && response.Results.length != 0) {
for (int i = 0; i < response.Results.length; i++) {
//get the text with highest confidence:
if(response.Results[i].Confidence.getValue() > cMax.getValue()){
cMax = response.Results[i].Confidence;
iMax = i;
}
}
System.out.println("Action to take: " + response.Results[iMax].DisplayText);
}
}
/**
* Called when a final response is received and its intent is parsed
*/
public void onIntentReceived(final String payload) {
System.out.println("--- Intent received by onIntentReceived() ---");
System.out.println(payload);
}
public void onPartialResponseReceived(final String response) {
System.out.println("--- Partial result received by onPartialResponseReceived() ---");
System.out.println(response);
}
public void onError(final int errorCode, final String response) {
System.err.println("--- Error received by onError() ---");
System.err.println("Error code: " + SpeechClientStatus.fromInt(errorCode) + " " + errorCode);
System.err.println("Error text: " + response);
}
/**
* Called when the microphone status has changed.
* #param recording The current recording state
*/
public void onAudioEvent(boolean recording) {
System.out.println("--- Microphone status change received by onAudioEvent() ---");
System.out.println("********* Microphone status: " + recording + " *********");
if (recording) {
System.out.println("Please start speaking.");
}
if (!recording) {
this.micClient.endMicAndRecognition();
}
}
}
You can clearly see that it is basically the same code but it gives me this error in the onError function after i call this.micClient.startMicAndRecognition();
:
Error code: LoginFailed -1910505470
I solved the problem.
I was getting a wrong Primary key in this line of code:
public String getPrimaryKey() {
return Integer.toString(R.string.primaryKey);
}
It is because the primary key is too long to be read by the processor as an integer then transformed to a String. I had to get the primary key from the main activity via getString(R.string.primaryKey) then pass it as a parameter to the constructor of the SpeechRecognition class.

Hibernate gives a strange ClassCast exception (using Transformers)

This code:
#Override
public List<FactCodeDto> getAllFactsWithoutParentsAsFactDto() {
String completeQuery = FactCodeQueries.SELECT_DTO_FROM_FACT_WITH_NO_PARENTS;
Query query = createHibernateQueryForUnmappedTypeFactDto(completeQuery);
List<FactCodeDto> factDtoList = query.list(); //line 133
return factDtoList;
}
calling this method:
private Query createHibernateQueryForUnmappedTypeFactDto(String sqlQuery) throws HibernateException {
return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(Transformers.aliasToBean(FactCodeDto.class));
}
gives me a ClassCastException -> part of the trace:
Caused by: java.lang.ClassCastException: org.bamboomy.cjr.dto.FactCodeDto cannot be cast to java.util.Map
at org.hibernate.property.access.internal.PropertyAccessMapImpl$SetterImpl.set(PropertyAccessMapImpl.java:102)
at org.hibernate.transform.AliasToBeanResultTransformer.transformTuple(AliasToBeanResultTransformer.java:78)
at org.hibernate.hql.internal.HolderInstantiator.instantiate(HolderInstantiator.java:75)
at org.hibernate.loader.custom.CustomLoader.getResultList(CustomLoader.java:435)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2423)
at org.hibernate.loader.Loader.list(Loader.java:2418)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:336)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1898)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:318)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125)
at org.bamboomy.cjr.dao.factcode.FactCodeDAOImpl.getAllFactsWithoutParentsAsFactDto(FactCodeDAOImpl.java:133)
Which is pretty strange because, indeed, if you look up the source code of Hibernate it tries to do this:
#Override
#SuppressWarnings("unchecked")
public void set(Object target, Object value, SessionFactoryImplementor factory) {
( (Map) target ).put( propertyName, value ); //line 102
}
Which doesn't make any sense...
target is of type Class and this code tries to cast it to Map,
why does it try to do that???
any pointers are more than welcome...
I'm using Hibernate 5 (and am upgrading from 3)...
edit: I also use Spring (4.2.1.RELEASE; also upgrading) which calls these methods upon deploy, any debugging pointers are most welcome as well...
edit 2: (the whole FactCodeDto class, as requested)
package org.bamboomy.cjr.dto;
import org.bamboomy.cjr.model.FactCode;
import org.bamboomy.cjr.model.FactCodeType;
import org.bamboomy.cjr.utility.FullDateUtil;
import org.bamboomy.cjr.utility.Locales;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.util.Assert;
import java.util.*;
#Getter
#Setter
#ToString
public class FactCodeDto extends TreeNodeValue {
private String cdFact;
private String cdFactSuffix;
private Boolean isSupplementCode;
private Boolean isTitleCode;
private Boolean mustBeFollowed;
private Date activeFrom;
private Date activeTo;
private Boolean isCode;
private Long idFact;
private Long idParent;
private String type;
Map<Locale, String> description = new HashMap<Locale, String>(3);
public FactCodeDto() {
}
public FactCodeDto(String prefix, String suffix) {
super();
this.cdFact = prefix;
this.cdFactSuffix = suffix;
}
public FactCodeDto(String cdFact, String cdFactSuffix, Boolean isSupplementCode, Boolean mustBeFollowed) {
super();
this.cdFact = cdFact;
this.cdFactSuffix = cdFactSuffix;
this.isSupplementCode = isSupplementCode;
this.mustBeFollowed = mustBeFollowed;
}
public FactCodeDto(String cdFact, String cdFactSuffix, Boolean isSupplementCode, Boolean mustBeFollowed, Long idFact, Long idParent, Boolean isCode, Boolean isTitleCode, Date from, Date to, Map<Locale, String> descriptions,String type) {
super();
this.cdFact = cdFact;
this.cdFactSuffix = cdFactSuffix;
this.isSupplementCode = isSupplementCode;
this.mustBeFollowed = mustBeFollowed;
this.idFact = idFact;
this.idParent = idParent;
this.isCode = isCode;
this.isTitleCode = isTitleCode;
this.activeFrom = from;
this.activeTo = to;
if (descriptions != null) {
this.description = descriptions;
}
this.type = type;
}
public FactCodeDto(FactCode fc) {
this(fc.getPrefix(), fc.getSuffix(), fc.isSupplementCode(), fc.isHasMandatorySupplCodes(), fc.getId(), fc.getParent(), fc.isActualCode(), fc.isTitleCode(), fc.getActiveFrom(), fc.getActiveTo(), fc.getAllDesc(),fc.getType().getCode());
}
public String formatCode() {
return FactCode.formatCode(cdFact, cdFactSuffix);
}
public boolean isActive() {
Date now = new Date(System.currentTimeMillis());
return FullDateUtil.isBetweenDates(now, this.activeFrom, this.activeTo);
}
public void setDescFr(String s) {
description.put(Locales.FRENCH, s);
}
public void setDescNl(String s) {
description.put(Locales.DUTCH, s);
}
public void setDescDe(String s) {
description.put(Locales.GERMAN, s);
}
/**
* public String toString() {
* StringBuilder sb = new StringBuilder();
* sb.append(getIdFact() + ": ")
* .append(getIdParent() + ": ")
* .append(" " + cdFact + cdFactSuffix + ": " + (isSupplementCode ? "NO Principal " : " Principal "))
* .append((mustBeFollowed ? " Must Be Followed " : "NOT Must Be Followed "));
* return sb.toString();
* }
*/
public Map<Locale, String> getDescription() {
return description;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
String fullCode = formatCode();
result = prime * result + ((fullCode == null) ? 0 : fullCode.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
FactCodeDto other = (FactCodeDto) obj;
return formatCode().equals(other.formatCode());
}
#Override
public boolean isChildOf(TreeNodeValue value) {
Assert.notNull(value);
boolean isChild = false;
if (value instanceof FactCodeDto) {
if (this.getIdParent() != null) {
isChild = this.getIdParent().equals(((FactCodeDto) value).getIdFact());
}
}
return isChild;
}
#Override
public boolean isBrotherOf(TreeNodeValue value) {
Assert.notNull(value);
boolean isBrother = false;
if (value instanceof FactCodeDto) {
if (this.getIdParent() != null) {
isBrother = this.getIdParent().equals(((FactCodeDto) value).getIdParent());
}
}
return isBrother;
}
#Override
public boolean isParentOf(TreeNodeValue value) {
Assert.notNull(value);
boolean isParent = false;
if (value instanceof FactCodeDto) {
isParent = this.getIdFact().equals(((FactCodeDto) value).getIdParent());
}
return isParent;
}
#Override
public int compareTo(TreeNodeValue to) {
if (to instanceof FactCodeDto) {
return formatCode().compareTo(((FactCodeDto) to).formatCode());
} else return 1;
}
public String getCode() {
return formatCode();
}
}
I found that AliasToBean has changed in Hibernate 5. For me adding getter for my field fixed the problem.
This exception occurs when the setters and getters are not mapped correctly to the column names.
Make sure you have the correct getters and setters for the query(Correct names and correct datatypes).
Read more about it here:
http://javahonk.com/java-lang-classcastexception-com-wfs-otc-datamodels-imagineexpirymodel-cannot-cast-java-util-map/
I do some investigation on this question. The problem is that Hibernate converts aliases for column names to upper case — cdFact becomesCDFACT.
Read for a more deeply explanation and workaround here:
mapping Hibernate query results to custom class?
In the end it wasn't so hard to find a solution,
I just created my own (custom) ResultTransformer and specified that in the setResultTransformer method:
private Query createHibernateQueryForUnmappedTypeFactDto(String sqlQuery) throws HibernateException {
return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(new FactCodeDtoResultTransformer());
//return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(Transformers.aliasToBean(FactCodeDto.class));
}
the code of the custom result transformer:
package org.bamboomy.cjr.dao.factcode;
import org.bamboomy.cjr.dto.FactCodeDto;
import java.util.Date;
import java.util.List;
/**
* Created by a162299 on 3-11-2015.
*/
public class FactCodeDtoResultTransformer implements org.hibernate.transform.ResultTransformer {
#Override
public Object transformTuple(Object[] objects, String[] strings) {
FactCodeDto result = new FactCodeDto();
for (int i = 0; i < objects.length; i++) {
setField(result, strings[i], objects[i]);
}
return result;
}
private void setField(FactCodeDto result, String string, Object object) {
if (string.equalsIgnoreCase("cdFact")) {
result.setCdFact((String) object);
} else if (string.equalsIgnoreCase("cdFactSuffix")) {
result.setCdFactSuffix((String) object);
} else if (string.equalsIgnoreCase("isSupplementCode")) {
result.setIsSupplementCode((Boolean) object);
} else if (string.equalsIgnoreCase("isTitleCode")) {
result.setIsTitleCode((Boolean) object);
} else if (string.equalsIgnoreCase("mustBeFollowed")) {
result.setMustBeFollowed((Boolean) object);
} else if (string.equalsIgnoreCase("activeFrom")) {
result.setActiveFrom((Date) object);
} else if (string.equalsIgnoreCase("activeTo")) {
result.setActiveTo((Date) object);
} else if (string.equalsIgnoreCase("descFr")) {
result.setDescFr((String) object);
} else if (string.equalsIgnoreCase("descNl")) {
result.setDescNl((String) object);
} else if (string.equalsIgnoreCase("descDe")) {
result.setDescDe((String) object);
} else if (string.equalsIgnoreCase("type")) {
result.setType((String) object);
} else if (string.equalsIgnoreCase("idFact")) {
result.setIdFact((Long) object);
} else if (string.equalsIgnoreCase("idParent")) {
result.setIdParent((Long) object);
} else if (string.equalsIgnoreCase("isCode")) {
result.setIsCode((Boolean) object);
} else {
throw new RuntimeException("unknown field");
}
}
#Override
public List transformList(List list) {
return list;
}
}
in hibernate 3 you could set Aliasses to queries but you can't do that anymore in hibernate 5 (correct me if I'm wrong) hence the aliasToBean is something you only can use when actually using aliasses; which I didn't, hence the exception.
Im my case :
=> write sql query and try to map result to Class List
=> Use "Transformers.aliasToBean"
=> get Error "cannot be cast to java.util.Map"
Solution :
=> just put \" before and after query aliases
ex:
"select first_name as \"firstName\" from test"
The problem is that Hibernate converts aliases for column names to upper case or lower case
I solved it by defining my own custom transformer as given below -
import org.hibernate.transform.BasicTransformerAdapter;
public class FluentHibernateResultTransformer extends BasicTransformerAdapter {
private static final long serialVersionUID = 6825154815776629666L;
private final Class<?> resultClass;
private NestedSetter[] setters;
public FluentHibernateResultTransformer(Class<?> resultClass) {
this.resultClass = resultClass;
}
#Override
public Object transformTuple(Object[] tuple, String[] aliases) {
createCachedSetters(resultClass, aliases);
Object result = ClassUtils.newInstance(resultClass);
for (int i = 0; i < aliases.length; i++) {
setters[i].set(result, tuple[i]);
}
return result;
}
private void createCachedSetters(Class<?> resultClass, String[] aliases) {
if (setters == null) {
setters = createSetters(resultClass, aliases);
}
}
private static NestedSetter[] createSetters(Class<?> resultClass, String[] aliases) {
NestedSetter[] result = new NestedSetter[aliases.length];
for (int i = 0; i < aliases.length; i++) {
result[i] = NestedSetter.create(resultClass, aliases[i]);
}
return result;
}
}
And used this way inside the repository method -
#Override
public List<WalletVO> getWalletRelatedData(WalletRequest walletRequest,
Set<String> requiredVariablesSet) throws GenericBusinessException {
String query = getWalletQuery(requiredVariablesSet);
try {
if (query != null && !query.isEmpty()) {
SQLQuery sqlQuery = mEntityManager.unwrap(Session.class).createSQLQuery(query);
return sqlQuery.setResultTransformer(new FluentHibernateResultTransformer(WalletVO.class))
.list();
}
} catch (Exception ex) {
exceptionThrower.throwDatabaseException(null, false);
}
return Collections.emptyList();
}
It worked perfectly !!!
Try putting Column names and field names both in capital letters.
This exception occurs when the class that you specified in the AliasToBeanResultTransformer does not have getter for the corresponding columns. Although the exception details from the hibernate are misleading.

Table info to an ArrayList

I have created an sql database with a table containing information about Airplanes, I want to be able to take this information and insert it into an ArrayList of type Aircraft(object) although the different info in the sql table are different primitive types........can this be done?`package uk.ac.qub.sqldbflights;
This is the Aircraft object with all the attributes which are the
public class Aircraft {
/**
* private String containing the airline name of the aircraft
* -Can't be blank
*/
private int aircraft_number;
/**
* private String containing the flight number belonging to the aircraft
* -Can't be blank
*/
private String airline_company;
/**
* private String containing the aircrafts city of origin
* -Can't be blank
*/
private String departure_airport;
/**
* private int which holds the aircrafts fuel level
* -Must be over 0 and less than 100
*/
private float passenger_number;
/**
* private int containing the number of passengers aboard the aircraft
* -Must be over 0 and less than 300
*/
private float fuel_percentage;
/**
* private Boolean indicting wether the aircraft is in the landing queue or not
*/
private int flight_time_remaining;
/**
* private Boolean indicating wether the aircraft is landed or not
*/
private boolean in_queue;
private boolean is_landed;
public Aircraft() {
}
/**
* Song creation
* #param name -not null
* #param artist -not null
* #param album -not null
* #param genre- not null and one of Pop, Dance, Rock
* #throws IllegalArgumentException
*/
public Aircraft(int aircraft_number, String airline_company, String departure_airport, int passenger_number, float fuel_percentage, int flight_time_remaining, boolean in_queue, boolean is_landed)
throws IllegalArgumentException {
try {
// set name
this.setAircraft_number(aircraft_number);
this.setAirline_company(airline_company);
this.setDeparture_airport(departure_airport);
this.setPassenger_number(passenger_number);
this.setFuel_percentage(fuel_percentage);
this.setFlight_time_remaining(flight_time_remaining);
this.setIn_queue(in_queue);
this.setIs_landed(is_landed);
} catch (IllegalArgumentException ex) {
System.out.println("Unable to create song due to arguments passed");
throw ex;
}}
public int getAircraft_number() {
return aircraft_number;
}
public void setAircraft_number(int aircraft_number) {
this.aircraft_number = aircraft_number;
}
public String getAirline_company() {
return airline_company;
}
public void setAirline_company(String airline_company) {
this.airline_company = airline_company;
}
public String getDeparture_airport() {
return departure_airport;
}
public void setDeparture_airport(String departure_airport) {
this.departure_airport = departure_airport;
}
public float getPassenger_number() {
return passenger_number;
}
public void setPassenger_number(float passenger_number) {
this.passenger_number = passenger_number;
}
public float getFuel_percentage() {
return fuel_percentage;
}
public void setFuel_percentage(float fuel_percentage) {
this.fuel_percentage = fuel_percentage;
}
public int isFlight_time_remaining() {
return flight_time_remaining;
}
public void setFlight_time_remaining(int flight_time_remaining) {
this.flight_time_remaining = flight_time_remaining;
}
public boolean isIn_queue() {
return in_queue;
}
public void setIn_queue(boolean in_queue) {
this.in_queue = in_queue;
}
public boolean isIs_landed() {
return is_landed;
}
public void setIs_landed(boolean is_landed) {
this.is_landed = is_landed;
}
}
This is the code which makes the connection to the sql DB and trys to add the info to an arraylist...
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class FlightsDbtoArrayList {
ArrayList<Aircraft> allFlights = new ArrayList<Aircraft>();
public static void main(String[] args) {
// Entering username to verify connection to SQL Server
String url = "jdbc:mysql://";
Connection con;
Statement statement1;
try {
Class.forName("com.mysql.jdbc.Driver");
//Catching any errors and printing a message to the user
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
// Entering username and password to verify connection to SQL Server
con = DriverManager.getConnection(url);
//Creating platform for a SQL query Statement
statement1 = con.createStatement();
//Creating and executing the designed SQL query statement
ResultSet results1 = statement1.executeQuery("SELECT aircraft_number, airline_company, departure_airport, passenger_number, fuel_Percentage, flight_time_remaining, in_queue, is_landed FROM flights");
//Displaying the results of the query to screen
printResults(results1);
con.close();
statement1.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
/**
* Method to display the results of the three SQL queries
* #param results
* #throws SQLException
*
*
*/
public ArrayList<Aircraft> allFlights() {
return allFlights;
}
/**
* set songs on the system
* #param allSongs
*/
public void setSongs(ArrayList<Aircraft> allSongs) {
allSongs = this.allFlights;
}
private static void printResults(ResultSet results) throws SQLException {
while (results.next()) {
int aircraft_number = results.getInt("aircraft_number");
String airline_company = results.getString("airline_company");
String departure_airport = results.getString("departure_airport");
int passenger_number = results.getInt("passenger_number");
float fuel_percentage = results.getFloat("fuel_percentage");
int flight_time_remaining = results.getInt("flight_time_remaining");
boolean in_queue = results.getBoolean("in_queue");
boolean is_landed = results.getBoolean("is_landed");
Aircraft a1;
ArrayList<Aircraft> allFlights = new ArrayList<Aircraft>();
a1 = new Aircraft(aircraft_number, airline_company, departure_airport, passenger_number, fuel_percentage, flight_time_remaining, in_queue, is_landed);
allFlights.add(a1);
System.out.println(allFlights);
}
}
}
`
Yes it is definitely possible to have list of objects(Aircraft) derived from database. But in this case your while loop inside the PrintResult has some errors.
You are creating list allFights within the while loop which will create new list in each iteration and add a1 to it so in the end you will only have a list with one aircraft details in it.
System.out.println(allFlights) will not give much desired output (or it might), but I would advice you should override toString() method in your AirCraft class.
Try to change your PrintResult method as following.
private static void printResults(ResultSet results) throws SQLException {
ArrayList<Aircraft> allFlights = new ArrayList<Aircraft>();
Aircraft a1;
while (results.next()) {
int aircraft_number = results.getInt("aircraft_number");
String airline_company = results.getString("airline_company");
String departure_airport = results.getString("departure_airport");
int passenger_number = results.getInt("passenger_number");
float fuel_percentage = results.getFloat("fuel_percentage");
int flight_time_remaining = results.getInt("flight_time_remaining");
boolean in_queue = results.getBoolean("in_queue");
boolean is_landed = results.getBoolean("is_landed");
a1 = new Aircraft(aircraft_number, airline_company, departure_airport, passenger_number, fuel_percentage, flight_time_remaining, in_queue, is_landed);
allFlights.add(a1);
//Instead of this line System.out.println(allFlights);
//write following code
For(AirCraft aircraft : allFlights){
System.out.println(aircraft.toString());
}
}
}
Edit 2: Write the following method in your AirCraft class.
#Override
Public String toString(){
String string;
//Write some code here so that you can represent you object using this method
//for example I am adding just the aircraft_number
string = getAircraft_number()+"";
return string;
}
Important: The toString() method I wrote is just an example you need to learn how to correctly write toString() method for any of your class. this and this are good starting point to learn that. And stop worrying about your your list of allFlights because as per this code it is getting created but you can not print it the way you are trying to.

Gson throws MalformedJsonException, and other Exceptions

I tried to save data to json string in a txt file using Gson and then restore it using Gson either. Things go well if I do it in eclipse. But when packaged to jar, Gson throws Exceptions.
Here is the code for saving the file.
String gsonStr = gson.toJson(masterShips); // masterShips is ArrayList<Ship>
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("D:\\master_ship.txt"));
writer.write(gsonStr);
} catch (IOException e) {
System.err.println(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
Then I read the file in eclipse using this code (and it works):
Scanner in = new Scanner(new FileReader("D:\\master_ship.txt"));
String str = in.nextLine();
Log.toDebug(str);
in.close();
JsonParser parser = new JsonParser();
JsonElement je = parser.parse(str);
JsonArray ja = je.getAsJsonArray();
for (int i=0; i<ja.size(); ++i) {
...
}
But after packaged into jar and run in cmd, Exception occurs:
Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.
stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malform
ed JSON at line 1 column 4
at com.google.gson.JsonParser.parse(JsonParser.java:65)
at com.google.gson.JsonParser.parse(JsonParser.java:45)
at kan.util.Master.loadMasterShip(Master.java:44)
at kan.util.Master.load(Master.java:27)
at kan.Main.main(Main.java:22)
Caused by: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLeni
ent(true) to accept malformed JSON at line 1 column 4
at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1505)
at com.google.gson.stream.JsonReader.checkLenient(JsonReader.java:1386)
at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:531)
at com.google.gson.stream.JsonReader.peek(JsonReader.java:414)
at com.google.gson.JsonParser.parse(JsonParser.java:60)
... 4 more
According to the hint of the Exception, I changed my code and it still works in eclipse:
Scanner in = new Scanner(new FileReader("D:\\master_ship.txt"));
String str = in.nextLine();
in.close();
Reader reader = new StringReader(str);
JsonReader jr = new JsonReader(reader);
jr.setLenient(true);
JsonParser parser = new JsonParser();
JsonElement je = parser.parse(jr);
JsonArray ja = je.getAsJsonArray();
for (int i=0; i<ja.size(); ++i) {
...
}
But jar failed and throws
Exception in thread "main" java.lang.IllegalStateException: This is not a JSON A
rray.
at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:106)
at kan.util.Master.loadMasterShip(Master.java:58)
at kan.util.Master.load(Master.java:30)
at kan.Main.main(Main.java:22)
As suggested by Sotirios I cut the length of the arraylist down, and when I increase the number of ships to 4, things go wrong. Here is the json:
[{"id":1,"name":"睦月","type":2,"rank":2,"fuelMax":15,"bulletMax":15,"slotNum":2,"speed":10,"afterLv":20,"afterId":254,"range":1,"powerups":[1,1,0,0]},{"id":2,"name":"如月","type":2,"rank":1,"fuelMax":15,"bulletMax":15,"slotNum":2,"speed":10,"afterLv":20,"afterId":255,"range":1,"powerups":[0,1,0,0]},{"id":6,"name":"長月","type":2,"rank":1,"fuelMax":15,"bulletMax":15,"slotNum":2,"speed":10,"afterLv":20,"afterId":258,"range":1,"powerups":[0,1,0,0]},{"id":7,"name":"三日月","type":2,"rank":1,"fuelMax":15,"bulletMax":15,"slotNum":2,"speed":10,"afterLv":20,"afterId":260,"range":1,"powerups":[0,1,0,0]}]
↑ colunm 473
Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.
stream.MalformedJsonException: Unterminated object at line 1 column 473
at com.google.gson.internal.Streams.parse(Streams.java:56)
at com.google.gson.JsonParser.parse(JsonParser.java:84)
at kan.util.Master.loadMasterShip(Master.java:55)
at kan.util.Master.load(Master.java:30)
at kan.Main.main(Main.java:22)
Caused by: com.google.gson.stream.MalformedJsonException: Unterminated object at
line 1 column 473
at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1505)
at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:480)
at com.google.gson.stream.JsonReader.hasNext(JsonReader.java:403)
at com.google.gson.internal.bind.TypeAdapters$25.read(TypeAdapters.java:
666)
at com.google.gson.internal.bind.TypeAdapters$25.read(TypeAdapters.java:
659)
at com.google.gson.internal.bind.TypeAdapters$25.read(TypeAdapters.java:
642)
at com.google.gson.internal.Streams.parse(Streams.java:44)
... 4 more
Can anyone help me with this, you will be reaally preciated!
Use this class
import java.util.List;
public class GsonResponse
{
public int id;
public String name;
public int type;
public int rank;
public int fuelMax;
public int bulletMax;
public int slotNum;
public int speed;
public int afterLv;
public int afterId;
public int range;
public List<Integer> powerups;
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the type
*/
public int getType() {
return type;
}
/**
* #param type the type to set
*/
public void setType(int type) {
this.type = type;
}
/**
* #return the rank
*/
public int getRank() {
return rank;
}
/**
* #param rank the rank to set
*/
public void setRank(int rank) {
this.rank = rank;
}
/**
* #return the fuelMax
*/
public int getFuelMax() {
return fuelMax;
}
/**
* #param fuelMax the fuelMax to set
*/
public void setFuelMax(int fuelMax) {
this.fuelMax = fuelMax;
}
/**
* #return the bulletMax
*/
public int getBulletMax() {
return bulletMax;
}
/**
* #param bulletMax the bulletMax to set
*/
public void setBulletMax(int bulletMax) {
this.bulletMax = bulletMax;
}
/**
* #return the slotNum
*/
public int getSlotNum() {
return slotNum;
}
/**
* #param slotNum the slotNum to set
*/
public void setSlotNum(int slotNum) {
this.slotNum = slotNum;
}
/**
* #return the speed
*/
public int getSpeed() {
return speed;
}
/**
* #param speed the speed to set
*/
public void setSpeed(int speed) {
this.speed = speed;
}
/**
* #return the afterLv
*/
public int getAfterLv() {
return afterLv;
}
/**
* #param afterLv the afterLv to set
*/
public void setAfterLv(int afterLv) {
this.afterLv = afterLv;
}
/**
* #return the afterId
*/
public int getAfterId() {
return afterId;
}
/**
* #param afterId the afterId to set
*/
public void setAfterId(int afterId) {
this.afterId = afterId;
}
/**
* #return the range
*/
public int getRange() {
return range;
}
/**
* #param range the range to set
*/
public void setRange(int range) {
this.range = range;
}
/**
* #return the powerups
*/
public List<Integer> getPowerups() {
return powerups;
}
/**
* #param powerups the powerups to set
*/
public void setPowerups(List<Integer> powerups) {
this.powerups = powerups;
}
}
just add below code where u parse
String strJson = "[{\"id\":1,\"name\":\"睦月\",\"type\":2,\"rank\":2,\"fuelMax\":15,\"bulletMax\":15,\"slotNum\":2,\"speed\":10,\"afterLv\":20,\"afterId\":254,\"range\":1,\"powerups\":[1,1,0,0]},{\"id\":2,\"name\":\"如月\",\"type\":2,\"rank\":1,\"fuelMax\":15,\"bulletMax\":15,\"slotNum\":2,\"speed\":10,\"afterLv\":20,\"afterId\":255,\"range\":1,\"powerups\":[0,1,0,0]},{\"id\":6,\"name\":\"長月\",\"type\":2,\"rank\":1,\"fuelMax\":15,\"bulletMax\":15,\"slotNum\":2,\"speed\":10,\"afterLv\":20,\"afterId\":258,\"range\":1,\"powerups\":[0,1,0,0]},{\"id\":7,\"name\":\"三日月\",\"type\":2,\"rank\":1,\"fuelMax\":15,\"bulletMax\":15,\"slotNum\":2,\"speed\":10,\"afterLv\":20,\"afterId\":260,\"range\":1,\"powerups\":[0,1,0,0]}]";
GsonResponse gsonResponse = null;
try {
gsonResponse = new Gson().fromJson(strJson,
GsonResponse.class);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

Categories