Project

General

Profile

« Previous | Next » 

Revision 5374

Added by berkley almost 14 years ago

refactored the sessionService to use a correct singleton initialization scheme. Added true authentication to ResourceHandler.

View differences:

test/edu/ucsb/nceas/metacat/dataone/CrudServiceTest.java
137 137
            //the correct objects
138 138
            
139 139
            ObjectList list = cs.listObjects(token, null, null, null);
140
            System.out.println("list size: " + list.sizeObjectInfoList());
140
            //System.out.println("list size: " + list.sizeObjectInfoList());
141 141
	        
142 142
            //should return sm1 and sm2
143 143
            ObjectList list1 = cs.listObjects(token, d1, d3, null);
src/edu/ucsb/nceas/metacat/restservice/ResourceHandler.java
58 58
import edu.ucsb.nceas.metacat.McdbDocNotFoundException;
59 59
import edu.ucsb.nceas.metacat.MetacatHandler;
60 60
import edu.ucsb.nceas.metacat.dataone.CrudService;
61
import edu.ucsb.nceas.metacat.service.SessionService;
61 62
import edu.ucsb.nceas.metacat.util.RequestUtil;
62 63
import edu.ucsb.nceas.metacat.util.SessionData;
63 64

  
......
203 204
    private static final String FUNCTION_NAME_GETNEXTOBJ = "getnextobject";
204 205
    private static final String FUNCTION_NAME_INSERT = "insert";
205 206
    private static final String FUNCTION_NAME_UPDATE = "update";
207
    private static final String FUNCTION_NAME_GENERATE_MISSING_SYSTEM_METADATA = "generatemissingsystemmetadata";
206 208

  
207 209
    private ServletContext servletContext;
208 210
    private Logger logMetacat;
......
225 227
    }
226 228

  
227 229
    /**
228
     *  copies request parameters to a hashtable which is given as argument to native metacathandler functions  
229
     */
230
    private void initParams() {
231

  
232
        String name = null;
233
        String[] value = null;
234
        Enumeration paramlist = request.getParameterNames();
235
        while (paramlist.hasMoreElements()) {
236
            name = (String) paramlist.nextElement();
237
            value = request.getParameterValues(name);
238
            //System.out.println("adding param: " + name + " = " + value);
239
            params.put(name, value);
240
        }
241

  
242
    }
243

  
244
    /**
245
     * 
246
     * Load user details of metacat session from the request 
247
     * 
248
     */
249
    private void loadSessionData() {
250
        SessionData sessionData = RequestUtil.getSessionData(request);
251

  
252
        // TODO: validate the session before allowing these values to be set
253
        username = sessionData.getUserName();
254
        password = sessionData.getPassword();
255
        groupNames = sessionData.getGroupNames();
256
        sessionId = sessionData.getId();
257
        //System.out.println("setting sessionid to " + sessionId);
258
        
259
        if (username == null) {
260
            username = "public";
261
        }
262
    }
263

  
264
    /**
265 230
     * This function is called from REST APU servlet and handles each request to the servlet 
266 231
     * 
267 232
     * @param httpVerb (GET, POST, PUT or DELETE)
......
302 267
                            //System.out.println("done setting access");
303 268
                        }
304 269
                    } else if (resource.equals(RESOURCE_META)) {
305
                        loadSessionData();
306
                        String objectId = request.getPathInfo();
307
                        if (objectId != null && objectId.length() > 1) 
270
                        if(params.get(FUNCTION_KEYWORD)[0].equals(FUNCTION_NAME_GENERATE_MISSING_SYSTEM_METADATA))
271
                        { //generate system metadata for any object that is
272
                          //a) not system metadata itself
273
                          //b) does not already have a system metadata id in the systemmetadata table
274
                          //c) not a BIN object (data)
275
                            generateMissingSystemMetadata();
276
                            status = true;
277
                        }
278
                        else
308 279
                        {
309
                            objectId = request.getPathInfo().substring(1);
280
                            loadSessionData();
281
                            String objectId = request.getPathInfo();
282
                            if (objectId != null && objectId.length() > 1) 
283
                            {
284
                                objectId = request.getPathInfo().substring(1);
285
                            }
286
                            getSystemMetadataObject(objectId);
287
                            status = true;
310 288
                        }
311
                        getSystemMetadataObject(objectId);
312
                        status = true;
313 289
                            
314 290
                    } else if (resource.equals(RESOURCE_OBJECTS)) {
315 291
                    logMetacat.debug("D1 Rest: Starting resource processing...");
......
383 359
            e.printStackTrace();
384 360
        }
385 361
    }
362
    
363
    /**
364
     *  copies request parameters to a hashtable which is given as argument to native metacathandler functions  
365
     */
366
    private void initParams() {
386 367

  
368
        String name = null;
369
        String[] value = null;
370
        Enumeration paramlist = request.getParameterNames();
371
        while (paramlist.hasMoreElements()) {
372
            name = (String) paramlist.nextElement();
373
            value = request.getParameterValues(name);
374
            //System.out.println("adding param: " + name + " = " + value);
375
            params.put(name, value);
376
        }
377

  
378
    }
379

  
387 380
    /**
388
     *  Earthgrid API > Identifier Service > isRegistered Function : calls MetacatHandler > handleIdIsRegisteredAction
381
     * 
382
     * Load user details of metacat session from the request 
383
     * 
384
     */
385
    private void loadSessionData()
386
      throws Exception
387
    {
388
        SessionData sessionData = RequestUtil.getSessionData(request);
389
        try
390
        {
391
            username = null;
392
            password = null;
393
            groupNames = null;
394
            sessionId = null;
395
            
396
            boolean validSession = false;
397
            SessionService ss = SessionService.getInstance();
398
            //validate the session
399
            if(ss.isSessionRegistered(sessionData.getId()))
400
            {
401
                validSession = true;
402
            }
403
            
404
            if(validSession)
405
            {
406
                //if the session is valid, set these variables
407
                username = sessionData.getUserName();
408
                password = sessionData.getPassword();
409
                groupNames = sessionData.getGroupNames();
410
                sessionId = sessionData.getId();
411
                //System.out.println("setting sessionid to " + sessionId);
412
            }
413
            
414
            //if the session is not valid or the username is null, set
415
            //username to public
416
            if (username == null) 
417
            {
418
                username = "public";
419
            }
420
        }
421
        catch(Exception e)
422
        {
423
            throw new Exception("Could not load the session data: " + e.getMessage());
424
        }
425
    }
426
    
427
    /**
428
     * generate missing system metadata for any science metadata objects
429
     * that don't already have it. https://trac.dataone.org/ticket/591
430
     */
431
    private void generateMissingSystemMetadata()
432
    {
433
        //generate system metadata for any object that is
434
        //a) not system metadata itself
435
        //b) does not already have a system metadata id in the systemmetadata table
436
        //c) not a BIN object (data)
437
        
438
    }
439

  
440
    /**
441
     *  Earthgrid API > Identifier Service > isRegistered Function : 
442
     *  calls MetacatHandler > handleIdIsRegisteredAction
389 443
     * @param guid
390 444
     * @throws IOException
391 445
     */
......
408 462
    }
409 463

  
410 464
    /**
411
     * Earthgrid API > Identifier Service > getAllDocIds Function : calls MetacatHandler > handleGetAllDocidsAction
465
     * Earthgrid API > Identifier Service > getAllDocIds Function : 
466
     * calls MetacatHandler > handleGetAllDocidsAction
412 467
     * @throws IOException
413 468
     */
414 469
    private void getAllDocIds() throws IOException {
......
418 473
    }
419 474

  
420 475
    /**
421
     * Earthgrid API > Identifier Service > getNextRevision Function : calls MetacatHandler > handleGetRevisionAndDocTypeAction
476
     * Earthgrid API > Identifier Service > getNextRevision Function : 
477
     * calls MetacatHandler > handleGetRevisionAndDocTypeAction
422 478
     * @param guid
423 479
     * @throws IOException
424 480
     */
......
467 523
    }
468 524

  
469 525
    /**
470
     * Earthgrid API > Identifier Service > getNextObject Function : calls MetacatHandler > handleGetMaxDocidAction
526
     * Earthgrid API > Identifier Service > getNextObject Function : 
527
     * calls MetacatHandler > handleGetMaxDocidAction
471 528
     * @throws IOException
472 529
     */
473 530
    private void getNextObject() throws IOException {
src/edu/ucsb/nceas/metacat/MetaCatServlet.java
416 416
			System.setProperty("replication.logfile.name", replicationLogPath);			
417 417
			PropertyConfigurator.configureAndWatch(LOG_CONFIG_NAME);
418 418
			
419
			SessionService.unRegisterAllSessions();
419
			SessionService.getInstance().unRegisterAllSessions();
420 420
			
421 421
	         //Initialize Metacat Handler
422 422
            handler = new MetacatHandler(timer);
......
632 632
		// Update the last update time for this user if they are not new
633 633
		HttpSession httpSession = request.getSession(false);
634 634
		if (httpSession != null) {
635
			SessionService.touchSession(httpSession.getId());
635
		    SessionService.getInstance().touchSession(httpSession.getId());
636 636
		}
637 637
		
638 638
		// Each time metacat is called, check to see if metacat has been 
......
788 788
				if (idsToValidate != null) {
789 789
					idToValidate = idsToValidate[0];
790 790
				}
791
				SessionService.validateSession(out, response, idToValidate);
791
				SessionService.getInstance().validateSession(out, response, idToValidate);
792 792
				out.close();
793 793

  
794 794
				// handle shrink DBConnection request
src/edu/ucsb/nceas/metacat/clientview/ClientViewHelper.java
334 334
        }
335 335
        
336 336
        boolean oldLoginValue = result.loggedIn;
337
        result.setLoggedIn(SessionService.validateSession(sessionId));
337
        result.setLoggedIn(SessionService.getInstance().validateSession(sessionId));
338 338
        if (result.isLoggedIn()) {
339
        	SessionData sessionData = SessionService.getRegisteredSession(sessionId);
339
        	SessionData sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
340 340
        	result.setUserName(sessionData.getName());
341 341
        }
342 342
        
src/edu/ucsb/nceas/metacat/PermissionController.java
47 47
import edu.ucsb.nceas.metacat.util.MetacatUtil;
48 48
import edu.ucsb.nceas.metacat.util.SessionData;
49 49
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
50
import edu.ucsb.nceas.metacat.shared.ServiceException;
50 51

  
51 52
public class PermissionController
52 53
{
......
97 98
   }
98 99

  
99 100
   public boolean hasPermission(String sessionId, String myPermission) throws SQLException {
100
	   SessionData sessionData = SessionService.getRegisteredSession(sessionId);
101
	   if (sessionData == null) {
102
		   return false;
103
	   }
101
       SessionData sessionData = null;
102
       sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
103
       if (sessionData == null) {
104
           return false;
105
       }
104 106
	   
105 107
	   return hasPermission(sessionData.getUserName(), sessionData.getGroupNames(), myPermission); 
106 108
   }
src/edu/ucsb/nceas/metacat/MetacatHandler.java
356 356
                    + " which has username" + session.getAttribute("username")
357 357
                    + " into hash in login method");
358 358
            try {
359
                SessionService.registerSession(id, 
359
                SessionService.getInstance().registerSession(id, 
360 360
                        (String) session.getAttribute("username"), 
361 361
                        (String[]) session.getAttribute("groupnames"), 
362 362
                        (String) session.getAttribute("password"), 
......
411 411
                    + sess.getAttribute("username")
412 412
                    + " will be invalidate in logout action");
413 413
            sess.invalidate();
414
            SessionService.unRegisterSession(sess.getId());
414
            SessionService.getInstance().unRegisterSession(sess.getId());
415 415
        }
416 416
        
417 417
        // produce output
src/edu/ucsb/nceas/metacat/service/SessionService.java
82 82
	 * 
83 83
	 * @return the single instance of SessionService
84 84
	 */
85
	public static SessionService getInstance() throws ServiceException {
86
		if (sessionService == null) {
87
			sessionService = new SessionService();
88
		}
89
		return sessionService;
85
	public static SessionService getInstance() {
86
	    try
87
	    {
88
	        if (sessionService == null) {
89
	            sessionService = new SessionService();
90
	        }
91
	        return sessionService;
92
	    }
93
	    catch(ServiceException se)
94
	    {
95
	        logMetacat.error("SessionService.getInstance - could not get " +
96
	                "an instance of SessionService: " + se.getMessage());
97
	    }
98
		return null;
90 99
	}
91 100
	
92 101
	public boolean refreshable() {
......
114 123
	 * @param password
115 124
	 *            the password for the session
116 125
	 */
117
	public static void registerSession(String sessionId, String userName,
126
	public void registerSession(String sessionId, String userName,
118 127
			String[] groupNames, String password, String name) throws ServiceException {
119 128
		synchronized(lockObj) {
120 129
			if (sessionId == null) {
......
134 143
	 * @param sessionData
135 144
	 *            the session data object to add to the session hash
136 145
	 */
137
	public static void registerSession(SessionData sessionData) throws ServiceException {
146
	public void registerSession(SessionData sessionData) throws ServiceException {
138 147
		synchronized(lockObj) {
139 148
			if (sessionData == null) {
140 149
				throw new ServiceException("SessionService.registerSession - " + 
......
152 161
	 * @param sessionId
153 162
	 *            the id of the session to remove.
154 163
	 */
155
	public static void unRegisterSession(String sessionId) {
164
	public void unRegisterSession(String sessionId) {
156 165
		synchronized(lockObj) {
157 166
			if (sessionId == null) {
158 167
				logMetacat.error("SessionService.unRegisterSession - trying to " + 
......
170 179
	 * @param sessionId
171 180
	 *            the id of the session to remove.
172 181
	 */
173
	public static void unRegisterAllSessions() {
182
	public void unRegisterAllSessions() {
174 183
		synchronized(lockObj) {
175 184
			Enumeration<String> keyEnum = sessionHash.keys();
176 185
			while (keyEnum.hasMoreElements()) {
......
189 198
	 * @param sessionId
190 199
	 *            the id of the session to look for.
191 200
	 */
192
	public static boolean isSessionRegistered(String sessionId) {		
201
	public boolean isSessionRegistered(String sessionId) {		
193 202
		if (sessionId == null) {
194 203
			logMetacat.error("SessionService.isSessionRegistered - trying to check if a " + 
195 204
					"session with null id is registered");
......
210 219
	 * @param sessionId
211 220
	 *            the id of the session to look for.
212 221
	 */
213
	public static void validateSession(PrintWriter out, HttpServletResponse response, 
222
	public void validateSession(PrintWriter out, HttpServletResponse response, 
214 223
			String sessionId) {		
215 224
		
216 225
		response.setContentType("text/xml");
......
232 241
	 * @param sessionId
233 242
	 *            the id of the session to look for.
234 243
	 */
235
	public static boolean validateSession(String sessionId) {				
244
	public boolean validateSession(String sessionId) {				
236 245
		if (sessionId != null && !sessionId.equals(PUBLIC_SESSION_ID) && isSessionRegistered(sessionId)) {
237 246
			return true;
238 247
		} else {
......
247 256
	 * @param sessionId
248 257
	 *            the id of the session to retrieve.
249 258
	 */
250
	public static SessionData getRegisteredSession(String sessionId) {
259
	public SessionData getRegisteredSession(String sessionId) {
251 260
		if (sessionId == null) {
252 261
			logMetacat.error("SessionService.getRegisteredSession - trying to get a session with null id");
253 262
			return null;
......
260 269
	/**
261 270
	 * Get the public session from the session hash table. 
262 271
	 */
263
	public static SessionData getPublicSession() {
272
	public SessionData getPublicSession() {
264 273
		return sessionHash.get(PUBLIC_SESSION_ID);
265 274
	}
266 275
	
......
270 279
	 * @param sessionId
271 280
	 *            the id of the session to update.
272 281
	 */
273
	public static synchronized void touchSession(String sessionId) {
282
	public synchronized void touchSession(String sessionId) {
274 283
		if (sessionId == null) {
275 284
			logMetacat.error("SessionService.touchSession - trying to touch a session with null id");
276 285
		} else if (isSessionRegistered(sessionId)) {
......
281 290
		}
282 291
	}
283 292
	
284
	private static void checkTimeout (String sessionId) {
293
	private void checkTimeout (String sessionId) {
285 294
		SessionData sessionData = null;
286 295
		if ((sessionData = sessionHash.get(sessionId)) != null) {
287 296
			Calendar expireTime = Calendar.getInstance();
src/edu/ucsb/nceas/metacat/util/AuthUtil.java
198 198
		String sessionId = session.getId();
199 199
		
200 200
		try {
201
		SessionService.registerSession(sessionId, 
201
		SessionService.getInstance().registerSession(sessionId, 
202 202
				(String) session.getAttribute("username"), 
203 203
				(String[]) session.getAttribute("groupnames"),
204 204
				(String) session.getAttribute("password"),
......
223 223

  
224 224
		try {
225 225

  
226
			if (sessionId != null && SessionService.isSessionRegistered(sessionId)) {
226
			if (sessionId != null && SessionService.getInstance().isSessionRegistered(sessionId)) {
227 227
				// get the registered session data
228
				sessionData = SessionService.getRegisteredSession(sessionId);
228
				sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
229 229

  
230 230
				// get the timeout limit
231 231
				String sessionTimeout = PropertyService.getProperty("auth.timeoutMinutes");
......
240 240
				// if the last accessed time is before now minus the timeout,
241 241
				// the session has expired. Unregister it and return false.
242 242
				if (lastAccessedTime.before(now)) {
243
					SessionService.unRegisterSession(sessionId);
243
					SessionService.getInstance().unRegisterSession(sessionId);
244 244
					return false;
245 245
				}
246 246

  
......
301 301
	 */
302 302
	public static String[] getGroupNames(HttpServletRequest request) {
303 303
		String sessionId = request.getSession().getId();;
304
		SessionData sessionData = SessionService.getRegisteredSession(sessionId);
304
		SessionData sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
305 305
		String[] groupNames = { "" };
306 306

  
307 307
		if (sessionData != null) {
src/edu/ucsb/nceas/metacat/util/RequestUtil.java
297 297

  
298 298
		// if the session id is registered in SessionService, get the
299 299
		// SessionData for it. Otherwise, use the public session.
300
		if (SessionService.isSessionRegistered(sessionId)) {
300
		if (SessionService.getInstance().isSessionRegistered(sessionId)) {
301 301
			logMetacat.debug("retrieving session data from session service "
302 302
					+ "for session id " + sessionId);
303
			sessionData = SessionService.getRegisteredSession(sessionId);
303
			sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
304 304
		} else {
305 305
			logMetacat.debug("using public session.  Given session id is "
306 306
					+ "registered: " + sessionId);
307
			sessionData = SessionService.getPublicSession();
307
			sessionData = SessionService.getInstance().getPublicSession();
308 308
		}
309 309
		
310 310
		return sessionData;
src/edu/ucsb/nceas/metacat/util/DocumentUtil.java
470 470
    	result += "<permission>" + permission + "</permission>";
471 471
    	result += "<sessionId>" + sessionId + "</sessionId>";
472 472

  
473
    	if (!SessionService.isSessionRegistered(sessionId)) {
473
    	if (!SessionService.getInstance().isSessionRegistered(sessionId)) {
474 474
    		message = "Session is not logged in";
475 475
    	} else {
476
    		SessionData sessionData = SessionService.getRegisteredSession(sessionId);
476
    		SessionData sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
477 477
    		
478 478
    		String docId = null;
479 479
    		try {
src/edu/ucsb/nceas/metacat/cart/CartManager.java
56 56
	}
57 57
	
58 58
	private void init() {
59
		documentCart = SessionService.getRegisteredSession(sessionId).getDocumentCart();
59
		documentCart = SessionService.getInstance().getRegisteredSession(sessionId).getDocumentCart();
60 60
		if (documentCart == null) {
61 61
			documentCart = new DocumentCart();
62 62
		}
......
95 95
			}
96 96
		}
97 97
		
98
		SessionService.getRegisteredSession(sessionId).setDocumentCart(documentCart);
98
		SessionService.getInstance().getRegisteredSession(sessionId).setDocumentCart(documentCart);
99 99
	}
100 100

  
101 101
}
src/edu/ucsb/nceas/metacat/dataone/CrudService.java
696 696
        
697 697
        // if the session id is registered in SessionService, get the
698 698
        // SessionData for it. Otherwise, use the public session.
699
        if (SessionService.isSessionRegistered(sessionId)) {
700
            sessionData = SessionService.getRegisteredSession(sessionId);
699
        if (SessionService.getInstance().isSessionRegistered(sessionId)) {
700
            sessionData = SessionService.getInstance().getRegisteredSession(sessionId);
701 701
        } else {
702
            sessionData = SessionService.getPublicSession();
702
            sessionData = SessionService.getInstance().getPublicSession();
703 703
        }
704 704
        
705 705
        return sessionData;
src/edu/ucsb/nceas/metacat/admin/MetacatAdminServlet.java
100 100
			// Update the last update time for this user if they are not new
101 101
			HttpSession httpSession = request.getSession(false);
102 102
			if (httpSession != null) {
103
				SessionService.touchSession(httpSession.getId());
103
				SessionService.getInstance().touchSession(httpSession.getId());
104 104
			}
105 105
			
106 106
			if (!ConfigurationUtil.isBackupDirConfigured()) {
src/edu/ucsb/nceas/metacat/replication/ReplicationServlet.java
126 126
				if (params.containsKey("sessionid")) {
127 127
					sess_id = ((String[]) params.get("sessionid"))[0];
128 128
					logReplication.info("ReplicationServlet.handleGetOrPost - in has sessionid " + sess_id);
129
					if (SessionService.isSessionRegistered(sess_id)) {
129
					if (SessionService.getInstance().isSessionRegistered(sess_id)) {
130 130
						logReplication.info("ReplicationServlet.handleGetOrPost - find the id " + sess_id + " in hash table");
131
						sessionData = SessionService.getRegisteredSession(sess_id);
131
						sessionData = SessionService.getInstance().getRegisteredSession(sess_id);
132 132
					}
133 133
				}
134 134
				if (sessionData == null) {

Also available in: Unified diff