ThreadContext class to handle arbitrary threads in XPages context


public class ThreadContext {
		private final String dbpath;
		private final NSFComponentModule module;
		private final String servername;
		private final String username;

		public ThreadContext(String username, String servername, String dpath, NSFComponentModule module) {
			this.username = username;
			this.servername = servername;
			this.dbpath = dpath;
			this.module = module;
		}

		public lotus.domino.Database getContextDatabase() {
			try {
				getSessionAsUser().getDatabase(this.servername, this.dbpath);
			} catch (Throwable t) {
				t.printStackTrace();
			}
			return null;
		}

		public lotus.domino.Session getSessionAsUser() {
			NotesContext nc = new NotesContext(this.module);
			NotesContext.initThread(nc);
			try {
				long hList = com.ibm.domino.napi.c.NotesUtil.createUserNameList(username);
				return XSPNative.createXPageSession(username, hList, true, false);
			} catch (Throwable t) {
				t.printStackTrace();
			}
			return null;
		}

		public void initClassLoader(Thread t) {
			t.setContextClassLoader(this.module.getModuleClassLoader());
		}
	}
All code submitted to OpenNTF XSnippets, whether submitted as a "Snippet" or in the body of a Comment, is provided under the Apache License Version 2.0. See Terms of Use for full details.
1 comment(s)Login first to comment...
Karsten Lehmann
(at 04:21 on 26.02.2014)
As discussed in the OpenNTF API skype chat, the hList handle must be disposed after the session is recycled, otherwise it may lead to a server crash when running out of handles;

long hList = NotesUtil.createUserNameList(ContextInfo.getUserSession().getUserName());
Session sessionAsUser = XSPNative.createXPageSession(username, hList, true, false);
//... use sessionAsUser
sessionAsUser.recycle();
//free up handle
com.ibm.domino.napi.c.Os.OSUnlock(hList);
com.ibm.domino.napi.c.Os.OSMemFree(hList);