Java file chooser that remembers last location

For those who got the Open Source fever, sharing only makes you hot!

Moderator: neilg

Java file chooser that remembers last location

Postby neilg » Fri Jun 17, 2005 6:05 am

Often you need to prompt the user for a file (e.g. in a Compiere process). The system (using the JFileChooser dialog java class) displays a prompt and the user must browse on the hard drive for the file or directory.

It would also be nice if the system remembered the last location the user used otherwise they are continually browsing their hard drive which can be a bit of a pain.

The plan is to store the user's last used directory in the AD_Preference table (could be there is a better place)

There are three classes FileChooserManager,ValuePreferenceManager and SystemException

You can use it from a SvrProcess (report & process) as follows
Code: Select all
File file=FileChooserManager.getFile(getCtx(), "Choose a file to import from", "csv");
       
if (file==null) {
   return "User cancelled the selection";
}


FileChooserManager
Code: Select all
import java.io.File;
import java.util.Properties;

import javax.swing.JFileChooser;

import org.compiere.model.MUser;
import org.compiere.util.Env;
import org.compiere.util.ExtensionFileFilter;
import org.compiere.util.Logger;
import org.compiere.util.Msg;

/**
* Managed file chooser
* Lookup a file, store the path that the user selected so that next time
*  we use the same path for convenience sake
*/
public class FileChooserManager
{
   
    /**   Logger                     */
    private static Logger s_log = Logger.getCLogger(FileChooserManager.class);
   
    /**   Logger                     */
    protected Logger         log = Logger.getCLogger (getClass());
   
   
    public FileChooserManager()
    {
    }
   
    /**
     * Display a file selection dialog
     *
     * File file=ZZLib.getFile("Export Allocation (Specify the .csv extension)", "csv");
     String status="";
     if (file==null) {
     status="User cancelled file selection";
     throw new Exception(status);
     }
     * @param ctx
     * @param title
     * @param fileExtension e.g. csv
     * @return  File or null
     */
    public static File getFile(Properties ctx, String title, String fileExtension)
    {
        s_log.debug("FileChooserManager");
        File file = null;
        String dirName =null;
        dirName=getLastUsedDirectory(ctx);
        if (!validateDir(dirName))
        {
            s_log.debug("FileChooserManager - '" + dirName + "' is invalid *******");
            dirName=org.compiere.Compiere.getCompiereHome() ;
        }
        JFileChooser chooser = new JFileChooser(dirName);
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setMultiSelectionEnabled(false);
        chooser.setDialogTitle(Msg.translate(Env.getCtx(), title));
        chooser.addChoosableFileFilter(new ExtensionFileFilter(fileExtension, fileExtension));
       
        //  Show it
        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
        {
            file = chooser.getSelectedFile();
            setLastUsedDirectory(ctx, file.getParent());
        }
        else
        {
            file = null;
        }
        chooser = null;
   
        return file;
    }   //  getFile
   

    private static String getLastUsedDirectory(Properties ctx)
    {
        String ret;
        ret=getPreference(ctx).get();
        return ret;
    }
   
    private static void setLastUsedDirectory(Properties ctx, String dir)
    {
        if (dir!=null)
        {
            getPreference(ctx).set(dir);
        } else
        {
            getPreference(ctx).set("");
        }
    }
   
    private static boolean validateDir(String dir)
    {
        File file;
       
        file=new File(dir);
        if (file.canRead())
        {
            return true;
        }
        return false;
    }
   
    private static ValuePreferenceManager getPreference(Properties ctx)
    {
        String prefName;
        MUser user;
        ValuePreferenceManager pref;
       
        user=new MUser(ctx, Env.getAD_User_ID(ctx));
        prefName="Last Used Directory " + user.getName();
       
        pref=new ValuePreferenceManager(
                ctx,
                new Integer(Env.getAD_Client_ID(ctx)),  /*m_AD_Client_ID*/
                new Integer(0),                         /*m_AD_Org_ID*/
                new Integer(Env.getAD_User_ID(ctx)) ,   /*Env.getAD_User_ID(ctx) */
                null,                                   /*m_AD_Window_ID*/
                prefName
        );
        return pref;
    }
   
}


ValuePreferenceManager
Code: Select all

import java.util.Properties;

import org.compiere.util.DB;
import org.compiere.util.Log;
import org.compiere.util.Logger;

/**
* Adapted from the standard Compiere value preference code
*
*/
/*
* UNIQUE INDEX COMPIERE.AD_PREFERENCE_ATTRIBUTE
    ON COMPIERE.AD_PREFERENCE(AD_CLIENT_ID, AD_ORG_ID, AD_WINDOW_ID, AD_USER_ID, ATTRIBUTE)
*/
public class ValuePreferenceManager
{

    /**   Logger                     */
    private static Logger s_log = Logger.getCLogger(ValuePreferenceManager.class);

    /**   Logger                     */
    protected Logger         log = Logger.getCLogger (getClass());
   
    private Properties m_ctx;
    private Integer m_AD_Client_ID;
    private Integer m_AD_Org_ID;
    private Integer m_AD_User_ID;
    private Integer m_AD_Window_ID;
    private String m_Attribute;
    private String m_Value;
   
    public ValuePreferenceManager(
            Properties ctx,
            Integer m_AD_Client_ID,
            Integer m_AD_Org_ID,
            Integer m_AD_User_ID,
            Integer m_AD_Window_ID,
            String m_Attribute
            )
    {
        this.m_ctx=ctx;
        this.m_AD_Client_ID=m_AD_Client_ID;
        this.m_AD_Org_ID=m_AD_Org_ID;
        this.m_AD_User_ID=m_AD_User_ID;
        this.m_AD_Window_ID=m_AD_Window_ID;
        this.m_Attribute=m_Attribute;
    }

    public void set(String value)
    {
        m_Value=value;
        insert();
    }
   
    /**
     *  Save to Disk
     */
    private void insert()
    {
        Log.trace(Log.l1_User, "ValuePreference.insert");

        //  --- Delete first
        int no = delete();
       

        //  --- Inserting
        int Client_ID = m_AD_Client_ID.intValue();
        int Org_ID = m_AD_Org_ID.intValue();
        int AD_Preference_ID = DB.getNextID(m_ctx, "AD_Preference", null);
        //
        /*
         * UNIQUE INDEX COMPIERE.AD_PREFERENCE_ATTRIBUTE
            ON COMPIERE.AD_PREFERENCE(AD_CLIENT_ID, AD_ORG_ID, AD_WINDOW_ID, AD_USER_ID, ATTRIBUTE)
         */
        StringBuffer sql = new StringBuffer ("INSERT INTO AD_Preference ("
            + "AD_Preference_ID, AD_Client_ID, AD_Org_ID, IsActive, Created,CreatedBy,Updated,UpdatedBy,"
            + "AD_Window_ID, AD_User_ID, Attribute, Value) VALUES (");
        sql.append(AD_Preference_ID).append(",").append(Client_ID).append(",").append(Org_ID)
            .append(", 'Y',SysDate,").append(m_AD_User_ID).append(",SysDate,").append(m_AD_User_ID).append(", ");
        if (m_AD_Window_ID==null)
            sql.append("null").append(",");
        else
            sql.append(m_AD_Window_ID).append(",");
        if (m_AD_User_ID==null)
            sql.append("null").append(",");
        else
            sql.append(m_AD_User_ID).append(",");
        //
        sql.append("'").append(m_Attribute).append("','").append(m_Value).append("')");
        //
        log.debug("sql=" + sql.toString());
        no = DB.executeUpdate(sql.toString());
        if (no != 1)
        {
            throw new SystemException("ValuePreference.insert -  preference not inserted");
        }

    }   //  insert
   
    /**
     *  Delete Preference
     *  @return number of rows deleted
     */
    public int delete()
    {
        Log.trace(Log.l1_User, "ValuePreferenceManager.delete...");

        StringBuffer sql = new StringBuffer ("DELETE FROM AD_Preference WHERE ");
        sql.append("AD_Client_ID=").append(m_AD_Client_ID);
        sql.append(" AND AD_Org_ID=").append(m_AD_Org_ID);
        if (m_AD_User_ID==null)
            sql.append(" AND AD_User_ID is null ");
        else
            sql.append(" AND AD_User_ID=").append(m_AD_User_ID);
        if (m_AD_Window_ID==null)
            sql.append(" AND AD_Window_ID is null ");
        else
            sql.append(" AND AD_Window_ID=").append(m_AD_Window_ID);
        sql.append(" AND Attribute='").append(m_Attribute).append("'");
        //
        Log.trace(Log.l6_Database, sql.toString());
        int no = DB.executeUpdate(sql.toString());
        return no;
    }   //  delete

   
   
    /**
     * @return "" if no value, else the value for this value preference
     */
    public String get()
    {
        String ret;
        Log.trace(Log.l1_User, "ValuePreferenceManager.get");
        StringBuffer sql=
            new StringBuffer();
        sql.append
            (" select value from ad_preference a ").append
            (" where " ).append
            (" a.ad_client_id=").append(m_AD_Client_ID).append(" and ").append
            (" a.ad_org_id=").append(m_AD_Org_ID);
        if (m_AD_User_ID==null)
            sql.append(" AND AD_User_ID is null ");
        else
            sql.append(" AND AD_User_ID=").append(m_AD_User_ID);
        if (m_AD_Window_ID==null)
            sql.append(" AND AD_Window_ID is null ");
        else
            sql.append(" AND AD_Window_ID=").append(m_AD_Window_ID);
         sql.append(" and ").append
            (" attribute=" + ZZLib.quote(m_Attribute))
            ;
        log.debug("sql=" + sql);
        ret=ZZLib.quickQueryString(m_ctx, sql.toString(), false);  //returns "" if no value
        return ret;
    }



SystemException
Code: Select all
public class SystemException extends RuntimeException
{

   public SystemException() {
      super();
   }

   public SystemException(String message, Throwable cause) {
      super(message, cause);
   }

   public SystemException(String message) {
      super(message);
   }

   public SystemException(Throwable cause) {
      super(cause);
   }
   
   
}
Last edited by neilg on Sat Jun 25, 2005 4:22 am, edited 1 time in total.
neilg
Regular
 
Posts: 141
Joined: Thu Jun 16, 2005 1:58 pm

Postby trifon » Fri Jun 17, 2005 5:00 pm

Hi neilg,

congratulations for the code, it is very usefull.

Regards,
Trifon
Trifon Trifonov
trifon
Senior
 
Posts: 324
Joined: Thu Dec 23, 2004 11:20 pm
Location: Bulgaria, Sofia

Postby trifon » Tue Jul 12, 2005 4:38 am

Hi Neil,

you use "ZZLib.quickQueryString" method.

Also "ZZLib.quote("

Where I can find it?

Regards,
Trifon
Trifon Trifonov
trifon
Senior
 
Posts: 324
Joined: Thu Dec 23, 2004 11:20 pm
Location: Bulgaria, Sofia

Postby neilg » Tue Jul 12, 2005 5:07 am

Oops.... :)

There might be an equivalent method in DB for this...


Code: Select all
public static String quickQueryString(Properties ctx, String sql, boolean checkClient) {

      String retValue=null;

      ResultSet rs = null;

      PreparedStatement pstmt=null;

      try {

         pstmt = DB

         .prepareStatement(sql);

            if (checkClient) {

             int AD_Client_ID = Env.getAD_Client_ID(ctx);

             pstmt.setInt(1, AD_Client_ID);

            }

         rs = pstmt.executeQuery();

         if (rs.next())

            retValue=rs.getString(1);

         else

            return "";

      } catch (Exception ex) {

         s_log.error("quickQueryString: Error: sql=" + sql, ex);

            throw new DataException(ex);

      } finally {

         try {

            pstmt.close();

         } catch (Exception ex) {

         } //ignored

         pstmt = null;

      }

      return retValue;

   }

   

    public static String quickQueryString(Properties ctx, String sql) {

        return quickQueryString(ctx, sql, true);

    }


quote:
Code: Select all
/**

    * Quote the sql in "'" for sql statements

    * @param sql

    * @return

    */

   public static String quote(String sql) {

        if (sql==null)

        {

            return "'null'";

        }

      return "'" + sql.replaceAll("'", "''") + "'";

   }
neilg
Regular
 
Posts: 141
Joined: Thu Jun 16, 2005 1:58 pm

Postby trifon » Tue Jul 12, 2005 5:40 am

Thanks Neil,

What about "DataException"?

Regards,
Trifon
Trifon Trifonov
trifon
Senior
 
Posts: 324
Joined: Thu Dec 23, 2004 11:20 pm
Location: Bulgaria, Sofia

Postby neilg » Tue Jul 12, 2005 12:53 pm

Same as systemexception. In fact just use systemexception instead
neilg
Regular
 
Posts: 141
Joined: Thu Jun 16, 2005 1:58 pm


Return to Contributor's Corner

Who is online

Users browsing this forum: No registered users and 1 guest

cron