Package net.sf.jpluck

Source Code of net.sf.jpluck.ClientConfiguration

package net.sf.jpluck;

import com.jgoodies.plaf.plastic.PlasticLookAndFeel;
import com.jgoodies.plaf.plastic.PlasticTheme;

import net.sf.jpluck.apps.jpluckx.ui.AutoUpdateFrame;
import net.sf.jpluck.apps.jpluckx.ui.ListFrame;
import net.sf.jpluck.apps.jpluckx.ui.ShowcaseFrame;
import net.sf.jpluck.conversion.Destination;
import net.sf.jpluck.http.CookieStore;
import net.sf.jpluck.http.HttpCache;
import net.sf.jpluck.http.HttpClient;
import net.sf.jpluck.http.NetscapeCookieStore;
import net.sf.jpluck.jxl.JXL;
import net.sf.jpluck.plucker.Document;
import net.sf.jpluck.swing.TableList;
import net.sf.jpluck.swing.TableListConfiguration;
import net.sf.jpluck.swing.WindowUtil;
import net.sf.jpluck.util.Period;
import net.sf.jpluck.util.Platform;

import org.w3c.dom.Element;

import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

import javax.swing.UIManager;


public class ClientConfiguration implements Configuration {
    private static final int[] DEFAULT_COLUMN_WIDTHS = { 150, 100, 100, 150, 100 };
    private static ClientConfiguration defaultConfiguration;
    private net.sf.jpluck.jxl.Document defaultDocument = null;
    private HttpCache httpCache;
    private List fileHistoryList = new ArrayList();
    private Preferences prefs;
    private TableListConfiguration tlc = new TableListConfiguration();
    private File tlcFile = new File(System.getProperty("user.home") + File.separator + ".jpluck2" + File.separator +
                                    "columnwidths.cfg");

    private ClientConfiguration(Preferences prefs) {
        this.prefs = prefs;
        populateFileHistory();
        if (tlcFile.exists()) {
            try {
                tlc.load(tlcFile);
            } catch (IOException e) {
                // Eat exception, but dump stacktrace.
                e.printStackTrace();
            }
        }
    }

    public boolean isConfirmCut() {
        return prefs.node("application").getBoolean("confirmcut", true);
    }

    public void setConfirmCut(boolean confirm) {
        prefs.node("application").putBoolean("confirmcut", confirm);
    }

    public void setMinimizeToTrayIcon(boolean minimize) {
        prefs.node("application").putBoolean("trayicon", minimize);
    }

    public boolean isMinimizeToTrayIcon() {
        return prefs.node("application").getBoolean("trayicon", false);
    }

    public void setShowcasePreview(boolean preview) {
        prefs.node("showcase").putBoolean("preview", preview);
    }

    public boolean isShowcasePreview() {
        return prefs.node("showcase").getBoolean("preview", true);
    }

    public static Preferences getDefaultPreferencesNode() {
        return Preferences.userRoot().node("jpluck2");
    }

    public static ClientConfiguration getDefault() {
        if (defaultConfiguration == null) {
            defaultConfiguration = new ClientConfiguration(getDefaultPreferencesNode());
        }
        return defaultConfiguration;
    }

    public void setAutoUpdateEnabled(boolean enabled) {
        prefs.node("autoupdate").putBoolean("enabled", enabled);
    }

    public boolean isAutoUpdateEnabled() {
        return prefs.node("autoupdate").getBoolean("enabled", false);
    }

    public String getAcceptCharset() {
        return prefs.node("http").get("acceptcharset", HttpClient.DEFAULT_ACCEPT_CHARSET);
    }

    public void setAutoCloseConversion(boolean autoClose) {
        prefs.node("application").putBoolean("autocloseconversion", autoClose);
    }

    public boolean isAutoCloseConversion() {
        return prefs.node("application").getBoolean("autocloseconversion", false);
    }

    public void setAutoCompactCache(boolean compact) {
        prefs.node("http/cache").putBoolean("autocompact", compact);
    }

    public boolean isAutoCompactCache() {
        return prefs.node("http/cache").getBoolean("autocompact", false);
    }

    public void setAutoSelectDue(boolean select) {
        prefs.node("application").putBoolean("autoselectdue", select);
    }

    public boolean isAutoSelectDue() {
        return prefs.node("application").getBoolean("autoselectdue", false);
    }

    public void setAutoUpdatePeriodEnabled(boolean enabled) {
        prefs.node("autoupdate").putBoolean("period", enabled);
    }

    public void setAutoUpdateInterval(int minutes) {
        prefs.node("autoupdate").putInt("interval", minutes);
    }

    public int getAutoUpdateInterval() {
        return prefs.node("autoupdate").getInt("interval", 15);
    }

    public void setAutoUpdateJXLs(File[] files) {
        try {
            Preferences jxl = prefs.node("autoupdate/jxl");
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                jxl.put("file" + i, file.getAbsolutePath());
            }
            for (int i = files.length, n = jxl.keys().length; i < n; i++) {
                jxl.remove("file" + i);
            }
        } catch (BackingStoreException e) {
        }
    }

    public File[] getAutoUpdateJXLs() {
        try {
            Preferences jxls = prefs.node("autoupdate/jxl");
            String[] keys = jxls.keys();
            List fileList = new ArrayList();
            for (int i = 0; i < keys.length; i++) {
                fileList.add(new File(jxls.get(keys[i], null)));
            }
            return (File[]) fileList.toArray(new File[fileList.size()]);
        } catch (BackingStoreException e) {
            return new File[0];
        }
    }

    public void setAutoUpdatePeriod(Period period) {
        Preferences autoUpdate = prefs.node("autoupdate");
        autoUpdate.putInt("from.hour", period.getFrom().getHour());
        autoUpdate.putInt("from.minute", period.getFrom().getMinute());
        autoUpdate.putInt("to.hour", period.getTo().getHour());
        autoUpdate.putInt("to.minute", period.getTo().getMinute());
    }

    public Period getAutoUpdatePeriod() {
        Preferences autoUpdate = prefs.node("autoupdate");
        Period.Time from = new Period.Time(autoUpdate.getInt("from.hour", 0), autoUpdate.getInt("from.minute", 0));
        Period.Time to = new Period.Time(autoUpdate.getInt("to.hour", 23), autoUpdate.getInt("to.minute", 59));
        return new Period(from, to);
    }

    public boolean isAutoUpdatePeriodEnabled() {
        return prefs.node("autoupdate").getBoolean("period", false);
    }

    public void setBackupDirectory(String dir) {
        prefs.node("destination").put("backupdirectory", dir);
    }

    public String getBackupDirectory() {
        return prefs.node("destination").get("backupdirectory", "");
    }

    public void setCacheDirectory(String directory) {
        if ((directory.length() == 0) || !getCacheDirectory().equals(directory)) {
            httpCache = null;
        }
        prefs.node("http/cache").put("directory", directory);
    }

    public String getCacheDirectory() {
        return prefs.node("http/cache").get("directory", "");
    }

    // TODO: Reconsider naming of cacheExpiration.
    public void setCacheExpiration(int days) {
        prefs.node("http/cache").putInt("expires", days);
    }

    public int getCacheExpiration() {
        return prefs.node("http/cache").getInt("expires", 7);
    }

    public void setCompression(int compression) {
        Preferences plucker = prefs.node("plucker");
        switch (compression) {
        case Document.NO_COMPRESSION:
            plucker.put("compression", "none");
            break;
        case Document.DOC_COMPRESSION:
            plucker.put("compression", "doc");
            break;
        case Document.ZLIB_COMPRESSION:
            plucker.put("compression", "zlib");
            break;
        default:
            throw new IllegalArgumentException("Invalid compression: " + compression);
        }
    }

    public int getCompression() {
        String s = prefs.node("plucker").get("compression", "zlib");
        if (s.equals("none")) {
            return Document.NO_COMPRESSION;
        } else if (s.equals("doc")) {
            return Document.DOC_COMPRESSION;
        } else {
            return Document.ZLIB_COMPRESSION;
        }
    }

    public CookieStore getCookieStore() {
        CookieStore cookieStore = null;
        String cookiesTxt = getCookiesTxt();
        if (cookiesTxt.length() > 0) {
            try {
                cookieStore = NetscapeCookieStore.createFromFile(new File(getCookiesTxt()));
            } catch (Exception e) {
                Logger.getLogger("config").log(Level.WARNING, "Could not find cookies.txt file " + cookiesTxt);
            }
        }
        return cookieStore;
    }

    public void setCookiesTxt(String cookiesTxt) {
        prefs.node("http").put("cookiestxt", cookiesTxt);
    }

    public String getCookiesTxt() {
        return prefs.node("http").get("cookiestxt", "");
    }

    public void setDateFormat(String format) {
        prefs.node("feed").put("dateformat", format);
    }

    public DateFormat getDateFormat() {
        String s = prefs.node("feed").get("dateformat", "full");
        if (s.equals("short")) {
            return DateFormat.getDateInstance(DateFormat.SHORT);
        } else if (s.equals("medium")) {
            return DateFormat.getDateInstance(DateFormat.MEDIUM);
        } else if (s.equals("long")) {
            return DateFormat.getDateInstance(DateFormat.LONG);
        } else {
            return DateFormat.getDateInstance(DateFormat.FULL);
        }
    }

    public String getDateFormatName() {
        return prefs.node("feed").get("dateformat", "full");
    }

    public net.sf.jpluck.jxl.Document getDefaultDocument()
                                                  throws IOException, SAXException {
        if (defaultDocument == null) {
            File file = new File(getDefaultJXLPath());
            if (file.exists()) {
                try {
                    JXL jxl = new JXL(file, false);
                    defaultDocument = jxl.getDocument("default");
                } catch (SAXException e) {
                    throw e;
                } catch (IOException e) {
                    throw e;
                }
            } else {
                JXL jxl = new JXL();
                Element site = jxl.createSiteElement();
                org.w3c.dom.Document dom = site.getOwnerDocument();
                Element name = dom.createElement("name");
                site.appendChild(name);
                name.appendChild(dom.createTextNode("default"));
                site.appendChild(dom.createElement("uri"));               
                defaultDocument = jxl.add(site);
                try {
                    jxl.save(new File(getDefaultJXLPath()));
                } catch (IOException e) {
                    defaultDocument = null;
                    throw e;
                }
            }
        }
        return defaultDocument;
    }

    public String getDefaultJXLPath() {
        return System.getProperty("user.home") + File.separator + ".jpluck2" + File.separator + "default-document.jxl";
    }

    public void setCreateCategoryDirectories(boolean create) {
        prefs.node("destination").putBoolean("categorydirectories", create);
    }

    public boolean isCreateCategoryDirectories() {
        return prefs.node("destination").getBoolean("categorydirectories", false);
    }

    public Destination getDestination() {
        Preferences dest = prefs.node("destination");
        String type = dest.get("type", "");
        if (type.equals("directory")) {
            String dir = dest.get("directory", ".");
            return Destination.createForDirectory(new File(dir), isCreateCategoryDirectories());
        } else if (type.equals("hotsync")) {
            String user = dest.get("user", null);
            if (user == null) {
                // Should not occur
                throw new IllegalStateException("HotSync user not set");
            }

            boolean card = dest.getBoolean("card", false);
            return Destination.createForHotSync(user, card);
        } else {
            return null;
        }
    }

    public void setDirectoryDestination(String directory) {
        Preferences dest = prefs.node("destination");
        dest.put("type", "directory");
        dest.put("directory", directory);
    }

    public Destination getDirectoryDestination() {
        Preferences dest = prefs.node("destination");
        String dir = dest.get("directory", "");
        if (dir.length() > 0) {
            return Destination.createForDirectory(new File(dir), isCreateCategoryDirectories());
        } else {
            return null;
        }
    }

    public void setDisplayFullFilePath(boolean display) {
        prefs.node("application").putBoolean("displayfullfilepath", display);
    }

    public boolean isDisplayFullFilePath() {
        return prefs.node("application").getBoolean("displayfullfilepath", false);
    }

    public void setDownloadAttempts(int attempts) {
        prefs.node("http").putInt("downloadattempts", attempts);
    }

    public int getDownloadAttempts() {
        return prefs.node("http").getInt("downloadattempts", 1);
    }

    public void setExtractFeedSettings(boolean extract) {
        prefs.node("feed").putBoolean("extractsettings", extract);
    }

    public boolean isExtractFeedSettings() {
        return prefs.node("feed").getBoolean("extractsettings", false);
    }

    public File[] getFileHistory() {
        return (File[]) fileHistoryList.toArray(new File[fileHistoryList.size()]);
    }

    public void setHotSyncDestination(String user, boolean card) {
        Preferences dest = prefs.node("destination");
        dest.put("type", "hotsync");
        dest.put("user", user);
        dest.putBoolean("card", card);
    }

    public Destination getHotSyncDestination() {
        Preferences dest = prefs.node("destination");
        String user = dest.get("user", null);
        if (user != null) {
            boolean card = dest.getBoolean("card", false);
            return Destination.createForHotSync(user, card);
        } else {
            return null;
        }
    }

    public HttpCache getHttpCache() {
        if (httpCache == null) {
            String dir = getCacheDirectory();
            if (dir.length() > 0) {
                httpCache = new HttpCache(dir + File.separator + "cache", getCacheExpiration());
            }
        }
        return httpCache;
    }

    public void setLastDirectory(String dir) {
        prefs.put("lastdirectory", dir);
    }

    public String getLastDirectory() {
        return prefs.get("lastdirectory", System.getProperty("user.home"));
    }

    public void setLastJXL(String filename) {
        prefs.put("lastjxl", filename);
    }

    public String getLastJXL() {
        return prefs.get("lastjxl", null);
    }

    public void setLogEnabled(boolean enabled) {
        prefs.node("log").putBoolean("enabled", enabled);
    }

    public boolean isLogEnabled() {
        return prefs.node("log").getBoolean("enabled", false);
    }

    public void setLogFile(String file) {
        prefs.node("log").put("file", file);
    }

    public String getLogFile() {
        return prefs.node("log").get("file", "");
    }

    public void setLogLevel(String level) {
        prefs.node("log").put("level", level);
    }

    public Level getLogLevel() {
        return Level.parse(prefs.node("log").get("level", "INFO"));
    }

    public void setPlasticTheme(String theme) {
        prefs.node("application").put("plastictheme", theme);
    }

    public String getPlasticTheme() {
        return prefs.node("application").get("plastictheme", "Experience Blue");
    }

    public void setLookAndFeel(String laf) {
        prefs.node("application").put("lookandfeel", laf);
    }

    public String getLookAndFeel() {
        String s;
        if (Platform.isMacOSX()) {
            s = UIManager.getSystemLookAndFeelClassName();
        } else {
            s = "com.jgoodies.plaf.plastic.PlasticXPLookAndFeel";
        }
        return prefs.node("application").get("lookandfeel", s);
    }

    public void setMaxConnections(int maxConnections) {
        prefs.node("http").putInt("maxconnections", maxConnections);
    }

    public int getMaxConnections() {
        return prefs.node("http").getInt("maxconnections", 2);
    }

    public void setMaxLogSize(int sizeKB) {
        prefs.node("log").putInt("maxsize", sizeKB);
    }

    public int getMaxLogSize() {
        return prefs.node("log").getInt("maxsize", 50);
    }

    public void setPluckThisAutoClose(boolean autoClose) {
        prefs.node("pluckthis").putBoolean("autoclose", autoClose);
    }

    public boolean isPluckThisAutoClose() {
        return prefs.node("pluckthis").getBoolean("autoclose", false);
    }

    public void setPluckThisJXL(String jxl) {
        prefs.node("pluckthis").put("jxl", jxl);
    }

    public String getPluckThisJXL() {
        return prefs.node("pluckthis").get("jxl", "");
    }

    public void setProxyHost(String host) {
        prefs.node("http/proxy").put("host", host);
    }

    public String getProxyHost() {
        return prefs.node("http/proxy").get("host", "");
    }

    public void setProxyPassword(String password) {
        prefs.node("http/proxy").put("password", password);
    }

    public String getProxyPassword() {
        return prefs.node("http/proxy").get("password", "");
    }

    public void setProxyPort(int port) {
        prefs.node("http/proxy").putInt("port", port);
    }

    public int getProxyPort() {
        return prefs.node("http/proxy").getInt("port", 8080);
    }

    public void setProxyUser(String user) {
        prefs.node("http/proxy").put("user", user);
    }

    public String getProxyUser() {
        return prefs.node("http/proxy").get("user", "");
    }

    public void setShowSplashScreen(boolean show) {
        prefs.node("application").putBoolean("showsplashscreen", show);
    }

    public boolean isShowSplashScreen() {
        return prefs.node("application").getBoolean("showsplashscreen", true);
    }

    public String getTimeFormat() {
        DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
        if (df instanceof SimpleDateFormat) {
            return ((SimpleDateFormat) df).toPattern();
        } else {
            return "HH:mm";
        }
    }

    public void setTimeout(int seconds) {
        prefs.node("http").putInt("timeout", seconds);
    }

    public int getTimeout() {
        return prefs.node("http").getInt("timeout", 20);
    }

    public void setUseFeedDate(boolean use) {
        prefs.node("feed").putBoolean("usefeeddate", use);
    }

    public boolean isUseFeedDate() {
        return prefs.node("feed").getBoolean("usefeeddate", false);
    }
   
    public boolean isGenerateBookmarks() {
      return prefs.node("feed").getBoolean("bookmarks", true);
    }
   
    public void setGenerateBookmarks(boolean bookmarks) {
      prefs.node("feed").putBoolean("bookmarks", bookmarks);
    }

    public void setUseFeedWizard(boolean use) {
        prefs.node("application").putBoolean("usefeedwizard", use);
    }

    public boolean isUseFeedWizard() {
        return prefs.node("application").getBoolean("usefeedwizard", true);
    }

    public void setUseMultiImage(boolean multiImage) {
        prefs.node("plucker").putBoolean("multi-image", multiImage);
    }

    public boolean isUseMultiImage() {
        return prefs.node("plucker").getBoolean("multi-image", true);
    }

    public void setUseProxy(boolean useProxy) {
        prefs.node("http/proxy").putBoolean("use", useProxy);
    }

    public boolean isUseProxy() {
        return prefs.node("http/proxy").getBoolean("use", false);
    }

    public void setUserAgent(String userAgent) {
        prefs.node("http").put("useragent", userAgent);
    }

    public String getUserAgent() {
        return prefs.node("http").get("useragent", VersionInfo.userAgent());
    }

    public void addToFileHistory(File file) {
        int idx = fileHistoryList.indexOf(file);
        if (idx != -1) {
            fileHistoryList.remove(idx);
        }
        fileHistoryList.add(0, file);
        if (fileHistoryList.size() > 8) {
            fileHistoryList.remove(8);
        }

        Preferences fileHistory = prefs.node("filehistory");
        for (int i = 0; i < fileHistoryList.size(); i++) {
            fileHistory.put("file" + i, ((File) fileHistoryList.get(i)).getAbsolutePath());
        }

        int i = 8;
        while (true) {
            if (fileHistory.get("file" + i, null) != null) {
                fileHistory.remove("file" + i++);
            } else {
                break;
            }
        }
    }

    public void cleanup() {
      List removeList = new ArrayList();
        for (Iterator it = tlc.getKeys(); it.hasNext();) {
            String key = (String) it.next();
            if (!new File(key).exists()) {
              removeList.add(key);
            }
        }
    for (Iterator it = removeList.iterator(); it.hasNext(); ) {
      tlc.remove((String)it.next());
    }       
        try {
            tlc.save(tlcFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void restoreListFramePrefs(ListFrame listFrame) {
        try {
            if (prefs.nodeExists("windows/list")) {
                Preferences winPrefs = prefs.node("windows/list");
                WindowUtil.restore(listFrame, winPrefs);
                return;
            }
        } catch (BackingStoreException e) {
        }
        listFrame.pack();
        WindowUtil.center(listFrame);
    }

    public void restoreTableListWidths(String key, TableList tableList) {
        tlc.restoreWidths(key, tableList, DEFAULT_COLUMN_WIDTHS);
        try {
            tlc.save(tlcFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void storeListFramePrefs(ListFrame listFrame) {
        Preferences winPrefs = prefs.node("windows/list");
        WindowUtil.store(listFrame, winPrefs);
    }

    public void storeAutoUpdateFramePrefs(AutoUpdateFrame autoUpdateFrame) {
        Preferences winPrefs = prefs.node("windows/autoupdate");
        WindowUtil.store(autoUpdateFrame, winPrefs);
    }

    public void storeShowcaseFramePrefs(ShowcaseFrame showcaseFrame) {
        Preferences winPrefs = prefs.node("windows/showcase");
        WindowUtil.store(showcaseFrame, winPrefs);
    }

    public void restoreShowcaseFramePrefs(ShowcaseFrame showcaseFrame) {
        try {
            if (prefs.nodeExists("windows/showcase")) {
                Preferences winPrefs = prefs.node("windows/showcase");
                WindowUtil.restore(showcaseFrame, winPrefs);
                return;
            }
        } catch (BackingStoreException e) {
        }
        showcaseFrame.pack();
        WindowUtil.center(showcaseFrame);
    }

    public void restoreAutoUpdateFramePrefs(AutoUpdateFrame autoUpdateFrame) {
        try {
            if (prefs.nodeExists("windows/autoupdate")) {
                Preferences winPrefs = prefs.node("windows/autoupdate");
                WindowUtil.restore(autoUpdateFrame, winPrefs);
                autoUpdateFrame.pack();
                return;
            }
        } catch (BackingStoreException e) {
        }
        WindowUtil.center(autoUpdateFrame);
    }

    public void storeTableListWidths(String key, TableList tableList) {     
        tlc.storeWidths(key, tableList);
    }

    private void populateFileHistory() {
        try {
            Preferences fileHistory = prefs.node("filehistory");
            String[] keys = fileHistory.keys();
            Arrays.sort(keys);
            for (int i = 0; i < keys.length; i++) {
                fileHistoryList.add(new File(fileHistory.get(keys[i], null)));
            }
        } catch (BackingStoreException e) {
        }
    }

    public void setAcceptCharset(String charset) {
        prefs.node("http").put("acceptcharset", charset);
    }

    public String getBrowser() {
        return prefs.node("application").get("browser", "");
    }

    public void setBrowser(String path) {
        prefs.node("application").put("browser", path);
    }

    public boolean isUseImageIO() {
        return prefs.getBoolean("imageio", true);
    }

    public void setUseImageIO(boolean use) {
        prefs.putBoolean("imageio", use);
    }

    public void applyPlasticTheme() {
        if (getLookAndFeel().startsWith("com.jgoodies.plaf.plastic")) {
            List themeList = PlasticLookAndFeel.getInstalledThemes();
            String name = getPlasticTheme();
            for (Iterator it = themeList.iterator(); it.hasNext();) {
                PlasticTheme theme = (PlasticTheme) it.next();
                if (theme.getName().equalsIgnoreCase(name)) {
                    PlasticLookAndFeel.setMyCurrentTheme(theme);
                }
            }
        }
    }
}
TOP

Related Classes of net.sf.jpluck.ClientConfiguration

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.