Read remote file in java which needs username and password - java

I am trying to read a remote file in java
File f = new File("//192.168.1.120/home/hustler/file.txt");
The remote machine needs a Username and Password to allow me to access the file.
Is there a way I could pass the parameters through the java code and read the file?

package com.eiq;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemOptions;
import org.apache.commons.vfs.Selectors;
import org.apache.commons.vfs.UserAuthenticator;
import org.apache.commons.vfs.VFS;
import org.apache.commons.vfs.auth.StaticUserAuthenticator;
import org.apache.commons.vfs.impl.DefaultFileSystemConfigBuilder;
public class RemoteFileDemo {
public static void main(String[] args) throws IOException {
String domain = "hyd\\all";
String userName = "chiranjeevir";
String password = "Acvsl#jun2013";
String remoteFilePath = "\\\\10.0.15.74\\D$\\Suman\\host.txt";
File f = new File("E:/Suman.txt"); //Takes the default path, else, you can specify the required path
if (f.exists()) {
f.delete();
}
f.createNewFile();
FileObject destn = VFS.getManager().resolveFile(f.getAbsolutePath());
//domain, username, password
UserAuthenticator auth = new StaticUserAuthenticator(domain, userName, password);
FileSystemOptions opts = new FileSystemOptions();
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
FileObject fo = VFS.getManager().resolveFile(remoteFilePath, opts);
System.out.println(fo.exists());
//fo.createFile();
destn.copyFrom(fo, Selectors.SELECT_SELF);
destn.close();
//InputStream is = new FileInputStream(f);
}
}
This is a program to read a file from the remote machine and store it in our local machine as file E:/Suman.txt.
Take care while writing the file path means instead of : we have to replace it with $ symbol, e.g.:
D:\Suman\Boorla\kpl.txt is wrong,
D$\\Suman\\Boorla\\kpl.txt is right.
In the above program, you have to change the domain name, username, password and file path of the remote machine.
To work with the above program we need to add the following jar files int the classpath.
commons-vfs.jar
commons-logging.jar

Another alternative with jCIFS you can easily specify authentication parameters:
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("domain", "user", "password"); // Authentication info here, domain can be null
try (InputStream is = new SmbFile("smb://192.168.1.120/home/hustler/file.txt", auth).getInputStream()) {
// Read from 'is' ...
} catch (IOException e) {
// Handle IOException
}

You can also try Commons VSF . Check UserAuthenticator

Here is the code, I've written and it is working Perfectly.
File f=new File("abc.txt"); //Takes the default path, else, you can specify the required path
if(f.exists())
{
f.delete();
}
f.createNewFile();
FileObject destn = VFS.getManager().resolveFile(f.getAbsolutePath());
UserAuthenticator auth = new StaticUserAuthenticator("", "myusername", "secret_password");
FileSystemOptions opts = new FileSystemOptions();
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
FileObject fo = VFS.getManager().resolveFile("\\\\192.168.0.1\\direcory\\to\\GetData\\sourceFile.txt",opts);
destn.copyFrom(fo,Selectors.SELECT_SELF);
destn.close();
Now you can use the file to perform the required operations. Something like...
InputStream is = new FileInputStream(f);

Related

Getting a file as a resource on classpath

I'm trying to read a keystore as a resource. Sample code below. The problem I'm running into is that inputStream remains null.
import java.io.InputStream;
import java.util.List;
import org.linguafranca.pwdb.kdbx.KdbxCreds;
import org.linguafranca.pwdb.kdbx.simple.SimpleDatabase;
import org.linguafranca.pwdb.kdbx.simple.SimpleEntry;
import org.linguafranca.pwdb.Credentials;
import org.apache.log4j.Logger;
public class Security {
private static final String PATH = null;
private static final String KEYSTORE_PASSWORD = "admin";
static List<SimpleEntry> entries = null;
final static Logger logger = Logger.getLogger(Security.class);
public Security(){
//TODO: initialize security and it's passwords
}
public static void init(){
try {
//InputStream inputStream = new FileInputStream(".keePass.kdbx");
InputStream inputStream = Security.class.getClassLoader().getResourceAsStream("keePass.kdbx");
// password credentials
Credentials credentials = new KdbxCreds(KEYSTORE_PASSWORD.getBytes());
SimpleDatabase database = SimpleDatabase.load(credentials, inputStream);
// Jaxb implementation seems a lot faster than the DOM implementation
// visit all groups and entries and list them to console
entries = database.getRootGroup().getEntries();
}catch(Exception exception){
logger.error(exception);
}
}
}
First I thought it's just a matter of path, however even though the file itself resides next to the classes, I can't load it.
Even if I use absolute path, result is the same.
What is the mistake I'm making?
When you are using getClassLoader().getResourceAsStream("...") it tries to find the file in the root of classpath. Try to use:
Security.class.getResourceAsStream("keePass.kdbx");
In this case it will try to find the file in the same location as the Security class
See more What is the difference between Class.getResource() and ClassLoader.getResource()?

how to give the password protection to Zip folder in java?

I need to set password protection for Zip folder via java, not for zip folder files. Without password i should not be able to open the Zip folder.
This is the code i found from google.
public static void encrypt(String key, InputStream is, OutputStream os)
throws Throwable {encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
}
Done using winzipaes1.0.1.jar...
Sample Code...
import java.io.File;
import java.io.IOException;
import de.idyl.winzipaes.AesZipFileEncrypter;
import de.idyl.winzipaes.impl.AESEncrypterBC;
public class Practice1Main {
public static void main(String[]args) throws IOException{
File aNewZipFile = new File("src.zip");
File existingUnzippedFile = new File("src.txt");
AESEncrypterBC encrypter = new AESEncrypterBC();
encrypter.init("password", 0); // The 0 is keySize, it is ignored for AESEncrypterBC
AesZipFileEncrypter zipEncrypter = new AesZipFileEncrypter(aNewZipFile, encrypter);
zipEncrypter.add(existingUnzippedFile, "src.txt", "password");
zipEncrypter.close();
}
}
The only free library I know of that does this is winzipaes. It has an Apache licence.
Google Code project page => https://code.google.com/p/winzipaes/
Maven Repo Link => http://mvnrepository.com/artifact/de.idyl/winzipaes

How to get a file resource in JSF project

I am trying to write a simple JSF application to let a user login on a web browser then my application should verify the users credentials on a MySQL database.
I am having trouble getting my code to see the database.properties file. I use the following code for all my stand alone database programs but I had to make some modifications for this JSF application that I am writing.
About 3/4 of the way down the following line throws a ClassNotFoundException because my url variable is null and I don't know why:
FileInputStream in = new FileInputStream(url.getFile()); // Do this if on Server
Can anyone help me? Thanks! The code in question is in the first half of method init(String fileName).
Below is the entire class for getting the data source:
package com.gmail.gmjord.datasource;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* A simple data source for getting database connections.
*/
public class SimpleDataSource {
private static String urlString;
private static String username;
private static String password;
/**
* Initializes the data source.
*
* #param fileName
* the name of the property file that contains the database
* driver, URL, username, and password
*/
public static void init(String fileName) throws IOException,
ClassNotFoundException {
// ****************** Added code for getting resource on a server
// *********************
System.out.println("In SimpleDataSource.init()");
**Class cls = Class.forName("com.gmail.gmjord.datasource.SimpleDataSource");**
System.out.println("Made it here 1");
// returns the ClassLoader object associated with this Class
ClassLoader cLoader = cls.getClassLoader();
System.out.println("Made it here 2");
System.out.println(cLoader.getClass());
// finds resource with the given name
URL url = cLoader.getResource(fileName); // This is the original line I copied from the web page
//URL url = cls.getClass().getClassLoader().getResource(fileName); // This is TA's way
System.out.println("Made it here 3");
System.out.println("File: " + fileName);
System.out.println("url Value = " + url);
// ********* End of code for getting resource on a server*******************************************************
Properties props = new Properties();
//System.out.println("File: " + fileName);
//FileInputStream in = new FileInputStream(fileName); // Do this if not on server
FileInputStream in = new FileInputStream(url.getFile()); // Do this if on Server
props.load(in);
String driver = props.getProperty("jdbc.driver");
urlString = props.getProperty("jdbc.url");
username = props.getProperty("jdbc.username");
if (username == null)
username = "";
password = props.getProperty("jdbc.password");
if (password == null)
password = "";
if (driver != null)
Class.forName(driver);
}
/**
* Gets a connection to the database.
*
* #return the database connection
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(urlString, username, password);
}
}
First you need to move the file inside to the src folder, for the next code it must be in the root of the src folder, you can load the file in this way:
Properties properties = new Properties();
properties.load(SimpleDataSource.class.getResourceAsStream("/database.properties"));

Eclipse shows errors when i write information in xml file

I use the JDOM library. When I write information into an xml file, Eclipse shows errors. The system cannot find the path specified. I try to create the file in the "language" folder. How can I create the folder automatically when I write info into this file? I think the error is in this line:
FileWriter writer = new FileWriter("language/variants.xml");
Here is my code:
package test;
import java.io.FileWriter;
import java.util.LinkedList;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
class Test {
private LinkedList<String> variants = new LinkedList<String>();
public Test() {
}
public void write() {
Element variantsElement = new Element("variants");
Document myDocument = new Document(variantsElement);
int counter = variants.size();
for(int i = 0;i < counter;i++) {
Element variant = new Element("variant");
variant.setAttribute(new Attribute("name",variants.pop()));
variantsElement.addContent(variant);
}
try {
FileWriter writer = new FileWriter("language/variants.xml");
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
outputter.output(myDocument,writer);
writer.close();
}
catch(java.io.IOException exception) {
exception.printStackTrace();
}
}
public LinkedList<String> getVariants() {
return variants;
}
}
public class MyApp {
public static void main(String[] args) {
Test choice = new Test();
choice.write();
}
}
Here is the error:
java.io.FileNotFoundException: language\variants.xml (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:104)
at java.io.FileWriter.<init>(FileWriter.java:63)
at test.Test.write(MyApp.java:31)
at test.MyApp.main(MyApp.java:49)`enter code here
As the name suggests FileWriter is for writing to file. You need to create the directory first if it doesnt already exist:
File theDir = new File("language");
if (!theDir.exists()) {
boolean result = theDir.mkdir();
// Use result...
}
FileWriter writer = ...
For creating directories you need to use mkdir() of File class.
Example:
File f = new File("/home/user/newFolder");
f.mkdir();
It returns a boolean: true if directory created and false if it failed.
mkdir() also throws Security Exception if security manager exists and it's checkWrite() method doesn't allow the named directory to be created.
PS: Before creating directory, you need to validate if this directory already exists or not by using exists() which also returns boolean.
Regards...
Mr.777

How to give FTP address in java?

I have written the code which downloads the file from FTP server. Since I have my FTP server locally and I want to access like "ftp://localhost/alfresco". It was alfresco's FTP.
I have the following Code
public class FtpTransfer {
public static final void main(String[] args)
{
FTPClient ftp = new FTPClient();
FileOutputStream br = null;
try
{
ftp.connect("ftp://localhost/alfresco");
ftp.login("admin", "admin");
String file = "KPUB//Admin//TMM//Pickup//TMM_TO_ARTESIA_06152010220246.xml";
br = new FileOutputStream("file");
ftp.retrieveFile("/"+file, br);
System.out.println("Downloaded...");
}
catch(IOException exception) {
System.out.println("Error : "+exception);
}
}
}
The following exception occurs.
Error : java.net.UnknownHostException: ftp://localhost/alfresco
Please let me know how should I give the FTP Host Address?
FTPClient f = new FTPClient();
f.connect("localhost");
f.login(username, password);
FTPFile[] files = listFiles(directory);
Also See
Article from JavaWorld
JavaDoc
Here is an example demonstrating connection to a server, changing present working directory, listing files in a directory and downloading a file to some specified directory.
package test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class FtpTransfer {
public static final void main(String[] args) throws SocketException, IOException {
FTPClient ftp = new FTPClient();
ftp.connect("ftp.somedomain.com"); // or "localhost" in your case
System.out.println("login: "+ftp.login("username", "pass"));
ftp.changeWorkingDirectory("folder/subfolder/");
// list the files of the current directory
FTPFile[] files = ftp.listFiles();
System.out.println("Listed "+files.length+" files.");
for(FTPFile file : files) {
System.out.println(file.getName());
}
// lets pretend there is a JPEG image in the present folder that we want to copy to the desktop (on a windows machine)
ftp.setFileType(FTPClient.BINARY_FILE_TYPE); // don't forget to change to binary mode! or you will have a scrambled image!
FileOutputStream br = new FileOutputStream("C:\\Documents and Settings\\casonkl\\Desktop\\my_downloaded_image_new_name.jpg");
ftp.retrieveFile("name_of_image_on_server.jpg", br);
ftp.disconnect();
}
}
Try remove protocol ("ftp://") from your url.
And please, look at the example.
The FTPClient.connect() method takes the name of a server, not a URL. Try:
ftp.connect("localhost");
Also, you may need to put alfresco somewhere else. If it's part of the file path,
String file = "alfresco/KPUB//Admin//TMM//Pickup//TMM_TO_ARTESIA_06152010220246.xml";

Categories