Dispatch File from AS400 to Mainframe using FTPS - java

Currently, My system send file from AS400 to Mainframe by FTP. The downstream Mainframe system will not support FTP any more. FTPS will be the only way to send files to it.
Currently we use com.ibm.as400.access.FTP and this package to execute FTP command. I want to know What package can be used by FTPS from AS400 to Mainframe.
currently ftp code is as follows:
boolean FTPFile(String filepath, String filename, String country) {
String ftpresult = "";
String region = bundle.getString("region." + country);
FTP ftp = new FTP(ftpHost, ftpId, ftpPw);
try {
if (country.equals("766") || country.equals("858")
|| country.equals("761") || country.equals("836")) {
ftp.setDataTransferType(FTP.BINARY);
}
if (ftp.connect()) {
getLogMsg().append("FTPing SIF file. Region = " + region,
LogMsg.TEXT_MSG);
String sendname = "'" + ftpDataset + country + ".LSIFATB'";
getLogMsg().append(
"sending file: = " + filepath + filename + " as "
+ sendname, LogMsg.TEXT_MSG);
// Korea
if (country.equals("766") || country.equals("761")) {
ftp.issueCommand("ltype c 933");
// ftpresult = ftp.issueCommand("type b 6");
}
// Taiwan
if (country.equals("858") || country.equals("836")) {
ftp.issueCommand("ltype c 937");
// ftpresult = ftp.issueCommand("type b 8");
}
boolean ftp_res = ftp.put(filepath + filename, sendname);
// System.out.println("ftp result: " + ftp_res);
getLogMsg().append("ftp result (sending SIF): " + ftp_res,
LogMsg.TEXT_MSG);
ftpresult = ftp.issueCommand("site filetype=jes");
System.out.println("ftp command result = " + ftpresult);
String jobname = bundle.getString("app.sif.jobname." + country);
// String jobname = "CISBL30D";
ftp.setDataTransferType(FTP.ASCII);
ftp_res = ftp.put(bundle.getString("app.sif.directory") + "/"
+ region + country + "/jcl.txt", "jcl.txt '" + jobname
+ "'");
getLogMsg().append("ftp result (sending jcl): " + ftp_res,
LogMsg.TEXT_MSG);
return true;
}
} catch(...) {}
}

I've used the Apache COMMONS Net module to do normal FTP.
It does have a FTPSClient class that should do what you want.

Related

Request parameters coming from jsps are changed when two different users access the code same time

public String generateDataPDF() {
System.out.println("Inside generate PDF");
String filePath = "";
HttpSession sess = ServletActionContext.getRequest().getSession();
try {
sess.setAttribute("msg", "");
if (getCrnListType().equalsIgnoreCase("F")) {
try {
filePath = getModulePath("CRNLIST_BASE_LOCATION") + File.separator + getCrnFileFileName();
System.out.println("File stored path : " + filePath);
target = new File(filePath);
FileUtils.copyFile(crnFile, target);
} catch (Exception e) {
System.out.println("File path Exception " + e);
}
}
System.out.println("Values from jsp are : 1)Mode of Generation : " + getCrnListType() + " 2)Policy Number : " + getCrnNumber() + " 3)Uploaded File Name : " + getCrnFileFileName() + " 4)LogoType : " + getLogoType()
+ " 5)Output Path : " + getOutputPath() + " 6)Type of Generation : " + getOptionId() + " 7)PDF Name : " + getPdfName());
String srtVAL = "";
String arrayVaue[] = new String[]{getCrnListType(), getCrnListType().equalsIgnoreCase("S") ? getCrnNumber() : filePath, getLogoType().equalsIgnoreCase("WL") ? "0" : "1",
getOutputPath(), getGenMode(), getRenType()};
//INS DB Connection
con = getInsjdbcConnection();
ArrayList selectedCRNList = new ArrayList();
String selectedCRNStr = "";
selectedCRNStr = getSelectedVal(selectedCRNStr, arrayVaue[1]);
String[] fileRes = selectedCRNStr.split("\\,");
if (fileRes[0].equalsIgnoreCase("FAIL")) {
System.out.println("fileRes is FAIL beacause of other extension file.");
sess.setAttribute("pr", "Please upload xls or csv file.");
return SUCCESS;
}
System.out.println("List file is : " + selectedCRNStr);
String st[] = srtVAL.split("[*]");
String billDateStr = DateUtil.getStrDateProc(new Date());
Timestamp strtPasrsingTm = new Timestamp(new Date().getTime());
String minAMPM = DateUtil.getTimeDate(new Date());
String str = "";
String batchID = callSequence();
try {
System.out.println("Inside Multiple policy Generation.");
String userName=sess.getAttribute("loginName").toString();
String list = getProcessesdList(userName);
if (list != null) {
System.out.println("list is not null Users previous data is processing.....");
//setTotalPDFgNERATEDmSG("Data is processing please wait.");
sess.setAttribute("pr","Batch Id "+list+" for User " + userName + " is currently running.Please wait till this Process complete.");
return SUCCESS;
}
String[] policyNo = selectedCRNStr.split("\\,");
int l = 0, f = 0,counter=1;
for (int j = 0; j < policyNo.length; j++,counter++) {
String pdfFileName = "";
int uniqueId=counter;
globUniqueId=uniqueId;
insertData(batchID, new Date(), policyNo[j], getOptionId(), userName,uniqueId);
System.out.println("Executing Proc one by one.");
System.out.println("policyNo[j]" + policyNo[j]);
System.out.println("getOptionId()" + getOptionId());
System.out.println("seqValue i.e batchId : " + batchID);
}
str = callProcedure(policyNo[j], getOptionId(), batchID);
String[] procResponse = str.split("\\|");
for (int i = 0; i < procResponse.length; i++) {
System.out.println("Response is : " + procResponse[i]);
}
if (procResponse[0].equals("SUCCESS")) {
Generator gen = new Generator();
if (getPdfName().equalsIgnoreCase("true")) {
System.out.println("Checkbox is click i.e true");
pdfFileName = procResponse[1];
} else {
System.out.println("Checkbox is not click i.e false");
String POLICY_SCH_GEN_PSS = getDetailsForFileName(userName, policyNo[j], batchID);
String[] fileName = POLICY_SCH_GEN_PSS.split("\\|");
if (getLogoType().equals("0") || getLogoType().equals("2")) {
System.out.println("If logo is O or 1");
pdfFileName = fileName[1];
} else if (getLogoType().equals("1")) {
System.out.println("If logo is 2");
pdfFileName = fileName[0];
}
}
b1 = gen.genStmt(procResponse[1], procResponse[2], "2", getLogoType(), "0", pdfFileName,"1",userName,batchID);
l++;
updateData(uniqueId,batchID, "Y");
} else {
f++;
updateData(uniqueId,batchID, "F");
}
}
sess.setAttribute("pr","Total "+l+" "+getGenericModulePath("PDF_RES1") + " " + " " + getGenericModulePath("PDF_RES2") + " " + f);
}catch (Exception e) {
updateData(globUniqueId,batchID, "F");
System.out.println("Exception in procedure call");
setTotalPDFgNERATEDmSG("Fail");
e.printStackTrace();
sess.setAttribute("pr", "Server Error.");
return SUCCESS;
}
}catch (Exception ex) {
ex.printStackTrace();
sess.setAttribute("pr", "Server Error.");
return SUCCESS;
}
System.out.println("Above second return");
return SUCCESS;
}
GenerateDataPDf method generates PDF based on the parameters i.e ProductType(GenMode),CrnList(uploaded in excel file...)Code works fine when only single user generates PDF. But If two different User(User and roles are assigned in application) start the process same time request paraeters are overridden then! Suppose first user request pdf for 50 customers for product 1. User1's process is still running and second user request for product2. Now User1's pdf are generated but for product2.....! Here batchId is unique for every single request.One table is maintained where batch_id,all pdf,generation flags are mainained there. How do I solve this?
As per your comment, this is what I would do, It's probably not the best way to do !
Firstly : Create a function to collet all your data at the beginning. You should not modify/update/create anything when you are generating a PDF. IE : array/list collectPDFData() wich should retourn an array/list.
Secondly : Use a synchronized methods like synchronized boolean generatePDF(array/list)
"Synchronized" methods use monitor lock or intrinsic lock in order to manage synchronization so when using synchronized, each method share the same monitor of the corresponding object.
NB : If you use Synchronize, it's probably useless to collect all your data in a separate way, but I think it's a good practice to make small function dedicated to a specific task.
Thus, your code should be refactored a little bit.

URLConnection doesn't work with public FTP servers in Android

My issue: my android device is unable to connect to a public FTP server using URLConnection. However, when the device tried to connect to a public FTP server (anonymous for username and no password), it cannot retrieve the InputStream from urlConnection.getInputStream();.
I do not use FTPClient from Apache Commons library because the speed is quite limited... A related question regarding that limited speed with FTPClient is here
FTPClient's download is slower than URLConnection's download.
Whatever I tried with the urlString:
urlString = protocol+"://" + username+"#" +address+":"+port + filepath + file;
// ftp://anonymous#speedtest.tele2.net:21/100GB.zip
urlString = protocol+"://" + username+":" + password + "#" +address+":"+port + filepath + file;
// ftp://anonymous:#speedtest.tele2.net:21/100GB.zip
urlString = protocol+"://" + username+":" + "password" + "#" +address+":"+port + filepath + file;
// ftp://anonymous:password#speedtest.tele2.net:21/100GB.zip
urlString = protocol+"://" + address+":"+port + filepath + file;
// ftp://speedtest.tele2.net:21/100GB.zip
downloadAndBroadcastURL:after getinputStream is never got logged with open FTP servers. I also tried with these two public FTP servers:
ftp://speedtest.tele2.net/100GB.zip
ftp://ftp.funet.fi/dev/1GBnull
But it doesn't connect as well.
My code:
private void downloadAndBroadcastURL() {
beginTime = System.currentTimeMillis();
try {
String urlString;
if (username.equals("anonymous")){
urlString = protocol+"://" + username+"#" +address+":"+port + filepath + file;
} else {
urlString = protocol+"://" + username+":" + password + "#" +address+":"+port + filepath + file;
}
Log.d(TAG, "downloadAndBroadcastURL: "+ urlString);
URL url = new URL(urlString);
URLConnection urlConnection = url.openConnection();
Log.d(TAG, "downloadAndBroadcastURL:after connect ");
inputStream = new BufferedInputStream(urlConnection.getInputStream());
Log.d(TAG, "downloadAndBroadcastURL:after getinputStream");
/*******************************
The rest is about handling the input stream, the download...
*****************************/
long difference;
byte data[] = new byte[4094];
int count;
while ((count = inputStream.read(data)) != -1 && download) {
downloadCount += count;
long stopTime = System.currentTimeMillis();
difference = stopTime - beginTime;
if (difference > 1000 && download) {
currentSpeed = downloadCount / (difference / 1000L); //for precision, because difference can be more than 1000 sometimes
averageSpeed = (averageSpeed + currentSpeed) / 2;
Log.d(TAG, "Speed: " + downloadCount + " bytes/s. " + (downloadCount / 1024) + "kB/s " + (downloadCount / 128) + "kbit/s " + (downloadCount / 1048576) + "Mb/s " + ((downloadCount) / (1024 * 128)) + "Mpbs" + (downloadCount / 131072) + "Mbit/s difference:" + difference + "ms");
if (download) {
broadcastSpeed();
}
downloadCount = 0; //Resetoidaan määrä
beginTime = stopTime;
}
if (!download) {
Log.d(TAG, "downloadAndBroadcast: download stops");
clearInputStream();
}
}
clearInputStream();
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "FAIL " + e.toString());
} finally {
Log.d(TAG, "downloadAndBroadcastURL: ");
clearInputStream();
Log.d(TAG, "downloadAndBroadcast: finally");
}
}
Does anyone have any idea? Thanks in advance!

How to split URL?

This is my code to split URL, but that code have problem. All link appear with double word, example www.utem.edu.my/portal/portal . the words /portal/portal always double in any link appear. Any suggestion to me extract links in the webpage?
public String crawlURL(String strUrl) {
String results = ""; // For return
String protocol = "http://";
// Assigns the input to the inURL variable and checks to add http
String inURL = strUrl;
if (!inURL.toLowerCase().contains("http://".toLowerCase()) &&
!inURL.toLowerCase().contains("https://".toLowerCase())) {
inURL = protocol + inURL;
}
// Pulls URL contents from the web
String contectURL = pullURL(inURL);
if (contectURL == "") { // If it fails, then try with https
protocol = "https://";
inURL = protocol + inURL.split("http://")[1];
contectURL = pullURL(inURL);
}
// Declares some variables to be used inside loop
String aTagAttr = "";
String href = "";
String msg = "";
// Finds A tag and stores its href value into output var
String bodyTag = contectURL.split("<body")[1]; // Find 1st <body>
String[] aTags = bodyTag.split(">"); // Splits on every tag
//To show link different from one another
int index = 0;
for (String s: aTags) {
// Process only if it is A tag and contains href
if (s.toLowerCase().contains("<a") && s.toLowerCase().contains("href")) {
aTagAttr = s.split("href")[1]; // Split on href
// Split on space if it contains it
if (aTagAttr.toLowerCase().contains("\\s"))
aTagAttr = aTagAttr.split("\\s")[2];
// Splits on the link and deals with " or ' quotes
href = aTagAttr.split(((aTagAttr.toLowerCase().contains("\""))? "\"" : "\'"))[1];
if (!results.toLowerCase().contains(href))
//results += "~~~ " + href + "\r\n";
/*
* Last touches to URl before display
* Adds http(s):// if not exist
* Adds base url if not exist
*/
if(results.toLowerCase().indexOf("about") != -1) {
//Contains 'about'
}
if (!href.toLowerCase().contains("http://") && !href.toLowerCase().contains("https://")) {
// http:// + baseURL + href
if (!href.toLowerCase().contains(inURL.split("://")[1]))
href = protocol + inURL.split("://")[1] + href;
else
href = protocol + href;
}
System.out.println(href);//debug
consider to use the URL class...
Use it as suggested by the documentation :
)
public static void main(String[] args) throws Exception {
URL aURL = new URL("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
}
}
the output:
protocol = http
authority = example.com:80
host = example.com
port = 80
etc
after this you can take the elements you need an create a new one string/URL :)

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;

Java FTP file get issue

I have a application that runs as a schedule.It connect to ftp server and get files from remote folder.scheduler runs in every 5min time.Sometimes when there are lot of files in remote location, scheduler runs again while first cycle is running.In such situation some times it download 0 size files even actual file size is greater than 0 in remote location.Does anyone have any idea why this happen?
below is the code to import files.
private void importEDIFiles(String host, String user, String password, String path, String road) {
try {
String edi824Path = path + "/" + EDI_824_FOLDER;
FTPBroker ftpBroker = new FTPBroker(host, user, password, edi824Path);
FTPClient client = ftpBroker.makeFTPConeection();
String os = client.getSystemName();
client.setFileTransferMode(FTP.ASCII_FILE_TYPE);
File edi824File = null;
File edi824Filebak = null;
ArrayList<FTPFile> files;
try {
FTPFile[] ftpfiles = client.listFiles();
logger.info("\t" + ftpfiles.length + " files are in ftp location ");
if (ftpfiles.length > 0) {
files = removeZeroFiles(ftpfiles);
for(int x=0;x<files.size();x++){
logger.info("name ---"+files.get(x).getName());
logger.info("size ----"+files.get(x).getSize());
}
String ftpFile = null;
logger.info("\t" + files.size() + " downloading from " + road + " rail road.");
for (int i = 0; i < files.size(); i++) {
ftpFile = files.get(i).getName();
logger.info("\t" + ftpFile + " is downloading....");
// logger.info("\t" + ftpFile + " size ...." + ftpFile.isEmpty());
String source = destinationFilePath + pathSeparator + road + pathSeparator + ftpFile;
String target = edi_824backupFilePath + pathSeparator + road + pathSeparator + ftpFile;
edi824File = new File(source);
edi824Filebak = new File(target);
FileOutputStream fosout = new FileOutputStream(source);
boolean isRetrieved = client.retrieveFile(ftpFile, fosout);
logger.debug("isRetrieved : " + isRetrieved);
FileUtils.copyFile(edi824File,edi824Filebak);
fosout.flush();
fosout.close();
boolean isDelete = client.deleteFile(ftpFile);
logger.debug("isDelete : " + isDelete);
}
} else {
logger.info("No files to Pull in the FTP Location for " + user);
//throw new RuntimeException("No files to Pull in FTP Location.");
}
} catch (Exception e) {
logger.error(e,e);
e.printStackTrace();
} finally {
client.logout();
client.disconnect();
}
} catch (Exception ex) {
logger.error(ex, ex);
ex.printStackTrace();
}
}
you can use a flag boolean isRunning(), setRunning(boolean ), and synchronize your code so that two or more threads would not run the same method at the same time

Categories

Resources