summaryrefslogtreecommitdiff
path: root/source/com/c2kernel/process/Gateway.java
blob: 3a03088e2b63d25a2e13d59011b36e0eca8eea8c (plain)
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
package com.c2kernel.process;

/**
 * @version $Revision: 1.17 $ $Date: 2005/10/12 12:51:54 $
 * @author  $Author: abranson $
 */

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;

import com.c2kernel.common.InvalidDataException;
import com.c2kernel.common.ObjectNotFoundException;
import com.c2kernel.entity.CorbaServer;
import com.c2kernel.entity.proxy.AgentProxy;
import com.c2kernel.entity.proxy.EntityProxyManager;
import com.c2kernel.lookup.AgentPath;
import com.c2kernel.lookup.LDAPLookup;
import com.c2kernel.lookup.LDAPProperties;
import com.c2kernel.persistency.ClusterStorageException;
import com.c2kernel.persistency.TransactionManager;
import com.c2kernel.utils.CastorXMLUtility;
import com.c2kernel.utils.FileStringUtility;
import com.c2kernel.utils.Language;
import com.c2kernel.utils.Logger;
import com.c2kernel.utils.Resource;
import com.c2kernel.utils.server.SimpleTCPIPServer;


/**************************************************************************
 * The Gateway is the central object of a CRISTAL process. It initializes,
 * maintains and shuts down every other subsystem in both the client and the
 * server.
 *
 * Child objects:
 * <ul>
 * <li>LDAPLookup - Provides access to the CRISTAL directory. Find or
 * search for Items or Agents.
 * <li>EntityProxyManager - Gives a local proxy object for Entities found
 * in LDAP. Execute activities in Items, query or subscribe to Entity data.
 * <li>TransactionManager - Access to the configured CRISTAL databases
 * <li>CorbaServer - Manages the memory pool of active Entities
 * <li>mORB - the Orbacus CORBA ORB
 * </ul>
 *
 * @author $Author: abranson $ $Date: 2005/10/12 12:51:54 $
 * @version $Revision: 1.17 $
 **************************************************************************/

public class Gateway
{
    static private Properties  mC2KProps;
    static private org.omg.CORBA.ORB    mORB;
    static private LDAPLookup           mLDAPLookup;
    static private TransactionManager   mStorage;
    static private EntityProxyManager   mProxyManager;
    static private CorbaServer          mCorbaServer;
    static private SimpleTCPIPServer    mHTTPServer;


    private Gateway() { }

    /**
     * Initialises the Gateway and all of the client objects it holds, with
     * the exception of the LDAPLookup, which is initialised during connect()
     *
     * @param props - java.util.Properties containing all application properties.
     * If null, the java system properties are used
     * @throws InvalidDataException - invalid properties caused a failure in initialisation
     */
    static public void init(Properties props) throws InvalidDataException {
        // if supplied props are null, use system props
        if (props == null) props = System.getProperties();

        // set resource URLs from config
        String resURL = props.getProperty("KernelResourceURL");
        if (resURL != null && resURL.length()>0)
            Resource.setKernelBaseURL(resURL);

        resURL = props.getProperty("DomainResourceURL");
        if (resURL != null && resURL.length()>0)
            Resource.setDomainBaseURL(resURL);

        // Start with default props from kernel jar
        try {
            mC2KProps = FileStringUtility.loadConfigFile( Resource.getKernelResourceURL("textFiles/defaultConf.properties").toString());
        } catch (MalformedURLException ex) {
            Logger.die("Default properties not found. Probable cause is missing resources");
        }

        // Overwrite with supplied props
        for (Enumeration<?> e = props.propertyNames(); e.hasMoreElements();) {
            String propName = (String)e.nextElement();
            mC2KProps.put(propName, props.get(propName));
        }

        // dump properties
        dumpC2KProps(7);

        // report version info
        Logger.msg("Domain version: "+Resource.getDomainVersion());
        Logger.msg("Kernel version: "+Resource.getKernelVersion());

        // load kernel and domain mapfiles
        try {
            CastorXMLUtility.loadMapsFrom(Resource.getKernelResourceURL("mapFiles/"));
            if (Resource.getDomainBaseURL()!=null)
                CastorXMLUtility.loadMapsFrom(Resource.getDomainResourceURL("mapFiles/"));
        } catch (MalformedURLException e1) {
            throw new InvalidDataException("Invalid Resource Location", "");
        }

        //Initialise language file
        String languageFile = getProperty("language.file");
        if (languageFile != null && languageFile.length() > 0) {
            Language.isTranlated=true;
            Language.mTableOfTranslation = FileStringUtility.loadLanguageFile(languageFile);
        }

        try {
            Resource.setImportURL(new URL("file:"+getProperty("Import.dir")));
        } catch (MalformedURLException e) {
            Logger.error("Import directory not set. "+getProperty("Import.dir"));
        }
    }

    /**
     * Makes this process capable of creating and managing server entities. Runs the
     * bootstrap to create the root LDAP contexts, initialises the CORBA server and
     * time-out manager.
     *
     * @throws InvalidDataException - error initialising
     */
    static public void startServer() throws InvalidDataException {
        try {
            // check top level LDAP contexts
            mLDAPLookup.install();

            // start entity proxy server
            EntityProxyManager.initServer();

            // Init ORB - set various config to sys properties
            java.util.Properties sysProps = System.getProperties();
            String serverName = getProperty("ItemServer.name");
            if (serverName != null)
                sysProps.put("ORBHost", serverName);
            String serverPort = getProperty("ItemServer.iiop", "1500");
            sysProps.put("ORBPort", serverPort);
            //TODO: externalize this (or replace corba completely)
            sysProps.put("com.sun.CORBA.POA.ORBServerId", "1");
            sysProps.put("com.sun.CORBA.POA.ORBPersistentServerPort", serverPort);

            //Standard initialisation of the ORB
            mORB = org.omg.CORBA.ORB.init(new String[0], sysProps);

            Logger.msg("Gateway.init() - ORB initialised. ORB is " + mORB.getClass().getName() );

            // start corba server components
            mCorbaServer = new CorbaServer();

            // start checking bootstrap items
            Bootstrap.run();

        } catch (Exception ex) {
            Logger.error(ex);
            Logger.die("Exception starting server components. Shutting down.");
        }

        // start the http server
        try {
            int httpPort = Integer.parseInt(Gateway.getProperty("ItemServer.HTTP.port"));
            Logger.msg(2, "Starting HTTP Server on port "+httpPort);
            mHTTPServer = new SimpleTCPIPServer(httpPort, ItemHTTPBridge.class, 5);
            mHTTPServer.startListening();
        } catch (NumberFormatException ex) {
            Logger.msg(3, "Invalid or no HTTP port defined. HTTP server not available.");
        }

        System.out.println("Server '"+Gateway.getCentreId()+"' initialised.");
    }

    /**
     * Connects to the LDAP server in an administrative context - using the admin username and
     * password given in the LDAP.user and LDAP.password props of the kernel properties.
     *
     * @throws InvalidDataException - bad params
     * @throws ClusterStorageException - error starting storages
     */
    static public void connect()
        throws InvalidDataException,
               ClusterStorageException
    {
        LDAPProperties ldapProps = new LDAPProperties();

        if( ldapProps.mHost != null && ldapProps.mPort     != null &&
            ldapProps.mUser != null && ldapProps.mPassword != null )
        {
            try
            {
				mLDAPLookup = new LDAPLookup(ldapProps);
            }
            catch (Exception ex)
            {
                Logger.error(ex);
                throw new InvalidDataException("Cannot authenticate. Name and/or password invalid.", "");
            }
        }
        else
        {
            Logger.error("LDAP not configured properly.");
            throw new InvalidDataException("Cannot authenticate. Name and/or password invalid.", "");
        }

        setup();
    }

    /**
     * Authenticates a user and returns and AgentProxy on them without overriding the system LDAP context.
     * Useful for handling multiple users in one context e.g. on a web server
     *
     * @param agentName - username
     * @param agentPassword - password
     * @return AgentProxy on that user
     * @throws InvalidDataException
     * @throws ObjectNotFoundException
     */
    static public AgentProxy login(String agentName, String agentPassword) throws InvalidDataException, ObjectNotFoundException {
        LDAPProperties ldapProps = new LDAPProperties();
        AgentPath agentPath;
        try {
            agentPath = mLDAPLookup.getRoleManager().getAgentPath(agentName);
        } catch (Exception ex) {
            Logger.error(ex);
            throw new ObjectNotFoundException("Could not resolve agent", "");
        }
        String agentDN = agentPath.getFullDN();
        ldapProps.mUser = agentDN;
        ldapProps.mPassword = agentPassword;

        try {
            LDAPLookup.createConnection(ldapProps);
            return (AgentProxy)getProxyManager().getProxy(mLDAPLookup.getRoleManager().getAgentPath(agentName));
        } catch (Exception ex) {
            Logger.error(ex);
            throw new InvalidDataException("Could not log in", "");
        }
    }


    /**
     * Logs into the LDAP server with the given username and password, and initialises the lookup.
     *
     * @param agentName - username
     * @param agentPassword - password
     * @return an AgentProxy on the requested user
     * @throws InvalidDataException
     */
    static public AgentProxy connect(String agentName, String agentPassword)
    throws InvalidDataException
    {

        LDAPProperties ldapProps = new LDAPProperties();
        if (ldapProps.mHost!=null && ldapProps.mPort!= null && ldapProps.mLocalPath!=null )
        {
            try {
                ldapProps.mUser = "";
                ldapProps.mPassword = "";
                mLDAPLookup = new LDAPLookup(ldapProps);
                String agentDN = mLDAPLookup.getRoleManager().getAgentPath(agentName).getFullDN();

                //found agentDN, try to log in with it
                ldapProps.mUser = agentDN;
                ldapProps.mPassword = agentPassword;
                mLDAPLookup = new LDAPLookup(ldapProps);

                // find agent proxy
                AgentPath agentPath = mLDAPLookup.getRoleManager().getAgentPath(agentName);

                if (agentPath!=null)
                {
                    setup();
                    return (AgentProxy) mProxyManager.getProxy(agentPath);
                }
                else
                {
                    throw new InvalidDataException("The agentDN " +agentDN+ " is invalid.", "");
                }
            } catch (ClusterStorageException e) {
                Logger.error(e);
                throw new InvalidDataException(Language.translate("Error initialising storage")+Language.translate(". See log."), "");
            } catch (ObjectNotFoundException e) {
                Logger.error(e);
                throw new InvalidDataException(Language.translate("Invalid username/password"), "");
            } catch (Exception e) {
                Logger.error(e);
                throw new InvalidDataException(Language.translate("Could not log in")+": "+Language.translate(e.getMessage()), "");
            }

        }
        else
        {
            throw new InvalidDataException("Cannot log in. Some connection properties are not set.", "");
        }

    }

    /**
     * Initializes the storage and proxy manager, called during connect.
     *
     * @throws InvalidDataException
     * @throws ClusterStorageException
     */
    static private void setup()
        throws InvalidDataException,
        ClusterStorageException
    {

        // Init storages
        mStorage = new TransactionManager();
        mProxyManager = new EntityProxyManager();

    }

    /**
     * Shuts down all kernel api objects
     */
    public static void close()
    {
        // shut down servers if running
        if (mCorbaServer != null)
            mCorbaServer.close();
        mCorbaServer = null;
        if (mHTTPServer != null)
            mHTTPServer.stopListening();
        mHTTPServer = null;

        // disconnect from storages
        if (mStorage != null)
            mStorage.close();
        mStorage = null;

        // disconnect from ldap
        if (mLDAPLookup != null)
            mLDAPLookup.disconnect();
        mLDAPLookup = null;

        // shut down proxy manager
        if (mProxyManager != null)
            mProxyManager.shutdown();
        mProxyManager = null;
        EntityProxyManager.shutdownServer();

        // close log consoles
        Logger.closeConsole();

        // finally, destroy the ORB
        getORB().destroy();
    }

    static public org.omg.CORBA.ORB getORB()
    {
    	if (mORB == null)
    		mORB = org.omg.CORBA.ORB.init(new String[0], null);
        return mORB;
    }

    static public LDAPLookup getLDAPLookup()
    {
        return mLDAPLookup;
    }

    static public CorbaServer getCorbaServer()
    {
        return mCorbaServer;
    }

    static public TransactionManager getStorage()
    {
        return mStorage;
    }

    static public EntityProxyManager getProxyManager()
    {
        return mProxyManager;
    }

    static public String getCentreId() {
        return getProperty("LocalCentre");
    }

    static public String getProperty(String propName) {
        return getProperty(propName, null);
    }

    static public String getProperty(String propName, String defaultValue) {
        if (mC2KProps == null) return defaultValue;
        return mC2KProps.getProperty(propName, defaultValue);
    }

    static public void setProperty(String propName, String propValue) {
        if (mC2KProps == null) return;
        mC2KProps.put(propName, propValue);
    }

    static public Enumeration<?> propertyNames() {
        return mC2KProps.propertyNames();
    }

    static public void dumpC2KProps(int logLevel) {
        if (!Logger.doLog(logLevel)) return;
        Logger.msg(logLevel, "C2K Properties:");
        for (Enumeration<?> e = propertyNames(); e.hasMoreElements();) {
            String name = (String) e.nextElement();
            Logger.msg("    "+name+": "+getProperty(name));
        }
    }
}