I am using Apache Commons VFS2 to upload a file to server. Below is the code for the same. I have all the credentials right. The code printed "File uploaded successfully" String as well. But, I could not find the file on server when i cross checked it. Is there anything i am missing here in the code ?
I have all the Jars required (Apache Commons VFS jars, JSH jar)
public static void main(String[] args) {
SendMyFiles sendMyFiles = new SendMyFiles();
sendMyFiles.startFTP("C:/useragent.log");
}
public boolean startFTP(String fileToFTP) {
props = new Properties();
StandardFileSystemManager manager = new StandardFileSystemManager();
try {
// props.load(new FileInputStream("properties/" +
// propertiesFilename));
String serverAddress = "10.111.111.11";
String userId = "username";
String password = "password";
String remoteDirectory = "local/home/client/files/";
// check if the file exists
String filepath = fileToFTP;
File file = new File(filepath);
if (!file.exists())
throw new RuntimeException("Error. Local file not found");
// Initializes the file manager
manager.init();
// Setup our SFTP configuration
FileSystemOptions opts = new FileSystemOptions();
SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
// Create the SFTP URI using the host name, userid, password, remote
// path and file name
String sftpUri = "sftp://" + userId + ":" + password + "#" + serverAddress + "/" + remoteDirectory;
// Create local file object
FileObject localFile = manager.resolveFile(file.getAbsolutePath());
// Create remote file object
FileObject remoteFile = manager.resolveFile(sftpUri, opts);
// Copy local file to sftp server
remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
System.out.println("File upload successful");
} catch (Exception ex) {
ex.printStackTrace();
return false;
} finally {
manager.close();
}
return true;
}
I'd assume that the sftpUri should be a path to the destination file, not directory:
String sftpUri =
"sftp://" + userId + ":" + password + "#" + serverAddress + "/" + remoteDirectory + "/" +
file.getName();
Related
I'm trying to make a launcher for my Java desktop application (separated applications), which has to look for an updated version of the main application on the server. My idea is to store the app version inside of a text file on each side.
I found (thanks to Google san) the way to read the version from the text file and download the jar directory with all of it's content (both on server side). I'm using the Apache Commons Net FTP library btw.
The problem comes when I try to download the jar directory from the server after beeing reading the text file. I get the text file content correctly, the files download fails though.
If I switch code lines to download the stuff first and then read the text file, both of them works well, but we all know that's not the way an update check should be.
I've been looking and I don't get what I'm doing wrong. It's my first time working with this library.
This is the code I'm working with:
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
class FTPUtil{
private String server = "www.server.host";
private int port = 21;
private String user = "user";
private String pass = "password";
private FTPClient ftpClient = new FTPClient();
public void Connect() throws IOException{
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
System.out.println("Connected");
}
public void Disconnect() throws IOException{
ftpClient.logout();
ftpClient.disconnect();
System.out.println("Disconnected");
}
public double getServerVersion(String remoteDirPath) throws IOException{
InputStream inputStream = ftpClient.retrieveFileStream(remoteDirPath + "/version.txt");
return Double.parseDouble(IOUtils.toString(inputStream, "UTF-8"));
}
public boolean downloadSingleFile(String remoteFilePath, String savePath) throws IOException{
File downloadFile = new File(savePath);
File parentDir = downloadFile.getParentFile();
if(!parentDir.exists())
parentDir.mkdir();
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));
try{
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
return ftpClient.retrieveFile(remoteFilePath, outputStream);
}catch(IOException e){
throw e;
}finally{
if(outputStream != null)
outputStream.close();
}
}
public void downloadDirectory(String parentDir, String currentDir, String saveDir) throws IOException{
String dirToList = parentDir;
if(!currentDir.equals(""))
dirToList += "/" + currentDir;
FTPFile[] subFiles = ftpClient.listFiles(dirToList);
if(subFiles != null && subFiles.length > 0){
for(FTPFile aFile : subFiles){
String currentFileName = aFile.getName();
// skip parent directory and the directory itself
if(currentFileName.equals(".") || currentFileName.equals(".."))
continue;
String filePath = parentDir + "/" + currentDir + "/" + currentFileName;
if(currentDir.equals(""))
filePath = parentDir + "/" + currentFileName;
String newDirPath = saveDir + parentDir + File.separator + currentDir + File.separator + currentFileName;
if(currentDir.equals(""))
newDirPath = saveDir + parentDir + File.separator + currentFileName;
if(aFile.isDirectory()){
// create the directory in saveDir
File newDir = new File(newDirPath);
boolean created = newDir.mkdirs();
if(created)
System.out.println("CREATED the directory: " + newDirPath);
else
System.out.println("COULD NOT create the directory: " + newDirPath);
// download the sub directory
downloadDirectory(dirToList, currentFileName, saveDir);
}else{
// download the file
boolean success = downloadSingleFile(filePath, newDirPath);
if(success)
System.out.println("DOWNLOADED the file: " + filePath);
else
System.out.println("COULD NOT download the file: " + filePath);
}
}
}
}
}
import java.io.IOException;
public class Main{
public static void main(String[] args){
String project = "ServerFolderName";
String remoteDirPath = "/" + project;
String saveDirPath = "C:/Users/username/Desktop";
FTPUtil ob = new FTPUtil();
try{
ob.Connect();
System.out.println(ob.getServerVersion(remoteDirPath));
ob.downloadDirectory(remoteDirPath, "", saveDirPath);
ob.Disconnect();
}catch(IOException e){
e.printStackTrace();
}
}
}
And the console output:
run:
Connected
1.0
Exception in thread "main" org.apache.commons.net.ftp.parser.ParserInitializationException: Unknown parser type: 0.000 seconds (measured here), 37.12 Kbytes per second
at org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory.createFileEntryParser(DefaultFTPFileEntryParserFactory.java:170)
at org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory.createFileEntryParser(DefaultFTPFileEntryParserFactory.java:94)
at org.apache.commons.net.ftp.FTPClient.__createParser(FTPClient.java:3381)
at org.apache.commons.net.ftp.FTPClient.initiateListParsing(FTPClient.java:3338)
at org.apache.commons.net.ftp.FTPClient.listFiles(FTPClient.java:3016)
at generateupdateinfo.FTPUtil.downloadDirectory(FTPUtil.java:58)
at generateupdateinfo.Main.main(Main.java:13)
C:\Users\username\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
Maybe I'm going the wrong way doing this launcher/updater, I'm open to suggestions and new ideas to achieve it.
Edit:
I noticed that it works if I renew the server connection with Disconnect() and Connect() after reading the text file and before downloading the files. I still feel should be another way, doesn't look quite good.
ob.Connect();
System.out.println(ob.getServerVersion(remoteDirPath));
ob.Disconnect();
ob.Connect();
ob.downloadDirectory(remoteDirPath, "", saveDirPath);
ob.Disconnect();
I found the problem. Apparently I just have to flush the server replies with ftpClient.completePendingCommand() after reading the version from the text file. I still do not get why happens just with one of both processes though, I would like to understand.
Thanks!:)
The following code works like a charm in eclipse under windows:
public static void main(String[] args)
{
try
{
String filePath = "\\\\myserver\\dir";
String fileName = "myFile.txt";
FileWriter myFileWriter = new FileWriter(filePath + File.separator + fileName);
BufferedWriter myBufferedWriter = new BufferedWriter(myFileWriter);
myBufferedWriter.write("test");
myBufferedWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Now I want to run this code from a unix machine in the same network. The program runs, but does not write my file or throws an exception. Any ides ?
Cheers
If that destination unix machine has Samba installed you might want to try the following library:
http://jcifs.samba.org/
You would need a username and password though.
try {
String filePath = "myserver/dir";
String fileName = "myFile.txt";
String user = "username";
String password = "password";
// URL: smb://user:passwd#host/share/filname
SmbFileOutputStream out = new SmbFileOutputStream("smb://" + user + ":" + password + "#" + filePath
+ File.separator + fileName);
out.write("test".getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
}
This would also work with a windows machine as the destination if the server is configured as an SMB server.
Because in Unix/Linux this is not the right path
String filePath = "\\\\myserver\\dir";
I suggest to check such path exist, and 99% chances you will not have permission to create them. It would be more or less
String filePath = "/usr/xx/";
Creating folder:
File temp = new File("temp");
boolean test = temp.mkDir();
Hello i m trying to upload file using java file.. but i don't get it.. i get file size=0 i'm providing here my java code. tell me why i cant upload on particular folder. i want to store my file in particular folder. i am trying to get file size, file name but i got the null value where am i wrong please tell me.
public void updateTesti(ActionRequest actionRequest,ActionResponse actionResponse) throws IOException, PortletException
{
//image upload logic
String folder_for_upload =(getPortletContext().getRealPath("/"));
//String folder=actionRequest.getParameter("uploadfolder");
realPath=getPortletContext().getRealPath("/");
logger.info("RealPath is" + realPath);
logger.info("Folder is :" + folder_for_upload);
try
{
logger.info("Admin is try to upload");
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
if (uploadRequest.getSize("fileName") == 0) {
SessionErrors.add(actionRequest, "error");
}
String sourceFileName = uploadRequest.getFileName("fileName");
File uploadedFile = uploadRequest.getFile("fileName");
System.out.println("Size of uploaded file: " + uploadRequest.getSize("fileName"));
logger.info("Uploded file name is: " + uploadRequest.getFileName("fileName"));
String destiFolder=("/home/ubuntu/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/webapps/imageUpload-portlet/image");
String newsourcefilename = (uploadRequest.getFileName("fileName"));
File newFile = new File(destiFolder +"/"+ newsourcefilename);
logger.info("New file name: " + newFile.getName());
logger.info("New file path: " + newFile.getPath());
InputStream in = new BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(uploadedFile);
FileOutputStream fos = new FileOutputStream(newFile);
byte[] bytes_ = FileUtil.getBytes(in);
int i = fis.read(bytes_);
while (i != -1) {
fos.write(bytes_, 0, i);
i = fis.read(bytes_);
}
fis.close();
fos.close();
Float size = (float) newFile.length();
System.out.println("file size bytes:" + size);
System.out.println("file size Mb:" + size / 1048576);
logger.info("File created: " + newFile.getName());
SessionMessages.add(actionRequest, "success");
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (NullPointerException e)
{
System.out.println("File Not Found");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (IOException e1)
{
System.out.println("Error Reading The File.");
SessionMessages.add(actionRequest, "error");
e1.printStackTrace();
}
}
You need to do this to upload small files < 1kb
File f2 = uploadRequest.getFile("fileupload", true);
They are stored in memory only. I have it in my catch statement incase I get a null pointer - or incase my original file (f1.length) == 0
I have executed your code.It is working as per expectation.There might be something wrong in your jsp page.I am not sure but might be your name attribute is not same as the one which you are using in processAction(assuming that you are using portlet).Parameter is case sensitive,so check it again.
You will find more on below link.It has good explanation in file upload.
http://www.codeyouneed.com/liferay-portlet-file-upload-tutorial/
I went through a file upload code, and when i implement that in my local system what i got is, portlet is saving the file i upload in tomcat/webbapp/abc_portlet_project location, what i dont understand is from where portlet found
String folder = getInitParameter("uploadFolder");
String realPath = getPortletContext().getRealPath("/");
System.out.println("RealPath" + realPath +"\\" + folder); try {
UploadPortletRequest uploadRequest =
PortalUtil.getUploadPortletRequest(actionRequest);
System.out.println("Size: "+uploadRequest.getSize("fileName"));
if (uploadRequest.getSize("fileName")==0)
{SessionErrors.add(actionRequest, "error");}
String sourceFileName = uploadRequest.getFileName("fileName"); File
file = uploadRequest.getFile("fileName");
System.out.println("Nome file:" +
uploadRequest.getFileName("fileName")); File newFolder = null;
newFolder = new File(realPath +"\" + folder);
if(!newFolder.exists()){ newFolder.mkdir(); }
File newfile = null;
newfile = new File(newFolder.getAbsoluteFile()+"\"+sourceFileName);
System.out.println("New file name: " + newfile.getName());
System.out.println("New file path: " + newfile.getPath());
InputStream in = new
BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(file); FileOutputStream fos
= new FileOutputStream(newfile);
How to backup a mysql database from a java code such that:
It's saving path is dynamically allocated.
Spaces in Path do not create problems.
Path is generated using the executing jar file.
DBname,DBusername or DBpass are dynamically allotted.
Creating a specialized folder to save the backup file.
Note: The codes given below are one way of solving the problem and probably not the best method. Everything is changeable inside the code. If you do not have mysql in environment variables, add the path before mysqldump and mysql (e.g. For XAMPP, C:\xampp\mysql\bin\mysqldump)
(Hope, this will solve your problems. Took me a day to completely figure out everything and implement them properly)
Method for Backup:
public static void Backupdbtosql() {
try {
/*NOTE: Getting path to the Jar file being executed*/
/*NOTE: YourImplementingClass-> replace with the class executing the code*/
CodeSource codeSource = YourImplementingClass.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
String jarDir = jarFile.getParentFile().getPath();
/*NOTE: Creating Database Constraints*/
String dbName = "YourDBName";
String dbUser = "YourUserName";
String dbPass = "YourUserPassword";
/*NOTE: Creating Path Constraints for folder saving*/
/*NOTE: Here the backup folder is created for saving inside it*/
String folderPath = jarDir + "\\backup";
/*NOTE: Creating Folder if it does not exist*/
File f1 = new File(folderPath);
f1.mkdir();
/*NOTE: Creating Path Constraints for backup saving*/
/*NOTE: Here the backup is saved in a folder called backup with the name backup.sql*/
String savePath = "\"" + jarDir + "\\backup\\" + "backup.sql\"";
/*NOTE: Used to create a cmd command*/
String executeCmd = "mysqldump -u" + dbUser + " -p" + dbPass + " --database " + dbName + " -r " + savePath;
/*NOTE: Executing the command here*/
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
/*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
if (processComplete == 0) {
System.out.println("Backup Complete");
} else {
System.out.println("Backup Failure");
}
} catch (URISyntaxException | IOException | InterruptedException ex) {
JOptionPane.showMessageDialog(null, "Error at Backuprestore" + ex.getMessage());
}
}
Method for Restore:
public static void Restoredbfromsql(String s) {
try {
/*NOTE: String s is the mysql file name including the .sql in its name*/
/*NOTE: Getting path to the Jar file being executed*/
/*NOTE: YourImplementingClass-> replace with the class executing the code*/
CodeSource codeSource = YourImplementingClass.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
String jarDir = jarFile.getParentFile().getPath();
/*NOTE: Creating Database Constraints*/
String dbName = "YourDBName";
String dbUser = "YourUserName";
String dbPass = "YourUserPassword";
/*NOTE: Creating Path Constraints for restoring*/
String restorePath = jarDir + "\\backup" + "\\" + s;
/*NOTE: Used to create a cmd command*/
/*NOTE: Do not create a single large string, this will cause buffer locking, use string array*/
String[] executeCmd = new String[]{"mysql", dbName, "-u" + dbUser, "-p" + dbPass, "-e", " source " + restorePath};
/*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
Process runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
/*NOTE: processComplete=0 if correctly executed, will contain other values if not*/
if (processComplete == 0) {
JOptionPane.showMessageDialog(null, "Successfully restored from SQL : " + s);
} else {
JOptionPane.showMessageDialog(null, "Error at restoring");
}
} catch (URISyntaxException | IOException | InterruptedException | HeadlessException ex) {
JOptionPane.showMessageDialog(null, "Error at Restoredbfromsql" + ex.getMessage());
}
}
If Hibernate is configured properly, this is cake:
Session session = HibernateUtil.getSessionFactory().openSession();
// for every table, have the bean implement Serializable and use the next 4 lines
List <TblBean> tblCollection = session.createCriteria(TblBean.class).list();
FileOutputStream backup = new FileOutputStream("backupOf"+TblBean.getClass().getName()+".dat");
ObjectOutputStream backupWriter = new ObjectOutputStream(backup);
backupWriter.write(tblCollection);
public static String getData(String host, String port, String user, String password, String db,String table) throws Exception {
//an "C:/xampp/mysql/bin/mysqldump" ---- location ito han mysqldump
Process run = Runtime.getRuntime().exec(
"C:/xampp/mysql/bin/mysqldump --host=" + host + " --port=" + port +
" --user=" + user + " --password=" + password +
" --compact --databases --add-drop-table --complete-insert --extended-insert " +
"--skip-comments --skip-triggers "+ db+" --tables "+table);
InputStream in = run.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuffer temp = new StringBuffer();
int count;
char[] cbuf = new char[BUFFER];
while ((count = br.read(cbuf, 0, BUFFER)) != -1)
temp.append(cbuf, 0, count);
br.close();
in.close();
return temp.toString();
}
In addition to chettyharish's answer, if your server os is ubuntu the path should have front slash '/' instead of backslash '\' such as /path/to/your/file
For example: String savePath = "\"" + jarDir + "\\backup\\" + "backup.sql\"";
Will be : String savePath="/"+jarDir+"/backup/backup.sql"
I have this file sharing program, where i can get mye files from a local location JFileChooser chooser = new JFileChooser("C://Users"), but i want to get files from a Server using an IP address. I have trying String hostname = "192.168.1.1"; but its not working. When i open the file chooser i get to my own folder. some tips?
public void download(String username) throws RemoteException, NullPointerException{
JFileChooser chooser = new JFileChooser("//" + hostname + "/C://");
chooser.setFileView(new FileView() {
#Override
public Boolean isTraversable(File f) {
return (f.isDirectory() && f.getName().equals("C://"));
}
});
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
} try {
String fileName = chooser.getSelectedFile().getName();
File selectedFile = chooser.getSelectedFile();
//String name = "//" + hostname + "/chatter";
System.out.println(fileName);
//ChatFront cf = (ChatFront) Naming.lookup(name);
String ClientDirectory = getProperty + "/desktop/";
byte[] filedata = cf.downloadFile(selectedFile);
File file = new File(fileName);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(ClientDirectory + file.getName()));
output.write(filedata, 0, filedata.length);
notifySelf(getUsername(), "You have now downloaded: " + file.getName() + " from the server");
output.flush();
output.close();
} catch (Exception e) {
System.err.println("FileServer exception: " + e.getMessage());
e.printStackTrace();
}
}
Thanks in Advance :)
You're using "//" + hostname + "/C://" as the path for your JFileChooser. That's not a valid path. If you're trying to access files in a shared folder on a LAN, the path for that looks like \\hostname\sharename.
Even if no shared folders have been defined on the remote machine, may be an "administrative share" of the C: drive called C$, so you could use \\hostname\C$. But you have to authenticate as a valid user on that system to have permission to access the share. (I'm not sure how that'll work when you try to acccess the path from a Java program — Windows might pop up a login box for the remote system, or it might just fail.)