Major update for the dict protocol

- Using an external library to manage the connection with the server
- Enhanced account registration wizard
cusax-fix
Damien Roth 18 years ago
parent 5417c1891a
commit 46ef85f493

@ -1740,6 +1740,7 @@ javax.swing.event, javax.swing.border"/>
manifest="${src}/net/java/sip/communicator/impl/protocol/dict/dict.provider.manifest.mf">
<zipfileset dir="${dest}/net/java/sip/communicator/impl/protocol/dict"
prefix="net/java/sip/communicator/impl/protocol/dict"/>
<zipfileset src="${lib.noinst}/dict4j.jar" prefix=""/>
</jar>
</target>

Binary file not shown.

@ -353,6 +353,7 @@ inviteIcon=resources/images/plugin/whiteboard/inviteDialogIcon.png
# dict status enum
dictProtocolIcon=resources/images/protocol/dict/dict-16x16.png
dictOfflineIcon=resources/images/protocol/dict/dict-16x16-offline.png
dict64x64Icon=resources/images/protocol/dict/dict-64x64.png
# gibberish status enum

Binary file not shown.

After

Width:  |  Height:  |  Size: 687 B

@ -434,16 +434,37 @@ contactExtendedDesc=Extended contact info for
contactInfoNotSupported=This protocol doesn't support server stored details for now. Try one of the other protocols.
notSpecified=[Not specified]
# dict accregwizz
protocolNameDict=Dict
protocolDescriptionDict=The Dict service protocol
strategyList=List of strategies:
strategyActu=Search strategies
strategyDesc=Strategie is use to search similar words,if a translation was not found, thanks to different approaches. For example the Prefix strategies will search words which begin like the word you would translate.
dictAccountInfoTitle=Dict Account Information
firstAccount=This wizard will create your first Dict Account for you on dict.org.\n\n\
# Dict protocol
dict.dictionaries=Dictionaries
dict.anyDictionary=Any Dictionary
dict.anyDictionaryFrom=Any Dictionary from {0}
dict.firstMatch=First Match
dict.noMatch=No match
dict.matchResult=No definitions found for "{0}", perhaps you mean:\n
dict.invalidDatabase=The current dictionary "{0}" doesn't exist anymore on the server.
dict.invalidStrategy=The current strategy isn't available on the server.
# DICT Protocol Account Wizard
dict.protocolName=Dict
dict.protocolDescription=The Dict service protocol
dict.host=Host
dict.port=Port
dict.serverInformations=Server informations
dict.strategy=Strategy
dict.strategySelection=Strategy selection
dict.strategyList=List of strategies:
dict.strategyActu=Search strategies
dict.strategyDesc=Strategie is use to search similar words,if a translation was not found, thanks to different approaches. For example the Prefix strategies will search words which begin like the word you would translate.
dict.accountInfoTitle=Dict Account Information
dict.firstAccount=This wizard will create your first Dict Account for you on dict.org.\n\n\
You can add new dictionary by going on Account Registration Wizard. Fill the host Field with dictionnary you would like to add.
dict.threadConnect=Trying to connect to server
dict.threadConnectFailed=Connexion attempt failed, this isn't a dict server or the server is offline
dict.retrievingStrategies=Retrieving strategies
dict.noStrategiesFound=No strategy found on the server
dict.populateList=Populating list
dict.closingConnexion=Closing connexion
# extendedcallsearchhistory
advancedCallHistorySearch=&Advanced call history search

@ -347,3 +347,34 @@ newMessage=Nouveau Message.
busyMessage=Désolé, je suis occupé pour le moment.
brbMessage=Je suis absent, je reviens dans un moment.
# DICT Protocol
dict.dictionaries=Dictionnaires
dict.anyDictionary=Tous les dictionnaires
dict.anyDictionaryFrom=Tous les dictionnaires de {0}
dict.firstMatch=Premier résultat
dict.noMatch=Aucun résultat
dict.matchResult=Aucune définition trouvée pour "{0}", vous souhaitez peut-être dire :\n
dict.invalidDatabase=Le dictionnaire actuel "{0}" n'existe plus sur le serveur.
dict.invalidStrategy=La stratégie actuelle n'existe plus sur le serveur.
# DICT Protocol Account Wizard
dict.protocolName=Dict
dict.protocolDescription=Protocol du service Dict
dict.host=Hôte
dict.port=Port
dict.serverInformations=Informations sur le serveur
dict.strategy=Stratégie
dict.strategySelection=Sélection de la stratégie
dict.strategyList=Liste des stratégies :
dict.strategyActu=Rechercher les stragéries
dict.strategyDesc=Les stratégies sont utilisées pour rechercher les mots similaires si aucune définition n'a été trouvée. Il existe différentes approches ; par exemple : la stratégie Prefix recherchera tous les mots qui commencent comme le mot dont vous cherchez la définition.
dict.accountInfoTitle=Information sur le compte Dict
dict.firstAccount=Cet assistant va créer votre premier compte Dict sur le serveur dict.org.\n\n\
Vous pouvez ajouter d'autres serveurs de dictionnaires en utilisant à nouveau cet assistant.
dict.threadConnect=Tentative de connexion au serveur
dict.threadConnectFailed=La tentative de connexion a échoué. Le serveur est hors ligne ou ce n'est pas un serveur de dictionnaires.
dict.retrievingStrategies=Récupération des stratégies
dict.noStrategiesFound=Aucune stratégie n'a été trouvée sur le serveur
dict.populateList=Mise à jour de la liste
dict.closingConnexion=Fermeture de la connexion

@ -6,6 +6,7 @@
*/
package net.java.sip.communicator.impl.protocol.dict;
import net.java.dict4j.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.*;
@ -20,6 +21,12 @@ public class ContactDictImpl
{
private Logger logger = Logger.getLogger(ContactDictImpl.class);
/**
* Icon
*/
private static byte[] icon = DictActivator.getResources()
.getImageInBytes("pageImageDict");
/**
* The id of the contact.
*/
@ -117,21 +124,30 @@ public String getDisplayName()
{
if (dictName == null)
{
try
if (this.contactID.equals("*"))
{
dictName = getDictAdapter().getDictionaryName(contactID);
// If the dict name is still null, set it to the contact ID
if (dictName == null)
{
dictName = contactID;
}
this.dictName = DictActivator.getResources()
.getI18NString("dict.anyDictionary");
}
else if (this.contactID.equals("!"))
{
this.dictName = DictActivator.getResources()
.getI18NString("dict.firstMatch");
}
catch (Exception e)
else
{
// Can't read data
logger.error("Error while getting dictionary long name", e);
dictName = contactID;
try
{
this.dictName = this.parentProvider.getConnection()
.getDictionaryName(this.contactID);
}
catch (DictException dx)
{
logger.error("Error while getting dictionary long name", dx);
}
if (this.dictName == null)
this.dictName = this.contactID;
}
}
@ -146,7 +162,7 @@ public String getDisplayName()
*/
public byte[] getImage()
{
return null;
return icon;
}
/**
@ -179,15 +195,6 @@ public ProtocolProviderService getProtocolProvider()
{
return parentProvider;
}
/**
* Return a reference to the socket connexion linked with the Account
* @return a reference to the socket connexion (DictAdapter)
*/
public DictAdapter getDictAdapter()
{
return parentProvider.getDictAdapter();
}
/**
* Determines whether or not this contact represents our own identity.

@ -7,6 +7,7 @@
package net.java.sip.communicator.impl.protocol.dict;
import net.java.sip.communicator.service.protocol.*;
import java.util.Map;
/**
@ -27,4 +28,34 @@ public class DictAccountID
{
super(userID, accountProperties, ProtocolNames.DICT, "dict.org");
}
/**
* Returns the dict server adress
* @return the dict server adress
*/
public String getHost()
{
return (String) this.getAccountProperties()
.get(ProtocolProviderFactory.SERVER_ADDRESS);
}
/**
* Returns the dict server port
* @return the dict server port
*/
public int getPort()
{
return Integer.parseInt((String) this.getAccountProperties()
.get(ProtocolProviderFactory.SERVER_PORT));
}
/**
* Returns the selected strategy
* @return the selected strategy
*/
public String getStrategy()
{
return (String) this.getAccountProperties()
.get(ProtocolProviderFactory.STRATEGY);
}
}

@ -28,7 +28,7 @@ public class DictActivator
/**
* The currently valid bundle context.
*/
static BundleContext bundleContext = null;
private static BundleContext bundleContext = null;
private ServiceRegistration dictPpFactoryServReg = null;
private static ProtocolProviderFactoryDictImpl
@ -58,7 +58,7 @@ public void start(BundleContext context)
dictProviderFactory = new ProtocolProviderFactoryDictImpl();
//reg the dict provider factory.
dictPpFactoryServReg = context.registerService(
dictPpFactoryServReg = context.registerService(
ProtocolProviderFactory.class.getName(),
dictProviderFactory,
hashtable);
@ -90,7 +90,7 @@ public void stop(BundleContext context)
throws Exception
{
this.dictProviderFactory.stop();
dictProviderFactory.stop();
dictPpFactoryServReg.unregister();
logger.info("DICT protocol implementation [STOPPED].");

@ -1,654 +0,0 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.protocol.dict;
import java.io.*;
import java.net.*;
import java.util.*;
/**
* Layer abstraction of a dict server
*
* @author LITZELMANN Cedric
* @author ROTH Damien
*/
public class DictAdapter
{
/**
* The host name of the server: i.e. "dict.org"
*/
private String host;
/**
* The port used by the server. The default one for the DICT protocol is
* 2628.
*/
private int port;
/**
* The name of the strategy used for searching words with command MATCH:
* i.e. the strategie can de "prefix", "suffix", "soundex", "levenshtein", etc.
*/
private String strategy;
/**
* A string representation used to identify the client to the serveur. In
* our case we will use the "SIP Communicator" string for the client name.
*/
private String clientName = "";
// Status
/**
* The socket used to connect to the DICT server.
*/
private Socket socket;
/**
* A output stream piped to the socket in order to send command to the server.
*/
private PrintWriter out;
/**
* A input stream piped to the socket in order to receive messages from the server.
*/
private BufferedReader in;
/**
* A boolean telling if we are currently connected to the DICT server.
*/
private boolean connected;
/**
* The list of all the databases hosted by the server. Each database
* correspond to a dictionnary.
*/
Vector<String> databasesList;
/**
* Initialize a basic instance with predefined settings
*/
public DictAdapter()
{
this.host = "dict.org";
this.port = 2628;
this.strategy = "prefix";
this.connected = false;
this.socket = null;
this.out = null;
this.in = null;
}
/**
* Initialize a basic instance and set th host
* @param host Host
*/
public DictAdapter(String host)
{
this.host = host;
this.port = 2628;
this.strategy = "prefix";
this.connected = false;
this.socket = null;
this.out = null;
this.in = null;
}
/**
* Initialize an instance and set the host and the port
* @param host Host
* @param port Port
*/
public DictAdapter(String host, int port)
{
this.host = host;
this.port = port;
this.strategy = "prefix";
this.connected = false;
this.socket = null;
this.out = null;
this.in = null;
}
/**
* Initialize an instance and set the host, port and strategy
* @param host Host
* @param port Port
* @param strategy Match strategy
*/
public DictAdapter(String host, int port, String strategy)
{
this.host = host;
this.port = port;
this.strategy = strategy;
this.connected = false;
this.socket = null;
this.out = null;
this.in = null;
}
/**
* Establish a connexion to the dict server
* @throws Exception
* @return DictResultset containing the error - null otherwise
*/
private void connect() throws Exception
{
String fromServer;
if (this.isConnected())
{
return;
}
try
{
this.socket = new Socket(this.host, this.port);
this.out = new PrintWriter(new OutputStreamWriter(this.socket.getOutputStream(),
"UTF-8"), true);
this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream(),
"UTF-8"));
fromServer = this.in.readLine(); // Server banner
if (fromServer.startsWith("220"))
{ // 220 = connect ok
this.connected = true;
this.client("SIP Communicator");
return;
}
else
{
throw new DictException(fromServer.substring(0, 3));
}
}
catch(UnknownHostException uhe)
{
throw new DictException(uhe);
}
catch(IOException ioe)
{
throw new DictException(ioe);
}
}
/**
* Close the actual connexion
* @throws Exception
*/
public void close() throws Exception
{
String fromServer;
boolean quit = false;
if (!this.isConnected())
{
return;
}
try
{
this.out.println("QUIT");
// Clean the socket buffer
while (quit == false && (fromServer = this.in.readLine()) != null)
{
if (fromServer.startsWith("221"))
{ // Quit response
quit = true;
}
}
this.out.close();
this.in.close();
this.socket.close();
this.connected = false;
}
catch (IOException ioe)
{
throw new DictException(ioe);
}
}
/**
* Get the database list from the server
* @throws Exception
* @return a DictResultset containing the database list - otherwise the error code
*/
public DictResultset showDB() throws Exception
{
String fromServer;
boolean quit = false;
DictResultset result = new DictResultset();
this.connect();
try
{
fromServer = this.query("SHOW DB");
if (fromServer.startsWith("110"))
{ // OK - getting responses from the server
result.newResultset();
while (quit == false && (fromServer = this.in.readLine()) != null)
{
if (fromServer.startsWith("250"))
{
quit = true;
}
else if (!fromServer.equals("."))
{
result.addResult(fromServer);
}
}
}
else
{
throw new DictException(fromServer.substring(0,3));
}
}
catch (IOException ioe)
{
throw new DictException(ioe);
}
return result;
}
/**
* Get the strategies allowed by the server for the MATCH command
* @throws Exception
* @return a DictResultset containing the database list - otherwise the error code
*/
public DictResultset showStrat() throws Exception
{
String fromServer;
boolean quit = false;
DictResultset result = new DictResultset();
this.connect();
try
{
fromServer = this.query("SHOW STRAT");
if (fromServer.startsWith("111"))
{ // OK - getting responses from the server
result.newResultset();
while (quit == false && (fromServer = this.in.readLine()) != null)
{
if (fromServer.startsWith("250"))
{
quit = true;
}
else if (!fromServer.equals("."))
{
result.addResult(fromServer);
}
}
}
else
{
throw new DictException(fromServer.substring(0,3));
}
}
catch (IOException ioe)
{
throw new DictException(ioe);
}
return result;
}
/**
* Get the definition of a word
* @param database the database in which the word will be searched
* @param word the search word
* @throws Exception
* @return a DictResultset containing the database list - otherwise the error code
*/
public DictResultset define(String database, String word) throws Exception
{
String fromServer;
boolean quit = false;
DictResultset result = new DictResultset();
String[] test;
this.connect();
try
{
fromServer = this.query("DEFINE " + database + " " + word);
if (fromServer.startsWith("150"))
{
while (quit == false && (fromServer = this.in.readLine()) != null)
{
if (fromServer.startsWith("151"))
{ // First line - Contains the DB Name
test = fromServer.split(" ", 4);
result.newResultset(test[3].substring(1, test[3].length() - 1));
continue;
}
else if (fromServer.startsWith("250"))
{ // End of the request
quit = true;
}
else if (!fromServer.equals("."))
{
result.addResult(fromServer);
}
}
}
else
{
throw new DictException(fromServer.substring(0,3));
}
}
catch (IOException ioe)
{
throw new DictException(ioe);
}
return result;
}
/**
* Get words that match with a strategie form a word with the stored strategy
* @param database The database in which the words will be searched
* @param word The base word
* @return a DictResultset containing the words list - otherwise throw an exception
* @throws Exception
*/
public DictResultset match(String database, String word) throws Exception
{
return this.match(database, this.strategy, word);
}
/**
* Get words that match with a strategie from a word
* @param database the database in which the words will be searched
* @param strat the strategies used
* @param word the base word
* @throws Exception
* @return a DictResultset containing the words list - otherwise the error code
*/
public DictResultset match(String database, String strat, String word) throws Exception
{
String fromServer;
boolean quit = false;
DictResultset result = new DictResultset();
this.connect();
try
{
fromServer = this.query("MATCH " + database + " " + strat + " " + word);
if (fromServer.startsWith("152"))
{
result.newResultset();
while (quit == false && (fromServer = this.in.readLine()) != null)
{
if (fromServer.startsWith("250"))
{
quit = true;
}
else if (!fromServer.equals("."))
{
result.addResult(fromServer);
}
}
}
else
{
throw new DictException(fromServer.substring(0,3));
}
}
catch (IOException ioe)
{
throw new DictException(ioe);
}
return result;
}
/**
* Provide information to the server about the clientname, for logging and statistical purposes
* @param clientname Client name
* @throws Exception
*/
public void client(String clientname) throws Exception
{
String fromServer;
this.connect();
fromServer = this.query("CLIENT " + clientname);
// 250 code is the only possible answer
if (!fromServer.startsWith("250"))
{
throw new DictException(fromServer.substring(0, 3));
}
}
/**
* Set the host
* @param newHost host address
*/
public void setHost(String newHost) throws Exception
{
if (isUrl(newHost))
{
this.host = newHost;
}
else
{
throw new DictException(900, "Host URL is incorrect");
}
}
/**
* Set the host port
* @param newPort Port
*/
public void setPort(int newPort)
{
this.port = newPort;
}
/**
* Set the strategy
* @param newStrat Strategy
*/
public void setStrategy(String newStrat)
{
this.strategy = newStrat;
}
/**
* Set the client name which is communicated to the server
* @param cn Client name
*/
public void setClientName(String cn)
{
this.clientName = cn;
}
/**
* Return the host
* @return return the host
*/
public String getHost()
{
return this.host;
}
/**
* Return the port
* @return return the port
*/
public int getPort()
{
return this.port;
}
/**
* Return the strategy
* @return return the strategy
*/
public String getStrategy()
{
return this.strategy;
}
/**
* Return the client name
* @return return the client name
*/
public String getClientName()
{
return this.clientName;
}
/**
* Gets the database's list from the server
* @return List of the databases
* @throws Exception
*/
public Vector<String> getDatabases() throws Exception
{
if (this.databasesList == null)
{
DictResultset drs = this.showDB();
DictResult list = drs.getResultset(0);
this.databasesList = new Vector<String>();
while(list.hasNext())
{
this.databasesList.add(list.next());
}
}
return this.databasesList;
}
/**
* Gets the dictionary name from the databases list
* @param code Dictionary code
* @return the dictionary name
* @throws Exception
*/
public String getDictionaryName(String code) throws Exception
{
int dictionary_id_and_description_separator;
String dictionary_id_and_description;
String dictionary_id;
String dictionary_description;
// First, we check if the code is a special code
// Checks the RFC-2229 for more details
if (code.equals("*"))
{
return "Any dictionary";
}
else if (code.equals("!"))
{
return "First match";
}
// Gets the databases list
if (this.databasesList == null)
{
getDatabases();
}
// Look down the databases list to get the name
for (int i=0; i<this.databasesList.size(); i++)
{
dictionary_id_and_description = this.databasesList.get(i);
dictionary_id_and_description_separator = dictionary_id_and_description.indexOf(' ');
dictionary_id = dictionary_id_and_description.substring(0, dictionary_id_and_description_separator);
if (dictionary_id.equals(code))
{
dictionary_description = dictionary_id_and_description.substring(dictionary_id_and_description_separator + 1);
return dictionary_description.replace("\"", "");
}
}
// If the name isn't in the list, return null
return null;
}
/**
* Check if we are connected to the server
* @return true if we are connected - false otherwise
*/
public boolean isConnected()
{
return this.connected;
}
/**
* Check if the URL is correct and a server exists
* @param url an Url
* @return true if everything is ok - false otherwise
*/
public static boolean isUrl(String url)
{
boolean ok;
if (url == null)
{
return false;
}
try
{
InetAddress.getByName(url);
ok = true;
}
catch (UnknownHostException uhex)
{
ok = false;
}
return ok;
}
/**
* Executes a query and deals with the automatic deconnexion
* @param query A query to send to the server
* @return The first ligne of the response from the server
* @throws Exception IOException and DictException
*/
private String query(String query) throws Exception
{
String result = null;
this.out.println(query);
result = in.readLine();
if (result == null)
{
// The connexion may be close, reconnexion
this.connected = false;
this.connect();
this.out.println(query);
result = in.readLine();
if (result == null)
{
// If result is still equal to null, the server is unavailable
// We send the appropriate exception
throw new DictException(420);
}
}
return result;
}
}

@ -1,287 +0,0 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.protocol.dict;
/**
* Exception class managing the basics dict server errors.
*
* @author LITZELMANN Cedric
* @author ROTH Damien
*/
public class DictException
extends Exception
{
// Error number
private int error;
// Error message
private String errorMessage;
/**
* Create an exception from the dict error code
* @param error Error code returned by the server
*/
public DictException(int error)
{
this.error = error;
}
/**
* Create an exception with a custom message
* @param error Error code returned by the server
* @param message Custom message
*/
public DictException(int error, String message)
{
this.error = error;
this.errorMessage = message;
}
/**
* Same as the first constructor but with a string (converted to an int)
* @param error Error code returned by the server
*/
public DictException(String error)
{
this.error = Integer.parseInt(error);
}
/**
* Create an exception from a java exception
* @param e Java Exception
*/
public DictException(Exception e)
{
String className = e.getClass().toString();
if (className.endsWith("IOException"))
{
this.error = 901;
this.errorMessage = "IOException";
}
else if (className.endsWith("UnknownHostException"))
{
this.error = 902;
this.errorMessage = "UnknownHostException";
}
else if (className.endsWith("SecurityException"))
{
this.error = 903;
this.errorMessage = "SecurityException";
}
else if (className.endsWith("SocketTimeoutException"))
{
this.error = 904;
this.errorMessage = "SocketTimeoutException";
}
else
{
this.error = 900;
this.errorMessage = "Unknown error [" + className + "]";
}
this.errorMessage += ": " + e.getMessage();
}
/**
* Return the error code
* @return the error code
*/
public int getErrorCode()
{
return this.error;
}
/**
* Return the error message
* @return the error message
*/
public String getMessage()
{
return this.errorMessage;
}
/**
* Get an explanation of the error
* @return Returns an explanation corresponding to the current error
* (this.error).
*/
public String getErrorMessage()
{
String result;
switch(this.error)
{
case 110 :
result = "n databases present";
break;
case 111 :
result = "n strategies available";
break;
case 112 :
result = "database information follows";
break;
case 113 :
result = "help text follows";
break;
case 114 :
result = "server information follows";
break;
case 130 :
result = "challenge follows";
break;
case 150 :
result = "n definitions retrieved";
break;
case 151 :
result = "word database name";
break;
case 152 :
result = "n matches found";
break;
case 210 :
result = "optional timing";
break;
case 220 :
result = "Connection OK";
break;
case 221 :
result = "Closing Connection";
break;
case 230 :
result = "Authentication successful";
break;
case 250 :
result = "OK";
break;
case 330 :
result = "send response";
break;
case 420 :
result = "Server temporarily unavailable";
break;
case 421 :
result = "Server shutting down at operator request";
break;
case 500 :
result = "Syntax error, command not recognized";
break;
case 501 :
result = "Syntax error, illegal parameters";
break;
case 502 :
result = "Command not implemented";
break;
case 503 :
result = "Command parameter not implemented";
break;
case 530 :
result = "Access denied";
break;
case 531 :
result = "Access denied, use SHOW INFO for server information";
break;
case 532 :
result = "Access denied, unknown mechanism";
break;
case 550 :
result = "Invalid database, use SHOW DB for list of databases";
break;
case 551 :
result = "Invalid strategy, use SHOW STRAT for a list of strategies";
break;
case 552 :
result = "No match";
break;
case 554 :
result = "No databases present";
break;
case 555 :
result = "No strategies available";
break;
default :
if (error >= 900)
{
result = this.errorMessage;
}
else
{
result = this.errorGen(error);
}
}
return result;
}
/**
* Get informations about unknowns errors
* @param err Error number
* @return Error definition
*/
private String errorGen(int err)
{
String error_type = Integer.toString(err);
String result = new String();
if(error_type.startsWith("1"))
{// test on digit one
result = "Positive Preliminary reply : ";
}
else if(error_type.startsWith("2"))
{
result = "Positive Completion reply : " ;
}
else if(error_type.startsWith("3"))
{
result = "Positive Intermediate reply : ";
}
else if(error_type.startsWith("4"))
{
result = "Transient Negative Completion reply : ";
}
else if(error_type.startsWith("5"))
{
result = "Permanent Negative Completion reply : ";
}
else
{
return "Unknown error";
}
//test on digit two
if(error_type.charAt(1) == '0')
{
result += "Syntax";
}
else if ( error_type.charAt(1) == '1')
{
result += "Information";
}
else if ( error_type.charAt(1) == '2')
{
result += "Connections";
}
else if ( error_type.charAt(1) == '3')
{
result += "Authentication";
}
else if ( error_type.charAt(1) == '4')
{
result += "Unspecified as yet";
}
else if ( error_type.charAt(1) == '5')
{
result += "DICT System";
}
else if ( error_type.charAt(1) == '8')
{
result += "Nonstandard (private implementation) extensions";
}
return result;
}
}

@ -1,64 +0,0 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.protocol.dict;
import java.util.*;
/**
* Static registry storing the connexions to dict servers
* @author ROTH Damien
* @author LITZELMANN Cedric
*/
public class DictRegistry
{
private static HashMap<String, DictAdapter> adapters = new HashMap<String,DictAdapter>();
/**
* Checks if an adapter associated with the given key is stored in the regitry
* @param key Key to the adapter
* @return true, if an adapter exists - false otherwise
*/
public static boolean has(String key)
{
return adapters.containsKey(key);
}
/**
* Stores a new adapter in the registry
* @param key Key
* @param value DictAdapter class
*/
public static void put(String key, DictAdapter value)
{
adapters.put(key, value);
}
/**
* Returns the adapter associated with the given key
* @param key Key
* @return the adapter associated with the given key - null otherwise
*/
public static DictAdapter get(String key)
{
if (DictRegistry.has(key))
{
return adapters.get(key);
}
return null;
}
/**
* Removes the adapter associated with the given key from the registry
* @param key
*/
public static void remove(String key)
{
if (DictRegistry.has(key)) {
adapters.remove(key);
}
}
}

@ -1,97 +0,0 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.protocol.dict;
import java.util.*;
/**
* Representation of the results of a response to a query
*
* @author ROTH Damien
* @author LITZEMANN Cedric
*/
public class DictResult
implements Iterator<String>
{
private String databaseName;
private int index;
private ArrayList<String> data;
/**
* Basic construct initializing the result
*/
public DictResult()
{
this.index = 0;
this.data = new ArrayList<String>();
this.databaseName = "";
}
/**
* Initialize the result and save the database name
* @param dbn Database name
*/
public DictResult(String dbn)
{
this.index = 0;
this.data = new ArrayList<String>();
this.databaseName = dbn;
}
/**
* Add a result
* @param s result
*/
public void add(String s)
{
this.data.add(s);
}
/**
* From the Iterator implementation, return the next part of the result
* @return the next part of the result
*/
public String next()
{
return (String) this.data.get(this.index++);
}
/**
* From the Iterator implementation, return true if the iteration has more elements
* @return true if the iteration has more elements - false otherwise
*/
public boolean hasNext()
{
return (this.index < this.data.size());
}
/**
* From the Iterator implementation but unsupported
*/
public void remove()
{
throw new UnsupportedOperationException();
}
/**
* Set the database name
* @param dbn Database name
*/
public void setDatabaseName(String dbn)
{
this.databaseName = dbn;
}
/**
* Return the database name
* @return the database name
*/
public String getDatabaseName()
{
return this.databaseName;
}
}

@ -1,107 +0,0 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.protocol.dict;
import java.util.*;
/**
* Class managing the results of a dict query
*
* @author ROTH Damien
* @author LITZELMANN Cedric
*/
public class DictResultset
{
/**
* The index number of the last resultset for this DictResultset. This
* parametre is set to "-1" if there is no resultset.
*/
private int cursor;
/**
* The list containing all the resultsets for this DictResultset.
*/
private ArrayList<DictResult> data;
/**
* Initialize a resultset list
*/
public DictResultset()
{
this.cursor = -1;
this.data = new ArrayList<DictResult>();
}
/**
* Create a new resultset
*/
public void newResultset()
{
this.cursor++;
this.data.add(new DictResult());
}
/**
* Create a new resultset and save the database name
* @param dbn Database name
*/
public void newResultset(String dbn)
{
this.cursor++;
this.data.add(new DictResult(dbn));
}
/**
* Set the database name for the current resultset
* @param dbn Database name
*/
public void setDatabaseName(String dbn)
{
this.data.get(this.cursor).setDatabaseName(dbn);
}
/**
* Add a result in the current resultset
* @param res a result line from a dict query
*/
public void addResult(String res)
{
this.data.get(this.cursor).add(res);
}
/**
* Return true if there is a resultset
* @return return true if there is a resultset - false otherwise
*/
public boolean hasResult()
{
return this.data.size() > 0;
}
/**
* Return the resultset at the given index
* @param index Index of the wished resultset
* @return a DictResult - null otherwise
*/
public DictResult getResultset(int index)
{
if (index < this.data.size())
{
return (DictResult) this.data.get(index);
}
return null;
}
/**
* Return the number of resultsets
* @return the number of resultsets
*/
public int getNbResults()
{
return this.data.size();
}
}

@ -30,9 +30,8 @@ public class DictStatusEnum
*/
public static final DictStatusEnum OFFLINE
= new DictStatusEnum(
0
, "Offline"
, getImageInBytes("dictProtocolIcon"));
0, "Offline",
DictActivator.getResources().getImageInBytes("dictOfflineIcon"));
/**
* The Online status. Indicate that the user is able and willing to
@ -40,9 +39,8 @@ public class DictStatusEnum
*/
public static final DictStatusEnum ONLINE
= new DictStatusEnum(
65
, "Online"
, getImageInBytes("dictProtocolIcon"));
65, "Online",
DictActivator.getResources().getImageInBytes("dictProtocolIcon"));
/**
* Initialize the list of supported status states.
@ -78,34 +76,4 @@ static Iterator supportedStatusSet()
{
return supportedStatusSet.iterator();
}
/**
* Returns the byte representation of the image corresponding to the given
* identifier.
*
* @param imageID the identifier of the image
* @return the byte representation of the image corresponding to the given
* identifier.
*/
public static byte[] getImageInBytes(String imageID)
{
InputStream in = DictActivator.getResources().
getImageInputStream(imageID);
if (in == null)
return null;
byte[] image = null;
try
{
image = new byte[in.available()];
in.read(image);
}
catch (IOException e)
{
logger.error("Failed to load image:" + imageID, e);
}
return image;
}
}

@ -7,11 +7,11 @@
package net.java.sip.communicator.impl.protocol.dict;
import java.util.*;
import net.java.dict4j.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
/**
* Instant messaging functionalities for the Dict protocol.
*
@ -22,9 +22,6 @@ public class OperationSetBasicInstantMessagingDictImpl
extends AbstractOperationSetBasicInstantMessaging
implements RegistrationStateChangeListener
{
private static final Logger logger
= Logger.getLogger(OperationSetBasicInstantMessagingDictImpl.class);
/**
* The currently valid persistent presence operation set.
*/
@ -34,6 +31,8 @@ public class OperationSetBasicInstantMessagingDictImpl
* The protocol provider that created us.
*/
private ProtocolProviderServiceDictImpl parentProvider = null;
private DictAccountID accountID;
/**
* Creates an instance of this operation set keeping a reference to the
@ -49,10 +48,17 @@ public OperationSetBasicInstantMessagingDictImpl(
{
this.opSetPersPresence = opSetPersPresence;
this.parentProvider = provider;
this.accountID = (DictAccountID) provider.getAccountID();
parentProvider.addRegistrationStateChangeListener(this);
}
public Message createMessage(String content)
{
return new MessageDictImpl(content, HTML_MIME_TYPE,
DEFAULT_MIME_ENCODING, null);
}
public Message createMessage(String content, String contentType,
String encoding, String subject)
{
@ -170,9 +176,8 @@ private void submitDictQuery(ContactDictImpl dictContact, Message message)
Message msg = this.createMessage("");
String database = dictContact.getContactID();
DictAdapter dictAdapter = dictContact.getDictAdapter();
DictConnection conn = this.parentProvider.getConnection();
boolean doMatch = false;
DictResultset fctResult;
String word;
@ -187,46 +192,33 @@ private void submitDictQuery(ContactDictImpl dictContact, Message message)
// Try to get the definition of the work
try
{
fctResult = dictAdapter.define(database, word);
msg =
this.createMessage(this.retrieveDefine(fctResult, word),
HTML_MIME_TYPE, DEFAULT_MIME_ENCODING, null);
List<Definition> definitions = conn.define(database, word);
msg = this.createMessage(retrieveDefine(definitions, word));
}
catch(DictException dex)
catch(DictException dx)
{
if (dex.getErrorCode() == 552)
if (dx.getErrorCode() == DictReturnCode.NO_MATCH)
{ // No word found, we are going to try the match command
doMatch = true;
}
else
{ // Otherwise we display the error returned by the server
msg = this.createMessage(manageException(dex, database));
msg = this.createMessage(manageException(dx, database));
}
}
catch(Exception ex)
{
logger.error("Failed to retrieve Definition. Error was: "
+ ex.getMessage()
, ex);
}
if (doMatch)
{
// Trying the match command
try
{
fctResult = dictAdapter.match(database, word);
msg = this.createMessage(this.retrieveMatch(fctResult, word));
}
catch(DictException dex)
{
msg = this.createMessage(manageException(dex, database));
List<MatchWord> matchWords = conn.match(database, word,
this.accountID.getStrategy());
msg = this.createMessage(retrieveMatch(matchWords, word));
}
catch(Exception ex)
catch(DictException dx)
{
logger.error("Failed to retrieve Match. Error was: "
+ ex.getMessage()
, ex);
msg = this.createMessage(manageException(dx, database));
}
}
@ -241,28 +233,26 @@ private void submitDictQuery(ContactDictImpl dictContact, Message message)
* @param word the queried word
* @return the formatted result
*/
private String retrieveDefine(DictResultset data, String word)
private String retrieveDefine(List<Definition> data, String word)
{
String result;
DictResult resultData;
StringBuffer res = new StringBuffer();
Definition def;
result = "<pre>";
for (int i=0; i<data.getNbResults(); i++)
for (int i=0; i<data.size(); i++)
{
resultData = data.getResultset(i);
def = data.get(i);
if(i != 0 && resultData.hasNext())
{
result += "<hr>";
}
while (resultData.hasNext())
if(i != 0 && data.size() > 0)
{
result += resultData.next() + "\n";
res.append("<hr>");
}
result = result.replaceAll("\n+\\z", "\n");
res.append(def.getDefinition().replaceAll("\n", "<br>"))
.append("<div align=\"right\"><font size=\"-2\">-- From ")
.append(def.getDictionary())
.append("</font></div>");
}
result += "</pre>";
String result = res.toString();
result = formatResult(result, "\\\\", "<em>", "</em>");
result = formatResult(result, "[\\[\\]]", "<cite>", "</cite>");
result = formatResult(result, "[\\{\\}]", "<strong>", "</strong>");
@ -328,45 +318,25 @@ private String formatResult(String result, String regex, String startTag, String
* @param word the queried word
* @return the formatted result
*/
private String retrieveMatch(DictResultset data, String word)
private String retrieveMatch(List<MatchWord> data, String word)
{
String result = "";
String temp;
DictResult resultData;
StringBuffer result = new StringBuffer();
boolean isStart = true;
result = "No definitions found for \""+ word +"\", perhaps you mean:\n";
result.append(DictActivator.getResources()
.getI18NString("dict.matchResult", new String[] {word}));
for (int i=0; i<data.getNbResults(); i++)
for (int i=0; i<data.size(); i++)
{
resultData = data.getResultset(i);
if (isStart)
isStart = false;
else
result.append(", ");
while(resultData.hasNext())
{
temp = resultData.next();
if (isStart)
{
isStart = false;
}
else
{
result += ", ";
}
// Return format : dictCode "match word"
temp = (temp.split(" ", 2))[1];
if (temp.indexOf(" ") == -1)
{
temp = temp.substring(1, temp.length() -1);
}
result += temp;
}
result.append(data.get(i).getWord());
}
return result;
return result.toString();
}
/**
@ -381,15 +351,22 @@ private String manageException(DictException dix, String database)
int errorCode = dix.getErrorCode();
// We change the text only for exception 550 (invalid dictionary) and 551 (invalid strategy)
if (errorCode == 550)
if (errorCode == DictReturnCode.INVALID_DATABASE)
{
return DictActivator.getResources()
.getI18NString("dict.invalidDatabase", new String[] {database});
}
else if (errorCode == DictReturnCode.INVALID_STRATEGY)
{
return "The current dictionary '" + database + "' doesn't exist anymore on the server";
return DictActivator.getResources()
.getI18NString("dict.invalidStrategy");
}
else if (errorCode == 551)
else if (errorCode == DictReturnCode.NO_MATCH)
{
return "The current strategy isn't available on the server";
return DictActivator.getResources()
.getI18NString("dict.noMatch");
}
return dix.getErrorMessage();
return dix.getMessage();
}
}

@ -6,14 +6,9 @@
*/
package net.java.sip.communicator.impl.protocol.dict;
import java.io.*;
import java.util.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.resources.*;
import net.java.sip.communicator.util.*;
import org.osgi.framework.*;
/**
* Reperesents the Dict protocol icon. Implements the <tt>ProtocolIcon</tt>
@ -25,20 +20,16 @@
public class ProtocolIconDictImpl
implements ProtocolIcon
{
private static Logger logger = Logger.getLogger(ProtocolIconDictImpl.class);
private static ResourceManagementService resourcesService;
/**
* A hash table containing the protocol icon in different sizes.
*/
private static Hashtable<String,byte[]> iconsTable = new Hashtable<String,byte[]>();
static {
iconsTable.put(ProtocolIcon.ICON_SIZE_16x16,
getImageInBytes("dictProtocolIcon"));
DictActivator.getResources().getImageInBytes("dictProtocolIcon"));
iconsTable.put(ProtocolIcon.ICON_SIZE_64x64,
getImageInBytes("dict64x64Icon"));
DictActivator.getResources().getImageInBytes("dict64x64Icon"));
}
/**
@ -81,51 +72,4 @@ public byte[] getConnectingIcon()
{
return iconsTable.get(ProtocolIcon.ICON_SIZE_16x16);
}
/**
* Returns the byte representation of the image corresponding to the given
* identifier.
*
* @param imageID the identifier of the image
* @return the byte representation of the image corresponding to the given
* identifier.
*/
private static byte[] getImageInBytes(String imageID)
{
InputStream in = DictActivator.getResources().
getImageInputStream(imageID);
if (in == null)
return null;
byte[] image = null;
try
{
image = new byte[in.available()];
in.read(image);
}
catch (IOException e)
{
logger.error("Failed to load image:" + imageID, e);
}
return image;
}
public static ResourceManagementService getResources()
{
if (resourcesService == null)
{
ServiceReference serviceReference = DictActivator.bundleContext
.getServiceReference(ResourceManagementService.class.getName());
if(serviceReference == null)
return null;
resourcesService = (ResourceManagementService)DictActivator.bundleContext
.getService(serviceReference);
}
return resourcesService;
}
}

@ -27,11 +27,6 @@ public class ProtocolProviderFactoryDictImpl
private static final Logger logger
= Logger.getLogger(ProtocolProviderFactoryDictImpl.class);
/**
* Name for the auto-create group
*/
private String groupName = "Dictionaries";
/**
* Creates an instance of the ProtocolProviderFactoryDictImpl.
*/
@ -124,6 +119,9 @@ private void createGroup()
try
{
String groupName = DictActivator.getResources()
.getI18NString("dict.dictionaries");
mcl.createMetaContactGroup(mcl.getRoot(), groupName);
}
catch (MetaContactListException ex)
@ -155,7 +153,15 @@ private void createDefaultContact(AccountID accountID)
ProtocolProviderService protocolProvider
= (ProtocolProviderService) DictActivator.getBundleContext()
.getService(serRef);
// Gets group name
String groupName = DictActivator.getResources()
.getI18NString("dict.dictionaries");
// Gets contact name
String contactName = DictActivator.getResources()
.getI18NString("dict.anyDictionaryFrom", new String[] {accountID.getUserID()});
// Gets the MetaContactGroup for the "dictionaries" group.
MetaContactGroup group = mcl.getRoot().getMetaContactSubgroup(groupName);
@ -165,7 +171,7 @@ private void createDefaultContact(AccountID accountID)
// Create the default contact.
mcl.createMetaContact(protocolProvider, group, dict_uin);
// Rename the default contact.
mcl.renameMetaContact(group.getMetaContact(protocolProvider, dict_uin), accountID.getUserID() + "_default_dictionary");
mcl.renameMetaContact(group.getMetaContact(protocolProvider, dict_uin), contactName);
}
@Override

@ -8,6 +8,7 @@
import java.util.*;
import net.java.dict4j.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.service.version.*;
@ -35,7 +36,7 @@ public class ProtocolProviderServiceDictImpl
/**
* The id of the account that this protocol provider represents.
*/
private AccountID accountID = null;
private DictAccountID accountID = null;
/**
* We use this to lock access to initialization.
@ -65,6 +66,11 @@ public class ProtocolProviderServiceDictImpl
private RegistrationState currentRegistrationState
= RegistrationState.UNREGISTERED;
/**
* the <tt>DictConnection</tt> opened by this provider
*/
private DictConnection dictConnection;
/**
* The default constructor for the Dict protocol provider.
*/
@ -91,7 +97,11 @@ protected void initialize(String userID,
{
synchronized(initializationLock)
{
this.accountID = accountID;
this.accountID = (DictAccountID) accountID;
this.dictConnection = new DictConnection(this.accountID.getHost(),
this.accountID.getPort());
this.dictConnection.setClientName(getSCVersion());
//initialize the presence operationset
OperationSetPersistentPresenceDictImpl persistentPresence =
@ -131,65 +141,14 @@ protected void initialize(String userID,
isInitialized = true;
}
}
/**
* Retrieve the DictAdapter linked with the account. If there is no instance, one is created
* @return a DictAdapter instance
*/
public DictAdapter getDictAdapter()
{
String host = (String) this.accountID.getAccountProperties()
.get(ProtocolProviderFactory.SERVER_ADDRESS);
int port = Integer.parseInt((String) this.accountID.getAccountProperties()
.get(ProtocolProviderFactory.SERVER_PORT));
String strategy = (String) this.accountID.getAccountProperties()
.get(ProtocolProviderFactory.STRATEGY);
String key = this.accountID.getUserID();
DictAdapter result = DictRegistry.get(key);
if (!(result instanceof DictAdapter))
{
result = new DictAdapter(host, port, strategy);
// Set the clientname from the current version
BundleContext bundleContext = DictActivator.getBundleContext();
ServiceReference versionServRef = bundleContext
.getServiceReference(VersionService.class.getName());
VersionService versionService = (VersionService) bundleContext
.getService(versionServRef);
result.setClientName(versionService.getCurrentVersion().toString());
// Store the DictAdapter
DictRegistry.put(key, result);
}
return result;
}
/**
* Close the DictAdapter linked with the account ID
* Returns the <tt>DictConnection</tt> opened by this provider
* @return the <tt>DictConnection</tt> opened by this provider
*/
public void closeDictAdapter()
public DictConnection getConnection()
{
String key = this.accountID.getUserID();
DictAdapter result = DictRegistry.get(key);
if ((result instanceof DictAdapter))
{
try
{
result.close();
DictRegistry.remove(key);
}
catch (Exception ex)
{
logger.error(ex);
}
}
return this.dictConnection;
}
/**
@ -279,14 +238,50 @@ public Map getSupportedOperationSets()
public void register(SecurityAuthority authority)
throws OperationFailedException
{
RegistrationState oldState = currentRegistrationState;
currentRegistrationState = RegistrationState.REGISTERED;
fireRegistrationStateChanged(
oldState
, currentRegistrationState
, RegistrationStateChangeEvent.REASON_USER_REQUEST
, null);
// Try to connect to the server
boolean connected = connect();
if (connected)
{
fireRegistrationStateChanged(
getRegistrationState(),
RegistrationState.REGISTERED,
RegistrationStateChangeEvent.REASON_USER_REQUEST,
null);
currentRegistrationState = RegistrationState.REGISTERED;
}
else
{
fireRegistrationStateChanged(
getRegistrationState(),
RegistrationState.CONNECTION_FAILED,
RegistrationStateChangeEvent.REASON_SERVER_NOT_FOUND,
null);
currentRegistrationState = RegistrationState.UNREGISTERED;
}
}
/**
* Checks if the connection to the dict server is open
* @return TRUE if the connection is open - FALSE otherwise
*/
private boolean connect()
{
if (this.dictConnection.isConnected())
{
return true;
}
try
{
return this.dictConnection.isAvailable();
}
catch (DictException dx)
{
logger.info(dx);
}
return false;
}
/**
@ -302,7 +297,8 @@ public void shutdown()
}
logger.trace("Killing the Dict Protocol Provider for account "
+ this.accountID.getUserID());
this.closeDictAdapter();
closeConnection();
if(isRegistered())
{
@ -335,13 +331,41 @@ public void shutdown()
public void unregister()
throws OperationFailedException
{
RegistrationState oldState = currentRegistrationState;
currentRegistrationState = RegistrationState.UNREGISTERED;
closeConnection();
fireRegistrationStateChanged(
oldState
, currentRegistrationState
, RegistrationStateChangeEvent.REASON_USER_REQUEST
, null);
getRegistrationState(),
RegistrationState.UNREGISTERED,
RegistrationStateChangeEvent.REASON_USER_REQUEST,
null);
}
/**
* Close the connection to the server
*/
private void closeConnection()
{
try
{
this.dictConnection.close();
}
catch (DictException dx)
{
logger.info(dx);
}
}
/**
* Returns the current version of SIP-Communicator
* @return the current version of SIP-Communicator
*/
private String getSCVersion()
{
BundleContext bc = DictActivator.getBundleContext();
ServiceReference vsr = bc.getServiceReference(VersionService.class.getName());
VersionService vs = (VersionService) bc.getService(vsr);
return vs.getCurrentVersion().toString();
}
}

@ -2,7 +2,7 @@ Bundle-Activator: net.java.sip.communicator.impl.protocol.dict.DictActivator
Bundle-Name: Dict Protocol Provider
Bundle-Description: A bundle providing support for the Dict protocol.
Bundle-Vendor: sip-communicator.org
Bundle-Version: 0.0.1
Bundle-Version: 1.0.0
Import-Package: org.osgi.framework,
net.java.sip.communicator.service.contactlist,
net.java.sip.communicator.service.configuration,
@ -12,3 +12,4 @@ Import-Package: org.osgi.framework,
net.java.sip.communicator.service.protocol,
net.java.sip.communicator.service.protocol.event,
net.java.sip.communicator.service.version
Export-Package: net.java.dict4j

@ -21,7 +21,8 @@
* @author ROTH Damien
* @author LITZELMANN Cedric
*/
public class DictAccRegWizzActivator implements BundleActivator
public class DictAccRegWizzActivator
implements BundleActivator
{
public static BundleContext bundleContext;

@ -6,6 +6,8 @@
*/
package net.java.sip.communicator.plugin.dictaccregwizz;
import net.java.dict4j.*;
/**
* The <tt>DictAccountRegistration</tt> is used to store all user input data
* through the <tt>DictAccountRegistrationWizard</tt>.
@ -16,7 +18,6 @@
public class DictAccountRegistration
{
private String userID;
private String password;
/**
* The hostname of the DICT server.
@ -29,15 +30,10 @@ public class DictAccountRegistration
private int port;
/**
* The code id of the strategie selected for the matching of words in dictionnaries.
* The strategy selected for the matching of words in dictionaries.
*/
private String strategyCode;
private Strategy strategy;
/**
* The real name of the strategie selected for the matching of words in dictionnaries.
*/
private String strategy;
/**
* Returns the User ID of the dict registration account.
* @return the User ID of the dict registration account.
@ -47,16 +43,6 @@ public String getUserID()
return userID;
}
/**
* Sets the password of the dict registration account.
*
* @param password the password of the dict registration account.
*/
public void setPassword(String password)
{
this.password = password;
}
/**
* Returns the port of the dict registration account.
* @return the port of the dict registration account.
@ -93,7 +79,7 @@ public void setHost(String host) {
* Returns the strategy that will be used for this dict account.
* @return the strategy that will be used for this dict account.
*/
public String getStrategy() {
public Strategy getStrategy() {
return this.strategy;
}
@ -101,23 +87,7 @@ public String getStrategy() {
* Sets the strategy for this dict account.
* @param strategy the strategy for this dict account.
*/
public void setStrategy(String strategy) {
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
/**
* Returns the strategy code that will be used for this dict account.
* @return the strategy code that will be used for this dict account.
*/
public String getStrategyCode() {
return this.strategyCode;
}
/**
* Sets the strategy code for this dict account.
* @param strategyCode the strategy code for this dict account.
*/
public void setStrategyCode(String strategyCode) {
this.strategyCode = strategyCode;
}
}

@ -86,7 +86,7 @@ public byte[] getPageImage()
*/
public String getProtocolName()
{
return Resources.getString("protocolNameDict");
return Resources.getString("dict.protocolName");
}
/**
@ -96,7 +96,7 @@ public String getProtocolName()
*/
public String getProtocolDescription()
{
return Resources.getString("protocolDescriptionDict");
return Resources.getString("dict.protocolDescription");
}
/**
@ -122,7 +122,7 @@ public Iterator getSummary()
summaryTable.put("Host", registration.getHost());
summaryTable.put("Port", String.valueOf(registration.getPort()));
summaryTable.put("Strategy", registration.getStrategy());
summaryTable.put("Strategy", registration.getStrategy().getName());
return summaryTable.entrySet().iterator();
}
@ -140,7 +140,7 @@ public ProtocolProviderService finish()
return this.installAccount(factory, registration.getHost(),
registration.getPort(),
registration.getStrategyCode());
registration.getStrategy().getCode());
}
/**
@ -165,11 +165,9 @@ public ProtocolProviderService signin(String userName, String password)
ProtocolProviderFactory factory
= DictAccRegWizzActivator.getDictProtocolProviderFactory();
/*return this.installAccount(factory,
userName);*/
return this.installAccount(factory, registration.getHost(),
registration.getPort(),
registration.getStrategyCode());
registration.getStrategy().getCode());
}
/**

@ -1,183 +0,0 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package net.java.sip.communicator.plugin.dictaccregwizz;
import java.io.*;
import java.net.*;
import java.util.*;
import net.java.sip.communicator.util.Logger;
/**
* Copy of DictAdapter class to solve the import problem
* @author ROTH Damien
* @author LITZELMANN Cedric
*/
public class DictAdapter
{
private static Logger logger = Logger.getLogger(DictAdapter.class);
/**
* The socket used to connect to the DICT server.
*/
private Socket socket = null;
/**
* A output stream piped to the socket in order to send command to the server.
*/
private PrintWriter out = null;
/**
* A input stream piped to the socket in order to receive messages from the server.
*/
private BufferedReader in = null;
/**
* A boolean telling if we are currently connected to the DICT server.
*/
private boolean connected = false;
/**
* Get the strategies allowed by the server for the MATCH command
* @return a HashMap containing the database list - otherwise null
*/
public ArrayList<String> getStrategies()
{
String fromServer;
boolean quit = false;
ArrayList<String> result = null;
// Connexion
if (!this.connected)
{
// Not connected
return null;
}
try
{
this.out.println("SHOW STRAT");
fromServer = this.in.readLine();
if (fromServer.startsWith("111"))
{ // OK - getting responses from the server
result = new ArrayList<String>();
while (quit == false && (fromServer = this.in.readLine()) != null)
{
if (fromServer.startsWith("250"))
{
quit = true;
}
else if (!fromServer.equals("."))
{
result.add(fromServer);
}
}
}
}
catch (IOException ioe)
{
logger.trace("Cannot get the strategies : " + ioe.getMessage());
result = null;
}
return result;
}
/**
* Open a connection to the given host on the given port
* @param host The hostname of the server.
* @param port The port used by the server.
* @return true, if a connection is open - false otherwise
*/
public boolean connect(String host, int port)
{
this.connected = false;
String fromServer;
try
{
this.socket = new Socket(host, port);
this.out = new PrintWriter(new OutputStreamWriter(this.socket.getOutputStream(),
"UTF-8"), true);
this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream(),
"UTF-8"));
fromServer = this.in.readLine(); // Server banner
if (fromServer.startsWith("220"))
{ // 220 = connect ok
this.connected = true;
}
}
catch(Exception ex)
{ // If an exception is throw == connexion impossible
logger.trace("Cannot establish a connexion to the server ("
+ host + ":" + port + ")", ex);
}
return this.connected;
}
/**
* Close the connexion to the server
*/
public void close()
{
String fromServer;
try
{
this.out.println("QUIT");
// Clean the socket buffer
while ((fromServer = this.in.readLine()) != null)
{
if (fromServer.startsWith("221"))
{ // Quit response
break;
}
}
this.out.close();
this.in.close();
this.socket.close();
}
catch (IOException ioe)
{
logger.info("Cannot close the connextion to the server", ioe);
}
}
/**
* Checks if the given url is correct and exists
* @param host The url that we have to test if it is correct and if it
* exists.
* @return true if the url exists - false otherwise
*/
public static boolean isUrl(String host)
{
boolean ok = false;
if (host == null || host.length() == 0)
{
return false;
}
// If an exception is throw, the host format isn't correct or isn't recheable
try
{
InetAddress.getByName(host);
ok = true;
}
catch (UnknownHostException uhex)
{
logger.trace("Test URL ("+host+") : " + uhex.getMessage(), uhex);
}
return ok;
}
}

@ -8,13 +8,14 @@
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.*;
import net.java.dict4j.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.*;
/**
* The <tt>FirstWizardPage</tt> is the page, where user could enter the host,
@ -27,8 +28,6 @@ public class FirstWizardPage
extends JPanel
implements WizardPage, DocumentListener, ActionListener
{
private static Logger logger = Logger.getLogger(FirstWizardPage.class);
public static final String FIRST_PAGE_IDENTIFIER = "FirstPageIdentifier";
private JPanel hostPortPanel = new JPanel(new BorderLayout(10, 10));
@ -37,13 +36,13 @@ public class FirstWizardPage
private JPanel valuesPanel = new JPanel();
private JLabel hostLabel = new JLabel("Host");
private JLabel hostLabel = new JLabel(Resources.getString("dict.host"));
private JPanel emptyPanel = new JPanel();
private JLabel hostExampleLabel = new JLabel("Ex: dict.org");
private JLabel portLabel = new JLabel("Port");
private JLabel portLabel = new JLabel(Resources.getString("dict.port"));
private JLabel existingAccountLabel =
new JLabel(Resources.getString("existingAccount"));
@ -57,18 +56,15 @@ public class FirstWizardPage
private JPanel strategyTitleBloc = new JPanel(new BorderLayout());
private JLabel strategyTitle = new JLabel(Resources.getString("strategyList"));
private JLabel strategyTitle = new JLabel(Resources.getString("dict.strategyList"));
private JButton strategyLoader = new JButton(Resources.getString("strategyActu"));
private JButton strategyLoader = new JButton(Resources.getString("dict.strategyActu"));
private Vector<String> strategyList;
private JScrollPane jScrollPane;
private JList strategyBox;
private JTextArea strategyDescription = new JTextArea(Resources.getString("strategyDesc"));
private JLabel strategyMessage;
private boolean strategyMessInstall = false;
private StrategiesList strategiesList;
private JTextArea strategyDescription = new JTextArea(Resources.getString("dict.strategyDesc"));
private ProgressPanel searchProgressPanel;
private JPanel mainPanel = new JPanel();
private JPanel mainPanel = new JPanel(new BorderLayout());
private Object nextPageIdentifier = WizardPage.SUMMARY_PAGE_IDENTIFIER;
@ -76,9 +72,7 @@ public class FirstWizardPage
private String initstrategy = "";
private ArrayList<String> strategiesAssoc = new ArrayList<String>();
private StrategyThread populateThread = null;
private ThreadManager searchThread = null;
private boolean firstAccount = false;
@ -105,7 +99,8 @@ public FirstWizardPage(DictAccountRegistrationWizard wizard)
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
this.populateThread = new StrategyThread(this);
this.searchThread = new ThreadManager(this);
this.searchProgressPanel = new ProgressPanel(this.searchThread);
this.firstAccount = !this.hasAccount();
@ -117,9 +112,6 @@ public FirstWizardPage(DictAccountRegistrationWizard wizard)
{
this.init();
}
this.populateThread = new StrategyThread(this);
this.populateThread.start();
this.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
}
@ -156,7 +148,8 @@ private void init()
hostPortPanel.add(labelsPanel, BorderLayout.WEST);
hostPortPanel.add(valuesPanel, BorderLayout.CENTER);
hostPortPanel.setBorder(BorderFactory.createTitledBorder("Server informations"));
hostPortPanel.setBorder(BorderFactory.createTitledBorder(
Resources.getString("dict.serverInformations")));
this.labelsPanel.setLayout(new BoxLayout(labelsPanel, BoxLayout.Y_AXIS));
this.valuesPanel.setLayout(new BoxLayout(valuesPanel, BoxLayout.Y_AXIS));
@ -178,22 +171,12 @@ public void keyTyped(KeyEvent evt)
public void keyReleased(KeyEvent evt) {;}
});
// Strategies
this.strategyList = new Vector<String>();
this.strategyBox = new JList(this.strategyList);
for (int i=0; i<20; i++)
{
this.strategyList.add("Elem "+i);
}
this.strategyBox.setVisibleRowCount(6);
this.strategyBox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
this.jScrollPane = new JScrollPane();
this.jScrollPane.getViewport().add(this.strategyBox);
this.strategyPanel.add(this.jScrollPane);
// Strategies list
this.strategiesList = new StrategiesList();
JScrollPane scrollPane = new JScrollPane();
scrollPane.getViewport().add(this.strategiesList);
this.strategyPanel.add(scrollPane);
// Strategy title + button
this.strategyTitleBloc.add(this.strategyTitle, BorderLayout.WEST);
@ -215,47 +198,49 @@ public void keyTyped(KeyEvent evt)
sSouthPanel.add(this.strategyDescription);
// Message
this.strategyMessage = new JLabel(" ");
sSouthPanel.add(this.strategyMessage, BorderLayout.SOUTH);
sSouthPanel.add(this.searchProgressPanel, BorderLayout.SOUTH);
this.strategyPanel.add(sSouthPanel, BorderLayout.SOUTH);
this.strategyPanel.add(this.strategyTitleBloc, BorderLayout.NORTH);
this.strategyPanel.setBorder(BorderFactory.createTitledBorder("Strategy selection"));
this.strategyPanel.setBorder(BorderFactory.createTitledBorder(
Resources.getString("dict.strategySelection")));
mainPanel.add(this.strategyPanel);
this.add(mainPanel, BorderLayout.NORTH);
}
/**
* Initialize the UI for the first account
*/
private void initFirstAccount()
{
// Data init
this.hostField = new JTextField("dict.org");
this.portField = new JTextField("2628");
// Init strategy box
this.strategyList = new Vector<String>();
this.strategyBox = new JList(this.strategyList);
this.strategyMessage = new JLabel(" ");
// Init strategies list
this.strategiesList = new StrategiesList();
this.mainPanel = new JPanel(new BorderLayout());
JPanel infoTitlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JTextArea firstDescription = new JTextArea(Resources.getString("firstAccount"));
JLabel title = new JLabel(Resources.getString("dictAccountInfoTitle"));
JTextArea firstDescription = new JTextArea(Resources.getString("dict.firstAccount"));
JLabel title = new JLabel(Resources.getString("dict.accountInfoTitle"));
// Title
title.setFont(title.getFont().deriveFont(Font.BOLD, 14.0f));
infoTitlePanel.add(title);
this.add(infoTitlePanel, BorderLayout.NORTH);
this.add(this.strategyMessage, BorderLayout.SOUTH);
this.mainPanel.add(infoTitlePanel, BorderLayout.NORTH);
this.mainPanel.add(this.searchProgressPanel, BorderLayout.SOUTH);
// Description
firstDescription.setLineWrap(true);
firstDescription.setLineWrap(true);
firstDescription.setRows(6);
firstDescription.setWrapStyleWord(true);
firstDescription.setAutoscrolls(false);
this.add(firstDescription);
this.mainPanel.add(firstDescription);
}
/**
@ -315,10 +300,8 @@ public void pageShowing()
*/
public void commitPage()
{
//*
String host = hostField.getText();
int port = Integer.parseInt(portField.getText());
int stPos;
boolean isModified = false;
if (this.initAccountID instanceof AccountID)
@ -335,14 +318,18 @@ public void commitPage()
}
// We check if a strategy has been selected
if (this.strategyList.size() == 0)
if (this.strategiesList.getModel().getSize() == 0)
{ // No Strategy, we get them
this.populateStrategies();
while (this.populateThread.isRunning()) {;}
if (!this.searchThread.waitThread())
{
// TODO error dialog : thread interrupted ? no thread ?
this.strategiesList.clear();
}
}
if (this.strategyList.size() == 0)
if (this.strategiesList.getModel().getSize() == 0)
{
// No strategy, maybe not connected
// Information message is already on the wizard
@ -365,12 +352,8 @@ else if ((!wizard.isModification() && isExistingAccount(host, port))
registration.setHost(host);
registration.setPort(port);
stPos = this.strategyBox.getSelectedIndex();
registration.setStrategyCode(this.strategiesAssoc.get(stPos));
registration.setStrategy(this.strategyBox.getSelectedValue().toString());
registration.setStrategy((Strategy) this.strategiesList.getSelectedValue());
}
//*/
isPageCommitted = true;
}
@ -380,7 +363,7 @@ else if ((!wizard.isModification() && isExistingAccount(host, port))
*/
private void setNextButtonEnabled()
{
boolean hostOK = DictAdapter.isUrl(hostField.getText());
boolean hostOK = DictConnection.isUrl(hostField.getText());
boolean portOK = (this.portField.getText().length() != 0)
&& Integer.parseInt(this.portField.getText()) > 10;
@ -399,7 +382,7 @@ else if (hostOK && portOK)
wizard.getWizardContainer().setNextFinishButtonEnabled(false);
// Clear the list and disable the button
this.strategyList.clear();
this.strategiesList.clear();
this.strategyLoader.setEnabled(false);
}
}
@ -536,7 +519,6 @@ private boolean hasAccount()
*/
private boolean isExistingAccount(String host, int port)
{
//*
ProtocolProviderFactory factory =
DictAccRegWizzActivator.getDictProtocolProviderFactory();
@ -563,99 +545,74 @@ private boolean isExistingAccount(String host, int port)
}
}
}
//*/
return false;
}
/**
* Start the thread which will populate the Strategy List
* Start the thread which will populate the Strategies List
*/
public void populateStrategies()
{
// Clear ArrayLists
this.strategiesAssoc.clear();
this.strategyList.clear();
//this.populateThread = new StrategyThread(this);
this.populateThread.setHost(this.hostField.getText())
.setPort(Integer.parseInt(this.portField.getText()))
.sendProcessRequest();
// Clear ArrayList
this.strategiesList.clear();
boolean ok = this.searchThread.submitRequest(this.hostField.getText(),
Integer.parseInt(this.portField.getText()));
if (!ok)
{
// TODO Display error
}
}
/**
* Called by the thread, display a message
* @param message a message
* Automatic selection of a strategy
*/
public void threadMessage(String message)
public void autoSelectStrategy()
{
this.strategyMessage.setText(message);
this.strategiesList.autoSelectStrategy(this.initstrategy);
}
/**
*
* @param strategies
*/
public void setStrategies(List<Strategy> strategies)
{
this.strategiesList.setStrategies(strategies);
}
/**
* Called by the thread, remove the special message section
* Informs the user of the current status of the search
* Should only be called by the thread
* @param message Search status
*/
public void threadRemoveMessage()
public void progressMessage(String message)
{
this.strategyMessage.setText(" ");
this.searchProgressPanel.nextStep(message);
}
/**
* Called by the thread, add a strategy in the list
* @param code The strategy code
* @param description The strategy description
* Informs the wizard that the search of the strategies is complete.
* Should only be called by the thread
*/
public void threadAddStrategy(String code, String description)
public void strategiesSearchComplete()
{
this.strategiesAssoc.add(code);
this.strategyList.add(description);
this.strategyBox.setListData(this.strategyList);
setStrategyButtonEnable(true);
this.searchProgressPanel.finish();
}
/**
* Automatic selection of a strategy
* Informs the wizard that the search of the strategies is a failure
* Should only be called by the thread
* @param reason Reason message
* @param de Exception thrown
*/
public void autoSelectStrategy()
public void strategiesSearchFailure(String reason, DictException de)
{
int index = -1;
if (this.initstrategy.length() > 0)
{ // saved strategy
index = this.strategiesAssoc.indexOf(this.initstrategy);
this.initstrategy = "";
}
if (index < 0)
{
// First case : levenstein distance
index = this.strategiesAssoc.indexOf("lev");
}
if (index < 0)
{
// Second case : soundex
index = this.strategiesAssoc.indexOf("soundex");
}
if (index < 0)
{
// Last case : prefix
index = this.strategiesAssoc.indexOf("prefix");
}
// If the index is still < 0, we select the first index
if (index < 0)
{
index = 0;
}
if (index < this.strategyBox.getVisibleRowCount())
{
// If the index is visible row, we don't need to scroll
this.strategyBox.setSelectedIndex(index);
}
else
{
// Otherwise, we scroll to the selected value
this.strategyBox.setSelectedValue(this.strategyList.get(index), true);
}
strategiesSearchComplete();
// TODO SHOW ERROR MESSAGE
}
/**
@ -678,6 +635,16 @@ public Object getSimpleForm()
return mainPanel;
}
/**
* Indicates if this is the first dict account
*
* @return TRUE if this is the first dict account - FALSE otherwise
*/
public boolean isFirstAccount()
{
return this.firstAccount;
}
public boolean isCommitted()
{
return isPageCommitted;

@ -0,0 +1,137 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package net.java.sip.communicator.plugin.dictaccregwizz;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* Panel showing the current status of the search of the strategies
*
* @author ROTH Damien
*/
public class ProgressPanel
extends JPanel
implements ActionListener
{
private JPanel rightPanel;
private JLabel messageLabel;
private JLabel progressLabel;
private JButton cancelButton;
private int currentStep;
private int totalSteps;
private boolean isBuild;
private ThreadManager searchThread;
/**
* Create an instance of <tt>ProgressPanel</tt>
* @param searchThread The thread manager
*/
public ProgressPanel(ThreadManager searchThread)
{
super(new BorderLayout());
// Element creation
this.messageLabel = new JLabel(" ");
this.progressLabel = new JLabel(" ");
this.cancelButton = new JButton(Resources.getString("cancel"));
this.cancelButton.addActionListener(this);
// Right panel init
this.rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
this.rightPanel.add(this.progressLabel);
this.rightPanel.add(this.cancelButton);
this.searchThread = searchThread;
init();
this.totalSteps = ThreadManager.NB_STEPS;
}
/**
* Init the values
*/
private void init()
{
this.isBuild = false;
this.currentStep = 1;
this.add(this.messageLabel, BorderLayout.CENTER);
}
/**
* Build the UI
*/
private void build()
{
if (this.isBuild)
{
return;
}
this.add(this.messageLabel, BorderLayout.CENTER);
this.add(this.rightPanel, BorderLayout.EAST);
this.isBuild = true;
}
/**
* Move to the next step without updating the message
*/
public void nextStep()
{
nextStep(this.messageLabel.getText());
}
/**
* Mode to the next step with a new message
* @param message Message
*/
public void nextStep(String message)
{
if (this.currentStep > this.totalSteps)
{
finish();
}
build();
this.messageLabel.setText(message);
this.progressLabel.setText(currentStep + "/" + totalSteps);
this.currentStep++;
}
/**
* Informs the end of the progress. Remove all the components and
* reset the values
*/
public void finish()
{
// Remove all elements
this.removeAll();
// Re-init the panel
this.messageLabel.setText(" ");
this.progressLabel.setText(" ");
init();
this.repaint();
this.validate();
}
@Override
public void actionPerformed(ActionEvent arg0)
{
this.searchThread.cancel();
this.finish();
}
}

@ -0,0 +1,213 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.plugin.dictaccregwizz;
import java.awt.Component;
import java.util.*;
import javax.swing.*;
import net.java.dict4j.*;
/**
* Class managing the list of strategies
*
* @author ROTH Damien
*/
public class StrategiesList
extends JList
{
private ListModel model;
private CellRenderer renderer;
/**
* Create an instance of the <tt>StrategiesList</tt>
*/
public StrategiesList()
{
super();
this.model = new ListModel();
this.renderer = new CellRenderer();
this.setCellRenderer(this.renderer);
this.setModel(model);
this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
this.setVisibleRowCount(6);
}
/**
* Stores a new set of strategies
* @param strategies List of strategies
*/
public void setStrategies(List<Strategy> strategies)
{
this.model.setStrategies(strategies);
}
/**
* Remove all the strategies of the list
*/
public void clear()
{
this.model.clear();
}
/**
* Automatic selection of strategies
* @param initStrategy
*/
public void autoSelectStrategy(String initStrategy)
{
int index = -1;
if (initStrategy.length() > 0)
{ // saved strategy
index = this.model.indexOf(initStrategy);
}
if (index < 0)
{
// First case : levenstein distance
index = this.model.indexOf("lev");
}
if (index < 0)
{
// Second case : soundex
index = this.model.indexOf("soundex");
}
if (index < 0)
{
// Last case : prefix
index = this.model.indexOf("prefix");
}
// If the index is still < 0, we select the first index
if (index < 0)
{
index = 0;
}
if (index < this.getVisibleRowCount())
{
// If the index is visible row, we don't need to scroll
this.setSelectedIndex(index);
}
else
{
// Otherwise, we scroll to the selected value
this.setSelectedValue(this.model.getElementAt(index), true);
}
}
/**
* Class managing the list datas
*
* @author ROTH Damien
*/
class ListModel
extends AbstractListModel
{
List<Strategy> data;
/**
* Create an instance of <tt>ListModel</tt>
*/
public ListModel()
{
this.data = new ArrayList<Strategy>();
}
/**
* Stores the strategies into this model
* @param data the strategies list
*/
public void setStrategies(List<Strategy> strategies)
{
this.data = strategies;
fireContentsChanged(this, 0, this.data.size());
}
/**
* Remove all the strategies of the list
*/
public void clear()
{
this.data.clear();
}
/**
* Implements <tt>ListModel.getElementAt</tt>
*/
@Override
public Object getElementAt(int row)
{
return this.data.get(row);
}
/**
* Implements <tt>ListModel.getSize</tt>
*/
@Override
public int getSize()
{
return this.data.size();
}
/**
* Find the index of a strategie
* @param strategyCode the code of the strategy
* @return the index of the strategy
*/
public int indexOf(String strategyCode)
{
for (int i=0; i<this.data.size(); i++)
{
if (this.data.get(i).getCode().equals(strategyCode))
{
return i;
}
}
return -1;
}
}
/**
* Class managing the cell rendering
*
* @author ROTH Damien
*/
class CellRenderer
extends JLabel
implements ListCellRenderer
{
@Override
/**
* implements <tt>ListCellRenderer.getListCellRendererComponent</tt>
*/
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus)
{
Strategy strategy = (Strategy) value;
this.setText(strategy.getName());
if (isSelected)
{
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else
{
setBackground(list.getBackground());
setForeground(list.getForeground());
}
setEnabled(list.isEnabled());
setFont(list.getFont());
setOpaque(true);
return this;
}
}
}

@ -1,207 +0,0 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package net.java.sip.communicator.plugin.dictaccregwizz;
import java.util.*;
import net.java.sip.communicator.util.*;
/**
* The <tt>StrategyThread</tt> is the thread called by the wizzard to populate
* the strategies list.
*
* @author ROTH Damien
* @author LITZELMANN Cedric
*/
public class StrategyThread
extends Thread
{
private static Logger logger = Logger.getLogger(StrategyThread.class);
/**
* The hostname of the DICT server.
*/
private String host;
/**
* The port used by the DICT server.
*/
private int port;
/**
* True if the thread is running.
*/
private boolean isRunning = false;
/**
* True if we need to search the strategies handled by the server in order
* to populate the list.
*/
private boolean needProcess = false;
/**
* The first page wizard for the DICT protocole.
*/
private FirstWizardPage wizard;
/**
* The java abstraction of the DICT server.
*/
private DictAdapter adapter = null;
/**
* Create a new StrategyThread
* @param wizard the wizard for callback methods
*/
public StrategyThread(FirstWizardPage wizard)
{
this.wizard = wizard;
}
/**
* Thread method running until it's destroy
*/
public void run()
{
while (true)
{
if (this.needProcess())
{
this.setRunning(true);
this.process();
this.processDone();
this.setRunning(false);
}
try
{
this.sleep(500);
}
catch (InterruptedException ie)
{
// Action de log
logger.info("DICT THREAD : " + ie);
}
}
}
/**
* Search the strategies on the server and populate the list
*/
private void process()
{
ArrayList<String> strategies = null;
String temp[];
if (adapter == null) {
adapter = new DictAdapter();
}
this.wizard.setStrategyButtonEnable(false);
// Initialize the connexion
this.wizard.threadMessage("Trying to connect to server");
if (!adapter.connect(this.host, this.port))
{
// Connexion attempt failed
this.wizard.threadMessage("Connexion attempt failed, this isn't a"
+ "dict server or the server is offline");
return;
}
// Retrieving strategies
this.wizard.threadMessage("Retrieving strategies");
strategies = adapter.getStrategies();
if (strategies == null)
{
// No strategy found
this.wizard.threadMessage("No strategy found on the server");
return;
}
// Insert the strategies in the list
for (int i=0; i<strategies.size(); i++)
{
temp = strategies.get(i).split(" ", 2);
this.wizard.threadAddStrategy(temp[0], temp[1].replace("\"", ""));
}
this.wizard.autoSelectStrategy();
// Closing connexion
this.wizard.threadMessage("Closing connexion");
adapter.close();
this.wizard.threadRemoveMessage();
this.wizard.setStrategyButtonEnable(true);
}
/**
* Set the hostname of the dict server
* @param host The hostname of the server.
* @return The thread for populating strategie list.
*/
public StrategyThread setHost(String host)
{
this.host = host;
return this;
}
/**
* Set the port of the dict server
* @param port The port of the DICT server.
* @return The thread for populating strategie list.
*/
public StrategyThread setPort(int port)
{
this.port = port;
return this;
}
/**
* Checks if the thread is processing a query
* @return TRUE if the thread is processing a query - FALSE otherwise
*/
public synchronized boolean isRunning()
{
return this.isRunning || this.needProcess;
}
/**
* Marks the thread as running or not
* @param r Activate or desactivate the strategie thread.
*/
public synchronized void setRunning(boolean r)
{
this.isRunning = r;
}
/**
* Checks if we need to process a query
* @return Returns true if we need to search and populate the strategie list. False otherwise.
*/
private synchronized boolean needProcess()
{
return this.needProcess;
}
/**
* Init the request
*/
public synchronized void sendProcessRequest()
{
this.needProcess = true;
}
/**
* Defines that the thread has done the query
*/
private synchronized void processDone()
{
this.needProcess = false;
}
}

@ -0,0 +1,182 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.plugin.dictaccregwizz;
import java.util.*;
import net.java.sip.communicator.util.*;
import net.java.dict4j.*;
/**
* Class manager the thread called for searching the strategies' list
*
* @author ROTH Damien
*/
public class ThreadManager
{
protected static Logger logger = Logger.getLogger(ThreadManager.class);
public static int NB_STEPS = 4;
private StrategyThread thread = null;
private FirstWizardPage wizard = null;
/**
* Create an instance of <tt>ThreadManager</tt>
* @param wiz Wizard
*/
public ThreadManager(FirstWizardPage wiz)
{
this.wizard = wiz;
}
/**
* Submit a request to launch the thread
* @param host Server host
* @param port Server port
* @return TRUE if the thread is started - FALSE otherwise
*/
public boolean submitRequest(String host, int port)
{
if (this.thread != null)
{
return false;
}
this.thread = new StrategyThread(this.wizard, host, port);
this.thread.start();
return true;
}
/**
* Stop the thread
*/
public void cancel()
{
if (this.thread != null)
{
this.thread.interrupt();
this.thread = null;
}
}
/**
* Wait for the searching thread to stop
* @return
*/
public boolean waitThread()
{
if (this.thread == null)
{
return false;
}
try
{
this.thread.join();
}
catch (InterruptedException e)
{
logger.info(e);
return false;
}
return true;
}
/**
* Thread used to search the strategies
*
* @author ROTH Damien
* @author LITZELMANN Cédric
*/
class StrategyThread
extends Thread
{
private FirstWizardPage wizard;
private String host;
private int port;
/**
* Informations messages
*/
private String[] messages = new String[] {
Resources.getString("dict.threadConnect"),
Resources.getString("dict.threadConnectFailed"),
Resources.getString("dict.retrievingStrategies"),
Resources.getString("dict.noStrategiesFound"),
Resources.getString("dict.populateList"),
Resources.getString("dict.closingConnexion")
};
/**
* Create an instance of the thread
* @param wizard The wizard who started the thread
* @param host Server host
* @param port Server port
*/
public StrategyThread(FirstWizardPage wizard, String host, int port)
{
this.wizard = wizard;
this.host = host;
this.port = port;
}
public void run()
{
List<Strategy> strategies = null;
DictConnection dictConnection = new DictConnection(host, port);
// Open the connection to the server
this.wizard.progressMessage(messages[0]);
try
{
dictConnection.connect();
}
catch (DictException e)
{
this.wizard.strategiesSearchFailure(this.messages[1], e);
return;
}
// Get the strategies
this.wizard.progressMessage(messages[2]);
try
{
strategies = dictConnection.getStrategies();
}
catch (DictException e)
{
this.wizard.strategiesSearchFailure(this.messages[3], e);
return;
}
// Store the strategies
this.wizard.progressMessage(messages[4]);
this.wizard.setStrategies(strategies);
this.wizard.autoSelectStrategy();
// Close the connection
this.wizard.progressMessage(messages[5]);
try
{
dictConnection.close();
}
catch (DictException e)
{
// An error while closing the connection isn't very important
// We just log it
ThreadManager.logger.info("DICT search strategies thread : " +
"Error while closing connection", e);
}
// End of the search
this.wizard.strategiesSearchComplete();
}
}
}

@ -4,6 +4,7 @@ Bundle-Description: Dict account registration wizard.
Bundle-Vendor: sip-communicator.org
Bundle-Version: 0.0.1
Import-Package: org.osgi.framework,
net.java.dict4j,
net.java.sip.communicator.util,
net.java.sip.communicator.service.resources,
net.java.sip.communicator.service.configuration,

Loading…
Cancel
Save