MrPostman.java
| Index Score | ||
|---|---|---|
![]() |
![]() |
org.mrbook.mrpostman |
![]() |
![]() |
MrPostman |
View: Reasons, Metrics, Source Code
These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.
/*
* -*- mode: java; c-basic-indent: 4; indent-tabs-mode: nil -*-
* :indentSize=4:noTabs=true:tabSize=4:indentOnTab=true:indentOnEnter=true:mode=java:
* ex: set tabstop=4 expandtab:
*
* MrPostman - webmail <-> email gateway
* Copyright (C) 2002-2003 MrPostman Development Group
* Projectpage: http://mrbook.org/mrpostman/
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* In particular, this implies that users are responsible for
* using MrPostman after reading the terms and conditions given
* by their web-mail provider.
*
* You should have received a copy of the GNU General Public License
* Named LICENSE in the base directory of this distribution,
* if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.mrbook.mrpostman;
import org.mrbook.mrpostman.gui.MrPostmanGui;
import org.mrbook.mrpostman.help.HelpServer;
import org.mrbook.mrpostman.pop.PopServer;
import org.mrbook.mrpostman.smtp.SmtpServer;
import org.mrbook.utils.ProgressIndicator;
import org.mrbook.utils.SubProgressIndicator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class MrPostman {
public static final String CVSID = "$Id: MrPostman.java,v 1.42 2005/08/18 20:31:36 mvlcek Exp $";
private static Logger logger = Logger.getLogger("org.mrbook.mrpostman.MrPostman");
public static int DEFAULT_POP_PORT = 11110;
public static int DEFAULT_SMTP_PORT = 25250;
public static int DEFAULT_HELP_PORT = 22220;
public static boolean DEFAULT_START_LOG = false;
private static HelpServer hs = null;
private boolean serverRunning = false;
private PopServer pops = null;
private SmtpServer smtps = null;
private MrPostmanGui gui = null;
private Vector modulesVector = null;
//private int helpPort = 0;
private boolean isService = false;
MrPostman() {
this(false);
}
MrPostman(boolean isService) {
this.isService = isService;
int popPort = 0;
int smtpPort = 0;
boolean allowOtherHosts = false;
popPort = Settings.getInt(Settings.PREF_POP_PORT, DEFAULT_POP_PORT);
smtpPort = Settings.getInt(Settings.PREF_SMTP_PORT, DEFAULT_SMTP_PORT);
allowOtherHosts = Settings.getBoolean(Settings.PREF_ALLOW_OTHER_HOSTS, false);
initModules();
initialiseProxy();
try {
pops = new PopServer(this, popPort, allowOtherHosts);
serverRunning = true;
} catch (Exception e) {
// Before showing an error, try to connect to localhost on
// that port and issue the GUI command.
try {
Socket s = new Socket("127.0.0.1", popPort);
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter pr = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
pr.print("GUI\n");
pr.flush();
logger.info("Port " + popPort + " already in use. Sent GUI command to (assumed) current MrPostman process");
br.readLine();
String str = br.readLine();
if (str.startsWith("+OK")) {
logger.info("Received an OK from server. Quitting.");
}
br.close();
pr.close();
System.exit(0);
} catch (Exception exc) {
final String msg = new String("Unable to start POP server on port " + popPort);
// There might be something already running on that port.
logger.severe(msg);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, msg, "Error", JOptionPane.WARNING_MESSAGE);
}
});
}
}
try {
smtps = new SmtpServer(this, smtpPort, allowOtherHosts);
} catch (Exception e) {
logger.severe("Unable to start SMTP server on port " + smtpPort);
}
// The server has been started succesfully, now bring up the gui
if (Settings.getBoolean(Settings.PREF_RUN_GUI, true)) {
logger.info("Starting gui according to preferences");
SwingUtilities.invokeLater(new Runnable() {
public void run() { showGui(); }
});
} else {
logger.info("NOT Starting gui according to preferences");
}
}
public boolean isService() {
return isService;
}
private void testAndAddModule(String className) {
Class c = null;
try {
c = Class.forName(className);
// changed test to support indirect implementations of WebMailSession
Object o = c.newInstance();
if (!(o instanceof WebMailSession)) {
logger.info(className + " Is not a valid module");
return;
} else {
if (o instanceof WebMailSessionExt) {
initialiseModuleOptions((WebMailSession) o, false);
}
modulesVector.add(c);
logger.info("Loaded module: " + className);
}
} catch (Throwable e) {
logger.severe("Error opening " + className);
return;
}
}
private void initModules() {
logger.info("initialisation of Modules");
modulesVector = new Vector();
// must be first to override other modules if needed:
testAndAddModule("org.mrbook.mrpostman.generic.GenericMailSession");
// all java based webmail modules have been removed
}
public static void startHelpServer(int helpPort) throws IOException {
if (hs == null) {
logger.info("Starting HelpServer on port: " + helpPort);
hs = new HelpServer(helpPort);
Thread t = new Thread(hs);
t.start();
}
}
/**
* Return the base URL for the help system. This will be the root of the doc tree. Requesting this
* URL will produce the /index.html document.
*/
public static String getHelpBaseUrl() {
int helpPort = Settings.getInt(Settings.PREF_HELP_PORT, DEFAULT_HELP_PORT);
try {
// start the help server...
startHelpServer(helpPort);
} catch (IOException e) {
logger.warning("A server is already running on the HelpServer port: " + helpPort);
}
return "http://localhost:" + helpPort + "/";
}
/**
* shows the GUI<br>
* only invoke from within SwingUtilities.invokeLater!
*/
public void showGui() {
if (gui == null) {
logger.info(" Starting gui");
gui = new MrPostmanGui(this);
logger.info(" Gui started ");
}
gui.show();
}
public void exit() {
logger.info("Exiting from application");
if (pops != null) {
pops.shutdown();
}
System.exit(1);
}
public Vector getModuleNamesVector() {
Vector names = new Vector();
for (Iterator i = modulesVector.iterator(); i.hasNext();) {
Class c = (Class) i.next();
WebMailSession wms = null;
try {
wms = (WebMailSession) c.newInstance();
} catch (Exception e) {
logger.log(Level.SEVERE, "should not happen", e);
}
if (wms instanceof WebMailSessionExt) {
// enhancement esp. for GenericMailSession:
WebMailSessionExt wmse = (WebMailSessionExt) wms;
/* initialiseModuleOptions(wmse); */
ModuleInfo[] modInfos = wmse.getModuleInfos();
for (int k = 0; k < modInfos.length; k++) {
names.add(modInfos[k].getModuleID());
}
} else {
names.add(wms.getModuleName());
}
}
return names;
}
public WebMailSession getModuleHandlerForExtension(String extension) {
for (Iterator i = modulesVector.iterator(); i.hasNext();) {
Class c = (Class) i.next();
WebMailSession wms = null;
// initialize proxy settings
initialiseProxy();
try {
wms = (WebMailSession) c.newInstance();
// must be done here for Outlook Web Access:
initialiseModuleOptions(wms, true);
} catch (Exception e) {
logger.log(Level.SEVERE, "should not happen", e);
}
String[] extensions = wms.getRecognizedExtensions();
for (int j = 0; j < extensions.length; j++) {
if (extensions[j].compareTo(extension) == 0) {
//found correct module
// initialization moved up:
//initialiseModuleOptions(wms);
return wms;
}
}
}
return null;
}
/**
* Return a list of ModuleInfo objects for all our loaded modules.
* This is required for the GUI to initialise the module info panels.
* This map is keyed on moduleId.
*/
public HashMap getLoadedModuleInfo() {
HashMap moduleInfoList = new HashMap();
for (Iterator i = modulesVector.iterator(); i.hasNext();) {
Class c = (Class) i.next();
WebMailSession wms = null;
try {
wms = (WebMailSession) c.newInstance();
} catch (Exception e) {
logger.log(Level.SEVERE, "should not happen", e);
}
if (wms instanceof WebMailSessionExt) {
// enhancement esp. for GenericMailSession:
WebMailSessionExt wmse = (WebMailSessionExt) wms;
/* initialiseModuleOptions(wmse); */
ModuleInfo[] mi = wmse.getModuleInfos();
for (int k = 0; k < mi.length; k++) {
moduleInfoList.put(mi[k].getModuleID(), mi[k]);
}
} else {
ModuleInfo mi = wms.getModuleInfo();
moduleInfoList.put(mi.getModuleID(), mi);
}
}
return moduleInfoList;
}
/**
* Set any user defined module specific option values for this module
* (MVL) changed to public for update
*/
public void initialiseModuleOptions(WebMailSession wms, boolean includeSubModules) {
//Retrieve the list of module options...
ModuleOption[] options = null;
if (includeSubModules && wms instanceof WebMailSessionExt) {
WebMailSessionExt wmse = (WebMailSessionExt) wms;
ModuleInfo[] mis = wmse.getModuleInfos();
ArrayList opts = new ArrayList();
for (int i = 0; i < mis.length; i++) {
for (int k = 0; k < mis[i].getOptions().length; k++) {
opts.add(mis[i].getOptions()[k]);
}
}
options = (ModuleOption[]) opts.toArray(new ModuleOption[0]);
} else {
options = wms.getModuleInfo().getOptions();
}
//For each attempt to retrieve the last know value for this option from
//our prefs, if not know use the default...
for (int currOption = 0; currOption < options.length; currOption++) {
String name = options[currOption].getName();
String value = Settings.get(name, options[currOption].getDefaultValue());
//Set this value on our loaded module...
if (options[currOption] instanceof ModuleOptionExt) {
// enhancement for GenericMailSession:
((ModuleOptionExt) options[currOption]).setValue(value);
} else {
wms.setOption(name, value);
}
logger.log(Level.FINEST,
"Setting option on module " + wms.getModuleInfo().getModuleID() + " [" + name + "=" + value + "]");
}
}
/**
* Return the current value for a module option
* This is retrieved from our preferences (if found) or the default value for that option
* This is used by the GUI to get current option values for display. This is NOT used by
* the WebMailSession objects.
*/
public String getModuleOptionValueForDisplay(String moduleId, String optionId) {
//Retrieve the list of module options...
ModuleInfo moduleInfo = (ModuleInfo) getLoadedModuleInfo().get(moduleId);
ModuleOption[] options = moduleInfo.getOptions();
//Find the particular option we are interested in (unfortunately we have to do this the long way)...
for (int currOption = 0; currOption < options.length; currOption++) {
String name = options[currOption].getName();
if (name.equals(optionId)) {
//return the value...
return Settings.get(name, options[currOption].getDefaultValue());
}
}
logger.log(Level.INFO, "Error - couldn't return option value " + optionId);
return null; //should never happen!
}
/**
* Update our option value in our Prefs for the specified optionId.
* Used by MrPostmanGui after the 'Apply' button is pressed.
*/
/*
public void updateModuleOption(String optionId, String value) {
logger.log(Level.FINEST, "Update [" + optionId + "] : " + value);
Settings.put(optionId, value);
}
*/
public boolean update(ProgressIndicator pm) {
boolean ok = true;
try {
List wmses = new ArrayList();
for (Iterator i = modulesVector.iterator(); i.hasNext();) {
if (pm.isAborted()) { return false; }
Class c = (Class) i.next();
WebMailSession wms = null;
try {
wms = (WebMailSession) c.newInstance();
} catch (Exception e) {
logger.log(Level.SEVERE, "Couldn't initialize WebMailSession " + c.getName() + " for update", e);
ok = false;
}
if (wms instanceof WebMailSessionExt) {
wmses.add((WebMailSessionExt) wms);
}
}
for (int i = 0; i < wmses.size(); i++) {
if (pm.isAborted()) { return false; }
WebMailSessionExt wmse = (WebMailSessionExt) wmses.get(i);
pm.setMessage("Updating " + wmse.getModuleName() + "...");
pm.setProgress(1.0 * i / wmses.size());
initialiseModuleOptions(wmse, false);
try {
if (!wmse.update(new SubProgressIndicator(pm, 1.0 * i / wmses.size(), 1.0 * (i + 1) / wmses.size(), wmse.getModuleName() + " - "))) {
logger.log(Level.WARNING, "Update of module " + wmse.getModuleName() + " was unsuccessful");
ok = false;
}
if (pm.isAborted()) { return false; }
} catch (Exception e) {
logger.log(Level.SEVERE, "Error while updating module " + wmse.getModuleName(), e);
ok = false;
}
}
} catch (Exception e) {
ok = false;
}
return ok;
}
public static void main(String[] args) {
logger.info("Beginning starting @APPNAME@ @VERSION@");
logger.info("Running with java version: " + System.getProperty("java.version"));
logger.info("from: " + System.getProperty("java.vendor"));
logger.info("compiled on @DSTAMP@ with @COMPILER@");
/*
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
// ignore
}
*/
MrPostman mpn = new MrPostman();
logger.info("Finished starting application");
}
public void initialiseProxy() {
// this is not used any more by the modules, but maybe by the help browser
logger.finest("initialiseProxy()");
if (Settings.getBoolean(Settings.PREF_USE_PROXY, false)) {
String httpProxyHost = Settings.get(Settings.PREF_PROXY_HOST, null);
String httpProxyPort = Settings.get(Settings.PREF_PROXY_PORT, null);
if (httpProxyHost != null && httpProxyPort != null) {
System.setProperty("http.proxyHost", httpProxyHost);
System.setProperty("http.proxyPort", httpProxyPort);
logger.info("Using HTTP proxy " + httpProxyHost + ":" + httpProxyPort);
} else {
logger.warning("Invalid HTTP proxy host/port");
}
} else {
System.getProperties().remove("http.proxyHost");
System.getProperties().remove("http.proxyPort");
}
if (Settings.getBoolean(Settings.PREF_USE_HTTPS_PROXY, false)) {
String httpsProxyHost = Settings.get(Settings.PREF_HTTPS_PROXY_HOST, null);
String httpsProxyPort = Settings.get(Settings.PREF_HTTPS_PROXY_PORT, null);
if (httpsProxyHost != null && httpsProxyPort != null) {
System.setProperty("https.proxyHost", httpsProxyHost);
System.setProperty("https.proxyPort", httpsProxyPort);
logger.info("Using HTTPS proxy " + httpsProxyHost + ":" + httpsProxyPort);
}
} else {
System.getProperties().remove("https.proxyHost");
System.getProperties().remove("https.proxyPort");
}
}
}
The table below shows all metrics for MrPostman.java.




