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

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]);
}
}

Related

How to get data from an ArrayList <List> in another class?

I'm using RecyclerView I have an Activity that queries my database and I insert this data into that ArrayList , and I want to list that data in another Activity.
This is where I query and add the data to the ArrayList
String queryProduto = "SELECT" +
" Produto_Servico.ID, Produto_Servico.Descricao," +
" Produto_Estoque.EstoqueAtual, ValorVenda" +
" FROM" +
" Produto_Valor" +
" INNER JOIN" +
" Produto_Servico" +
" ON" +
" Produto_Servico.ID = Produto_Valor.ID_Produto" +
" INNER JOIN" +
" Produto_Estoque" +
" ON" +
" Produto_Estoque.ID_Produto = Produto_Servico.ID" +
" WHERE" +
" Produto_Estoque.EstoqueAtual > 0" +
" ORDER BY" +
" Produto_Servico.Descricao";
Statement stmtP = connect.createStatement();
ResultSet rsP = stmtP.executeQuery(queryProduto);
String queryPessoa = "SELECT ID_Pessoa FROM Novo_Pedido";
Statement stmtPS = connect.createStatement();
ResultSet rsPS = stmtPS.executeQuery(queryPessoa);
while (rsPS.next()){
cod = rsPS.getString("ID_Pessoa");
}
if (rsP != null) {
while (rsP.next()) {
id = String.valueOf(rsP.getString("ID"));
desc = rsP.getString("Descricao");
estoque = String.valueOf(rsP.getString("EstoqueAtual"));
valorDec = rsP.getBigDecimal(4);
qtdStr = String.valueOf(qtd);
valorStr = decimalFormat.format(valorDec);
String descFinal = desc;
String qtdFinal = qtdStr;
final BigDecimal[] valorFinal = {valorDec};
try {
listProdutosPedidosFinalizar.add(new ListProdutosPedidosFinalizar(descFinal, qtdFinal, valorFinal[0], BigDecimal.ZERO));
classeLists.setListProdutosPedidosFinalizar(listProdutosPedidosFinalizar);
produtosPedidosAdapter = new ProdutosPedidosAdapter(listProdutosPedidos, this, new ProdutosPedidosAdapter.OnClickListener() {
/*METHODS*/
produtosPedidosAdapter.notifyDataSetChanged();
listProdutosPedidos.add(new ListProdutosPedidos(id, desc, estoque, valorStr, qtdStr));
} catch (Exception ex) {
ex.printStackTrace();
}
rvProdutosPedidos.setAdapter(produtosPedidosAdapter);
produtosPedidosAdapter.notifyDataSetChanged();
isSuccess = true;
}
And now I want to list the listProdutosPedidos data in another Activity.
Define listProdutosPedidos list as static member of your class and then use className.listProdutosPedidos code to access records in it.

Unable to cover List<Tuple> in JUnit Test case

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 );
}

Why is my jpql .getResultList() returning 0 rows for a good query

I was using the exact same query yesterday and it was working fine today I made a few changes to flow of the program and the query no longer returns and rows.
the first function that my programs goes to:
public void prepareSummary(Date startDate , Date endDate)
{
int getStartDay = getDayFromDate(startDate);
int getStartMonth = getMonthFromDate(startDate);
//
int getEndDay = getDayFromDate(endDate);
int getEndMonth = getMonthFromDate(endDate);
int getYear = getYearFromDate(startDate);
if(getStartMonth <= getEndMonth)
{
if(getStartMonth == getEndMonth)
{
if(getStartDay < getEndDay)
{
while(getStartDay <= getEndDay)
{
Calendar cal = Calendar.getInstance();
cal.set( getYear, getStartMonth, getStartDay);
Date queryStart = getStartOfDay(cal.getTime());
Date queryEnd = getEndOfDay(cal.getTime());
List<Object[]> res = getSumList(queryStart, queryEnd);
doQuery(res);
++getStartDay;
}
}
else
{
}
}
else
{
}
}
else
{
}
}
Here is what getSumList looks like:
public List<Object[]> getSumList(Date start, Date end) {
String query = "";
query += "SELECT COUNT(s) pCount,"
+ "p.nameText,"
+ "g.nameText,"
+ "t.shiftID"
+ " FROM Sheets s , GradeNames g , SpecieNames p, ShiftTimes t"
+ " WHERE s.createdLocal > :start and s.createdLocal < :end"
+ " AND s.specieNameIndex = p.nameIndex "
+ " AND s.gradeNameIndex = g.nameIndex"
+ " AND s.shiftIndex = t.shiftIndex"
+ " GROUP BY p.nameText , g.nameText , t.shiftID";
Query q = em.createQuery(query);
q.setParameter("start", start);
q.setParameter("end", end);
return q.getResultList();
}
This next function doesn't matter at this point because nothing is being executed because the list length is zero:
private void doQuery(List<Object[]> obj)
{
int length = obj.size();
String grade = null;
Long standingCount = (long) 0;
System.out.println("Length" + length);
for (int i = 0; i < length; ++i) {
// HAVE A LIST OF ALL ITEMS PULLED FROM DATABASE
Object[] tmpObj = obj.get(i);
Long tmpCount = (Long) tmpObj[0];
String tmpSpecieName = (String) tmpObj[1];
Double tmpThickness = Double.parseDouble(getSpecie().getThicknessFromSpecie(tmpSpecieName));
String tmpLength = getSpecie().getLengthFromSpecie(tmpSpecieName);
String tmpGradeName = (String) tmpObj[2];
String tmpShift = (String) tmpObj[3];
tmpSpecieName = getSpecie().getSpecieFromSpecie(tmpSpecieName);
//// END OF ALL ITEMS PULLED FROM DATABASE
if (grade != pullGradeName(tmpGradeName) && grade != null) {
System.out.println("Count:" + standingCount + "Grade:" + tmpGradeName + "--" + "Specie" + tmpSpecieName + "Shift:" + tmpShift + "Thickness:" + tmpThickness + "Length:" + tmpLength + "SpecieNAme:" + tmpSpecieName);
// do previous insert
grade = pullGradeName(tmpGradeName);
} else if (grade != pullGradeName(tmpGradeName) && grade == null) {
grade = pullGradeName(tmpGradeName);
} else if (grade == pullGradeName(tmpGradeName)) {
standingCount = standingCount + tmpCount;
}
System.out.println("Count:" + tmpCount + "Grade:" + tmpGradeName + "--" + "Specie" + tmpSpecieName + "Shift:" + tmpShift + "Thickness:" + tmpThickness + "Length:" + tmpLength + "SpecieNAme:" + tmpSpecieName);
}
}
Check the SQL that is generated, and the tables you are querying over. As the query requires inner joins, if one of the tables was cleared, it would return no results. If you want to get a 0 count, you need to use an outer join syntax which isn't possible in JPA unless you use object level mappings:
"SELECT COUNT(s) pCount,"
+ "p.nameText,"
+ "g.nameText,"
+ "t.shiftID"
+ " FROM Sheets s outer join s.specialNameIndex p,"
+ " outer join s.gradeNameIndex g, outer join s.shiftIndex t"
+ " WHERE s.createdLocal > :start and s.createdLocal < :end"
+ " GROUP BY p.nameText , g.nameText , t.shiftID";

Sorting arrayList from resultset

I'm working on a project that involves 2 separate db to generate the report. The result of one is passed into the other query and a final report is generated. Now, i wan to sort the final report but having issues with it. Java constructor for "java.util.Arrays" with arguments "" not found.
var fist = new java.util.Arrays();
var list = new java.util.ArrayList();
var gist = new java.util.ArrayList();
var arr = '';
var dbConn = DatabaseConnectionFactory.createDatabaseConnection('Postgres connection');
var result3 = dbConn.executeCachedQuery(...)
while (result3.next()) {
var value1 = result3.getString(1);
var value2 = result3.getString(2);
var dbConn3 = DatabaseConnectionFactory.createDatabaseConnection('Oracle connection'));
var result2 = dbConn3.executeCachedQuery("SELECT name FROM producer WHERE send = '" + value1 + "' AND code = '" + value2 + "' ORDER BY name")
while (result2.next()) {
var sending = result2.getString(1);
}
dbConn3.close();
if (sending != undefined) {
arr += gist.add(sending);
arr += gist.add(value1);
arr += gist.add(value2);
arr += gist.add(result3.getString(3));
fist.add(arr);
}
}
Arrays.sort(fist); //i'm thinking this should sort it before displaying it
while (fist.next()) {
xmlMs += "<tr>"
xmlMs += "<td>" + sending + "</td>";
xmlMs += "<td>" + value1 + "</td>";
xmlMs += "<td>" + value2 + "</td>";
xmlMs += "<td align='center'>" + result3.getString(3) + "</td>";
xmlMs += "</tr>";
}
Well yes, your compiler is telling you that var fist = new java.util.Arrays(); is invalid, java.util.Arrays doesn't provide a public no-args constructor. Did you by chance mean ArrayList instead of Arrays?
Arrays doesn't have a constructor defined in the source code, so new Arrays(); causes the compiler to scream at you.
If you want an array of something you use
type[] varname = new type[size];
Note that the [] is what makes it an Array.
Ex:
int[] x = new int[5];
That will hold an array of 5 ints.

Java program that outputs an XML file - multiple issues

I'm new to this so please forgive me if I tagged something incorrectly or left something out.
I'm writing a java program (new to java also) - the purpose of the program is to generate an XML file with information from multiple databases.
The setup - I have sql.java which is the main class and has the main method. Sql.java calls methods located in the CCReturns.java class, GBLRets.java class, and CWSReturns.java class. Each method returns a string of XML containing pertinent information and then the main method in sql.java puts them all together in one string and creates an xml file.
Problem: One of my methods in CWSReturns should return a resultset containing 74 rows in all but is only returning the data from one of the rows. When I put this same code into the sql.java main method all 74 rows are returned in the console but the xml file only shows the data from one of the rows and all of the data from all of my other methods is repeated even though I only need it to output once.
What would be the best way to go about fixing this issue? I'm stumped.
Method in CWSReturns:
public static String getUnitInfo(Connection connection, Statement stmt, ResultSet rs) throws SQLException, ClassNotFoundException
{
String unitinfo = null;
//Get Connection
connection = getCWSConnection();
//Create the SQL Query and put it into a String Variable
stmt = connection.createStatement();
//Pull Policy Claim Unit Information from CLM_UNIT Table
String query = "SELECT CLUT.UNIT_TYPE AS CLUNITTYPE, CLUT.UNIT_SUBTYPE AS CLUNITSUBTYPE, CLUT.UNIT_CATEGORY AS CLUNITCATEGORY, CLUT.UNIT_IDENTIFIER AS CLUNITIDENTIFIER, CLUT.UNIT_NUM AS CLUNITNUM, " +
"CLUT.YEAR AS CLUNITYEAR, CLUT.MAKE AS CLMAKE, CLUT.MODEL AS CLMODEL, CLUT.VEHICLE_ID AS CLVEHICLEID, CLUT.ITEM_DESC1 AS CLITEMDESC1, CLUT.LICENSE, " +
"DAM.LOCATION1, DAM.DESC1, " +
"UNT.UNIT_TYPE, UNT.UNIT_SUB_TYPE, UNT.UNIT_CATEGORY, UNT.UNIT_IDENTIFIER, UNT.UNIT_NUM, UNT.YEAR, UNT.MAKE, UNT.MODEL, UNT.VEHICLE_ID, UNT.LICENSE, UNT.ITEM_DESC, " +
//Pull Coverage Information from POL_COVERAGE Table
"COV.COVERAGE_TYPE, COV.DED_TYPE_CODE1, COV.DEDUCTIBLE1, COV.DED_TYPE_CODE2, COV.DEDUCTIBLE2, COV.DED_TYPE_CODE3, COV.DEDUCTIBLE3, COV.LIMIT_TYPE1, COV.LIMIT1, " +
"COV.LIMIT_TYPE2, COV.LIMIT2, COV.LIMIT_TYPE3, COV.LIMIT3, COV.LIMIT_TYPE4, COV.LIMIT4 " +
"FROM DB2ADMIN.CLM_CLAIM CLM, DB2ADMIN.CLM_UNIT CLUT, DB2ADMIN.POL_GENERAL_REC POL, DB2ADMIN.POL_UNIT UNT, DB2ADMIN.POL_COVERAGE COV, DB2ADMIN.CLM_DAMAGE DAM " +
"WHERE CLM.CLAIM_ID = CLUT.CLAIM_ID AND CLM.POLICY_ID = POL.POLICY_ID AND POL.POLICY_ID = UNT.POLICY_ID AND UNT.POL_UNIT_ID = COV.POL_UNIT_ID AND CLUT.UNIT_ID = DAM.UNIT_ID " +
"AND CLM.CLAIM_ID = 14701";
//Execute the query and save it as a ResultSet
rs = stmt.executeQuery(query);
//Pull out all of the information and save it as a string
while(rs.next())
{
//Retrieve by column name
//Claim Unit Info
String CL_UNIT_YEAR = "<CL_UNIT_YEAR>" + rs.getString("CLUNITYEAR") + "</CL_UNIT_YEAR>\n";
String CL_UNIT_TYPE = "<CL_UNIT_TYPE>" + rs.getString("CLUNITTYPE") + "</CL_UNIT_TYPE>\n";
String CL_UNIT_SUB_TYPE = "<CL_UNIT_SUB_TYPE>" + rs.getString("CLUNITSUBTYPE") + "</CL_UNIT_SUB_TYPE>\n";
String CL_UNIT_CATEGORY = "<CL_UNIT_CATEGORY>" + rs.getString("CLUNITCATEGORY") + "</CL_UNIT_CATEGORY>\n";
String CL_UNIT_IDENTIFIER = "<CL_UNIT_IDENTIFIER>" + rs.getString("CLUNITIDENTIFIER") + "</CL_UNIT_IDENTIFIER>\n";
String CL_UNIT_NUM = "<CL_UNIT_NUM>" + rs.getString("CLUNITNUM") + "</CL_UNIT_NUM>\n";
String CL_UNIT_MAKE = "<CL_UNIT_MAKE>" + rs.getString("CLMAKE") + "</CL_UNIT_MAKE>\n";
String CL_UNIT_MODEL = "<CL_UNIT_MODEL>" + rs.getString("CLMODEL") + "</CL_UNIT_MODEL>\n";
String CL_UNIT_VEH_ID = "<CL_UNIT_VEH_ID>" + rs.getString("CLVEHICLEID") + "</CL_UNIT_VEH_ID>\n";
String CL_UNIT_DESC1 = "<CL_UNIT_DESC1>" + rs.getString("CLITEMDESC1") + "</CL_UNIT_DESC1>\n";
String TAG_NUMBER = "<TAG_NUMBER>" + rs.getString("LICENSE") + "</TAG_NUMBER>\n";
String DAMLOC = "<DAMAGE_LOCATION>" + rs.getString("LOCATION1") + "</DAMAGE_LOCATION>\n";
String DAMDESC = "<DAMAGE_DESCRIPTION>" + rs.getString("DESC1") + "</DAMAGE_DESCRIPTION>\n";
String UNIT_TYPE = "<UNIT_TYPE>" + rs.getString("UNIT_TYPE") + "</UNIT_TYPE>\n";
String UNIT_SUB_TYPE = "<UNIT_SUB_TYPE>" + rs.getString("UNIT_SUB_TYPE") + "</UNIT_SUB_TYPE>\n";
String UNIT_CATEGORY = "<UNIT_CATEGORY>" + rs.getString("UNIT_CATEGORY") + "</UNIT_CATEGORY>\n";
String UNIT_IDENTIFIER = "<UNIT_IDENTIFIER>" + rs.getString("UNIT_IDENTIFIER") + "</UNIT_IDENTIFIER>\n";
String UNIT_NUMBER = "<UNIT_NUMBER>" + rs.getString("UNIT_NUM") + "</UNIT_NUMBER>\n";
String UNIT_YEAR = "<UNIT_YEAR>" + rs.getString("YEAR") + "</UNIT_YEAR>\n";
String UNIT_MAKE = "<UNIT_MAKE>" + rs.getString("MAKE") + "</UNIT_MAKE>\n";
String UNIT_MODEL = "<UNIT_MODEL>" + rs.getString("MODEL") + "</UNIT_MODEL>\n";
String VEH_ID = "<VEH_ID>" + rs.getString("VEHICLE_ID") + "</VEH_ID>\n";
String ITEM_DESC = "<ITEM_DESC>" + rs.getString("ITEM_DESC") + "</ITEM_DESC>\n";
//Coverage Info
String COVERAGE_TYPE = "<COVERAGE_TYPE>" + rs.getString("COVERAGE_TYPE") + "</COVERAGE_TYPE>\n";
String DED_TYPE_CODE1 = "<DED_TYPE_CODE1>" + rs.getString("DED_TYPE_CODE1") + "</DED_TYPE_CODE1>\n";
String DEDUCTIBLE1 = "<DEDUCTIBLE1>" + rs.getString("DEDUCTIBLE1") + "</DEDUCTIBLE1>\n";
String DED_TYPE_CODE2 = "<DED_TYPE_CODE2>" + rs.getString("DED_TYPE_CODE2") + "</DED_TYPE_CODE2>\n";
String DEDUCTIBLE2 = "<DEDUCTIBLE2>" + rs.getString("DEDUCTIBLE2") + "</DEDUCTIBLE2>\n";
String DED_TYPE_CODE3 = "<DED_TYPE_CODE3>" + rs.getString("DED_TYPE_CODE3") + "</DED_TYPE_CODE3>\n";
String DEDUCTIBLE3 = "<DEDUCTIBLE3>" + rs.getString("DEDUCTIBLE3") + "</DEDUCTIBLE3>\n";
String LIMIT_TYPE1 = "<LIMIT_TYPE1>" + rs.getString("LIMIT_TYPE1") + "</LIMIT_TYPE1>\n";
String LIMIT1 = "<LIMIT1>" + rs.getString("LIMIT1") + "</LIMIT1>\n";
String LIMIT_TYPE2 = "<LIMIT_TYPE2>" + rs.getString("LIMIT_TYPE2") + "</LIMIT_TYPE2>\n";
String LIMIT2 = "<LIMIT2>" + rs.getString("LIMIT2") + "</LIMIT2>\n";
String LIMIT_TYPE3 = "<LIMIT_TYPE3>" + rs.getString("LIMIT_TYPE3") + "</LIMIT_TYPE3>\n";
String LIMIT3 = "<LIMIT3>" + rs.getString("LIMIT3") + "</LIMIT3>\n";
String LIMIT_TYPE4 = "<LIMIT_TYPE4>" + rs.getString("LIMIT_TYPE4") + "</LIMIT_TYPE4>\n";
String LIMIT4 = "<LIMIT4>" + rs.getString("LIMIT4") + "</LIMIT4>\n";
//Create one large string that incorporates all of the above nodes
String unitinfo1 = CL_UNIT_YEAR + CL_UNIT_TYPE + CL_UNIT_SUB_TYPE + CL_UNIT_CATEGORY + CL_UNIT_IDENTIFIER +
CL_UNIT_NUM + CL_UNIT_MAKE + CL_UNIT_MODEL + CL_UNIT_VEH_ID + CL_UNIT_DESC1 + TAG_NUMBER + DAMLOC + DAMDESC +
UNIT_TYPE + UNIT_SUB_TYPE + UNIT_CATEGORY + UNIT_IDENTIFIER + UNIT_NUMBER + UNIT_YEAR + UNIT_MAKE +
UNIT_MODEL + VEH_ID + ITEM_DESC + COVERAGE_TYPE + DED_TYPE_CODE1 + DEDUCTIBLE1 + DED_TYPE_CODE2 +
DEDUCTIBLE2 + DED_TYPE_CODE3 + DEDUCTIBLE3 + LIMIT_TYPE1 + LIMIT1 + LIMIT_TYPE2 + LIMIT2 +
LIMIT_TYPE3 + LIMIT3 + LIMIT_TYPE4 + LIMIT4;
return unitinfo1;
}
stmt.close();
rs.close();
connection.close();
return unitinfo;
}
sql.java - main method snippet:
//Get unit info
String unitinfo = CWSReturns.getUnitInfo(connection, stmt, rs);
String xmlStr = (Root+mainclaimnode+mainclaiminfo+lossState+clientname+clientaddress+communicationinfo+agentname+adjustername+secondaryclientname+policyinfo+cancelpendinginfo+endmainclaimnode+claimunitnode+unitinfo+OIPName+OIPAddress+rollinjuryinfo+unitaddress+endclaimunitnode+EndRoot);
Document doc = convertStringToDocument(xmlStr);
String str = convertDocumentToString(doc);
System.out.println(str);
PrintWriter writer = new PrintWriter("C:\\Temp\\TestXML.xml");
writer.println(str);
writer.close();
Output when running method from CWSReturns (only one resultset returned...)
<CWS_XML>
<MAIN_CLAIM_INFO>
<CLAIM_ID>14701</CLAIM_ID>
<DATE_LOSS>2013-09-01 04:00:00.0</DATE_LOSS>
<CLAIM_MADE_DATE>null</CLAIM_MADE_DATE>
<CALLER_NAME>asdf asdf</CALLER_NAME>
<ACTUAL_NOT_DATE>2014-02-25 10:25:00.0</ACTUAL_NOT_DATE>
<METHOD_REPORT>PHONE</METHOD_REPORT>
<NAME_TYPE_FLAG>I</NAME_TYPE_FLAG>
<NAME_TYPE>null</NAME_TYPE>
<NAME_PREFIX>null</NAME_PREFIX>
<LAST_NAME>Luke</LAST_NAME>
<NAME_SUFFIX>null</NAME_SUFFIX>
</MAIN_CLAIM_INFO>
**<CLAIM_UNIT_INFO>
<CL_UNIT_YEAR>2014</CL_UNIT_YEAR>
<CL_UNIT_TYPE>DRIVE_OTHR</CL_UNIT_TYPE>
<CL_UNIT_SUB_TYPE>COMBO</CL_UNIT_SUB_TYPE>
<CL_UNIT_CATEGORY>DRIVE_OTHR</CL_UNIT_CATEGORY>
<CL_UNIT_IDENTIFIER>2014 Cadillac</CL_UNIT_IDENTIFIER>
<CL_UNIT_NUM/>
<CL_UNIT_MAKE>Cadillac </CL_UNIT_MAKE>
<CL_UNIT_MODEL/>
<CL_UNIT_VEH_ID/>
<CL_UNIT_DESC1>null</CL_UNIT_DESC1>
<TAG_NUMBER/>
<DAMAGE_LOCATION>Unknown</DAMAGE_LOCATION>
<DAMAGE_DESCRIPTION>Unknown</DAMAGE_DESCRIPTION>
<UNIT_TYPE>NON_OWNED</UNIT_TYPE>
<UNIT_SUB_TYPE>COMBO</UNIT_SUB_TYPE>
<UNIT_CATEGORY>NON_OWNED</UNIT_CATEGORY>
<UNIT_IDENTIFIER>NON OWNED</UNIT_IDENTIFIER>
<UNIT_NUMBER>null</UNIT_NUMBER>
<UNIT_YEAR>null</UNIT_YEAR>
<UNIT_MAKE>null</UNIT_MAKE>
<UNIT_MODEL>null</UNIT_MODEL>
<VEH_ID>null</VEH_ID>
<ITEM_DESC>null</ITEM_DESC>
<COVERAGE_TYPE>ADB</COVERAGE_TYPE>
<DED_TYPE_CODE1>null</DED_TYPE_CODE1>
<DEDUCTIBLE1>null</DEDUCTIBLE1>
<DED_TYPE_CODE2>null</DED_TYPE_CODE2>
<DEDUCTIBLE2>null</DEDUCTIBLE2>
<DED_TYPE_CODE3>null</DED_TYPE_CODE3>
<DEDUCTIBLE3>null</DEDUCTIBLE3>
<LIMIT_TYPE1>LIM</LIMIT_TYPE1>
<LIMIT1>15000.000</LIMIT1>
<LIMIT_TYPE2>null</LIMIT_TYPE2>
<LIMIT2>null</LIMIT2>
<LIMIT_TYPE3>null</LIMIT_TYPE3>
<LIMIT3>null</LIMIT3>
<LIMIT_TYPE4>null</LIMIT_TYPE4>
<LIMIT4>null</LIMIT4>
<OIP_NAME>Null</OIP_NAME>
<OIP_ADDR>Null</OIP_ADDR>
<ROLE_TYPE>DRIVER</ROLE_TYPE>
<INJURY_TEXT>head</INJURY_TEXT>
<CL_UNIT_ID>Null</CL_UNIT_ID>
<CL_UNIT_HOUSE>Null</CL_UNIT_HOUSE>
<CL_UNIT_ADDR1>Null</CL_UNIT_ADDR1>
<CL_UNIT_ADDR2>Null</CL_UNIT_ADDR2>
<CL_UNIT_CITY>Null</CL_UNIT_CITY>
<CL_UNIT_STATE>Null</CL_UNIT_STATE>
<CL_UNIT_ZIP>Null</CL_UNIT_ZIP>
</CLAIM_UNIT_INFO>**
</CWS_XML>
The elements in the "CLAIM_UNIT_INFO" node should repeat upwards of 74 times...
Inside the while loop you are returning. So it iterates only one time.
Make unitinfo in getUnitInfo() method as a StringBuilder and inside the while(rs.next) instead or returning append the unitinfo1 to unitinfo
public static String getUnitInfo(Connection connection, Statement stmt, ResultSet rs) throws SQLException, ClassNotFoundException
{
StringBuilder unitinfo = new StringBuilder();
...
while(rs.next()) {
...
unitinfo.append("<CLAIM_UNIT_INFO>");
//Create one large string that incorporates all of the above nodes
String unitinfo1 = CL_UNIT_YEAR + CL_UNIT_TYPE + CL_UNIT_SUB_TYPE + CL_UNIT_CATEGORY + CL_UNIT_IDENTIFIER +
CL_UNIT_NUM + CL_UNIT_MAKE + CL_UNIT_MODEL + CL_UNIT_VEH_ID + CL_UNIT_DESC1 + TAG_NUMBER + DAMLOC + DAMDESC +
UNIT_TYPE + UNIT_SUB_TYPE + UNIT_CATEGORY + UNIT_IDENTIFIER + UNIT_NUMBER + UNIT_YEAR + UNIT_MAKE +
UNIT_MODEL + VEH_ID + ITEM_DESC + COVERAGE_TYPE + DED_TYPE_CODE1 + DEDUCTIBLE1 + DED_TYPE_CODE2 +
DEDUCTIBLE2 + DED_TYPE_CODE3 + DEDUCTIBLE3 + LIMIT_TYPE1 + LIMIT1 + LIMIT_TYPE2 + LIMIT2 +
LIMIT_TYPE3 + LIMIT3 + LIMIT_TYPE4 + LIMIT4;
unitinfo.append(unitinfo1);
unitinfo.append("</CLAIM_UNIT_INFO>");
}
...
return unitinfo.toString();
}
As #SyamS mentioned you are returning inside of your loop.
If you don't want to combine all of the rows into one String: One way to fix this would be to store the String found in the loop into an ArrayList, and then return the ArrayList of String.
You would have to change the return type of your method, and handle iterating through the resulting ArrayList when you called the method.
public static ArrayList<String> getUnitInfo(...){
ArrayList<String> unitinfo = new ArrayList<String>();
...
while(...){
...
unitinfo.add(unitinfo1); // Instead of return
}
...
return unitinfo; // Only return at the end
}
The reason this is happening is because you have return unitinfo1 inside your while loop. So it is just returning after the first row has been populated.
You need to declare String unitinfo1 outside of the while loop, and append each line to the string during each iteration of the loop.
String unitinfo1;
while(condition)
{
unitinfo1.append(nextLine);
}
return unitinfo1;

Categories

Resources