Exception: Operating System error code 3 - java

I am doing text file bulk upload in SQL Server. Whenever i tries to upload the files, gets Following Exception:
[Microsoft] [ODBC SQL Server Driver] [SQL Server]Could not bulk insert
because file 'C:/Form/Input_File/Form.txt' could not be opened.
Operating System error code 3(The system cannot find the path
specified).
Please find the below code:
public void uploadFiles()
{
File dir = new File(inputFilesPath);
String[] children = dir.list();
String completePathFileName = "";
System.out.println(" Inside Upload ::");
String saveFileNames = "";
PreparedStatement prepStat;
DBConnection dbConnection=new DBConnection();
Connection conHandler= dbConnection.getConnection();
if(null!=conHandler)
System.out.println(" Clear ::"+conHandler);
try
{
if (children != null)
{
for (int i = 0; i < children.length; i++)
{
String filename = children[i];
System.out.println(" children[i]::"+children[i]);
// File is validated based on some business rules.
if (isValidFile(filename) == 1)
{
String[] fileSplit = filename.split("E");
String[] extnSplit = fileSplit[1].trim().split(".TXT");
completePathFileName += (completePathFileName.equals(""))
? extnSplit[0] : "^" + extnSplit[0];
saveFileNames += (saveFileNames.equals(""))
? filename : "," + filename;
System.out.println(extnSplit[0]);
}
else
{
inValidFileNames += (inValidFileNames.equals(""))
? filename : ";\n" + filename;
}
}
if (!completePathFileName.trim().equals(""))
{
System.out.println(completePathFileName);
prepStat = conHandler.prepareStatement("Exec StartFileImport ?");
prepStat.setString(1, completePathFileName);
prepStat.execute();
saveFileNameToDatabase(saveFileNames);
}
}
}
catch (SQLException sql)
{
System.out.println(sql.getMessage());
}
}
Getting Connection Object from the below code:
public Connection getConnection()
{
System.out.println("In side DB Connection...");
try{
// get a database connection
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Before Driver");
conn= DriverManager.getConnection("jdbc:odbc:form26qa","form26","form26");
System.out.println("After Driver");
if(conn != null)
{
System.out.println("Connection established...");
}//if
else
{
System.out.println("Connection failed...");
}//else
}//try
catch(Exception e)
{
System.out.println("Exception ocurred..."+e);
e.printStackTrace();
}//catch
return conn;
}
Explanation:
I am reading files from the input path and tried to get the fileName and file path and uploading file into SQL Server.
Application is able to find the input file in the specified path. while uploading i am getting the above mentioned Exception
Please check and suggest me to fix the issue.

The file needs to be accessable on the server. The file path is
relative to the server, not your PC. Also, if you are trying to use a
share or a mapped drive it will not work. You need to use the UNC
path.
UNC Name Examples
\\teela\admin$ (to reach C:\WINNT)
\\teela\admin$\system32 (to reach C:\WINNT\system32)
\\teela\temp (to reach C:\temp)

Related

Trying to get a db backup from different pc on LAN network generates empty sql file

When I try to get a database backup from a different PC (called pac 1), which is connected to same local network with the accessing computer (called pac 2) server to a local machine using mysqldump
Database is on PC 1 and I want to generate a database backup on PC by executing java program. Currently I achieved this, but there is an error so an empty SQL file is created.
userPathForDbBackup is a string which takes the path from user through filechooser
mySqlPath is a variable which is a file path on pc2
String mySqlPath="C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin\\mysqldump.exe";
String name="name";
String pathFinal=userPathForDbBackup + "\\Backup_" + name + ".sql";
String[] command = {mySqlPath,"mysqldump", "-h"+dbh, "-u "+dbUser, "-p" + dbPass, dbName,">"+pathFinal};
try{
connection = create_connection.jdbc.getCon();
String executeCmd = "";
if(connection!=null){
executeCmd = "mysqldump -h"+dbh+"-u"+dbUser+" -p"+dbPass+" "+dbName+"file.sql" ;
System.out.println();
ProcessBuilder pb = new ProcessBuilder(command);
Process runtimeProcess =pb.start();
// Process runtimeProcess =Runtime.getRuntime().exec(command);
int processComplete = runtimeProcess.waitFor();
if(processComplete == 0){
System.out.println("Backup taken successfully");
} else {
System.out.println("Could not take mysql backup");
}
} else{
System.out.println("connection not sucess");
}
}catch (Exception e) {
e.printStackTrace();
}
This doesn't throw any exception, but it creates an empty SQL file in the user selected directory.
String dbName = "";
String dbUser = "";
String dbPass = "";
String dbh = "";
String dbport = "";
Connection connection;
//userPathForDbBackup is user selected path from file chooser
String pathFinal=userPathForDbBackup + "\\Backup_" + name + ".sql";
System.out.println(userPathForDbBackup+"before");
userPathForDbBackup= userPathForDbBackup+"\\Backup_name.sql";
System.out.println(userPathForDbBackup+"after");
String folderPath = userPathForDbBackup.substring(0, userPathForDbBackup.lastIndexOf("\\")) ;
File path =new File(userPathForDbBackup);
String[] executeCmd = new String[]{"C:/Program Files/MySQL/MySQL Server 5.6/bin/mysqldump.exe", "--user=" + dbUser, "--password=" + dbPass,""+ dbName,"-r"+path};
try{
connection = create_connection.jdbc.getCon();
if(connection!=null){
Process runtimeProcess =Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete != 0) { //4
// something went wrong
InputStream errorStream = runtimeProcess.getErrorStream();
byte[] buffer = new byte[errorStream.available()];
errorStream.read(buffer);
System.out.println(new String(buffer));
}
} else{
System.out.println("connection not sucess");
}
}catch (Exception e) {
e.printStackTrace();
}
finaly got this code to work

Why is the file Read-Only?

I have got a Microsoft Access database in the resource folder of my Java application.
When the user clicks a button, this database is copied to the temp directory of the PC. Then I make a temporary VBS file in the same directory and execute it.
(This VBS file calls a VBA macro within the database, that deletes some records.)
However, as the macro attempts to delete the records an error is thrown stating that the database is read only.
Why does this happen?
Here is my code:
When the user clicks the button, some variables are set and then the following code is executed:
private void moveAccess() throws IOException {
String dbName = "sys_cl_imp.accdb";
String tempDbPath = System.getenv("TEMP").replace('\\', '/') + "/" + dbName;
InputStream in = ConscriptioLegere.class.getResourceAsStream("res/" + dbName);
File f = new File(tempDbPath);
Files.copy(in, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
this.dbFilePath = tempDbPath;
System.out.println("access in temp");
f = null;
}
Then a connection is made to the database to update some data;
with
Connection con = DriverManager.getConnection("jdbc:ucanaccess://" + dbFilePath);
Statement sql = con.createStatement();
...
sql.close();
con.close();
Afterwards this is executed:
public boolean startImport() {
File vbsFile = new File(vbsFilePath);
PrintWriter pw;
try {
updateAccess();
} catch (IOException e) {
e.printStackTrace();
return false;
}
try{
pw = new PrintWriter(vbsFile);
pw.println("Set accessApp = CreateObject(\"Access.Application\")");
pw.println("accessApp.OpenCurrentDatabase (\"" + dbFilePath + "\")");
pw.println("accessApp.Run \"sys_cl_imp.importData\", \"" + saveLoc + "\"");
pw.println("accessApp.CloseCurrentDatabase");
pw.close();
Process p = Runtime.getRuntime().exec("cscript /nologo \"" + vbsFilePath + "\"");
While the process is running, the error occurres.
I don't understand why the database is open as ReadOnly.
I tried setting f to null after the copying of the db, but it proved not to work that way.
Based on this dicussion.
The solution is adding ;singleconnection=true to JDBC url. UCanAccess will close the file after JDBC connection closed.
Connection con = DriverManager.getConnection("jdbc:ucanaccess://" + dbFilePath +";singleconnection=true");
Thank you for your solution beckyang.
I managed to get it working with it, but there was a second mistake:
I deleted the contents of a table with java then closed the connection and run the vba procedure.
In the VBA I was attempting to delete the data again; but as there were none, this didn't work out.
After deleting the SQL from the VBA, the project worked :)

upload 1 GB file to unix sever using java

My requirement is to copy the file from local machine(Windows) to unix serevr. I have the code which was working fine with some Mbs data. i am using jsch lib to connect and to transfer.
But now i have to transfer the files of 1GB, 2Gb or may be 5GB.
When i am using the same approach.
Its getting failed. Its stucking at
channelsftpObj.put(from,to);
and then exception is "faliure". Nothing else coming in exception.
May i know the reason or how can i transfer these files?
private boolean executeCommand (String localDir, String remoteDir, String fileList, String actionFlg) {
boolean boolError = false;
String localPath, destinationPath;
ChannelSftp channelSFTPObj = (ChannelSftp) channelObj;
for (int i = 0; i < filelistArr.length; i++ ) {
localPath = localDir + "/" + filelistArr[i];
destinationPath = remoteDir + "/" + filelistArr[i];
try {
if (actionFlg.toLowerCase() == "upload") {
channelSFTPObj.put (localPath, destinationPath);
System.out.println ("Uploaded " + filelistArr[i] + " to " + remoteDir);
}
}
catch (SftpException e) {
System.out.println(e);
boolError = true;
}
}
channelSFTPObj.exit();
return boolError;
}
localDir is my path of my local system, remoteDir is the server path.
Successfully connected to the server.

Making Oracle DB connection Dynnamically in JSP

Connecting to database dynamically jsp
Hi, I'm trying to make connection to database dynamically.
So when user clicks link from index page, it will send parameter "OS"
so my test page will receive parameter OS, looks for matchs in textfile that has list of database information like
XP-jdbc:oracle:thin#xx.xxx.xx.xx:xxxx:XPXP1-XP_user-XP_pass
W7-jdbc:oracle:thin#YY.YYY.YY.YY:YYYY:W7W71-W7_user-W7_pass
MAC-jdbc:oracle:thin#ZZ.ZZZ.ZZ.ZZ:ZZZZ:MACO1-MAC_user-MAC_pass
LINNUX-jdbc:oracle:thin#AA.AAA.A.AA:AAAA:LINN1-LINNUX_user-LINNUX_ph1
my attempt:
String userName = request.getParameter("OS");
try{
String db = "";
String[] temp1;
String dblist = root + "\\" + "dblist.txt";
BufferedReader dbin = new BufferedReader(new FileReader(dblist));
while ((db = dbin.readLine()) != null){
temp1=db.split("-");
if ((temp1[0].equals(userName))){
connString = temp1[1].toString();
connUser = temp1[2].toString();
connPass = temp1[3].toString();
}
}
dbin.close();
}catch (IOException ex) {
System.out.println(ex);
}
try{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
Connection conn = DriverManager.getConnection(connString, connUser, connPass);
Statement stmt = conn.createStatement();
}
My problem is, this doesn't work!
I get java.sql.SQLException: Invalid Oracle URL specified when i open my web page....
What did i have wrong?
Apparently my property file was corrutped >.> that was the reason why my property file only read half of it's components...thanks for your help anyways
you could use Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); instead of DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
Also,have you checked if YY.YYY.YY.YY:YYYY is replaced by proper IP and port?

Difference in Reading .CSV file in UNIX System & Windows System

I have created a JSP code where we can upload a .csv file. The JSP Code is supported by a java code that reads the .csv file and compares the urls in the file with the DB and adds it into to the DB if the urls are not already present.
The above scenario works absolutely fine when its executed in a windows system.
I uploaded the succesfully executed web application folder to a unix system. When I executed the program in the UNIX system, the tool is not comparing the URLs with the DB and adds it.
I suspect there should be some problem in reading the .csv file in a UNIX sytem.
Am using fedora(linux) OS. Kindly let me know whether there is any differences in reading .csv file between a windows system and a unix system.
The .csv file I am using has the following contents,
http://www.topix.com,sdfasdf
http://rss.news.yahoo.com/rss/topstories,Apple
http://www.apple.com/354,sdfasdf
http://www.topix.com/rss/city/emporia-ks,sdfasdf
http://www.topix.com/rss/,sdfasdf
http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topsongs/limit=10/xml,sdfasdf
http://www.topix.com/rss/city/emp,sdfasdf
http://www.topix.com/rss/city/sandy-ut,dfgsdfg
http://www.apple.com,Yahoo
UPDATE FOR JEFF
try {
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if(item.isFormField()) {
out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
} else {
File file = new File(destinationDir,item.getName());
item.write(file);
//String temp=item.getName();
String fileToBeRead = "C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/Readcsv/files/"+item.getName();
String urlcnt="";
String srccnt="";
String contentType="";
Connection con=null;
Statement stmt=null;
final String rssvar="Rss";
final String other="Other";
int i=0;
int j=0;
try {
BufferedReader br = new BufferedReader(new FileReader(fileToBeRead));
String strLine = "";
StringTokenizer st = null;
while( (strLine = br.readLine()) != null)
{
st = new StringTokenizer(strLine, ",");
while(st.hasMoreTokens()){
urlcnt=st.nextToken();
srccnt=st.nextToken();
}
if(con==null){
SQLConnection.setURL("jdbc:sqlserver://192.168.2.53\\SQL2005;user=sa;password=365media;DatabaseName=LN_ADWEEK");
con=SQLConnection.getNewConnection();
stmt=con.createStatement();
}
try{
ResultSet rs;
boolean hasRows=false;
rs=stmt.executeQuery("select url from urls_linkins where url='"+urlcnt+"'");
while(rs.next()){
hasRows=true;
i++;
}
if(!hasRows){
j++;
URL url = new URL(urlcnt);
URLConnection url1=url.openConnection();
contentType=url1.getContentType();
PreparedStatement insertUrlStatement = con.prepareStatement("INSERT INTO urls_linkins(url, source_name, is_active, is_periodic, Link_Type, New_Entry) VALUES(?, ?, ?, ?, ?, ?)");
if(contentType.contains("rss") || contentType.contains("xml"))
{
insertUrlStatement.setString(1, urlcnt);
insertUrlStatement.setString(2, srccnt);
insertUrlStatement.setInt(3, 1);
insertUrlStatement.setInt(4, 0);
insertUrlStatement.setString(5, rssvar);
insertUrlStatement.setInt(6, 1);
insertUrlStatement.executeUpdate();
insertUrlStatement.close();
}
else{
insertUrlStatement.setString(1, urlcnt);
insertUrlStatement.setString(2, srccnt);
insertUrlStatement.setInt(3, 1);
insertUrlStatement.setInt(4, 0);
insertUrlStatement.setString(5, other);
insertUrlStatement.setInt(6, 1);
insertUrlStatement.executeUpdate();
insertUrlStatement.close();
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
out.println("<h2>"+j+" url has been added and "+i+" url already exists in the DB</h2>");
out.println("<a href=Addurl.jsp>Check URL</a>");
out.println("<a href=Addurl1.jsp>Add Single URL</a>");
out.println("<a href=uploadcsv.jsp>Add Multiple URL</a>");
}
}
out.close();
}
}catch(FileUploadException ex) {
log("Error encountered while parsing the request",ex);
} catch(Exception ex) {
log("Error encountered while uploading file",ex);
}
This is my reading code of the .csv file.
Yes there will be differences in reading the .csv file when you transfer from a windows machine to a unix machine even when it's a text file. There are hidden space characters which may be represented differently on the unix machine.
I suspect that the reason it is not comparing the URLs is because the space characters might be different ASCII values so it thinks they are different and adds the URL into the DB.
One suggestion would be to use the dos2unix command.
http://kb.iu.edu/data/acux.html
Hope it helps.

Categories