Skip to main content
summaryrefslogtreecommitdiffstats
blob: 3a2cb81ffbddda89f8f41f566edf3075274403a5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
/********************************************************************************
 * Copyright (c) 2002, 2006 IBM Corporation. All rights reserved.
 * This program and the accompanying materials are made available under the terms
 * of the Eclipse Public License v1.0 which accompanies this distribution, and is 
 * available at http://www.eclipse.org/legal/epl-v10.html
 * 
 * Initial Contributors:
 * The following IBM employees contributed to the Remote System Explorer
 * component that contains this file: David McKnight, Kushal Munir, 
 * Michael Berger, David Dykstal, Phil Coulthard, Don Yantzi, Eric Simpson, 
 * Emily Bruner, Mazen Faraj, Adrian Storisteanu, Li Ding, and Kent Hawley.
 * 
 * Contributors:
 * {Name} (company) - description of contribution.
 ********************************************************************************/

package org.eclipse.rse.internal.model;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import org.eclipse.rse.core.IRSEUserIdConstants;
import org.eclipse.rse.core.SystemPreferencesManager;
import org.eclipse.rse.core.model.IHost;
import org.eclipse.rse.core.model.ISystemHostPool;
import org.eclipse.rse.core.model.ISystemProfile;
import org.eclipse.rse.core.model.RSEModelObject;
import org.eclipse.rse.ui.RSEUIPlugin;
import org.eclipse.rse.ui.SystemResources;


/**
 * A pool of host objects.
 * There is one pool per profile.
 * It is named the same as its owning profile.
 * It is not persisted but provides a means of manipulating lists of host objects.
 * Hosts are created and destroyed by the host pool so that the the relationships between the two can be maintained. 
 */
public class SystemHostPool extends RSEModelObject implements ISystemHostPool
{

	protected static final String NAME_EDEFAULT = null;

    private static Hashtable pools = null;
    private static String CONNECTION_FILE_NAME = "connection"; //$NON-NLS-1$


	protected String name = NAME_EDEFAULT;
    private java.util.List connections = null;

    /**
     * Default constructor.
     */
	protected SystemHostPool()
    {
	 	  super();
	}

	/**
	 * Reset for a full refresh from disk, such as after a team synch
	 */
	public static void reset()
	{
		pools = null;
	}

    // -------------------------------------------------------------------------------------
    // CONNECTION POOL METHODS...
    // -------------------------------------------------------------------------------------
	/**
	 * Return (and create if necessary) the connection pool for a given system profile.
	 */
	public static ISystemHostPool getSystemHostPool(ISystemProfile profile)
	    throws Exception
	{
		//System.out.println("in getSystemConnectionPool for " + profile);
		if (pools == null)
		  pools = new Hashtable();
		SystemHostPool pool = (SystemHostPool)pools.get(profile);
		//System.out.println("... pool: " + pool);
		if (pool == null)
		{
		  pool = new SystemHostPool();
			  // FIXME (SystemConnectionPoolImpl)initMOF().createSystemConnectionPool();
		  pool.setName(profile.getName());
		  try {
		    pool.restore(); // restore connections
		  } catch (Exception exc) {
		  }
		  pools.put(profile, pool); // store this pool reference, keyed by profile object.
		}
		return pool;
	}
	
    /**
     * Return the system profile that owns this connection pool
     */
    public ISystemProfile getSystemProfile()
    {
    	return SystemProfileManager.getSystemProfileManager().getSystemProfile(getName());
    }	
	
	/**
	 * Rename this connection pool.
	 */
	public void renameHostPool(String newName)
	{
		IHost[] connections = getHosts();
		String oldName = getName();
		for (int idx=0; idx<connections.length; idx++)
		{
			connections[idx].renamingSystemProfile(oldName, newName);
		}
		setName(newName);
	}
	

    /**
     * Private debug method to print connections, to test restored ok.
     * @deprecated
     */
    public void printConnections()
    {
        java.util.List conns = getHostList();
        Iterator connsList = conns.iterator();
        if (!connsList.hasNext())
        {
          System.out.println();
          System.out.println("No connections"); //$NON-NLS-1$
        }
        while (connsList.hasNext())
        {
           System.out.println();
           IHost conn = (IHost)connsList.next();
           System.out.println("  AliasName.....: " + conn.getAliasName()); //$NON-NLS-1$
           System.out.println("  -----------------------------------------------------"); //$NON-NLS-1$
           System.out.println("  HostName......: " + conn.getHostName()); //$NON-NLS-1$
           System.out.println("  SystemType....: " + conn.getSystemType()); //$NON-NLS-1$
           System.out.println("  Description...: " + conn.getDescription()); //$NON-NLS-1$
           System.out.println("  UserId........: " + conn.getDefaultUserId()); //$NON-NLS-1$
        }
    }


    // -------------------------------------------------------------------------------------
    // CONNECTION METHODS...
    // -------------------------------------------------------------------------------------
    /**
     * Create a connection object, given only the minimal information.
     * <p>
     * THE RESULTING CONNECTION OBJECT IS ADDED TO THE LIST OF EXISTING CONNECTIONS FOR YOU.
     * @param systemType system type matching one of the system type names defined via the
     *                    systemTypes extension point.
     * @param aliasName unique connection name.
     * @param hostName ip name of host.
     * @return SystemConnection object, or null if it failed to create
     *   because the aliasName is not unique. All other errors throw an exception.
     */
    public IHost createHost(String systemType, String aliasName, String hostName)
        throws Exception                                                 
    {
        return createHost(systemType,aliasName,hostName,null,null,IRSEUserIdConstants.USERID_LOCATION_HOST);
    }
    /**
     * Create a connection object, given all the possible attributes except default userId.
     * <p>
     * THE RESULTING CONNECTION OBJECT IS ADDED TO THE LIST OF EXISTING CONNECTIONS FOR YOU.
     * @param systemType system type matching one of the system type names defined via the
     *                    systemTypes extension point.
     * @param aliasName unique connection name.
     * @param hostName ip name of host.
     * @param description optional description of the connection. Can be null.
     * @return SystemConnection object, or null if it failed to create
     *   because the aliasName is not unique. All other errors throw an exception.
     */
    public IHost createHost(String systemType, String aliasName, String hostName, String description)
        throws Exception                                                 
    {
        return createHost(systemType,aliasName,hostName,description,null,IRSEUserIdConstants.USERID_LOCATION_HOST);
    }
    /**
     * Create a connection object, given all the possible attributes.
     * <p>
     * The new connection is added to the list and saved to disk.
     * @param systemType system type matching one of the system type names defined via the
     *                    systemTypes extension point.
     * @param aliasName unique connection name.
     * @param hostName ip name of host.
     * @param description optional description of the connection. Can be null.
     * @param defaultUserId userId to use as the default for the subsystems.
     * @param defaultUserIdLocation where to set the given default user Id. See IRSEUserIdConstants for values.
     * @return SystemConnection object, or null if it failed to create
     *   because the aliasName is not unique. All other errors throw an exception.
     * @see IRSEUserIdConstants
     */
    public IHost createHost(String systemType, String aliasName, String hostName,
                                             String description,String defaultUserId,int defaultUserIdLocation)        
        throws Exception                                             
    {
        IHost conn = null;
        boolean exists = getHost(aliasName) != null;
        if (exists)
        {
          return null;
        }
        try
        {
          ISystemProfile profile = getSystemProfile();
          conn = new Host(profile);
          addHost(conn); // only record internally if saved successfully
          conn.setHostPool(this);          
          conn.setAliasName(aliasName);
          // if default userID is null, and location is in the connection we should retrieve it and use it as the initial value.
          if (defaultUserId == null && defaultUserIdLocation == IRSEUserIdConstants.USERID_LOCATION_HOST) {
              defaultUserId = conn.getDefaultUserId();
          }
          updateHost(conn, systemType, aliasName, hostName, description, defaultUserId, defaultUserIdLocation);          

        } catch (Exception e)
        {
          throw e;
        }
        return conn;
    }
    /**
     * Update an existing connection given the new information.
     * This method:
     * <ul>
     *  <li>calls the setXXX methods on the given connection object, updating the information in it.
     *  <li>saves the connection to disk (renaming its folder if needed)
     * </ul>
     * <p>
     * @param conn SystemConnection to be updated
     * @param systemType system type matching one of the system type names defined via the
     *                    systemTypes extension point.
     * @param aliasName unique connection name.
     * @param hostName ip name of host.
     * @param description optional description of the connection. Can be null.
     * @param defaultUserId userId to use as the default for the subsystems.
     * @param defaultUserIdLocation where to set the given default user Id. See IRSEUserIdConstants for values.
     * @see IRSEUserIdConstants
     */
    public void updateHost(IHost conn, String systemType,
                                 String aliasName, String hostName,
                                 String description,String defaultUserId, int defaultUserIdLocation)
        throws Exception
    {
    	boolean aliasNameChanged = !aliasName.equalsIgnoreCase(conn.getAliasName());    	
    	if (aliasNameChanged)
    	  renameHost(conn,aliasName);
    	conn.setSystemType(systemType);
    	conn.setHostName(hostName);
    	if (defaultUserIdLocation != IRSEUserIdConstants.USERID_LOCATION_NOTSET)
    	{
    	  if (defaultUserIdLocation != IRSEUserIdConstants.USERID_LOCATION_HOST)
    	  {
    	    conn.setDefaultUserId(null); // clear what was there, to ensure inheritance
   	        SystemPreferencesManager prefMgr = SystemPreferencesManager.getPreferencesManager();    	
   	        boolean forceToUpperCase = conn.getForceUserIdToUpperCase();
   	        if (forceToUpperCase && (defaultUserId != null))
   	          defaultUserId = defaultUserId.toUpperCase();
    	    if (defaultUserIdLocation == IRSEUserIdConstants.USERID_LOCATION_DEFAULT_SYSTEMTYPE)
    	    {
    	      prefMgr.setDefaultUserId(systemType, defaultUserId);    	      
    	    }
    	    //else if (defaultUserIdLocation == IRSEUserIdConstants.USERID_LOCATION_DEFAULT_OVERALL)
    	    //{
    	      //prefMgr.setDefaultUserId(defaultUserId);    	          	    	
    	    //}
    	  }
    	  else
    	  {
    	    conn.setDefaultUserId(defaultUserId);
    	  }
    	}
    	conn.setDescription(description);
   	    commit(conn);
    }
    
    
    /**
     * Return array of connections in this pool
     */
    public IHost[] getHosts()
    {

    	return (IHost[])getHostList().toArray(new IHost[connections.size()]);
    }
    
 
    
    /*
     * Invalidate cache so it will be regenerated
     */
    protected void invalidateCache()
    {
    	setDirty(true);
    }

    /**
     * Return a connection object, given its alias name.
     * Can be used to test if an alias name is already used (non-null return).
     * @param aliasName unique aliasName (case insensitive) to search on.
     * @return SystemConnection object with unique aliasName, or null if
     *  no connection object with this name exists.
     */
    public IHost getHost(String aliasName)
    {
        IHost conn = null;
        IHost currconn = null;
        java.util.List conns = getHostList();
        Iterator i = conns.iterator();
        while (i.hasNext() && (conn==null))
        {
           currconn = (IHost)i.next();
           if (currconn.getAliasName().equalsIgnoreCase(aliasName))
             conn = currconn;
        }
        return conn;
    }
    /**
     * Return the connection at the given zero-based offset
     */
    public IHost getHost(int pos)
    {
        java.util.List conns = getHostList();
        if (pos < conns.size())
          return (IHost)conns.get(pos);
        else
          return null;
    }
    /**
     * Return the zero-based position of a SystemConnection object within its profile.
     */
    public int getHostPosition(IHost conn)
    {
    	int position = -1;
    	boolean match = false;    	
    	java.util.List conns = getHostList();
    	Iterator i = conns.iterator();
    	int idx = 0;
    	while (!match && i.hasNext())
    	{
           IHost currConn = (IHost)i.next();
           if (conn.equals(currConn))
           {
           	 match = true;
           	 position = idx;
           }
           idx++;
    	}
    	return position;
    }
    
    /**
     * Return the number of SystemConnection objects within this pool.
     */
    public int getHostCount()
    {
        java.util.List conns = getHostList();    	
        return conns.size();
    }


    public boolean addHost(IHost conn)
    {
    	List hostList = getHostList();
    	if (!hostList.contains(conn))
    	{
    		hostList.add(conn);
    	}
        conn.setHostPool(this);
        invalidateCache();
        return true;
    }

    /**
     * Removes a given connection from the list and deletes it from disk.
     * <p>
	 * This will:
	 * <ul>
	 *    <li>Delete the connection in memory
	 *    <li>Delete the underlying folder
	 * </ul> 
     * <p>
     * @param conn SystemConnection object to remove
     */
    public void deleteHost(IHost conn)
    {
    	conn.deletingHost(); // let connection do any necessary cleanup
        getHostList().remove(conn);
        setDirty(true);
        RSEUIPlugin.getThePersistenceManager().commit(conn.getSystemProfile());
    }

    /**
     * Renames a given connection in the list.
	 * This will:
	 * <ul>
	 *    <li>Rename the profile in memory
	 *    <li>Rename the underlying folder
	 *    <li>Update the user preferences if this profile is currently active.
	 * </ul>
     * @param conn SystemConnection object to rename
     * @param newName The new name to give that connection.
     */
    public void renameHost(IHost conn, String newName)
           throws Exception
    {
        conn.setAliasName(newName);
        invalidateCache();
   	    commit(conn);
    }


    /**
     * Duplicates a given connection in this list within this list or another list.
     * @param targetPool The SystemConnectionPool to hold the copied connection. Can equal this connection, as long as alias name is unique
     * @param conn SystemConnection object (within our pool) to clone
     * @param aliasName New, unique, alias name to give this connection. Clone will fail if this is not unique.
     */
    public IHost cloneHost(ISystemHostPool targetPool, IHost conn, String aliasName)
       throws Exception
    {
        IHost copy =
            targetPool.createHost(conn.getSystemType(), aliasName,
                 conn.getHostName(), conn.getDescription(), conn.getLocalDefaultUserId(), IRSEUserIdConstants.USERID_LOCATION_HOST);
        return copy;
    }

    /**
     * Move existing connections a given number of positions in the same pool.
     * If the delta is negative, they are all moved up by the given amount. If 
     * positive, they are all moved down by the given amount.<p>
     * <ul>
     * <li>After the move, the pool containing the moved connection is saved to disk.
     * <li>The connection's alias name must be unique in pool.
     * </ul>
     * <b>TODO PROBLEM: CAN'T RE-ORDER FOLDERS SO CAN WE SUPPORT THIS ACTION?</b>
     * @param conns Array of SystemConnections to move.
     * @param newPosition new zero-based position for the connection
     */
    public void moveHosts(IHost conns[], int delta)
    {
    	int[] oldPositions = new int[conns.length];
    	for (int idx=0; idx<conns.length; idx++)
    	   oldPositions[idx] = getHostPosition(conns[idx]);    	
    	if (delta > 0) // moving down, process backwards
          for (int idx=conns.length-1; idx>=0; idx--)
             moveConnection(conns[idx], oldPositions[idx]+delta);	
        else    	   
          for (int idx=0; idx<conns.length; idx++)
             moveConnection(conns[idx], oldPositions[idx]+delta);	

          commit();    	
    }
    
    /**
     * Move one connection to a new location
     * <b>TODO PROBLEM: CAN'T RE-ORDER FOLDERS SO CAN WE SUPPORT THIS ACTION?</b>
     */
    private void moveConnection(IHost conn, int newPos)
    {
    	/*
    	 * DWD revisit, make sure that connections can be "moved", whatever that means.
    	 * It appears that connections can be moved up and down in the list which
    	 * probably provides for some rational for keeping this around.
    	 */
//        java.util.List connList = getHostList();
       //FIXME connList.move(newPos, conn);
        invalidateCache();
    }

    /**
     * Order connections according to user preferences.
     * Called after restore.
     */
    public void orderHosts(String[] names)
    {
    	java.util.List connList = getHostList();
    	IHost[] conns = new IHost[names.length];
    	for (int idx=0; idx<conns.length; idx++)
    	   conns[idx] = getHost(names[idx]);
    	connList.clear();
    	//System.out.println("Ordering connections within pool " + getName() + "...");
    	for (int idx=0; idx<conns.length; idx++)
    	{
    	   connList.add(conns[idx]); 
    	   //System.out.println("  '"+conns[idx].getAliasName()+"'");
    	}
    	//System.out.println();
        invalidateCache();
    }

	// -------------------------
	// SAVE / RESTORE METHODS...
	// -------------------------
	/**
	 * Save all connections to disk.
	 * Attempts to save all of them, swallowing exceptions, then at the end throws the last exception caught.
	 */
	public boolean commit()
	{
		return RSEUIPlugin.getThePersistenceManager().commit(this);
	}
	
    /**
     * Attempt to save single connection to disk.
     */
    public void commit(IHost connection)
    {
    	commit();
     }

	/**
	 * Restore connections from disk
	 */
	protected void restore()
	   throws Exception
	{
		//System.out.println("... . in pool.restore ");
		
		//FIXME 
	}
	
    /**
     * Restore a connection of a given name from disk...
     */
    protected IHost restore(String connectionName)  
        throws Exception  
    {
    	/*FIXME
    	//System.out.println("in SystemConnectionPoolImpl#restore for connection " + connectionName);
        String fileName = getRootSaveFileName(connectionName);                
        //System.out.println(".......fileName = " + fileName);
        //System.out.println(".......folderName = " + getConnectionFolder(connectionName).getName());
    	java.util.List ext = getMOFHelpers().restore(getConnectionFolder(connectionName),fileName);
    	
        // should be exactly one profile...
        Iterator iList = ext.iterator();
        SystemConnection connection = (SystemConnection)iList.next();        
        if (connection != null)
        {
          if (!connection.getAliasName().equalsIgnoreCase(connectionName))
          {
            RSEUIPlugin.logDebugMessage(this.getClass().getName(),"Incorrect alias name found in connections.xmi file for " + connectionName+". Name was reset");
            connection.setAliasName(connectionName); // just in case!
          }
          internalAddConnection(connection);
        }        
        return connection;
        */
    	return null;
    }

   
    
    /**
     * Return the unqualified save file name with the extension .xmi
     */
    protected static String getSaveFileName(IHost connection)
    {
        return null;//FIXME return SystemMOFHelpers.getSaveFileName(getRootSaveFileName(connection));
    }

    /**
     * Return the root save file name without the extension .xmi
     */
    protected static String getRootSaveFileName(IHost connection)
    {
        return getRootSaveFileName(connection.getAliasName());
    }
    /**
     * Return the root save file name without the extension .xmi
     */
    protected static String getRootSaveFileName(String connectionName)
    {
    	//String fileName = connectionName; // maybe a bad idea to include connection name in it!
    	String fileName = CONNECTION_FILE_NAME;
        return fileName;    	
    }
    
   

    


	public String toString()
    {
        if (getName() == null)
          return this.toStringGen();
        else
          return getName();
    }
	/**
	 * @generated This field/method will be replaced during code generation 
	 */
	public String getName()
	{
		return name;
	}
	
	public String getDescription()
	{
		return SystemResources.RESID_MODELOBJECTS_HOSTPOOL_DESCRIPTION;
	}

	/**
	 * @generated This field/method will be replaced during code generation.
	 */
	public void setName(String newName)
	{
		name = newName;
	}


	public List getHostList()
	{
		if (connections == null)
		{
			connections = new ArrayList();
		}
		return connections;
	}

	/**
	 * @deprecated This field/method will be replaced during code generation.
	 */
	public String toStringGen()
	{
		StringBuffer result = new StringBuffer(super.toString());
		result.append(" (name: "); //$NON-NLS-1$
		result.append(name);
		result.append(')');
		return result.toString();
	}
	

}

Back to the top