Unable to cover List<Tuple> in JUnit Test case - java

In my code i have used List < Tuple > to capture the query results by joining various
tables and mapping to DTO object. This code works fine in the main. But
when i try to create a test case, i'm unable to cover the List < Tuple > code.
Please provide your inputs.
For Ex :
#SuppressWarnings("unchecked")
private List<FeedbackDTO> getList(String sortingProperty, String direction, UUID workflowId, UUID categoryId,
String type) {
StringBuilder query = new StringBuilder(
"select feedback.id, feedback.workflowId, user.userName, user.firstName, "
+ "user.lastName, feedback.submittedDate, country.countryName, "
+ "region.regionName, feedback.comments, feedback.ratings, feedback.acknowledged "
+ "from Feedback feedback, User user, Country country, Region region "
+ "where feedback.userId = user.id and user.countryId = country.id and user.regionId = region.id "
+ "and feedback.workflowId = " + "'" + workflowId + "'" + " and feedback.categoryId = " + "'"
+ categoryId + "'" + " and feedback.type = " + "'" + type + "'" + " order by ");
if (sortingProperty.equalsIgnoreCase("firstName")) {
query.append("user.firstName ");
}
query.append(direction);
Query queryList = entityManager.createNativeQuery(query.toString(), Tuple.class);
List<Tuple> tupleList = queryList.getResultList();
List<FeedbackDTO> feedbackList = new ArrayList<FeedbackDTO>();
for (Tuple tuple : tupleList) {
FeedbackDTO feedbackDTO = new FeedbackDTO();
feedbackDTO.setId(UUID.fromString((String) tuple.get("id")));
feedbackDTO.setUserName((String) tuple.get("userName"));
feedbackDTO.setFirstName((String) tuple.get("firstName"));
feedbackDTO.setLastName((String) tuple.get("lastName"));
feedbackDTO.setCountryName((String) tuple.get("countryName"));
feedbackDTO.setAcknowledged((Boolean) tuple.get("acknowledged"));
feedbackDTO.setRegionName((String) tuple.get("regionName"));
feedbackDTO.setComments((String) tuple.get("comments"));
feedbackDTO.setSubmittedDate((Date) tuple.get("submittedDate"));
feedbackDTO.setRatings((Double) tuple.get("ratings"));
feedbackList.add(feedbackDTO);
}
return feedbackList;
}
In My Test Case:
#Test
public void testGetFeedbackListNoFeedback() {
try {
Query queryList = mock(Query.class);
FeedbackTestDTO feedback = new FeedbackTestDTO();
feedback.setId(id);
feedback.setSolutionId(solutionId);
feedback.setComments("Please swich-on the power");
feedback.setType("Alternate Solution");
List<Object> tupleList = new ArrayList<>();
tupleList.add(feedback);
StringBuilder query = new StringBuilder(
"select * from feedback order by user.firstName ASC");
Sort sort = new Sort("firstName:ASC");
Pageable pageable = PageRequest.of(0, 20, sort);
when(entityManager.createNativeQuery(query.toString(), javax.persistence.Tuple.class)).thenReturn(queryList);
when(queryList.getResultList()).thenReturn(tupleList);
this.mockFeedbackListDTO = feedbackServiceImpl.getFeedbackList(workflowId, categoryId, "", "",
"2019-08-29T01:00:00Z", "2019-08-29T13:00:00Z", "5", pageable, true);
assertEquals(201, this.mockFeedbackListDTO.getCode());
} catch (BusinessException | ParseException be) {
assertEquals("No feedback from users", accessor.getMessage(be.getLocalizedMessage()));
}
}

List<Tuple> tupleList = new ArrayList<>();
NativeQueryTupleTransformer nativeQueryTupleTransformer = new NativeQueryTupleTransformer();
tupleList.add((Tuple)nativeQueryTupleTransformer.transformTuple(new BigDecimal[]{new BigDecimal(123),new BigDecimal(123),new BigDecimal(123)},new String[]{"0","1","2"} ));
tupleList.add((Tuple)nativeQueryTupleTransformer.transformTuple(new BigDecimal[]{new BigDecimal(123),new BigDecimal(123),new BigDecimal(123)},new String[]{"0","1","2"} ));
tupleList.add((Tuple)nativeQueryTupleTransformer.transformTuple(new BigDecimal[]{new BigDecimal(123),new BigDecimal(123),new BigDecimal(123)},new String[]{"0","1","2"} ));
Mockito.when(service.getRecordRangeForPagination(Mockito.anyString(),Mockit.anyLong(),Mockito.anyString())).thenReturn(tupleList);

It looks like your list is empty, therefore your for-loop is never examined.
Add an assertion that the expected size of the list should be of size 3:
List<Tuple> tupleResults = queryResults.getResultList();
// Check that the list is of size 3
Assert.assertTrue(tupleResults.size() == 3);
for(Tuple t : tupleResults) {
myDtoObject.setName(t.get("name")); //0
myDtoObject.setAge(t.get("age")); //1
myDtoObject.setSalary(t.get("salary"); //2
}
#Test
public void test() {
Query query = mock(Query.class);
List<Tuple> tupleList = new ArrayList<>();
when(query.getResultList().size() > 0).thenReturn(tupleList );
}

Related

How to read from a SQL with multiple fields from Native SQL

First of all, apologize for my grammatical errors. My English level is not good.
I'm trying to read multiple fields that will be columns in a table. But I don't know how do it. Because, I've tried using a loop from getResultList() from query.
I'm using spring boot (jpa + hibernate) with postgsql.
The idea is instead of next code:
public List<Object> readTable(String nameTable) {
String SQL_COLUMN_TABLE_ID = "SELECT table_id FROM " + nameTable + " ORDER BY table_id asc;";
String SQL_COLUMN_GEOM = "SELECT GeometryType(geom) FROM " + nameTable + " ORDER BY table_id asc;";
String SQL_COLUMN_PROPERTIES = "SELECT CAST(properties AS text) FROM " + nameTable + " ORDER BY table_id asc;";
List<String> table_id = executeSQLReadTable(SQL_COLUMN_TABLE_ID);
List<String> geom_type = executeSQLReadTable(SQL_COLUMN_GEOM);
List<String> properties = executeSQLReadTable(SQL_COLUMN_PROPERTIES);
List<Object> results = new ArrayList<>();
for (int i=0; i<table_id.size(); i++) {
List<Object> item = new ArrayList<>();
item.add(table_id.get(i));
item.add(geom_type.get(i));
item.add(properties.get(i));
results.add(item);
}
return results;
}
To use this:
public List<String> readPerfectTable(String nameTable) {
String SQL = "SELECT table_id, CAST(properties AS text), GeometryType(geom) FROM " + nameTable + " ORDER BY table_id asc;";
return executeSQLReadTable(SQL);
}
In this part, I do not know how to use the results of multiple fields from select:
private List<String> executeSQLReadTable(String SQL) {
List<String> results = new ArrayList<>();
try {
Query query = em.createNativeQuery(SQL);
List<?> list = query.getResultList();
for (Object item : list) {
// Here WTF!
results.add(item.toString());
}
} catch(Throwable e) {
throw e;
} finally {
em.close();
}
return results;
}
I solved :D
Thanks a lot :D
private List<Object> executeSQLReadTable(String SQL) {
List<Object> results = new ArrayList<>();
try {
Query query = em.createNativeQuery(SQL);
List<?> result = query.getResultList();
Iterator<?> itr = result.iterator();
while(itr.hasNext()){
Object[] obj = (Object[]) itr.next();
List<Object> row = new ArrayList<>();
row.add(Long.parseLong(String.valueOf(obj[0])));
row.add(String.valueOf(obj[1]));
row.add(String.valueOf(obj[2]));
results.add(row);
}
} catch(Throwable e) {
throw e;
} finally {
em.close();
}
return results;
}

how to cast the result to String From Native Query in Java?

i have a query which will return single record with 2 columns from Table
i want to get the result to a List each element hold a column value , but i keep getting ClassCastExceptoion
this is the code :
public List<String> getStatus(Long requestId) {
List result = new ArrayList();
if (requestId != null)
{
StringBuilder querySBuilder = new StringBuilder();
querySBuilder.append(" select R.request_status_id , L.request_status_desc ");
querySBuilder.append(" from Table1 R join Table2 L ");
querySBuilder.append(" on R.request_status_id = L.REQUEST_STATUS_Id ");
querySBuilder.append(" where R.REQUEST_ID = " + requestId);
System.out.print(querySBuilder.toString());
List resultList =
em.createNativeQuery(querySBuilder.toString()).getResultList();
Vector resultVec = (Vector)resultList.get(0);
int id = ((BigDecimal)resultVec.elementAt(0)).intValue();
String statusName = ((String)resultVec.elementAt(0));
System.out.println("id" + id);
System.out.println("name " + statusName);
result.add(id);
result.add(statusName);
if (resultVec == null || resultVec.isEmpty()) {
return new ArrayList<String>();
}
return result;
}
return null;
}
The pattern I would use would be to phrase the incoming native result set as a List<Object[]>, where each object array represents a single record:
Query q = em.createNativeQuery(querySBuilder.toString());
List<Object[]> result = q.getResultList();
for (Object[] row : result) {
int id = (Integer)row[0];
String statusName = (String)row[1];
// do something with the id and statusName from above
}
I think it is a typo.
String statusName = ((String)resultVec.elementAt(0));
The elementAt(1) should be used instead of elementAt(0).

Performance tuning for JavaRDD function

I want to convert dataframe to Array of Json using Java and Spark version 1.6, for which am converting the data from
Dataframe -> Json -> RDD -> Array
where the data looks like this.
[
{
"prtdy_pgm_x":"P818_C",
"prtdy_pgm_x":"P818",
"prtdy_attr_c":"Cost",
"prtdy_integer_r":0,
"prtdy_cds_d":"prxm",
"prtdy_created_s":"2018-05-12 04:12:19.0",
"prtdy_created_by_c":"brq",
"prtdy_create_proc_x":"w_pprtdy_security_t",
"snapshot_d":"2018-05-12-000018"
},
{
"prtdy_pgm_x":"P818_I",
"prtdy_pgm_x":"P818",
"prtdy_attr_c":"Tooling",
"prtdy_integer_r":0,
"prtdy_cds_d":"prxm",
"prtdy_created_s":"2018-05-12 04:12:20.0",
"prtdy_created_by_c":"brq",
"prtdy_create_proc_x":"w_pprtdy_security_t",
"snapshot_d":"2018-05-12-000018"
},
{
"prtdy_pgm_x":"P818_W",
"prtdy_pgm_x":"P818",
"prtdy_attr_c":"Weight",
"prtdy_integer_r":0,
"prtdy_cds_d":"prxm",
"prtdy_created_s":"2018-05-12 04:12:20.0",
"prtdy_created_by_c":"brq",
"prtdy_create_proc_x":"w_pprtdy_security_t",
"snapshot_d":"2018-05-12-000018"
},
......
]
so I wrote my code something like this.
if(cmnTableNames != null && cmnTableNames.length > 0)
{
for(int i=0; i < cmnTableNames.length; i++)
{
String cmnTableName = cmnTableNames[i];
DataFrame cmnTableContent = null;
if(cmnTableName.contains("PTR_security_t"))
{
cmnTableContent = hiveContext.sql("SELECT * FROM " + cmnTableName + " where fbrn04_snapshot_d = '" + snapshotId + "'");
}
else
{
cmnTableContent = hiveContext.sql("SELECT * FROM " + cmnTableName);
}
String cmnTable = cmnTableName.substring(cmnTableName.lastIndexOf(".") + 1);
if (cmnTableContent.count() > 0)
{
String cmnStgTblDir = hdfsPath + "/staging/" + rptName + "/common/" + cmnTable;
JavaRDD<String> cmnTblCntJson = cmnTableContent.toJSON().toJavaRDD();
String result = cmnTblCntJson.reduce((ob1, ob2) -> (String)ob1+","+(String)ob2); //This Part, takes more time than usual contains large set of data.
String output = "["+result+"]";
ArrayList<String> outputList = new ArrayList<String>();
outputList.add(output);
JavaRDD<String> finalOutputRDD = sc.parallelize(outputList);
String cmnStgMrgdDir = cmnStgTblDir + "/mergedfile";
if(dfs.exists(new Path(cmnStgTblDir + "/mergedfile"))) dfs.delete(new Path(cmnStgTblDir + "/mergedfile"), true);
finalOutputRDD.coalesce(1).saveAsTextFile(cmnStgMrgdDir, GzipCodec.class);
fileStatus = dfs.getFileStatus(new Path(cmnStgMrgdDir + "/part-00000.gz"));
dfs.setPermission(fileStatus.getPath(),FsPermission.createImmutable((short) 0770));
dfs.rename(new Path(cmnStgMrgdDir + "/part-00000.gz"), new Path(CommonPath + "/" + cmnTable + ".json.gz"));
}
else
{
System.out.println("There are no records in " + cmnTableName);
}
}
}
else
{
System.out.println("The common table lists are null.");
}
sc.stop();
but while reduce function is applied it's taking more time
JavaRDD<String> cmnTblCntJson = cmnTableContent.toJSON().toJavaRDD();
String result = cmnTblCntJson.reduce((ob1, ob2) -> (String)ob1+","+(String)ob2); //This Part, takes more time than usual contains large set of data.
the table with the partition "PTR_security_t" is huge and takes a lot of time compared to other tables which don't have partitions (40-50 mins odd for 588kb)
I Tried Applying Lambda but i ended up with Task not serializable error. Check the code below.
if(cmnTableNames != null && cmnTableNames.length > 0)
{
List<String> commonTableList = Arrays.asList(cmnTableNames);
DataFrame commonTableDF = sqc.createDataset(commonTableList,Encoders.STRING()).toDF();
commonTableDF.toJavaRDD().foreach(cmnTableNameRDD -> {
DataFrame cmnTableContent = null;
String cmnTableName = cmnTableNameRDD.mkString();
if(cmnTableName.contains("PTR_security_t"))
{
cmnTableContent = hiveContext.sql("SELECT * FROM " + cmnTableName + " where fbrn04_snapshot_d = '" + snapshotId + "'");
}
else
{
cmnTableContent = hiveContext.sql("SELECT * FROM " + cmnTableName);
}
String cmnTable = cmnTableName.substring(cmnTableName.lastIndexOf(".") + 1);
if (cmnTableContent.count() > 0)
{
String cmnStgTblDir = hdfsPath + "/staging/" + rptName + "/common/" + cmnTable;
JavaRDD<String> cmnTblCntJson = cmnTableContent.toJSON().toJavaRDD();
String result = cmnTblCntJson.reduce((ob1, ob2) -> (String)ob1+","+(String)ob2);
String output = "["+result+"]";
ArrayList<String> outputList = new ArrayList<String>();
outputList.add(output);
JavaRDD<String> finalOutputRDD = sc.parallelize(outputList);
String cmnStgMrgdDir = cmnStgTblDir + "/mergedfile";
if(dfs.exists(new Path(cmnStgTblDir + "/mergedfile"))) dfs.delete(new Path(cmnStgTblDir + "/mergedfile"), true);
finalOutputRDD.coalesce(1).saveAsTextFile(cmnStgMrgdDir, GzipCodec.class);
fileStatus = dfs.getFileStatus(new Path(cmnStgMrgdDir + "/part-00000.gz"));
dfs.setPermission(fileStatus.getPath(),FsPermission.createImmutable((short) 0770));
dfs.rename(new Path(cmnStgMrgdDir + "/part-00000.gz"), new Path(CommonPath + "/" + cmnTable + ".json.gz"));
}
else
{
System.out.println("There are no records in " + cmnTableName);
}
});
}
else
{
System.out.println("The common table lists are null.");
}
sc.stop();
is there any efficient way where i can enhance my Performance ?

Hibernate JOIN query not working: Java/JSP with Hibernate, IDE Netbeans/GlassFish, Windows 10

Why doesn't this query work?
query = "SELECT itm.itemId, itm.itemModel, itm.itemDescription, "
+ " itmImages.imageFileName, part.participant_id "
+ " FROM Users user "
+ " INNER JOIN user.participant part "
+ " INNER JOIN part.addresses addr "
+ " INNER JOIN part.item itm "
+ " INNER JOIN itm.itemImages itmImages "
+ " WHERE user.userType LIKE '%borrow%') AND itm.itemDescription LIKE '%mower%') AND addr.addressType = 'primary'";
It always returns all items, disregards itemDescription LIKE... I checked the database and all of the join ids are fine
This works:
query = "SELECT user"
+ " FROM Users user "
+ " INNER JOIN user.participant part "
+ " INNER JOIN part.addresses addr "
+ " WHERE user.userType LIKE '%borrow%') AND addr.addressType = 'primary'";
I have a table Users. It has a one-to-many association with table Participant.
In Users.java I have..
private Set<Participant> participant = new HashSet<Participant>();
with
#OneToMany
#JoinTable(name = "echomarket.hibernate.Participant")
#JoinColumn(name = "user_id")
public Set<Participant> getParticipant() {
return participant;
}
public void setParticipant(Set<Participant> participant) {
this.participant = participant;
}
This join works fine.
In Participant.java I have
private Set<Addresses> addresses = new HashSet<Addresses>();
with
#OneToMany
#JoinTable(name = "echomarket.hibernate.Addresses")
#JoinColumn(name = "participant_id")
public Set<Addresses> getAddresses() {
return addresses;
}
public void setAddresses(Set<Addresses> addresses) {
this.addresses = addresses;
}
And
private Set item = new HashSet();
With
#OneToMany
#JoinTable(name = "echomarket.hibernate.Items")
#JoinColumn(name = "participant_id")
public Set<Items> getItem() {
return item;
}
No association statement with regard to Users.
In Addresses.java I make no associations.
In Items.java I have
private Set<ItemImages> itemImages = new HashSet<ItemImages>();
with
#OneToMany
#JoinTable(name = "echomarket.hibernate.ItemImages")
#JoinColumn(name = "itemId")
public Set<ItemImages> getItemImages() {
return itemImages;
}
public void setItemImages(Set<ItemImages> itemImages) {
this.itemImages = itemImages;
}
In ItemImages.java I make no associations...
Very much thanks for your help. If you need more information, please just ask...
Liz
Couldn't get the above INNER JOIN query to work-- intended for a search that involves many tables. I tested each JOIN independently successfully, but together the JOIN does not work. Also had problems with query recognizing LIKE statement. I worked really hard to find solutions. So I rewrote with the following, data gathering is split in two query calls. The following works:
public String SearchResults() {
Session sb = null;
Transaction tx = null;
String queryString = "";
String forceString = this.found_zip_codes;
List results = null;
String fromStatement = "";
if (this.lenderOrBorrower == 2) {
this.which = "borrow";
} else {
this.which = "lend";
}
this.imageLibrary = this.which + "_images";
fromStatement = " SELECT part "
+ " FROM Participant part "
+ " INNER JOIN part.addresses addr "
+ " WHERE addr.addressType = 'primary' ";
if (ubean.getComDetailID() != null) {
fromStatement = fromStatement + " AND part.communityId = \'" + ubean.getComDetailID() + "\' ";
} else {
fromStatement = fromStatement + " AND part.communityId = ''";
}
if (this.postalCode.isEmpty() == false) {
fromStatement = fromStatement + " OR addr.postalCode LIKE \'" + this.postalCode + "%\'";
}
try {
sb = hib_session();
tx = sb.beginTransaction();
results = sb.createQuery(fromStatement).list();
tx.commit();
} catch (Exception ex) {
tx.rollback();
Logger.getLogger(SearchesBean.class.getName()).log(Level.SEVERE, null, ex);
} finally {
tx = null;
sb = null;
}
String[] pids = new String[results.size()];
String hold_pid = "";
if (results != null) {
if (results.size() > 0) {
for (int i = 0; i < results.size(); i++) {
Participant cArray = (Participant) results.get(i);
if (cArray.getParticipant_id().isEmpty() == false) {
hold_pid = "\'" + cArray.getParticipant_id() + "\'";
pids[i] = hold_pid;
}
}
hold_pid = String.join(",", pids);
}
}
results = null;
fromStatement = " FROM Items itm WHERE itm.itemType = :which "
+ (hold_pid.isEmpty() ? "" : " AND itm.participant_id IN ( " + hold_pid + " )");
if ((this.startDate.isEmpty() == false) && (this.endDate.isEmpty() == false)) {
try {
queryString = queryString + " OR ";
queryString = queryString + " ( itm.dateCreated >= \'" + this.startDate + "\' AND itm.dateCreated <= \'" + this.endDate + "\' ) ";
} catch (Exception ex) {
Logger.getLogger(SearchesBean.class.getName()).log(Level.INFO, null, ex);
}
}
forceString = this.keyword;
if (forceString.isEmpty() == false) {
queryString = queryString + " OR ";
queryString = queryString + " (itm.itemDescription like \'%" + forceString + "%\' OR itm.itemModel like \'%" + forceString + "%\')";
}
if ((this.categoryId != -2)) {
queryString = queryString + " OR";
queryString = queryString + " itm.categoryId = " + this.categoryId;
}
fromStatement = fromStatement + queryString;
try {
sb = hib_session();
tx = sb.beginTransaction();
results = sb.createQuery(fromStatement).setParameter("which", this.which).list();
tx.commit();
} catch (Exception ex) {
tx.rollback();
Logger.getLogger(SearchesBean.class.getName()).log(Level.SEVERE, null, ex);
} finally {
tx = null;
sb = null;
}
this.itemDetail = results;
return "search";
}

Pass value of an object from DAO to servlet in 2D array

I would like to print the values of an object from DAO to servlet.
DAO:
public static List getFree(String svLectID,String ExLectID) throws SQLException, ClassNotFoundException
{
currentCon = JavaConnectionDB.getConnection() ;
PreparedStatement ps1 = currentCon.prepareStatement("SELECT *\n" +
"FROM (\n" +
" SELECT e1.FreeID,\n" +
" e1.lecturerID SVID,\n" +
" e1.availableID SVavail,\n" +
" e1.freedate AS SVFree,\n" +
" e2.lecturerID AS Examiner, \n" +
" e2.freedate EXFree,\n" +
" s.studentID,\n" +
" s.studentName,\n" +
" s.lecturerID AS lectID,\n" +
" sv.lecturerID AS SVlecturerID,\n" +
" sv.lecturerFullname AS SVlecturerName,\n" +
" ex.lecturerID AS EXlecturerID,\n" +
" ex.lecturerFullname AS EXlecturerName,\n" +
" v.availableID availID,\n" +
" v.availableDay,\n" +
" v.availableStart,\n" +
" v.availableEnd,\n" +
" ROW_NUMBER() OVER (PARTITION BY e1.lecturerID \n" +
" ORDER BY dbms_random.random) AS rn\n" +
" FROM free e1 \n" +
" INNER JOIN free e2 \n" +
" ON e1.availableID = e2.availableID\n" +
" INNER JOIN student s\n" +
" ON s.lecturerID = e1.lecturerID\n" +
" INNER JOIN lecturer sv\n" +
" ON sv.lecturerID = e1.lecturerID\n" +
" INNER JOIN lecturer ex\n" +
" ON ex.lecturerID = e2.lecturerID\n" +
" INNER JOIN availability v\n" +
" ON v.availableID = e2.availableID\n" +
" \n" +
" \n" +
" WHERE e1.lecturerID = ? \n" +
" AND e2.lecturerID = ? \n" +
" ORDER BY e2.availableID asc\n" +
" \n" +
" )\n" +
"WHERE rn <=5") ;
ps1.setString(1, svLectID) ;
ps1.setString(2, ExLectID);
List list = new ArrayList() ;
ResultSet rs1 = ps1.executeQuery() ;
while(rs1.next())
{
Object[] obj = new Object[17] ;
obj[0] = rs1.getString(1) ;
obj[1] = rs1.getString(2);
obj[2] = rs1.getInt(3);
obj[3] = rs1.getDate(4);
obj[4] = rs1.getString(5);
obj[5] = rs1.getDate(6);
obj[6] = rs1.getString(7);
obj[7] = rs1.getString(8);
obj[8] = rs1.getString(9);
obj[9] = rs1.getString(10);
obj[10] = rs1.getString(11);
obj[11] = rs1.getString(12);
obj[12] = rs1.getString(13);
obj[13] = rs1.getInt(14);
obj[14] = rs1.getString(15);
obj[15] = rs1.getDate(16);
obj[16] = rs1.getDate(17);
list.add(obj) ;
System.out.println("zabir "+rs1.getString(8));
}
return list ;
}
As you can see these values are stored in an object into a list. I retrieve these values to servlet.
SERVLET:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
currentCon = JavaConnectionDB.getConnection();
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletContext context=getServletContext();
String[] studentID = request.getParameterValues("studentID");
String[] supervisorID = request.getParameterValues("supervisorID");
String[] examinerID = request.getParameterValues("examinerID");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
try{
out.println("<br><center><table><tr>"
+ "<th>Student Name</th>"
+ "<th>Project Title</th>"
+ "<th>Supervisor Name</th>"
+ "<th>Examiner Name</th>"
+ "<th>Start</th>"
+ "<th>End</th>"
+ "<th>Date</th>"
+ "</tr>");
for (int i=0 ; i<studentID.length ; i++){
FreeBean free = new FreeBean();
PresentationBean present = new PresentationBean();
StudentBean student = new StudentBean();
List list = new ArrayList() ;
int SVavailableID = free.getAvailableID();
int EXavailableID = free.getAvailableID();
list = GenerateScheduleDAO.getFree(supervisorID[i],examinerID[i]);
System.out.println(list.get(0)); //DEBUGGED HERE
System.out.println(list); //DEBUGGED HERE
out.println("<tr>");
out.println("<tr>");
out.println("<td>"+ studentID[i]+"</td>");
out.println("<td> Hello </td>");
out.println("<td>"+ supervisorID[i] +"</td>");
out.println("<td>"+ examinerID[i] +"</td>");
out.println("<td>"+ SVavailableID+"</td>");
out.println("<td>"+ EXavailableID+"</td>");
out.println("<td>"+ EXFreeDate+"</td>");
out.println("</tr>");
}//student loop
out.println("</center></table><br><br>");
out.println("</body>");
out.println("</html>");
}// first try
catch (Exception e)
{
e.printStackTrace() ;
}//first catch
}//throws method
I tried to get the value using SOP first like this:
System.out.println(list.get(0)); //DEBUGGED HERE
System.out.println(list); //DEBUGGED HERE
First SOP produce : [Ljava.lang.Object;#13432ad
Second SOP produce : [[Ljava.lang.Object;#1dd079f,
My first assumption was get(0) wil give me FreeID value. As declared in DAO.
So how can i get the value if using get(0) is wrong?
Your freeId should be in the first position of each array present in the list returned by the method getFree.
To get the freeId of the first element of the list you should do something like:
System.out.println((Object[]) list.get(0))[0]);
For the freeId of the second element of the list:
System.out.println((Object[]) list.get(1))[0]);
and so on.
It will be more readable doing something like that:
Object[] firstObjectAsArray = (Object[]) list.get(0);
System.out.println(firstObjectAsArray[0]);
Object[] secondObjectAsArray = (Object[]) list.get(1);
System.out.println(secondObjectAsArray[0]);
To print the freeId of all elements of the list
for (Object objectAsArray : list) {
System.out.println(((Object[]) objectAsArray)[0]);
}
Note: looking at your code there is a not necessary creation of an empty list. The code:
List list = new ArrayList() ; // Not necessary
int SVavailableID = free.getAvailableID();
int EXavailableID = free.getAvailableID();
list = GenerateScheduleDAO.getFree(supervisorID[i],examinerID[i]);
can be optimized as follow:
int SVavailableID = free.getAvailableID();
int EXavailableID = free.getAvailableID();
List list = GenerateScheduleDAO.getFree(supervisorID[i],examinerID[i]);
Note: using generics you don't need the cast. To do that replace the definition of the list
List list = new ArrayList();
with
List<Object[]> list = new ArrayList<Object[]>();
Your list contains arrays of Object, so you have to call the relevant indexes of the array.
You could debug the full list like this
// iterate over the list
for (int i = 0; i < list.size(); i++) {
Object[] array = (Object[])(list.get(i));
// iterate over the Object array
for (int j = 0; j < array.length; j++) {
System.out.println(array[j]);
}
}

Categories

Resources