I am trying to turn a DTO to string to store in a database. I am calling:
ObjectMapper mapper = new ObjectMapper();
TypeFactory factory = mapper.getTypeFactory();
// type of key of response map
JavaType stringType = factory.constructType(String.class);
// type of value of response map
JavaType listOfDtosType = factory.constructCollectionType(ArrayList.class, SummonerRankedInfoDTOEntry.class);
// create type of map
JavaType responseType = factory.constructMapType(HashMap.class, stringType, listOfDtosType);
try {
assert json != null;
Map<String, List<SummonerRankedInfoDTOEntry>> response = new ObjectMapper().readValue(json, responseType);
summonerRankedInfoDTO.setIntegerSummonerRankedInfoDTOEntryMap(response);
logger.info("Json has been de-serialized" + summonerRankedInfoDTO.getIntegerSummonerRankedInfoDTOEntryMap());
} catch (IOException e) {
e.printStackTrace();
}
return summonerRankedInfoDTO;
on my DTO which is: http://codebeautify.org/javaviewer/cb5e233b.
Notice the fields:
LeagueDTOEntry {
division = 'V ', isFreshBlood = false, isHotStreak = false, isInactive = false, isVeteran = false, leaguePoints = 0, losses = 32, miniSeries = null, playerOrTeamId = 'TEAM - 77 b4b970 - 5e e2 - 11e4 - 9 d98 - c81f66db96d8 ', playerOrTeamName = 'Team Invertebrate ', wins = 32
}
the isFreshBlood, isHotStreak, isInactive and isVeteran fields.
I call the above code and log the string it returns, which is: https://jsonblob.com/56852fd6e4b01190df4650cd
All the fields above have lost the "is" part: freshBlood, hotStreak... etc.
I can post my DTOs but I've been looking for a long time and have no idea why it's changing their names. I don't think I ever named them without the "is" as the "is" is on the values returned from an API call.
Any help is appreciated, not sure how to make this question less confusing...
EDIT: My LeagueEntryDTO is:
private String division;
private boolean isFreshBlood;
private boolean isHotStreak;
private boolean isInactive;
private boolean isVeteran;
private int leaguePoints;
private MiniSeriesDTOEntry miniSeries;
private String playerOrTeamId;
private String playerOrTeamName;
private int wins;
private int losses;
#Override
public String toString() {
return "LeagueDTOEntry{" +
"division='" + division + '\'' +
", isFreshBlood=" + isFreshBlood +
", isHotStreak=" + isHotStreak +
", isInactive=" + isInactive +
", isVeteran=" + isVeteran +
", leaguePoints=" + leaguePoints +
", losses=" + losses +
", miniSeries=" + miniSeries +
", playerOrTeamId='" + playerOrTeamId + '\'' +
", playerOrTeamName='" + playerOrTeamName + '\'' +
", wins=" + wins +
'}';
}
If you really want to keep the is prefixes rather than respecting the standard JavaBean conventions, annotate your getters with (for example)
#JsonProperty("isInactive")
Also, your JSON logic is way too complex. You should just have to do
Map<String, List<SummonerRankedInfoDTOEntry>> response =
new ObjectMapper().readValue(
json,
new TypeReference<Map<String, List<SummonerRankedInfoDTOEntry>>>() {});
Related
I want to return valid json string.
Ex:
{
"status":"Success",
"total_amt": "41",
"igst_amt": 14,
"sgst_amt": 0,
"cgst_amt": "12",
"cess_amt": 15
}
Expected:
{
"status":"Success",
"total_amt": "41",
"igst_amt": "14",
"sgst_amt": "0",
"cgst_amt": "12",
"cess_amt": "15"
}
I have wrote below code:
public String toString() {
return "{\"status\":\"" + status + "\",\"total_amt\":\"" + total_amt + "\",\"igst_amt\":\"" + igst_amt
+ "\",\"sgst_amt\":\"" + sgst_amt + "\",\"cgst_amt:\"" + cgst_amt + "\",\"cess_amt\":\"" + cess_amt + "\"}";
}
It is not returning valid JSON.
You can use a third party lib. This example uses GSON
class Result {
private String status;
#SerializedName("total_amt")
private int totalAmount;
#SerializedName("igst_amt")
private int igstAmount;
#SerializedName("sgst_amt")
private int sgstAmount;
#SerializedName("cgst_amt")
private int cgstAmount;
#SerializedName("cess_amt")
private int cessAmount;
public Result() {}
}
Result result = new Result();
// set your fields
String json = new Gson().toJson(result);
I hope igst_amt, sgst_amt and cess_amt are Integers.
So you add .toString() to them
public String toString() {
return "{\"status\":\"" + status + "\",\"total_amt\":\"" + total_amt + "\",\"igst_amt\":\"" + igst_amt.toString()
+ "\",\"sgst_amt\":\"" + sgst_amt.toString() + "\",\"cgst_amt:\"" + cgst_amt + "\",\"cess_amt\":\"" + cess_amt.toString() + "\"}";
}
Read about gson for returning json format. link to gson github
To simple use it you can:
final Gson gson = new GsonBuilder().setPrettyPrinting().create();
final String string = "you string";
return gson.toJson(string);
I want to create a run time String name in Java.
I tried something like using in JavaScript, but it is printing value like Status_Name_0 instead Open assigned to the String Status_Name_0
public static void GetPaymentStatusList(){
int i=0;
String Status_Name_0="Open";
String Status_ID_0="0";
String Status_Name_1="Approved";
String Status_ID_1="1";
String Status_Name_2="Denied";
String Status_ID_2="2";
for(i=0; i<3; i++){
Vars.PaymentStatusName_List.add("Status_Name_"+i);
Vars.PaymentStatusId_List.add("Status_ID_"+i);
}
}
but it is printing value like Status_Name_0 instead Open
Because that's what you added to the list...
add("Status_Name_"+i);
The way to get what you want would be a Map<String, String>
Map<String, String> map = new HashMap<>();
map.put("Status_Name_0", "Open");
// ...
for (int i=0;i<map.size();i++) {
String open = map.get("Status_Name_"+i);
}
How about you make some class instead, though?
public class PaymentStatus {
int id;
String name;
public PaymentStatus(int id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return String.format("%s[id: %d, name: %s]",
getClass().getSimpleName(), id, name);
}
}
And a List<PaymentStatus> would be preferred over appending integers to any variables.
public static List<PaymentStatus> getPaymentStatusList() {
List<PaymentStatus> list = new ArrayList<>();
paymentStatusList.add(new PaymentStatus(0, "Open"));
paymentStatusList.add(new PaymentStatus(1, "Approved"));
paymentStatusList.add(new PaymentStatus(2, "Denied"));
return list;
}
You're actually concatenating the string "Status_name_" with "0" which would result in "Status_name_0", a string, not a variable like Status_name_0. As far as I understand, you want the values of String_name_i (i= 0, 1, 2,....). To get that working, use String array.
String[] string_names = { "Open", "Approved", "Denied" };
int[] string_id = { 0, 1, 2 };
:You may not need a string_id array, as you can use the values of i in the for loop.
And add them in the list like:
Vars.PaymentStatusName_List.add(string_name[i]);
StringBuilder param = new StringBuilder();
param.append("shopid"
+ "=" + shopDetails.getShopId() + "&" + "username" + "=" + userDetail.getUserName() + "&" + "userid" + "=" + userDetail.getUserId() + "&");
for (int i = 0; i < brandList.size(); i++) {
param.append("brandId" + "[" + i + "]" + "=" + brandList.get(i).getBrandId()
+ "&" + "shortqua" + "[" + i + "]" + "=" + shortageStockList.get(i) + "&");
}
param.append("lattude" + "=" + String.valueOf(latitude) + "&" + "longitude" + "=" + String.valueOf(longitude));
I want to parse the json string in java class (.java) created by stringify() function in javascript. I know to parse the string like:
String JSON_DATA
= "{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " ]"
+ "}";
but how to parse this string?
var IO = {
//returns array with storable google.maps.Overlay-definitions
IN: function(arr, //array with google.maps.Overlays
encoded//boolean indicating whether pathes should be stored encoded
) {
var shapes = [],
goo = google.maps,
shape, tmp;
for (var i = 0; i < arr.length; i++)
{
shape = arr[i];
tmp = {type: this.t_(shape.type), id: shape.id || null};
switch (tmp.type) {
case 'CIRCLE':
tmp.radius = shape.getRadius();
tmp.geometry = this.p_(shape.getCenter());
break;
case 'MARKER':
tmp.geometry = this.p_(shape.getPosition());
break;
case 'RECTANGLE':
tmp.geometry = this.b_(shape.getBounds());
break;
case 'POLYLINE':
tmp.geometry = this.l_(shape.getPath(), encoded);
break;
case 'POLYGON':
tmp.geometry = this.m_(shape.getPaths(), encoded);
break;
}
shapes.push(tmp);
}
return shapes;
}
and the string formed to be parsed is:
[{"type":"CIRCLE","id":null,"radius":1730.4622192451884,"geometry":[32.3610810916614,50.91339111328125]},{"type":"CIRCLE","id":null,"radius":1831.5495077322266,"geometry":[32.35528086804335,50.997161865234375]},{"type":"CIRCLE","id":null,"radius":1612.2461023303567,"geometry":[32.34454947365649,51.011924743652344]}]
You can use Gson or Jackson for this. Create a POJO that hold the data and use these libs. An eg with Gson
import java.lang.reflect.Type;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
class JsonData {
private String type;
private String id;
private double radius;
private List<Double> geometry;
//Getters & Setters
}
public class JsonParser {
public static void main(String[] args) {
String json = "[{\"type\":\"CIRCLE\",\"id\":null,\"radius\":1730.4622192451884,\"geometry\":[32.3610810916614,50.91339111328125]},{\"type\":\"CIRCLE\",\"id\":null,\"radius\":1831.5495077322266,\"geometry\":[32.35528086804335,50.997161865234375]},{\"type\":\"CIRCLE\",\"id\":null,\"radius\":1612.2461023303567,\"geometry\":[32.34454947365649,51.011924743652344]}]";
Type listType = new TypeToken<List<JsonData>>() {}.getType();
List<JsonData> disputeSummaryArraylistobjectList = new Gson().fromJson(json, listType);
System.out.println(disputeSummaryArraylistobjectList);
}
}
You will need a JSON parser for Java like GSON or Jackson.
There are two strategies for parsing:
Creating Java objects and let the JSON parsers map elements in the input to fields
Iterating over the generic JSON data structure which the parser returns
The documentation of both projects contain lots of examples how to achieve either.
I'm writing a special permission forms program using MySQL, Javascript, and HTML code, which both respond to. I'm doing all of this using singleton pattern access and facade code(s) in java, and a services code, which responds to the singleton pattern codes.
I'm trying To retrieve a form (AKA 1 Result) by the variables, courseDept & courseNm.
This is a snippet of code I'm using to do all this:
FormDataFacade.java code snippet:
#Path("/specialPermissions/sp")
#GET
#Produces("text/plain")
public Response getSpecialPermissionFormByDeptAndRoomNm(#QueryParam("courseDept") String theDept, #QueryParam("courseNm") String theNm)
throws NamingException, SQLException, ClassNotFoundException
{
//Referenciation to FormDataFacade class.
FormDataFacade iFacade = FormDataFacade.getInstance();
int intNm = 0;
try {
intNm = Integer.parseInt(theNm);
}catch (NumberFormatException FAIL) {
intNm = 1;
}
//Aiming for forms with matching departments & room numbers by calling FormDataFacade
//method, getSpecialPermissionFormByDeptAndRoomNm.
SpecialPermissionForms[] orgaForm = iFacade.getSpecialPermissionFormByDeptAndRoomNm(theDept, intNm);
//Json String Representation...
if (orgaForm != null)
{
Gson neoArcadia = new Gson();
String result = neoArcadia.toJson(orgaForm);
//Json String added to response message body...
ResponseBuilder rb = Response.ok(result, MediaType.TEXT_PLAIN);
rb.status(200); //HTTP Status code has been set!
return rb.build(); //Creating & Returning Response.
}
else
{ //In case of finding no form data for the procedure...
return Response.status(700).build();
}
}
FormDataServices.java code snippet:
public SpecialPermissionForms[] getSpecialPermissionFormByDeptAndRoomNm(String theDept, int theNm) throws SQLException, ClassNotFoundException
{
Connection con = zeon.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT formID, studentName, courseDept, courseNm, semester, year, reasonCode FROM spforms WHERE courseDept = ? & courseNm = ?");
pstmt.setString(1, theDept);
pstmt.setInt(2, theNm);
ResultSet rs = pstmt.executeQuery();
SpecialPermissionForms[] neoForm = new SpecialPermissionForms[50];
int current = 0;
while (rs.next())
{
int formID3 = rs.getInt("formID");
String studentName3 = rs.getString("studentName");
String courseDept3 = rs.getString("courseDept");
String courseNm3 = rs.getString("courseNm");
String semester3 = rs.getString("semester");
int year3 = rs.getInt("year");
String reasonCode3 = rs.getString("reasonCode");
SpecialPermissionForms neo = new SpecialPermissionForms(formID3, studentName3, courseDept3, courseNm3, semester3, year3, reasonCode3);
neoForm[current] = neo;
current++;
}
if (current > 0)
{
neoForm = Arrays.copyOf(neoForm, current);
return neoForm;
}
else
{
return null;
}
}
Forms.html code snippet which both pieces of java code respond to:
$("#btnOneName").click(function() {
alert("clicked");
var inputId1=document.getElementById("t_specialFormCourseDept").value;
var inputId2=document.getElementById("t_specialFormCourseNm").value;
var theData = "courseDept=" + inputId1 + "&" + "courseNm=" + inputId2;
alert("Sending: " + theData);
var theUrl = "http://localhost:8080/onlineforms/services/enrollment/specialPermissions/sp?courseDept=&courseNm="+ theData;
$.ajax( {
url: theUrl,
type: "GET",
dataType: "text",
success: function(result) {
alert("success");
var neoForm = JSON.parse(result);
alert(neoForm);
var output="<h3>Current Form Lists:</h3>";
output += "<ul>";
for (var current = 0; current < neoForm.length; current++)
{
output += "<li>" + neoForm[current].formID + ": " + neoForm[current].studentName + " (" + neoForm[current].courseDept + " - " + neoForm[current].courseNm + ") " +
" (" + neoForm[current].semester + " - " + neoForm[current].year + ") " + " - " + neoForm[current].reasonCode + "</li>";
}
output += "</ul>";
alert(output);
$("#p_retrieveOneName").html(output);
},
error:function(xhr) {
alert("error");
$("#p_retrieveOneName").html("Error:"+xhr.status+" "+xhr.statusText);}
} );
});
});
Now, when I go test this code in my webservice after successfully compiling it, it does work, however it retrieves everything, including the specific results I was searching for - I only want to return the results I have specifically searched for and nothing else. What exactly am I doing wrong here in these snippets of code?
Any suggestions or steps in the right direction are highly welcome.
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;