1
0
mirror of https://github.com/moparisthebest/davmail synced 2024-11-10 11:25:00 -05:00

I18N : externalize and translate exception messages

git-svn-id: http://svn.code.sf.net/p/davmail/code/trunk@544 3d1905a2-6b24-0410-a738-b14d5a86fcbd
This commit is contained in:
mguessan 2009-04-27 23:03:58 +00:00
parent 871efb7831
commit 9ad2490e3c
13 changed files with 239 additions and 96 deletions

View File

@ -1,5 +1,7 @@
package davmail;
import davmail.exception.DavMailException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Locale;
@ -43,6 +45,13 @@ public class BundleMessage {
buffer.append(bundleMessage.format(locale));
}
formattedArguments[i] = buffer.toString();
} else if (arguments[i] instanceof DavMailException) {
formattedArguments[i] = ((DavMailException)arguments[i]).getMessage(locale);
} else if (arguments[i] instanceof Throwable) {
formattedArguments[i] = ((Throwable)arguments[i]).getMessage();
if (formattedArguments[i] == null) {
formattedArguments[i] = arguments[i].toString();
}
} else {
formattedArguments[i] = arguments[i];
}
@ -55,5 +64,13 @@ public class BundleMessage {
return MessageFormat.format(ResourceBundle.getBundle(MESSAGE_BUNDLE_NAME).getString(key), arguments);
}
public static String format(Locale locale, String key, Object... arguments) {
return MessageFormat.format(ResourceBundle.getBundle(MESSAGE_BUNDLE_NAME, locale).getString(key), arguments);
}
public static String formatLog(String key, Object... arguments) {
return MessageFormat.format(ResourceBundle.getBundle(MESSAGE_BUNDLE_NAME, Locale.ROOT).getString(key), arguments);
}
public static class BundleMessageList extends ArrayList<BundleMessage>{}
}

View File

@ -1,15 +1,14 @@
package davmail.caldav;
import davmail.AbstractConnection;
import davmail.Settings;
import davmail.BundleMessage;
import davmail.*;
import davmail.exception.DavMailException;
import davmail.exception.DavMailAuthenticationException;
import davmail.exchange.ExchangeSession;
import davmail.exchange.ExchangeSessionFactory;
import davmail.exchange.ICSBufferedReader;
import davmail.ui.tray.DavGatewayTray;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.auth.AuthenticationException;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.log4j.Logger;
@ -48,7 +47,7 @@ public class CaldavConnection extends AbstractConnection {
while ((line = readClient()) != null && line.length() > 0) {
int index = line.indexOf(':');
if (index <= 0) {
throw new IOException("Invalid header: " + line);
throw new DavMailException("EXCEPTION_INVALID_HEADER", line);
}
headers.put(line.substring(0, index).toLowerCase(), line.substring(index + 1).trim());
}
@ -63,14 +62,14 @@ public class CaldavConnection extends AbstractConnection {
try {
size = Integer.parseInt(contentLength);
} catch (NumberFormatException e) {
throw new IOException("Invalid content length: " + contentLength);
throw new DavMailException("EXCEPTION_INVALID_CONTENT_LENGTH", contentLength);
}
char[] buffer = new char[size];
StringBuilder builder = new StringBuilder();
int actualSize = in.read(buffer);
builder.append(buffer, 0, actualSize);
if (actualSize < 0) {
throw new IOException("End of stream reached reading content");
throw new DavMailException("EXCEPTION_END_OF_STREAM");
}
// dirty hack to ensure full content read
// TODO : replace with a dedicated reader
@ -89,7 +88,7 @@ public class CaldavConnection extends AbstractConnection {
try {
keepAlive = Integer.parseInt(keepAliveValue);
} catch (NumberFormatException e) {
throw new IOException("Invalid Keep-Alive: " + keepAliveValue);
throw new DavMailException("EXCEPTION_INVALID_KEEPALIVE", keepAliveValue);
}
if (keepAlive > MAX_KEEP_ALIVE_TIME) {
keepAlive = MAX_KEEP_ALIVE_TIME;
@ -130,7 +129,7 @@ public class CaldavConnection extends AbstractConnection {
ExchangeSessionFactory.checkConfig();
try {
session = ExchangeSessionFactory.getInstance(userName, password);
} catch (AuthenticationException e) {
} catch (DavMailAuthenticationException e) {
sendUnauthorized();
}
}
@ -576,7 +575,7 @@ public class CaldavConnection extends AbstractConnection {
while ((line = reader.readLine()) != null) {
int index = line.indexOf(':');
if (index <= 0) {
throw new IOException("Invalid request: " + body);
throw new DavMailException("EXCEPTION_INVALID_REQUEST", body);
}
String fullkey = line.substring(0, index);
String value = line.substring(index + 1);
@ -727,7 +726,7 @@ public class CaldavConnection extends AbstractConnection {
if (index > 0) {
String mode = authorization.substring(0, index).toLowerCase();
if (!"basic".equals(mode)) {
throw new IOException("Unsupported authorization mode: " + mode);
throw new DavMailException("EXCEPTION_UNSUPPORTED_AUTHORIZATION_MODE", mode);
}
String encodedCredentials = authorization.substring(index + 1);
String decodedCredentials = base64Decode(encodedCredentials);
@ -736,10 +735,10 @@ public class CaldavConnection extends AbstractConnection {
userName = decodedCredentials.substring(0, index);
password = decodedCredentials.substring(index + 1);
} else {
throw new IOException("Invalid credentials");
throw new DavMailException("EXCEPTION_INVALID_CREDENTIALS");
}
} else {
throw new IOException("Invalid credentials");
throw new DavMailException("EXCEPTION_INVALID_CREDENTIALS");
}
}
@ -961,7 +960,7 @@ public class CaldavConnection extends AbstractConnection {
}
}
} catch (XMLStreamException e) {
throw new IOException(e.getMessage());
throw new DavMailException("EXCEPTION_INVALID_CALDAV_REQUEST", e.getMessage());
} finally {
try {
if (streamReader != null) {

View File

@ -0,0 +1,12 @@
package davmail.exception;
import davmail.exception.DavMailException;
/**
* I18 AuthenticationException subclass.
*/
public class DavMailAuthenticationException extends DavMailException {
public DavMailAuthenticationException(String key) {
super(key);
}
}

View File

@ -0,0 +1,34 @@
package davmail.exception;
import davmail.BundleMessage;
import java.io.IOException;
import java.util.Locale;
/**
* I18 IOException subclass.
*/
public class DavMailException extends IOException {
private final BundleMessage message;
public DavMailException(String key, Object... arguments) {
this.message = new BundleMessage(key, arguments);
}
@Override
public String getMessage() {
return message.format();
}
public String getMessage(Locale locale) {
return message.format(locale);
}
public String getLogMessage() {
return message.format(Locale.ROOT);
}
public BundleMessage getBundleMessage() {
return message;
}
}

View File

@ -1,9 +1,11 @@
package davmail.exchange;
import davmail.Settings;
import davmail.BundleMessage;
import davmail.exception.DavMailAuthenticationException;
import davmail.exception.DavMailException;
import davmail.http.DavGatewayHttpClientFacade;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.auth.AuthenticationException;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
@ -145,7 +147,7 @@ public class ExchangeSession {
httpURL = new HttpsURL(poolKey.userName, poolKey.password,
urlObject.getHost(), urlObject.getPort());
} else {
throw new IllegalArgumentException("Invalid URL: " + poolKey.url);
throw new DavMailException("LOG_INVALID_URL", poolKey.url);
}
@ -161,7 +163,7 @@ public class ExchangeSession {
if (status == HttpStatus.SC_UNAUTHORIZED) {
method.releaseConnection();
throw new AuthenticationException("Authentication failed: invalid user or password");
throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
} else if (status != HttpStatus.SC_OK) {
method.releaseConnection();
throw DavGatewayHttpClientFacade.buildHttpException(method);
@ -175,20 +177,12 @@ public class ExchangeSession {
// got base http mailbox http url
getWellKnownFolders();
} catch (AuthenticationException exc) {
LOGGER.error(exc.toString());
} catch (DavMailAuthenticationException exc) {
LOGGER.error(exc.getLogMessage());
throw exc;
} catch (IOException exc) {
StringBuilder message = new StringBuilder();
message.append("DavMail login exception: ");
if (exc.getMessage() != null) {
message.append(exc.getMessage());
} else {
message.append(exc);
}
LOGGER.error(message.toString());
throw new IOException(message.toString());
LOGGER.error(BundleMessage.formatLog("EXCEPTION_EXCHANGE_LOGIN_FAILED", exc));
throw new DavMailException("EXCEPTION_EXCHANGE_LOGIN_FAILED", exc);
}
LOGGER.debug("Session " + this + " created");
}
@ -354,7 +348,7 @@ public class ExchangeSession {
}
if (logonMethod == null) {
throw new IOException("Authentication form not found at " + initmethod.getURI());
throw new DavMailException("EXCEPTION_AUTHENTICATION_FORM_NOT_FOUND", initmethod.getURI());
}
return logonMethod;
}
@ -380,20 +374,19 @@ public class ExchangeSession {
return logonMethod;
}
protected void checkFormLoginQueryString(HttpMethod logonMethod) throws AuthenticationException {
protected void checkFormLoginQueryString(HttpMethod logonMethod) throws DavMailAuthenticationException {
String queryString = logonMethod.getQueryString();
if (queryString != null && queryString.contains("reason=2")) {
logonMethod.releaseConnection();
if (poolKey.userName != null && poolKey.userName.contains("\\")) {
throw new AuthenticationException("Authentication failed: invalid user or password");
throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
} else {
throw new AuthenticationException("Authentication failed: invalid user or password, " +
"retry with domain\\user");
throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED_RETRY");
}
}
}
protected void buildMailPath(HttpMethod method) throws HttpException {
protected void buildMailPath(HttpMethod method) throws DavMailAuthenticationException {
// get user mail URL from html body (multi frame)
BufferedReader mainPageReader = null;
try {
@ -432,11 +425,8 @@ public class ExchangeSession {
method.releaseConnection();
}
if (mailPath == null) {
throw new AuthenticationException("Unable to build mail path, authentication failed: password expired ?");
}
if (email == null) {
throw new AuthenticationException("Unable to get email, authentication failed: password expired ?");
if (mailPath == null || email == null) {
throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED_PASSWORD_EXPIRED");
}
}
@ -490,7 +480,7 @@ public class ExchangeSession {
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executePropFindMethod(
httpClient, URIUtil.encodePath(mailPath), 0, WELL_KNOWN_FOLDERS);
if (responses.length == 0) {
throw new IOException("Unable to get mail folders");
throw new DavMailException("EXCEPTION_UNABLE_TO_GET_MAIL_FOLDERS");
}
DavPropertySet properties = responses[0].getProperties(HttpStatus.SC_OK);
inboxUrl = getURIPropertyIfExists(properties, "inbox", URN_SCHEMAS_HTTPMAIL);
@ -528,7 +518,7 @@ public class ExchangeSession {
// update message with blind carbon copy and other flags
int statusCode = httpClient.executeMethod(patchMethod);
if (statusCode != HttpStatus.SC_MULTI_STATUS) {
throw new IOException("Unable to create message " + messageUrl + ": " + statusCode + ' ' + patchMethod.getStatusLine());
throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode, ' ', patchMethod.getStatusLine());
}
} finally {
@ -545,7 +535,7 @@ public class ExchangeSession {
int code = httpClient.executeMethod(putmethod);
if (code != HttpStatus.SC_OK && code != HttpStatus.SC_CREATED) {
throw new IOException("Unable to create message " + messageUrl + ": " + code + ' ' + putmethod.getStatusLine());
throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, code, ' ', putmethod.getStatusLine());
}
} finally {
putmethod.releaseConnection();
@ -558,7 +548,7 @@ public class ExchangeSession {
// update message with blind carbon copy and other flags
int statusCode = httpClient.executeMethod(patchMethod);
if (statusCode != HttpStatus.SC_MULTI_STATUS) {
throw new IOException("Unable to patch message " + messageUrl + ": " + statusCode + ' ' + patchMethod.getStatusLine());
throw new DavMailException("EXCEPTION_UNABLE_TO_PATCH_MESSAGE", messageUrl, statusCode, ' ', patchMethod.getStatusLine());
}
} finally {
@ -629,7 +619,7 @@ public class ExchangeSession {
try {
int statusCode = httpClient.executeMethod(patchMethod);
if (statusCode != HttpStatus.SC_MULTI_STATUS) {
throw new IOException("Unable to update message properties");
throw new DavMailException("EXCEPTION_UNABLE_TO_UPDATE_MESSAGE");
}
} finally {
@ -683,7 +673,7 @@ public class ExchangeSession {
return folders;
}
protected Folder buildFolder(MultiStatusResponse entity) throws URIException {
protected Folder buildFolder(MultiStatusResponse entity) throws IOException {
String href = URIUtil.decode(entity.getHref());
Folder folder = new Folder();
DavPropertySet properties = entity.getProperties(HttpStatus.SC_OK);
@ -714,7 +704,7 @@ public class ExchangeSession {
folder.folderUrl = href.substring(index + mailPath.length());
}
} else {
throw new URIException("Invalid folder url: " + folder.folderUrl);
throw new DavMailException("EXCEPTION_INVALID_FOLDER_URL", folder.folderUrl);
}
}
return folder;
@ -917,7 +907,7 @@ public class ExchangeSession {
try {
int statusCode = httpClient.executeMethod(method);
if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) {
throw new HttpException("Unable to move message, target already exists");
throw new DavMailException("EXCEPTION_UNABLE_TO_MOVE_MESSAGE");
} else if (statusCode != HttpStatus.SC_CREATED) {
throw DavGatewayHttpClientFacade.buildHttpException(method);
}
@ -934,7 +924,7 @@ public class ExchangeSession {
try {
int statusCode = httpClient.executeMethod(method);
if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) {
throw new HttpException("Unable to move folder, target already exists");
throw new DavMailException("EXCEPTION_UNABLE_TO_MOVE_FOLDER");
} else if (statusCode != HttpStatus.SC_CREATED) {
throw DavGatewayHttpClientFacade.buildHttpException(method);
}
@ -1121,7 +1111,7 @@ public class ExchangeSession {
int index = messageUrl.lastIndexOf('/');
if (index < 0) {
throw new IOException("Invalid message url: " + messageUrl);
throw new DavMailException("EXCEPTION_INVALID_MESSAGE_URL", messageUrl);
}
String encodedPath = URIUtil.encodePath(messageUrl.substring(0, index));
String encodedMessageName = URIUtil.encodePath(messageUrl.substring(index + 1));
@ -1208,7 +1198,7 @@ public class ExchangeSession {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mimeMessage.getDataHandler().writeTo(baos);
baos.close();
throw new IOException("Invalid calendar message content: " + new String(baos.toByteArray(), "UTF-8"));
throw new DavMailException("EXCEPTION_INVALID_MESSAGE_CONTENT", new String(baos.toByteArray(), "UTF-8"));
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bodyPart.getDataHandler().writeTo(baos);
@ -1216,7 +1206,7 @@ public class ExchangeSession {
result = fixICS(new String(baos.toByteArray(), "UTF-8"), true);
} catch (MessagingException e) {
throw new IOException(e.getMessage());
throw new DavMailException("EXCEPTION_INVALID_MESSAGE_CONTENT", e.getMessage());
} finally {
method.releaseConnection();
}
@ -1280,7 +1270,7 @@ public class ExchangeSession {
String eventPath = URIUtil.encodePath(path + '/' + eventName);
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executePropFindMethod(httpClient, eventPath, 0, EVENT_REQUEST_PROPERTIES);
if (responses.length == 0) {
throw new IOException("Unable to get calendar event");
throw new DavMailException("EXCEPTION_EVENT_NOT_FOUND");
}
return buildEvent(responses[0]);
}
@ -1421,7 +1411,7 @@ public class ExchangeSession {
int valueIndex = line.lastIndexOf(':');
int valueEndIndex = line.lastIndexOf('T');
if (valueIndex < 0 || valueEndIndex < 0) {
throw new IOException("Invalid ICS line: " + line);
throw new DavMailException("EXCEPTION_INVALID_ICS_LINE", line);
}
String dateValue = line.substring(valueIndex + 1, valueEndIndex);
String key = line.substring(0, Math.max(keyIndex, valueIndex));
@ -1669,13 +1659,13 @@ public class ExchangeSession {
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executePropFindMethod(
httpClient, URIUtil.encodePath(folderPath), 0, davPropertyNameSet);
if (responses.length == 0) {
throw new IOException("Unable to get folder at "+folderPath);
throw new DavMailException("EXCEPTION_UNABLE_TO_GET_FOLDER", folderPath);
}
DavPropertySet properties = responses[0].getProperties(HttpStatus.SC_OK);
DavPropertyName davPropertyName = davPropertyNameSet.iterator().nextPropertyName();
result = getPropertyIfExists(properties, davPropertyName);
if (result == null) {
throw new IOException("Unable to get property "+davPropertyName);
throw new DavMailException("EXCEPTION_UNABLE_TO_GET_PROPERTY", davPropertyName);
}
return result;
}
@ -1709,7 +1699,7 @@ public class ExchangeSession {
if (index >= 0 && mailPath.endsWith("/")) {
return mailPath.substring(index + 1, mailPath.length() - 1);
} else {
throw new IOException("Invalid mail path: " + mailPath);
throw new DavMailException("EXCEPTION_INVALID_MAIL_PATH", mailPath);
}
}
@ -1721,7 +1711,7 @@ public class ExchangeSession {
MultiStatusResponse[] responses = DavGatewayHttpClientFacade.executePropFindMethod(
httpClient, URIUtil.encodePath(mailPath), 0, DISPLAY_NAME);
if (responses.length == 0) {
throw new IOException("Unable to get mail folder");
throw new DavMailException("EXCEPTION_UNABLE_TO_GET_MAIL_FOLDER");
}
displayName = getPropertyIfExists(responses[0].getProperties(HttpStatus.SC_OK), "displayname", Namespace.getNamespace("DAV:"));
return displayName;
@ -1734,7 +1724,7 @@ public class ExchangeSession {
if (index >= 0 && mailPath.endsWith("/")) {
buffer.append(mailPath.substring(0, index + 1)).append(principal).append('/');
} else {
throw new IOException("Invalid mail path: " + mailPath);
throw new DavMailException("EXCEPTION_INVALID_MAIL_PATH", mailPath);
}
} else if (principal != null) {
buffer.append(mailPath);
@ -1770,7 +1760,7 @@ public class ExchangeSession {
try {
int status = httpClient.executeMethod(getMethod);
if (status != HttpStatus.SC_OK) {
throw new IOException("Unable to get user email from: " + getMethod.getPath());
throw new DavMailException("EXCEPTION_UNABLE_TO_GET_EMAIL", getMethod.getPath());
}
Map<String, Map<String, String>> results = XMLStreamUtil.getElementContentsAsMap(getMethod.getResponseBodyAsStream(), "item", "AN");
Map<String, String> result = results.get(alias.toLowerCase());
@ -1897,7 +1887,7 @@ public class ExchangeSession {
try {
int status = httpClient.executeMethod(getMethod);
if (status != HttpStatus.SC_OK) {
throw new IOException(status + "Unable to find users from: " + getMethod.getURI());
throw new DavMailException("EXCEPTION_UNABLE_TO_FIND_USERS", status, getMethod.getURI());
}
results = XMLStreamUtil.getElementContentsAsMap(getMethod.getResponseBodyAsStream(), "item", "AN");
} finally {
@ -1914,7 +1904,7 @@ public class ExchangeSession {
getMethod = new GetMethod(URIUtil.encodePathQuery(getCmdBasePath()+"?Cmd=gallookup&ADDR=" + person.get("EM")));
int status = httpClient.executeMethod(getMethod);
if (status != HttpStatus.SC_OK) {
throw new IOException(status + "Unable to find users from: " + getMethod.getURI());
throw new DavMailException("EXCEPTION_UNABLE_TO_FIND_USERS", status, getMethod.getURI());
}
Map<String, Map<String, String>> results = XMLStreamUtil.getElementContentsAsMap(getMethod.getResponseBodyAsStream(), "person", "alias");
// add detailed information
@ -1966,7 +1956,7 @@ public class ExchangeSession {
"&interval=" + FREE_BUSY_INTERVAL +
"&u=SMTP:" + attendee;
} catch (ParseException e) {
throw new IOException(e.getMessage());
throw new DavMailException("EXCEPTION_INVALID_DATES", e.getMessage());
}
FreeBusy freeBusy = null;
@ -1976,7 +1966,7 @@ public class ExchangeSession {
try {
int status = httpClient.executeMethod(getMethod);
if (status != HttpStatus.SC_OK) {
throw new IOException("Unable to get free-busy from: " + getMethod.getPath());
throw new DavMailException("EXCEPTION_UNABLE_TO_GET_FREEBUSY", getMethod.getPath());
}
String body = getMethod.getResponseBodyAsString();
int startIndex = body.lastIndexOf("<a:fbdata>");

View File

@ -1,6 +1,8 @@
package davmail.exchange;
import davmail.Settings;
import davmail.BundleMessage;
import davmail.exception.DavMailException;
import davmail.http.DavGatewayHttpClientFacade;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
@ -92,7 +94,7 @@ public final class ExchangeSessionFactory {
if (checkNetwork()) {
throw e;
} else {
throw new NetworkDownException("All network interfaces down !");
throw new NetworkDownException("EXCEPTION_NETWORK_DOWN");
}
}
}
@ -109,27 +111,24 @@ public final class ExchangeSessionFactory {
ExchangeSession.LOGGER.debug("Test configuration status: " + status);
if (status != HttpStatus.SC_OK && status != HttpStatus.SC_UNAUTHORIZED
&& status != HttpStatus.SC_MOVED_TEMPORARILY && status != HttpStatus.SC_MOVED_PERMANENTLY) {
throw new IOException("Unable to connect to OWA at " + url + ", status code " +
status + ", check configuration");
throw new DavMailException("EXCEPTION_CONNECTION_FAILED", url, status);
}
} catch (UnknownHostException exc) {
String message = "DavMail configuration exception: \n";
if (checkNetwork()) {
message += "Unknown host " + exc.getMessage();
ExchangeSession.LOGGER.error(message, exc);
throw new IOException(message);
} else {
message = "All network interfaces down !";
BundleMessage message = new BundleMessage("EXCEPTION_UNKNOWN_HOST", exc.getMessage());
ExchangeSession.LOGGER.error(message);
throw new NetworkDownException(message);
throw new DavMailException("EXCEPTION_DAVMAIL_CONFIGURATION", message);
} else {
ExchangeSession.LOGGER.error(BundleMessage.formatLog("EXCEPTION_NETWORK_DOWN"));
throw new NetworkDownException("EXCEPTION_NETWORK_DOWN");
}
} catch (NetworkDownException exc) {
throw exc;
} catch (Exception exc) {
ExchangeSession.LOGGER.error("DavMail configuration exception: \n" + exc.getMessage(), exc);
throw new IOException("DavMail configuration exception: \n" + exc.getMessage());
ExchangeSession.LOGGER.error(BundleMessage.formatLog("EXCEPTION_DAVMAIL_CONFIGURATION", exc), exc);
throw new DavMailException("EXCEPTION_DAVMAIL_CONFIGURATION", exc);
} finally {
testMethod.releaseConnection();
}

View File

@ -1,12 +1,12 @@
package davmail.exchange;
import java.io.IOException;
import davmail.exception.DavMailException;
/**
* Custom exception to mark network down case.
*/
public class NetworkDownException extends IOException {
public NetworkDownException(String message) {
super(message);
public class NetworkDownException extends DavMailException {
public NetworkDownException(String key) {
super(key);
}
}

View File

@ -4,6 +4,7 @@ import com.sun.mail.imap.protocol.BASE64MailboxDecoder;
import com.sun.mail.imap.protocol.BASE64MailboxEncoder;
import davmail.AbstractConnection;
import davmail.BundleMessage;
import davmail.exception.DavMailException;
import davmail.exchange.ExchangeSession;
import davmail.exchange.ExchangeSessionFactory;
import davmail.ui.tray.DavGatewayTray;
@ -483,7 +484,7 @@ public class ImapConnection extends AbstractConnection {
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z", Locale.ENGLISH);
buffer.append(" INTERNALDATE \"").append(dateFormatter.format(date)).append('\"');
} catch (ParseException e) {
throw new IOException("Invalid date: " + message.date);
throw new DavMailException("EXCEPTION_INVALID_DATE", message.date);
}
} else if ("BODY.PEEK[HEADER]".equals(param) || param.startsWith("BODY.PEEK[HEADER")) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
@ -560,7 +561,7 @@ public class ImapConnection extends AbstractConnection {
}
int slashIndex = multiPart.getContentType().indexOf('/');
if (slashIndex < 0) {
throw new IOException("Invalid content type: " + multiPart.getContentType());
throw new DavMailException("EXCEPTION_INVALID_CONTENT_TYPE", multiPart.getContentType());
}
int semiColonIndex = multiPart.getContentType().indexOf(';');
if (semiColonIndex < 0) {
@ -573,7 +574,7 @@ public class ImapConnection extends AbstractConnection {
appendBodyStructure(buffer, mimeMessage);
}
} catch (MessagingException me) {
throw new IOException(me);
throw new DavMailException("EXCEPTION_INVALID_MESSAGE_CONTENT", me.getMessage());
}
}
@ -581,7 +582,7 @@ public class ImapConnection extends AbstractConnection {
String contentType = bodyPart.getContentType();
int slashIndex = contentType.indexOf('/');
if (slashIndex < 0) {
throw new IOException("Invalid content type: " + contentType);
throw new DavMailException("EXCEPTION_INVALID_CONTENT_TYPE", contentType);
}
buffer.append("(\"").append(contentType.substring(0, slashIndex).toUpperCase()).append("\" \"");
int semiColonIndex = contentType.indexOf(';');
@ -707,22 +708,23 @@ public class ImapConnection extends AbstractConnection {
} else if (range.endsWith(":*")) {
conditions.startUid = Long.parseLong(range.substring(0, range.indexOf(':')));
} else {
throw new IOException("Invalid search parameters");
throw new DavMailException("EXCEPTION_INVALID_SEARCH_PARAMETERS", range);
}
} else if ("BEFORE".equals(token)) {
SimpleDateFormat parser = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateFormatter.setTimeZone(ExchangeSession.GMT_TIMEZONE);
String dateToken = tokens.nextToken();
try {
Date date = parser.parse(tokens.nextToken());
Date date = parser.parse(dateToken);
conditions.append(operator).append("\"urn:schemas:httpmail:datereceived\"<'").append(dateFormatter.format(date)).append('\'');
} catch (ParseException e) {
throw new IOException("Invalid search parameters");
throw new DavMailException("EXCEPTION_INVALID_SEARCH_PARAMETERS", dateToken);
}
} else if ("OLD".equals(token) || "RECENT".equals(token)) {
// ignore
} else {
throw new IOException("Invalid search parameter: " + token);
throw new DavMailException("EXCEPTION_INVALID_SEARCH_PARAMETERS", token);
}
}
@ -733,14 +735,15 @@ public class ImapConnection extends AbstractConnection {
parser.setTimeZone(ExchangeSession.GMT_TIMEZONE);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateFormatter.setTimeZone(ExchangeSession.GMT_TIMEZONE);
String dateToken = tokens.nextToken();
try {
startDate = parser.parse(tokens.nextToken());
startDate = parser.parse(dateToken);
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
calendar.add(Calendar.DAY_OF_MONTH, 1);
endDate = calendar.getTime();
} catch (ParseException e) {
throw new IOException("Invalid search parameters");
throw new DavMailException("EXCEPTION_INVALID_SEARCH_PARAMETERS", dateToken);
}
if ("SENTON".equals(token)) {
conditions.append("(\"urn:schemas:httpmail:date\" > '")
@ -862,13 +865,13 @@ public class ImapConnection extends AbstractConnection {
if (tokens.hasMoreTokens()) {
userName = tokens.nextToken();
} else {
throw new IOException("Invalid credentials");
throw new DavMailException("EXCEPTION_INVALID_CREDENTIALS");
}
if (tokens.hasMoreTokens()) {
password = tokens.nextToken();
} else {
throw new IOException("Invalid credentials");
throw new DavMailException("EXCEPTION_INVALID_CREDENTIALS");
}
int backslashindex = userName.indexOf('\\');
if (backslashindex > 0) {

View File

@ -6,6 +6,7 @@ import com.sun.jndi.ldap.BerEncoder;
import davmail.AbstractConnection;
import davmail.Settings;
import davmail.BundleMessage;
import davmail.exception.DavMailException;
import davmail.exchange.ExchangeSessionFactory;
import davmail.ui.tray.DavGatewayTray;
@ -817,7 +818,7 @@ public class LdapConnection extends AbstractConnection {
responseBer.encodeString((String) value, isLdapV3());
}
} else {
throw new IllegalArgumentException();
throw new DavMailException("EXCEPTION_UNSUPPORTED_VALUE", values);
}
responseBer.endSeq();
responseBer.endSeq();

View File

@ -2,6 +2,7 @@ package davmail.smtp;
import davmail.AbstractConnection;
import davmail.BundleMessage;
import davmail.exception.DavMailException;
import davmail.exchange.ExchangeSessionFactory;
import davmail.ui.tray.DavGatewayTray;
@ -97,7 +98,7 @@ public class SmtpConnection extends AbstractConnection {
InternetAddress internetAddress = new InternetAddress(line.substring("RCPT TO:".length()));
recipients.add(internetAddress.getAddress());
} catch (AddressException e) {
throw new IOException("Invalid recipient: " + line);
throw new DavMailException("EXCEPTION_INVALID_RECIPIENT", line);
}
sendClient("250 Recipient OK");
} else {
@ -187,7 +188,7 @@ public class SmtpConnection extends AbstractConnection {
userName = decodedCredentials.substring(1, index);
password = decodedCredentials.substring(index + 1);
} else {
throw new IOException("Invalid credentials");
throw new DavMailException("EXCEPTION_INVALID_CREDENTIALS");
}
}

View File

@ -2,6 +2,7 @@ package davmail.ui.tray;
import davmail.Settings;
import davmail.BundleMessage;
import davmail.exception.DavMailException;
import davmail.exchange.NetworkDownException;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
@ -60,7 +61,9 @@ public class DavGatewayTray {
if (message != null) {
buffer.append(message.format(locale)).append(' ');
}
if (e.getMessage() != null) {
if (e instanceof DavMailException) {
buffer.append(((DavMailException)e).getMessage(locale));
} else if (e.getMessage() != null) {
buffer.append(e.getMessage());
} else {
buffer.append(e.toString());

View File

@ -159,3 +159,45 @@ UI_UNTRUSTED_CERTIFICATE=Server provided an untrusted certificate,\n you can cho
UI_UNTRUSTED_CERTIFICATE_HTML=<html><b>Server provided an untrusted certificate,<br> you can choose to accept or deny access</b></html>
UI_VALID_FROM=Valid from
UI_VALID_UNTIL=Valid until
LOG_UNABLE_TO_CREATE_LOG_FILE_DIR=Unable to create log file directory
LOG_UNABLE_TO_SET_LOG_FILE_PATH=Unable to set log file path
EXCEPTION_INVALID_DATE=Invalid date: {0}
EXCEPTION_INVALID_CREDENTIALS=Invalid credentials
EXCEPTION_AUTHENTICATION_FAILED=Authentication failed: invalid user or password
EXCEPTION_AUTHENTICATION_FAILED_RETRY=Authentication failed: invalid user or password, retry with domain\\user
EXCEPTION_AUTHENTICATION_FAILED_PASSWORD_EXPIRED=Authentication failed: password expired ?
EXCEPTION_AUTHENTICATION_FORM_NOT_FOUND=Authentication form not found at {0}
EXCEPTION_INVALID_HEADER=Invalid header: {0}
EXCEPTION_INVALID_CONTENT_LENGTH=Invalid content length: {0}
EXCEPTION_END_OF_STREAM=End of stream reached reading content
EXCEPTION_INVALID_KEEPALIVE=Invalid Keep-Alive: {0}
EXCEPTION_INVALID_REQUEST=Invalid request: {0}
EXCEPTION_UNSUPPORTED_AUTHORIZATION_MODE=Unsupported authorization mode: {0}
EXCEPTION_INVALID_CALDAV_REQUEST=Invalid Caldav request: {0}
EXCEPTION_UNABLE_TO_GET_MAIL_FOLDERS=Unable to get mail folders
EXCEPTION_UNABLE_TO_CREATE_MESSAGE=Unable to create message {0}: {1}{2}{3}
EXCEPTION_UNABLE_TO_PATCH_MESSAGE=Unable to patch message {0}: {1}{2}{3}
EXCEPTION_UNABLE_TO_UPDATE_MESSAGE=Unable to update message properties
EXCEPTION_INVALID_FOLDER_URL=Invalid folder URL: {0}
EXCEPTION_UNABLE_TO_MOVE_MESSAGE=Unable to move message, target already exists
EXCEPTION_UNABLE_TO_MOVE_FOLDER=Unable to move folder, target already exists
EXCEPTION_INVALID_MESSAGE_URL=Invalid message URL: {0}
EXCEPTION_INVALID_MESSAGE_CONTENT=Invalid calendar message content: {0}
EXCEPTION_EVENT_NOT_FOUND=Calendar event not found
EXCEPTION_INVALID_ICS_LINE=Invalid ICS line: {0}
EXCEPTION_UNABLE_TO_GET_FOLDER=Unable to get folder at {0}
EXCEPTION_UNABLE_TO_GET_PROPERTY=Unable to get property {0}
EXCEPTION_INVALID_MAIL_PATH=Invalid mail path: {0}
EXCEPTION_UNABLE_TO_GET_MAIL_FOLDER=Unable to get mail folder
EXCEPTION_UNABLE_TO_GET_EMAIL=Unable to get user email from: {0}
EXCEPTION_UNABLE_TO_FIND_USERS={0} Unable to find users from: {1}
EXCEPTION_INVALID_DATES=Invalid dates: {0}
EXCEPTION_UNABLE_TO_GET_FREEBUSY=Unable to get free-busy from: {0}
EXCEPTION_INVALID_RECIPIENT=Invalid recipient: {0}
EXCEPTION_UNSUPPORTED_VALUE=Unsupported value: {0}
EXCEPTION_INVALID_CONTENT_TYPE=Invalid content type: {0}
EXCEPTION_INVALID_SEARCH_PARAMETERS=Invalid search parameters: {0}
EXCEPTION_NETWORK_DOWN=All network interfaces down !
EXCEPTION_DAVMAIL_CONFIGURATION=DavMail configuration exception: \n{0}
EXCEPTION_UNKNOWN_HOST=Unknown host {0}
EXCEPTION_CONNECTION_FAILED=Unable to connect to OWA at {0}, status code {1}, check configuration

View File

@ -159,3 +159,45 @@ UI_UNTRUSTED_CERTIFICATE=Le certificat fourni par le serveur n''est certifi
UI_UNTRUSTED_CERTIFICATE_HTML=<html><b>Le certificat fourni par le serveur n''est certifié par aucune autorité de confiance,<br> vous pouvez choisir d''accepter ou de rejeter l''accès</b></html>
UI_VALID_FROM=Emis le
UI_VALID_UNTIL=Expire le
LOG_UNABLE_TO_CREATE_LOG_FILE_DIR=Impossible de créer le répertoire de traces
LOG_UNABLE_TO_SET_LOG_FILE_PATH=Echec à la mise à jour du chemin du fichier de traces
EXCEPTION_INVALID_DATE=Date invalide {0}
EXCEPTION_INVALID_CREDENTIALS=Identifiant ou mot de passe invalide
EXCEPTION_AUTHENTICATION_FAILED=Echec d''authentification : identifiant ou mot de passe invalide
EXCEPTION_AUTHENTICATION_FAILED_RETRY=Echec d''authentification : identifiant ou mot de passe invalide, réessayer avec domaine\\utilisateur
EXCEPTION_AUTHENTICATION_FAILED_PASSWORD_EXPIRED=Echec d''authentification : mot de passe expiré ?
EXCEPTION_AUTHENTICATION_FORM_NOT_FOUND=Formulaire d''authentification non trouvé à l''adresse {0}
EXCEPTION_INVALID_HEADER=Entête invalide : {0}
EXCEPTION_INVALID_CONTENT_LENGTH=Longueur du contenu invalide : {0}
EXCEPTION_END_OF_STREAM=Fin de flux âtteint pendant la lecture du contenu
EXCEPTION_INVALID_KEEPALIVE=Keep-Alive invalide : {0}
EXCEPTION_INVALID_REQUEST=Requête invalide {0}
EXCEPTION_UNSUPPORTED_AUTHORIZATION_MODE=Mode d'authentification invalide : {0}
EXCEPTION_INVALID_CALDAV_REQUEST=Reuqête Caldav invalide : {0}
EXCEPTION_UNABLE_TO_GET_MAIL_FOLDERS=Impossible d''obtenir les répertoires de messagerie
EXCEPTION_UNABLE_TO_CREATE_MESSAGE=Impossible de créer le message {0} : {1}{2}{3}
EXCEPTION_UNABLE_TO_PATCH_MESSAGE=Impossible de mettre ) jour le message {0} : {1}{2}{3}
EXCEPTION_UNABLE_TO_UPDATE_MESSAGE=Impossible de mettre à jour les propriétés du message
EXCEPTION_INVALID_FOLDER_URL=URL du dossier invalide : {0}
EXCEPTION_UNABLE_TO_MOVE_MESSAGE=Impossible de déplacer le message, la cible existe
EXCEPTION_UNABLE_TO_MOVE_FOLDER=Impossible de déplacer le dossier, la cible existe
EXCEPTION_INVALID_MESSAGE_URL=URL de message invalide : {0}
EXCEPTION_INVALID_MESSAGE_CONTENT=Contenu du message invalide : {0}
EXCEPTION_EVENT_NOT_FOUND=Evènement non trouvé
EXCEPTION_INVALID_ICS_LINE=Ligne ICS invalide : {0}
EXCEPTION_UNABLE_TO_GET_FOLDER=Impossible d''obtenir le dossier {0}
EXCEPTION_UNABLE_TO_GET_PROPERTY=Impossible d''obtenir la propriété {0}
EXCEPTION_INVALID_MAIL_PATH=Chemin de messagerie invalide : {0}
EXCEPTION_UNABLE_TO_GET_MAIL_FOLDER=Impossible d''obtenir le dossier de messagerie
EXCEPTION_UNABLE_TO_GET_EMAIL=Impossible d''obtenir l''adresse de messagerie depuis : {0}
EXCEPTION_UNABLE_TO_FIND_USERS={0} Impossible de chercher les utilisateurs à l''adresse : {1}
EXCEPTION_INVALID_DATES=Dates invalides : {0}
EXCEPTION_UNABLE_TO_GET_FREEBUSY=Impossible d''obtenir les informations de disponibilité depuis : {0}
EXCEPTION_INVALID_RECIPIENT=Destinataire invalide : {0}
EXCEPTION_UNSUPPORTED_VALUE=Valeur non supportée : {0}
EXCEPTION_INVALID_CONTENT_TYPE=Type de contenu invalide : {0}
EXCEPTION_INVALID_SEARCH_PARAMETERS=Paremètres de recherche invalides : {0}
EXCEPTION_NETWORK_DOWN=Toutes les interfaces réseaux sont indisponibles !
EXCEPTION_DAVMAIL_CONFIGURATION=Erreur de configuration DavMail : \n{0}
EXCEPTION_UNKNOWN_HOST=Nom de serveur invalide {0}
EXCEPTION_CONNECTION_FAILED=Connection OWA à {0} impossible, code retour {1}, vérifier la configuration