Monday, November 30, 2009

JCIFS rocks!

Actually, JCIFS works, the way I excpected.

Look at this:

import java.io.*;
import jcifs.smb.*;
public class t_getfile {
    public static void main(String[] args) {
        jcifs.Config.setProperty("jcifs.smb.client.username", "administrator");
        jcifs.Config.setProperty("jcifs.smb.client.password", "password");     
        try {
        SmbFileInputStream in = new SmbFileInputStream("smb://10.112.27.31/c$/Program files/Avaya/IC71/MessageCenter/Messages/9698.msg");
        byte[] b = new byte[8192];
        int n;
        while(( n = in.read( b )) > 0 ) {
            System.out.write( b, 0, n );
        }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}


What I want to achieve: from a servlet, I want to connect to a Samba (Windows) "share" and read the contents of the file.

Update:

This is even cleaner, supports multiple authentication sessions:


import jcifs.smb.*;
import java.io.*;
public class t_getfile2 {
    public static void main(String[] args) {   
        /* NtlmPasswordAuthentication object from the userinfo
         * component of an SMB URL like "domain;user:pass".
         * This constructor is used internally be jCIFS
         * when parsing SMB URLs.
         */
        NtlmPasswordAuthentication auth =  new NtlmPasswordAuthentication("administrator:password");
        try {
        SmbFile file = new SmbFile( "smb://10.112.27.31/c$/Program files/Avaya/IC71/MessageCenter/Messages/9698.msg", auth );
        InputStream in = file.getInputStream();
        byte[] b = new byte[8192];
        int n;
        while(( n = in.read( b )) > 0 ) {
            System.out.write( b, 0, n );
        } //while
        } catch (Exception e) {
            e.printStackTrace();
        } //try..catch
    }
}