KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > directory > ldapstudio > browser > core > ConnectionManager


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  *
19  */

20
21 package org.apache.directory.ldapstudio.browser.core;
22
23
24 import java.beans.ExceptionListener JavaDoc;
25 import java.beans.XMLDecoder JavaDoc;
26 import java.beans.XMLEncoder JavaDoc;
27 import java.io.BufferedInputStream JavaDoc;
28 import java.io.BufferedOutputStream JavaDoc;
29 import java.io.File JavaDoc;
30 import java.io.FileInputStream JavaDoc;
31 import java.io.FileOutputStream JavaDoc;
32 import java.io.FileReader JavaDoc;
33 import java.io.FileWriter JavaDoc;
34 import java.io.IOException JavaDoc;
35 import java.util.ArrayList JavaDoc;
36 import java.util.Iterator JavaDoc;
37 import java.util.List JavaDoc;
38
39 import org.apache.directory.ldapstudio.browser.core.events.BookmarkUpdateEvent;
40 import org.apache.directory.ldapstudio.browser.core.events.BookmarkUpdateListener;
41 import org.apache.directory.ldapstudio.browser.core.events.ConnectionRenamedEvent;
42 import org.apache.directory.ldapstudio.browser.core.events.ConnectionUpdateEvent;
43 import org.apache.directory.ldapstudio.browser.core.events.ConnectionUpdateListener;
44 import org.apache.directory.ldapstudio.browser.core.events.EventRegistry;
45 import org.apache.directory.ldapstudio.browser.core.events.SearchUpdateEvent;
46 import org.apache.directory.ldapstudio.browser.core.events.SearchUpdateListener;
47 import org.apache.directory.ldapstudio.browser.core.internal.model.Bookmark;
48 import org.apache.directory.ldapstudio.browser.core.internal.model.Connection;
49 import org.apache.directory.ldapstudio.browser.core.internal.model.Search;
50 import org.apache.directory.ldapstudio.browser.core.model.BookmarkParameter;
51 import org.apache.directory.ldapstudio.browser.core.model.ConnectionParameter;
52 import org.apache.directory.ldapstudio.browser.core.model.IBookmark;
53 import org.apache.directory.ldapstudio.browser.core.model.IConnection;
54 import org.apache.directory.ldapstudio.browser.core.model.ISearch;
55 import org.apache.directory.ldapstudio.browser.core.model.SearchParameter;
56 import org.apache.directory.ldapstudio.browser.core.model.schema.Schema;
57 import org.apache.directory.ldapstudio.browser.core.utils.LdifUtils;
58 import org.eclipse.core.runtime.IPath;
59
60
61 /**
62  * This class is used to manage {@link IConnection}s.
63  *
64  * @author <a HREF="mailto:dev@directory.apache.org">Apache Directory Project</a>
65  * @version $Rev$, $Date$
66  */

67 public class ConnectionManager implements ConnectionUpdateListener, SearchUpdateListener, BookmarkUpdateListener
68 {
69
70     /** The list of connections. */
71     private List JavaDoc<IConnection> connectionList;
72
73
74     /**
75      * Creates a new instance of ConnectionManager.
76      */

77     public ConnectionManager()
78     {
79         this.connectionList = new ArrayList JavaDoc<IConnection>();
80         loadConnections();
81         EventRegistry.addConnectionUpdateListener( this, BrowserCorePlugin.getDefault().getEventRunner() );
82         EventRegistry.addSearchUpdateListener( this, BrowserCorePlugin.getDefault().getEventRunner() );
83         EventRegistry.addBookmarkUpdateListener( this, BrowserCorePlugin.getDefault().getEventRunner() );
84     }
85
86
87     /**
88      * Gets the Schema Cache filename for the corresponding Connection name.
89      *
90      * @param connectionName
91      * the connection name
92      * @return
93      * the Schema Cache filename for the corresponding Connection name
94      */

95     public static final String JavaDoc getSchemaCacheFileName( String JavaDoc connectionName )
96     {
97         return BrowserCorePlugin.getDefault().getStateLocation().append(
98             "schema-" + toSaveString( connectionName ) + ".ldif" ).toOSString(); //$NON-NLS-1$ //$NON-NLS-2$
99
}
100
101
102     /**
103      * Gets the Modification Log filename for the corresponding Connection name.
104      *
105      * @param connectionName
106      * the connection name
107      * @return
108      * the Modification Log filename
109      */

110     public static final String JavaDoc getModificationLogFileName( String JavaDoc connectionName )
111     {
112         IPath p = BrowserCorePlugin.getDefault().getStateLocation().append( "logs" ); //$NON-NLS-1$
113
File JavaDoc file = p.toFile();
114         if ( !file.exists() )
115         {
116             file.mkdir();
117         }
118         return p.append( "modifications-" + toSaveString( connectionName ) + "-%u-%g.ldiflog" ).toOSString(); //$NON-NLS-1$ //$NON-NLS-2$
119
}
120
121
122     /**
123      * Gets the filename of the Connection Store.
124      *
125      * @return
126      * the filename of the Connection Store
127      */

128     public static final String JavaDoc getConnectionStoreFileName()
129     {
130         return BrowserCorePlugin.getDefault().getStateLocation().append( "connections.xml" ).toOSString(); //$NON-NLS-1$
131
}
132
133
134     /**
135      * Converts a String into a Saveable String.
136      *
137      * @param s
138      * the String to convert
139      * @return
140      * the converted String
141      */

142     private static String JavaDoc toSaveString( String JavaDoc s )
143     {
144         if ( s == null )
145         {
146             return null;
147         }
148
149         byte[] b = LdifUtils.utf8encode( s );
150         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
151         for ( int i = 0; i < b.length; i++ )
152         {
153
154             if ( b[i] == '-' || b[i] == '_' || ( '0' <= b[i] && b[i] <= '9' ) || ( 'A' <= b[i] && b[i] <= 'Z' )
155                 || ( 'a' <= b[i] && b[i] <= 'z' ) )
156             {
157                 sb.append( ( char ) b[i] );
158             }
159             else
160             {
161                 int x = ( int ) b[i];
162                 if ( x < 0 )
163                     x = 256 + x;
164                 String JavaDoc t = Integer.toHexString( x );
165                 if ( t.length() == 1 )
166                     t = "0" + t; //$NON-NLS-1$
167
sb.append( t );
168             }
169         }
170
171         return sb.toString();
172     }
173
174
175     /**
176      * Adds the connection to the end of the connection list. If there is
177      * already a connection with this name, the new connection is renamed.
178      *
179      * @param connection
180      */

181     public void addConnection( IConnection connection )
182     {
183         addConnection( connectionList.size(), connection );
184     }
185
186
187     /**
188      * Adds the connection at the specified position of the connection list.
189      * If there is already a connection with this name the new connection is
190      * renamed.
191      *
192      * @param index
193      * @param connection
194      */

195     public void addConnection( int index, IConnection connection )
196     {
197         if ( getConnection( connection.getName() ) != null )
198         {
199             String JavaDoc newConnectionName = BrowserCoreMessages.bind( BrowserCoreMessages.copy_n_of_s,
200                 "", connection.getName() ); //$NON-NLS-1$
201
for ( int i = 2; getConnection( newConnectionName ) != null; i++ )
202             {
203                 newConnectionName = BrowserCoreMessages.bind( BrowserCoreMessages.copy_n_of_s,
204                     i + " ", connection.getName() ); //$NON-NLS-1$
205
}
206             connection.getConnectionParameter().setName( newConnectionName );
207         }
208
209         connectionList.add( index, connection );
210         EventRegistry.fireConnectionUpdated( new ConnectionUpdateEvent( connection,
211             ConnectionUpdateEvent.EventDetail.CONNECTION_ADDED ), this );
212     }
213
214
215     /**
216      * Gets a connection from its name.
217      *
218      * @param name
219      * the name of the Connection
220      * @return
221      * the corresponding Connection
222      */

223     public IConnection getConnection( String JavaDoc name )
224     {
225         for ( Iterator JavaDoc it = connectionList.iterator(); it.hasNext(); )
226         {
227             IConnection conn = ( IConnection ) it.next();
228             if ( conn.getName().equals( name ) )
229             {
230                 return conn;
231             }
232         }
233         return null;
234     }
235
236
237     /**
238      * Gets the index in the Connection list of the first occurrence of the specified Connection.
239      *
240      * @param connection
241      * the Connection to search for
242      * @return
243      * the index in the Connection list of the first occurrence of the specified Connection
244      */

245     public int indexOf( IConnection connection )
246     {
247         return connectionList.indexOf( connection );
248     }
249
250
251     /**
252      * Removes the given Connection from the Connection list.
253      *
254      * @param conn
255      * the connection to remove
256      */

257     public void removeConnection( IConnection conn )
258     {
259         connectionList.remove( conn );
260         EventRegistry.fireConnectionUpdated(
261             new ConnectionUpdateEvent( conn, ConnectionUpdateEvent.EventDetail.CONNECTION_REMOVED ), this );
262     }
263
264
265     /**
266      * Gets an array containing all the Connections.
267      *
268      * @return
269      * an array containing all the Connections
270      */

271     public IConnection[] getConnections()
272     {
273         return ( IConnection[] ) connectionList.toArray( new IConnection[0] );
274     }
275
276
277     /**
278      * Gets the number of Connections.
279      *
280      * @return
281      * the number of Connections
282      */

283     public int getConnectionCount()
284     {
285         return connectionList.size();
286     }
287
288
289     /**
290      * {@inheritDoc}
291      */

292     public void connectionUpdated( ConnectionUpdateEvent connectionUpdateEvent )
293     {
294         if ( connectionUpdateEvent.getDetail() == ConnectionUpdateEvent.EventDetail.CONNECTION_ADDED
295             || connectionUpdateEvent.getDetail() == ConnectionUpdateEvent.EventDetail.CONNECTION_REMOVED
296             || connectionUpdateEvent.getDetail() == ConnectionUpdateEvent.EventDetail.CONNECTION_RENAMED
297             || connectionUpdateEvent.getDetail() == ConnectionUpdateEvent.EventDetail.CONNECTION_PARAMETER_UPDATED )
298         {
299             saveConnections();
300         }
301
302         if ( connectionUpdateEvent instanceof ConnectionRenamedEvent )
303         {
304             String JavaDoc oldName = ( ( ConnectionRenamedEvent ) connectionUpdateEvent ).getOldName();
305             String JavaDoc newName = connectionUpdateEvent.getConnection().getName();
306             String JavaDoc oldSchemaFile = getSchemaCacheFileName( oldName );
307             String JavaDoc newSchemaFile = getSchemaCacheFileName( newName );
308             File JavaDoc oldFile = new File JavaDoc( oldSchemaFile );
309             File JavaDoc newFile = new File JavaDoc( newSchemaFile );
310             if ( oldFile.exists() )
311             {
312                 oldFile.renameTo( newFile );
313             }
314         }
315         if ( connectionUpdateEvent.getDetail() == ConnectionUpdateEvent.EventDetail.SCHEMA_LOADED
316             || connectionUpdateEvent.getDetail() == ConnectionUpdateEvent.EventDetail.CONNECTION_OPENED )
317         {
318             saveSchema( connectionUpdateEvent.getConnection() );
319         }
320         if ( connectionUpdateEvent.getDetail() == ConnectionUpdateEvent.EventDetail.CONNECTION_REMOVED )
321         {
322             File JavaDoc file = new File JavaDoc( getSchemaCacheFileName( connectionUpdateEvent.getConnection().getName() ) );
323             if ( file.exists() )
324             {
325                 file.delete();
326             }
327         }
328     }
329
330
331     /**
332      * {@inheritDoc}
333      */

334     public void searchUpdated( SearchUpdateEvent searchUpdateEvent )
335     {
336         if ( searchUpdateEvent.getDetail() == SearchUpdateEvent.EventDetail.SEARCH_ADDED
337             || searchUpdateEvent.getDetail() == SearchUpdateEvent.EventDetail.SEARCH_REMOVED
338             || searchUpdateEvent.getDetail() == SearchUpdateEvent.EventDetail.SEARCH_RENAMED
339             || searchUpdateEvent.getDetail() == SearchUpdateEvent.EventDetail.SEARCH_PARAMETER_UPDATED )
340         {
341             saveConnections();
342         }
343     }
344
345
346     /**
347      * {@inheritDoc}
348      */

349     public void bookmarkUpdated( BookmarkUpdateEvent bookmarkUpdateEvent )
350     {
351         if ( bookmarkUpdateEvent.getDetail() == BookmarkUpdateEvent.Detail.BOOKMARK_ADDED
352             || bookmarkUpdateEvent.getDetail() == BookmarkUpdateEvent.Detail.BOOKMARK_REMOVED
353             || bookmarkUpdateEvent.getDetail() == BookmarkUpdateEvent.Detail.BOOKMARK_UPDATED )
354         {
355             saveConnections();
356         }
357     }
358
359
360     /**
361      * Saves the Connections
362      */

363     private void saveConnections()
364     {
365         Object JavaDoc[][] object = new Object JavaDoc[connectionList.size()][3];
366
367         Iterator JavaDoc connectionIterator = connectionList.iterator();
368         for ( int i = 0; connectionIterator.hasNext(); i++ )
369         {
370             IConnection conn = ( IConnection ) connectionIterator.next();
371             ConnectionParameter connectionParameters = conn.getConnectionParameter();
372             ISearch[] searches = conn.getSearchManager().getSearches();
373             SearchParameter[] searchParameters = new SearchParameter[searches.length];
374             for ( int k = 0; k < searches.length; k++ )
375             {
376                 searchParameters[k] = searches[k].getSearchParameter();
377             }
378             IBookmark[] bookmarks = conn.getBookmarkManager().getBookmarks();
379             BookmarkParameter[] bookmarkParameters = new BookmarkParameter[bookmarks.length];
380             for ( int k = 0; k < bookmarks.length; k++ )
381             {
382                 bookmarkParameters[k] = bookmarks[k].getBookmarkParameter();
383             }
384
385             object[i][0] = connectionParameters;
386             object[i][1] = searchParameters;
387             object[i][2] = bookmarkParameters;
388         }
389
390         save( object, getConnectionStoreFileName() );
391     }
392
393
394     /**
395      * Saves the Schema of the Connection
396      *
397      * @param connection
398      * the Connection
399      */

400     private void saveSchema( IConnection connection )
401     {
402         try
403         {
404             String JavaDoc filename = getSchemaCacheFileName( connection.getName() );
405             FileWriter JavaDoc writer = new FileWriter JavaDoc( filename );
406             connection.getSchema().saveToLdif( writer );
407             writer.close();
408         }
409         catch ( Exception JavaDoc e )
410         {
411             e.printStackTrace();
412         }
413     }
414
415
416     /**
417      * Loads the Connections
418      */

419     private void loadConnections()
420     {
421         try
422         {
423             Object JavaDoc[][] object = ( Object JavaDoc[][] ) this.load( getConnectionStoreFileName() );
424
425             if ( object != null )
426             {
427                 try
428                 {
429                     for ( int i = 0; i < object.length; i++ )
430                     {
431                         IConnection conn = new Connection();
432
433                         ConnectionParameter connectionParameters = ( ConnectionParameter ) object[i][0];
434                         conn.setConnectionParameter( connectionParameters );
435
436                         if ( object[i].length > 1 )
437                         {
438                             SearchParameter[] searchParameters = ( SearchParameter[] ) object[i][1];
439                             for ( int k = 0; k < searchParameters.length; k++ )
440                             {
441                                 ISearch search = new Search( conn, searchParameters[k] );
442                                 conn.getSearchManager().addSearch( search );
443                             }
444                         }
445
446                         if ( object[i].length > 2 )
447                         {
448                             BookmarkParameter[] bookmarkParameters = ( BookmarkParameter[] ) object[i][2];
449                             for ( int k = 0; k < bookmarkParameters.length; k++ )
450                             {
451                                 IBookmark bookmark = new Bookmark( conn, bookmarkParameters[k] );
452                                 conn.getBookmarkManager().addBookmark( bookmark );
453                             }
454                         }
455
456                         try
457                         {
458                             String JavaDoc schemaFilename = getSchemaCacheFileName( conn.getName() );
459                             FileReader JavaDoc reader = new FileReader JavaDoc( schemaFilename );
460                             Schema schema = new Schema();
461                             schema.loadFromLdif( reader );
462                             conn.setSchema( schema );
463                         }
464                         catch ( Exception JavaDoc e )
465                         {
466                         }
467
468                         connectionList.add( conn );
469                     }
470
471                 }
472                 catch ( ArrayIndexOutOfBoundsException JavaDoc e )
473                 {
474                     // Thrown by decoder.readObject(), signals EOF
475
}
476                 catch ( Exception JavaDoc e )
477                 {
478                     e.printStackTrace();
479                 }
480             }
481         }
482         catch ( Exception JavaDoc e )
483         {
484         }
485     }
486
487
488     /**
489      * Loads an Object from an XML file
490      *
491      * @param filename
492      * the filename of the XML file
493      * @return
494      * the deserialized Object
495      */

496     private synchronized Object JavaDoc load( String JavaDoc filename )
497     {
498         try
499         {
500             Thread.currentThread().setContextClassLoader( getClass().getClassLoader() );
501             XMLDecoder JavaDoc decoder = new XMLDecoder JavaDoc( new BufferedInputStream JavaDoc( ( new FileInputStream JavaDoc( filename ) ) ) );
502             Object JavaDoc object = decoder.readObject();
503             decoder.close();
504             return object;
505         }
506         catch ( IOException JavaDoc ioe )
507         {
508             return null;
509         }
510         catch ( Exception JavaDoc e )
511         {
512             e.printStackTrace();
513             return null;
514         }
515     }
516
517
518     /**
519      * Saves an Object into a serialized XML file
520      *
521      * @param object
522      * the object to save
523      * @param filename
524      * the filename to save to
525      */

526     private synchronized void save( Object JavaDoc object, String JavaDoc filename )
527     {
528         XMLEncoder JavaDoc encoder = null;
529         try
530         {
531             Thread.currentThread().setContextClassLoader( getClass().getClassLoader() );
532             encoder = new XMLEncoder JavaDoc( new BufferedOutputStream JavaDoc( new FileOutputStream JavaDoc( filename ) ) );
533
534             encoder.setExceptionListener( new ExceptionListener JavaDoc()
535             {
536
537                 public void exceptionThrown( Exception JavaDoc e )
538                 {
539                     e.printStackTrace();
540                 }
541
542             } );
543
544             encoder.writeObject( object );
545         }
546         catch ( Exception JavaDoc e )
547         {
548             e.printStackTrace();
549         }
550         finally
551         {
552             if ( encoder != null )
553             {
554                 encoder.close();
555             }
556         }
557     }
558 }
559
Popular Tags