diff --git a/build.xml b/build.xml index 798927185..afd43f372 100644 --- a/build.xml +++ b/build.xml @@ -1740,6 +1740,7 @@ javax.swing.event, javax.swing.border"/> manifest="${src}/net/java/sip/communicator/impl/protocol/dict/dict.provider.manifest.mf"> + diff --git a/lib/installer-exclude/dict4j.jar b/lib/installer-exclude/dict4j.jar new file mode 100755 index 000000000..4b65d35f7 Binary files /dev/null and b/lib/installer-exclude/dict4j.jar differ diff --git a/resources/images/images.properties b/resources/images/images.properties index 6f4c4d592..b1c15842a 100644 --- a/resources/images/images.properties +++ b/resources/images/images.properties @@ -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 diff --git a/resources/images/protocol/dict/dict-16x16-offline.png b/resources/images/protocol/dict/dict-16x16-offline.png new file mode 100755 index 000000000..f450b0481 Binary files /dev/null and b/resources/images/protocol/dict/dict-16x16-offline.png differ diff --git a/resources/languages/resources.properties b/resources/languages/resources.properties index f3a6f25d2..1be7cc13a 100644 --- a/resources/languages/resources.properties +++ b/resources/languages/resources.properties @@ -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 diff --git a/resources/languages/resources_fr.properties b/resources/languages/resources_fr.properties index 0939a37b9..aca074355 100644 --- a/resources/languages/resources_fr.properties +++ b/resources/languages/resources_fr.properties @@ -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 + diff --git a/src/net/java/sip/communicator/impl/protocol/dict/ContactDictImpl.java b/src/net/java/sip/communicator/impl/protocol/dict/ContactDictImpl.java index ffd19b1df..aceb18c29 100644 --- a/src/net/java/sip/communicator/impl/protocol/dict/ContactDictImpl.java +++ b/src/net/java/sip/communicator/impl/protocol/dict/ContactDictImpl.java @@ -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. diff --git a/src/net/java/sip/communicator/impl/protocol/dict/DictAccountID.java b/src/net/java/sip/communicator/impl/protocol/dict/DictAccountID.java index 861ee8691..39f44fc9d 100644 --- a/src/net/java/sip/communicator/impl/protocol/dict/DictAccountID.java +++ b/src/net/java/sip/communicator/impl/protocol/dict/DictAccountID.java @@ -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); + } } diff --git a/src/net/java/sip/communicator/impl/protocol/dict/DictActivator.java b/src/net/java/sip/communicator/impl/protocol/dict/DictActivator.java index d0bc20dce..e5e6646a1 100644 --- a/src/net/java/sip/communicator/impl/protocol/dict/DictActivator.java +++ b/src/net/java/sip/communicator/impl/protocol/dict/DictActivator.java @@ -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]."); diff --git a/src/net/java/sip/communicator/impl/protocol/dict/DictAdapter.java b/src/net/java/sip/communicator/impl/protocol/dict/DictAdapter.java deleted file mode 100644 index b458e4252..000000000 --- a/src/net/java/sip/communicator/impl/protocol/dict/DictAdapter.java +++ /dev/null @@ -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 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 getDatabases() throws Exception - { - if (this.databasesList == null) - { - DictResultset drs = this.showDB(); - DictResult list = drs.getResultset(0); - - this.databasesList = new Vector(); - - 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= 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; - } -} diff --git a/src/net/java/sip/communicator/impl/protocol/dict/DictRegistry.java b/src/net/java/sip/communicator/impl/protocol/dict/DictRegistry.java deleted file mode 100644 index 257744fe1..000000000 --- a/src/net/java/sip/communicator/impl/protocol/dict/DictRegistry.java +++ /dev/null @@ -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 adapters = new HashMap(); - - /** - * 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); - } - } -} diff --git a/src/net/java/sip/communicator/impl/protocol/dict/DictResult.java b/src/net/java/sip/communicator/impl/protocol/dict/DictResult.java deleted file mode 100644 index 101515ddf..000000000 --- a/src/net/java/sip/communicator/impl/protocol/dict/DictResult.java +++ /dev/null @@ -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 -{ - private String databaseName; - private int index; - private ArrayList data; - - /** - * Basic construct initializing the result - */ - public DictResult() - { - this.index = 0; - this.data = new ArrayList(); - 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(); - 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; - } -} diff --git a/src/net/java/sip/communicator/impl/protocol/dict/DictResultset.java b/src/net/java/sip/communicator/impl/protocol/dict/DictResultset.java deleted file mode 100644 index 14b629a21..000000000 --- a/src/net/java/sip/communicator/impl/protocol/dict/DictResultset.java +++ /dev/null @@ -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 data; - - /** - * Initialize a resultset list - */ - public DictResultset() - { - this.cursor = -1; - this.data = new ArrayList(); - } - - /** - * 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(); - } -} diff --git a/src/net/java/sip/communicator/impl/protocol/dict/DictStatusEnum.java b/src/net/java/sip/communicator/impl/protocol/dict/DictStatusEnum.java index 3f41afcc3..17ba603f6 100644 --- a/src/net/java/sip/communicator/impl/protocol/dict/DictStatusEnum.java +++ b/src/net/java/sip/communicator/impl/protocol/dict/DictStatusEnum.java @@ -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; - } } diff --git a/src/net/java/sip/communicator/impl/protocol/dict/OperationSetBasicInstantMessagingDictImpl.java b/src/net/java/sip/communicator/impl/protocol/dict/OperationSetBasicInstantMessagingDictImpl.java index fd958a903..32a092065 100644 --- a/src/net/java/sip/communicator/impl/protocol/dict/OperationSetBasicInstantMessagingDictImpl.java +++ b/src/net/java/sip/communicator/impl/protocol/dict/OperationSetBasicInstantMessagingDictImpl.java @@ -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 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 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 data, String word) { - String result; - DictResult resultData; + StringBuffer res = new StringBuffer(); + Definition def; - result = "
";
-        
-        for (int i=0; i 0)
             {
-                result += resultData.next() + "\n";
+                res.append("
"); } - result = result.replaceAll("\n+\\z", "\n"); + res.append(def.getDefinition().replaceAll("\n", "
")) + .append("
-- From ") + .append(def.getDictionary()) + .append("
"); } - result += "
"; + + String result = res.toString(); result = formatResult(result, "\\\\", "", ""); result = formatResult(result, "[\\[\\]]", "", ""); result = formatResult(result, "[\\{\\}]", "", ""); @@ -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 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; iProtocolIcon @@ -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 iconsTable = new Hashtable(); 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; - } } diff --git a/src/net/java/sip/communicator/impl/protocol/dict/ProtocolProviderFactoryDictImpl.java b/src/net/java/sip/communicator/impl/protocol/dict/ProtocolProviderFactoryDictImpl.java index 45eabaf3e..59df9161b 100644 --- a/src/net/java/sip/communicator/impl/protocol/dict/ProtocolProviderFactoryDictImpl.java +++ b/src/net/java/sip/communicator/impl/protocol/dict/ProtocolProviderFactoryDictImpl.java @@ -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 diff --git a/src/net/java/sip/communicator/impl/protocol/dict/ProtocolProviderServiceDictImpl.java b/src/net/java/sip/communicator/impl/protocol/dict/ProtocolProviderServiceDictImpl.java index edf97f4be..b803c6c75 100644 --- a/src/net/java/sip/communicator/impl/protocol/dict/ProtocolProviderServiceDictImpl.java +++ b/src/net/java/sip/communicator/impl/protocol/dict/ProtocolProviderServiceDictImpl.java @@ -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 DictConnection 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 DictConnection opened by this provider + * @return the DictConnection 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(); + } } diff --git a/src/net/java/sip/communicator/impl/protocol/dict/dict.provider.manifest.mf b/src/net/java/sip/communicator/impl/protocol/dict/dict.provider.manifest.mf index b2e050cda..a9d53a206 100644 --- a/src/net/java/sip/communicator/impl/protocol/dict/dict.provider.manifest.mf +++ b/src/net/java/sip/communicator/impl/protocol/dict/dict.provider.manifest.mf @@ -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 diff --git a/src/net/java/sip/communicator/plugin/dictaccregwizz/DictAccRegWizzActivator.java b/src/net/java/sip/communicator/plugin/dictaccregwizz/DictAccRegWizzActivator.java index a41813d04..f9584ae56 100644 --- a/src/net/java/sip/communicator/plugin/dictaccregwizz/DictAccRegWizzActivator.java +++ b/src/net/java/sip/communicator/plugin/dictaccregwizz/DictAccRegWizzActivator.java @@ -21,7 +21,8 @@ * @author ROTH Damien * @author LITZELMANN Cedric */ -public class DictAccRegWizzActivator implements BundleActivator +public class DictAccRegWizzActivator + implements BundleActivator { public static BundleContext bundleContext; diff --git a/src/net/java/sip/communicator/plugin/dictaccregwizz/DictAccountRegistration.java b/src/net/java/sip/communicator/plugin/dictaccregwizz/DictAccountRegistration.java index 4be06eb42..f031c6afa 100644 --- a/src/net/java/sip/communicator/plugin/dictaccregwizz/DictAccountRegistration.java +++ b/src/net/java/sip/communicator/plugin/dictaccregwizz/DictAccountRegistration.java @@ -6,6 +6,8 @@ */ package net.java.sip.communicator.plugin.dictaccregwizz; +import net.java.dict4j.*; + /** * The DictAccountRegistration is used to store all user input data * through the DictAccountRegistrationWizard. @@ -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; - } } diff --git a/src/net/java/sip/communicator/plugin/dictaccregwizz/DictAccountRegistrationWizard.java b/src/net/java/sip/communicator/plugin/dictaccregwizz/DictAccountRegistrationWizard.java index 1d48b4101..54053bb5f 100644 --- a/src/net/java/sip/communicator/plugin/dictaccregwizz/DictAccountRegistrationWizard.java +++ b/src/net/java/sip/communicator/plugin/dictaccregwizz/DictAccountRegistrationWizard.java @@ -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()); } /** diff --git a/src/net/java/sip/communicator/plugin/dictaccregwizz/DictAdapter.java b/src/net/java/sip/communicator/plugin/dictaccregwizz/DictAdapter.java deleted file mode 100644 index 9ffdb5038..000000000 --- a/src/net/java/sip/communicator/plugin/dictaccregwizz/DictAdapter.java +++ /dev/null @@ -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 getStrategies() - { - String fromServer; - boolean quit = false; - ArrayList 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(); - 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; - } -} diff --git a/src/net/java/sip/communicator/plugin/dictaccregwizz/FirstWizardPage.java b/src/net/java/sip/communicator/plugin/dictaccregwizz/FirstWizardPage.java index 00d052851..a3a22e4e8 100644 --- a/src/net/java/sip/communicator/plugin/dictaccregwizz/FirstWizardPage.java +++ b/src/net/java/sip/communicator/plugin/dictaccregwizz/FirstWizardPage.java @@ -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 FirstWizardPage 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 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 strategiesAssoc = new ArrayList(); - - 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(); - 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(); - 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 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; diff --git a/src/net/java/sip/communicator/plugin/dictaccregwizz/ProgressPanel.java b/src/net/java/sip/communicator/plugin/dictaccregwizz/ProgressPanel.java new file mode 100755 index 000000000..7b569624d --- /dev/null +++ b/src/net/java/sip/communicator/plugin/dictaccregwizz/ProgressPanel.java @@ -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 ProgressPanel + * @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(); + } +} diff --git a/src/net/java/sip/communicator/plugin/dictaccregwizz/StrategiesList.java b/src/net/java/sip/communicator/plugin/dictaccregwizz/StrategiesList.java new file mode 100755 index 000000000..713ff8628 --- /dev/null +++ b/src/net/java/sip/communicator/plugin/dictaccregwizz/StrategiesList.java @@ -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 StrategiesList + */ + 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 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 data; + + /** + * Create an instance of ListModel + */ + public ListModel() + { + this.data = new ArrayList(); + } + + /** + * Stores the strategies into this model + * @param data the strategies list + */ + public void setStrategies(List strategies) + { + this.data = strategies; + fireContentsChanged(this, 0, this.data.size()); + } + + /** + * Remove all the strategies of the list + */ + public void clear() + { + this.data.clear(); + } + + /** + * Implements ListModel.getElementAt + */ + @Override + public Object getElementAt(int row) + { + return this.data.get(row); + } + + /** + * Implements ListModel.getSize + */ + @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; iListCellRenderer.getListCellRendererComponent + */ + 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; + } + } +} \ No newline at end of file diff --git a/src/net/java/sip/communicator/plugin/dictaccregwizz/StrategyThread.java b/src/net/java/sip/communicator/plugin/dictaccregwizz/StrategyThread.java deleted file mode 100644 index 8dab524e6..000000000 --- a/src/net/java/sip/communicator/plugin/dictaccregwizz/StrategyThread.java +++ /dev/null @@ -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 StrategyThread 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 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; iThreadManager + * @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 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(); + } + } +} \ No newline at end of file diff --git a/src/net/java/sip/communicator/plugin/dictaccregwizz/dictaccregwizz.manifest.mf b/src/net/java/sip/communicator/plugin/dictaccregwizz/dictaccregwizz.manifest.mf index c1c4169b0..301d7f429 100644 --- a/src/net/java/sip/communicator/plugin/dictaccregwizz/dictaccregwizz.manifest.mf +++ b/src/net/java/sip/communicator/plugin/dictaccregwizz/dictaccregwizz.manifest.mf @@ -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,