Commit 89de7b23 authored by spawar's avatar spawar

D15HKAT003 added component for upload inventory on france DDUK Server


git-svn-id: http://15.206.35.175/svn/proteus/business-java/trunk@99556 ce508802-f39f-4f6c-b175-0d175dae99d5
parent cef68231
/**
* PURPOSE : Upload Inventory Stock on FTP Server
* AUTHOR : Samadhan On 07/12/2015
* Request Id: D15HKAT003
*/
package ibase.webitm.utility.wms;
import ibase.scheduler.utility.interfaces.Schedule;
import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
import ibase.webitm.utility.GenericUtility;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Properties;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTP;
import org.w3c.dom.Document;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UpoadInventorySchedule implements Schedule
{
private String hostName = "";
private String userName = "";
private String password = "";
private String remoteFilePath = "";
private String localFilePath = "";
private String uploadProtocol = "";
private String fileName = "";
public String schedulePriority( String wrkflwPriority )throws Exception
{
return "";
}
public String schedule(HashMap map)throws Exception
{
return "";
}
public String schedule(String scheduleParamXML)throws Exception
{
System.out.println("UploadInventorySchedule:schedule:calling scheduler UploadInventorySchedule..................");
Connection conn = null;
ConnDriver connDriver = null;
String tranDate="",localFileName = "fr_stock.csv",remoteFileName = "fr_stock.csv";
try
{
setDDSalesConfig();
localFileName = fileName;
remoteFileName = fileName;
connDriver = new ConnDriver();
conn = connDriver.getConnectDB("DriverITM");
connDriver = null;
GenericUtility genericUtility = GenericUtility.getInstance();
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
tranDate = simpleDateFormat.format(currentDate.getTime());
System.out.println("UploadInventorySchedule:schedule:TranDate---->>["+tranDate+"]");
System.out.println("UploadInventorySchedule:schedule:csvFileNameUpd12---->>["+localFilePath+"]");
File file = new File(localFilePath);
System.out.println("UploadInventorySchedule:schedule:file.separatorChar---->>["+File.separatorChar+"]");
file.mkdirs();
char ch = localFilePath.charAt(localFilePath.length() -1 );
System.out.println("UploadInventorySchedule:schedule:Ch @@@@---->>["+ch+"]");
if(ch != file.separatorChar)
{
localFileName = file.separator+localFileName;
}
final String localFile = localFilePath+localFileName;
char ch1 = remoteFilePath.charAt(remoteFilePath.length() -1 );
System.out.println("Ch @@@@---->>["+ch1+"]");
if(ch1 != file.separatorChar)
{
remoteFileName = file.separator+remoteFileName;
}
final String remoteFile = remoteFilePath+remoteFileName;
generateCsvFile (localFile,conn);
System.out.println("UploadInventorySchedule:schedule:CSV file successfully created....... ");
System.out.println("UploadInventorySchedule:schedule:Befour Calling putFile........");
if("SFTP".equalsIgnoreCase(uploadProtocol))
{
putFileSFTP(userName, hostName, password, remoteFilePath,localFile,22);
}
else if("SCP".equalsIgnoreCase(uploadProtocol))
{
putFileSCP(userName, hostName, password, remoteFile,localFile,22);
}
else
{
putFileFTP(userName, hostName, password, remoteFile,localFile,21);
}
System.out.println("UploadInventorySchedule:schedule:After putFile........");
System.out.println("UploadInventorySchedule:schedule:End of program........");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(conn != null)
{
conn.close();
conn = null;
}
}
return "";
}
private void generateCsvFile(String sFileName,Connection conn) throws IOException,Exception
{
System.out.println("UploadInventorySchedule:schedule:calling generateCsvFile..................");
ResultSet rs = null;
PreparedStatement pstmt = null;
String sql="";
File newFile = new File(sFileName);
if(newFile.exists())
newFile.createNewFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(sFileName));
writer.append("productID");
writer.append(',');
writer.append("productBarcodeUPC");
writer.append(',');
writer.append("productStock");
writer.append(',');
writer.append("productStockExpected");
writer.append('\n');
sql="SELECT S.ITEM_CODE,I.UDF__STR2,SUM(S.QUANTITY) - (DECODE(SUM(S.ALLOC_QTY),NULL,0,SUM(S.ALLOC_QTY)))+" +
"(DECODE(SUM(S.HOLD_QTY),NULL,0,SUM(S.HOLD_QTY))) AS QUANTITY FROM STOCK S,ITEM I " +
"WHERE S.ITEM_CODE = I.ITEM_CODE AND I.ITEM_SER = ? AND S.QUANTITY > 0 " +
"GROUP BY I.ACTIVE, S.ITEM_CODE,I.UDF__STR2 HAVING SUM(S.QUANTITY) - " +
"(DECODE(SUM(S.ALLOC_QTY),NULL,0,SUM(S.ALLOC_QTY)))+" +
"(DECODE(SUM(S.HOLD_QTY),NULL,0,SUM(S.HOLD_QTY))) >0";
pstmt =conn.prepareStatement(sql);
pstmt.setString(1, "COS");
rs = pstmt.executeQuery();
while(rs.next())
{
writer.append("\""+checkNullAndTrim(rs.getString(1))+"\"");
writer.append(',');
writer.append("\""+checkNullAndTrim(rs.getString(2))+"\"");
writer.append(',');
writer.append("\""+checkNullAndTrim(rs.getString(3))+"\"");
writer.append(',');
writer.append("\"\"");
writer.append('\n');
}
if(rs != null)
{
rs.close();
rs = null;
}
if(pstmt !=null)
{
pstmt.close();
pstmt = null;
}
writer.flush();
writer.close();
}
private static void showServerReply(FTPClient ftpClient)
{
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0)
{
for (String aReply : replies)
{
System.out.println("UploadInventorySchedule:showServerReply:SERVER: " + aReply);
}
}
}
public String checkNullAndTrim(String input)
{
if (input == null || "null".equalsIgnoreCase(input))
{
input= "";
}
return input.trim();
}
private void setDDSalesConfig()
{
GenericUtility genericUtility=GenericUtility.getInstance();
String xmlString = "";
Document dom=null;
String sCurrentLine = "";
System.out.println(" in setDDSalesConfig -------------------------");
String xmlFileName = CommonConstants.APPLICATION_CONTEXT + "setting" + File.separator + "DDSalesConfig.xml";
StringBuilder sb = new StringBuilder();
System.out.println("xmlFileName-->>["+xmlFileName+"]");
try
{
BufferedReader br = new BufferedReader(new FileReader(xmlFileName));
while (( sCurrentLine = br.readLine()) != null)
{
sb.append(sCurrentLine);
}
xmlString =sb.toString();
System.out.println("DDSalesConfig xmlString---->>["+xmlString+"]");
dom = genericUtility.parseString(xmlString);
if(dom != null)
{
this.localFilePath = genericUtility.getColumnValue("STOCK_TEMP_UPD_PATH",dom);
this.hostName = genericUtility.getColumnValue("INVTR_UPD_HOST",dom);
this.userName = genericUtility.getColumnValue("INVTR_UPD_USER",dom);
this.password = genericUtility.getColumnValue("INVTR_UPD_PWD",dom);
this.remoteFilePath = genericUtility.getColumnValue("INVTR_UPD_REMOTE_PATH",dom);
this.uploadProtocol = genericUtility.getColumnValue("INVTR_UPD_PROTOCOL",dom);
this.fileName = genericUtility.getColumnValue("INVTR_UPD_FILE_NAME", dom);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
private void putFileFTP(String username, String host, String password, String remotefile, String localfile,int port)
{
FTPClient ftpClient = new FTPClient();
System.out.println("preparing the host information for ftp.");
try
{
System.out.println("Remote File: "+remotefile);
System.out.println("Local File: "+localfile);
ftpClient.connect(host, port);
showServerReply(ftpClient);
int replyCode = ftpClient.getReplyCode();
boolean uploadStatus= false;
if (!FTPReply.isPositiveCompletion(replyCode))
{
System.out.println("Operation failed. Server reply code: " + replyCode);
return;
}
boolean success = ftpClient.login(username, password);
showServerReply(ftpClient);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
if (!success)
{
System.out.println("Could not login to the server");
return;
}
else
{
System.out.println("LOGGED IN SERVER");
File firstLocalFile = new File(localfile);
InputStream inputStream = new FileInputStream(firstLocalFile);
uploadStatus = ftpClient.storeFile(remotefile, inputStream);
inputStream.close();
if (ftpClient.isConnected())
{
ftpClient.logout();
ftpClient.disconnect();
}
System.out.println("File Uploaded Status:"+uploadStatus);
if(uploadStatus)
{
System.out.println("File Uploaded successfully");
}
else
{
System.out.println("File can't Uploaded successfully");
}
}
}
catch (IOException ex)
{
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
}
}
private void putFileSFTP(String username, String host, String password, String remoteDestPath, String localFile,int port)
{
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try
{
System.out.println("user name: ["+username+"]password["+password+"]host["+host+"]Port["+port+"]");
System.out.println("Localfile:"+localFile);
System.out.println("RemotePath:"+remoteDestPath);
JSch jsch = new JSch();
session = jsch.getSession(username, host, port);
session.setPassword(password);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(remoteDestPath);
File f = new File(localFile);
channelSftp.put(new FileInputStream(f), f.getName());
System.out.println("File Uploaded successfully");
} catch (Exception ex)
{
System.out.println("Exception found while Uploading a file.");
ex.printStackTrace();
}
finally
{
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
private boolean putFileSCP(String username, String host, String password, String remotefile, String localfile,int port)
{
FileInputStream fis=null;
JSch jsch=new JSch();
Session session = null;
Channel channel = null;
OutputStream out=null;
InputStream in=null;
try
{
System.out.println("preparing the host information for SCP.");
session=jsch.getSession(username, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking","no");
session.setConfig(config);
session.connect();
boolean ptimestamp = true;
String command="scp " + (ptimestamp ? "-p" :"") +" -t "+remotefile;
channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
out=channel.getOutputStream();
in=channel.getInputStream();
channel.connect();
if(checkAck(in)!=0)
{
out.close();
channel.disconnect();
session.disconnect();
return false;
}
File _lfile = new File(localfile);
if(ptimestamp)
{
command="T "+(_lfile.lastModified()/1000)+" 0";
command+=(" "+(_lfile.lastModified()/1000)+" 0\n");
out.write(command.getBytes());
out.flush();
if(checkAck(in)!=0)
{
out.close();
channel.disconnect();
session.disconnect();
return false;
}
}
long filesize=_lfile.length();
command="C0644 "+filesize+" ";
if(localfile.lastIndexOf('/')>0){
command+=localfile.substring(localfile.lastIndexOf('/')+1);
}
else{
command+=localfile;
}
command+="\n";
out.write(command.getBytes()); out.flush();
if(checkAck(in)!=0)
{
out.close();
channel.disconnect();
session.disconnect();
return false;
}
fis=new FileInputStream(localfile);
byte[] buf=new byte[1024];
while(true)
{
int len=fis.read(buf, 0, buf.length);
if(len<=0)
break;
out.write(buf, 0, len);
}
fis.close();
fis=null;
buf[0]=0;
out.write(buf, 0, 1);
out.flush();
if(checkAck(in)!=0)
{
System.out.println("File can't Uploaded Successfully.......");
out.close();
channel.disconnect();
session.disconnect();
return false;
}
out.close();
channel.disconnect();
session.disconnect();
System.out.println("File Uploaded Successfully.......");
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e);
try
{
if(fis!=null)fis.close();
}
catch(Exception ee){}
}
finally
{
try
{
if(fis!=null)
{
fis.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
if(channel!=null)
{
channel.disconnect();
}
if(channel!=null)
{
session.disconnect();
}
if(in !=null)
{
try
{
in.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
if(out != null)
{
try
{
out.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
return true;
}
static int checkAck(InputStream in) throws IOException
{
int b=in.read();
if(b==0)
return b;
if(b==-1)
return b;
if(b==1 || b==2)
{
StringBuffer sb=new StringBuffer();
int c;
do
{
c=in.read();
sb.append((char)c);
}
while(c!='\n');
if(b==1){ // error
System.out.print(sb.toString());
}
if(b==2){ // fatal error
System.out.print(sb.toString());
}
}
return b;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment