下面列出了javax.servlet.http.HttpSessionContext#org.apache.openejb.loader.SystemInstance 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testConfigureApplicationWebModule() throws OpenEJBException {
SystemInstance.get().setProperty("openejb.environment.default", "false");
final String moduleId = "testConfigureApplicationWebModule";
final String fileSeparator = System.getProperty("file.separator");
SystemInstance.get().setProperty(ConfigurationFactory.VALIDATION_SKIP_PROPERTY, "false");
SystemInstance.get().setProperty(DeploymentsResolver.SEARCH_CLASSPATH_FOR_DEPLOYMENTS_PROPERTY, "false");
final ConfigurationFactory factory = new ConfigurationFactory();
final WebApp webApp = new WebApp();
// no real classes engaged so disable metadata (annotation) processing
webApp.setMetadataComplete(true);
final WebModule webModule = new WebModule(webApp, null, null, fileSeparator + "some" + fileSeparator + "where.war", moduleId);
final WebAppInfo info = factory.configureApplication(webModule);
assertEquals(moduleId, info.moduleId);
SystemInstance.get().getProperties().remove("openejb.environment.default");
}
@Test
public void run() {
assertNotNull(SystemInstance.get().getComponent(Assembler.class));
assertEquals("val", SystemInstance.get().getProperty("simple"));
assertEquals("set", SystemInstance.get().getProperty("t"));
assertEquals("p", SystemInstance.get().getProperty("prog"));
assertEquals("128463", SystemInstance.get().getProperty("my.server.port"));
assertEquals("true", SystemInstance.get().getProperty("configurer"));
assertNotEquals(8080, app.port);
assertTrue(app.base.toExternalForm().endsWith("/app"));
assertEquals(app.port, port);
assertNotNull(app.task);
assertNotNull(app.tasks);
assertEquals(1, app.tasks.size());
assertEquals(app.task, app.tasks.iterator().next());
assertEquals(app.task, MyTask.instance);
assertNotNull(app.custom);
}
@Test
public void testRollback() throws Exception {
SystemInstance.init(new Properties());
final BeanContext cdi = new BeanContext("foo", null, new ModuleContext("foo", null, "bar", new AppContext("foo", SystemInstance.get(), null, null, null, false), null, null), Object.class, null, new HashMap<>());
cdi.addApplicationException(AE1.class, true, true);
cdi.addApplicationException(AE3.class, true, false);
cdi.addApplicationException(AE6.class, false, true);
assertEquals(ExceptionType.APPLICATION_ROLLBACK, cdi.getExceptionType(new AE1()));
assertEquals(ExceptionType.APPLICATION_ROLLBACK, cdi.getExceptionType(new AE2()));
assertEquals(ExceptionType.APPLICATION_ROLLBACK, cdi.getExceptionType(new AE3()));
assertEquals(ExceptionType.SYSTEM, cdi.getExceptionType(new AE4()));
assertEquals(ExceptionType.SYSTEM, cdi.getExceptionType(new AE5()));
assertEquals(ExceptionType.APPLICATION, cdi.getExceptionType(new AE6()));
assertEquals(ExceptionType.APPLICATION, cdi.getExceptionType(new AE7()));
}
/**
* lookup datasource in openejb resources
*/
private void init() {
dataSources = new ConcurrentHashMap<>();
for (final String ds : dataSourceNames.split(" ")) {
final ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class);
Object o = null;
final Context ctx = containerSystem.getJNDIContext();
try {
o = ctx.lookup("openejb:Resource/" + ds);
if (o instanceof DataSource) {
dataSources.put(ds, (DataSource) o);
}
} catch (final NamingException e) {
}
}
}
@Override
public Object getObjectInstance(final Object object, final Name name, final Context context, final Hashtable environment) throws Exception {
// get the transaction manager
final TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
if (transactionManager == null) {
throw new NamingException("transaction manager not found");
}
// if transaction manager implements user transaction we are done
if (transactionManager instanceof UserTransaction) {
return transactionManager;
}
// wrap transaction manager with user transaction
return new CoreUserTransaction(transactionManager);
}
public synchronized void initAdditionalRepos() {
if (additionalRepos != null) {
return;
}
if (CONTEXT.get() != null) {
additionalRepos = new LinkedList<>();
final String contextPath = CONTEXT.get().getServletContext().getContextPath();
final String name = contextPath.isEmpty() ? "ROOT" : contextPath.substring(1);
final String externalRepositories = SystemInstance.get().getProperty("tomee." + name + ".externalRepositories");
if (externalRepositories != null) {
for (final String additional : externalRepositories.split(",")) {
final String trim = additional.trim();
if (!trim.isEmpty()) {
final File file = new File(trim);
additionalRepos.add(file);
}
}
}
}
}
@SuppressWarnings("UseOfObsoleteCollectionType")
private void initializeOpenEJB(final Hashtable env) throws javax.naming.NamingException {
try {
final Properties props = new Properties();
/* DMB: We should get the defaults from the functionality
* Alan is working on. This is temporary.
* When that logic is finished, this block should
* probably just be deleted.
*/
props.put(EnvProps.ASSEMBLER, "org.apache.openejb.assembler.classic.Assembler");
props.put(EnvProps.CONFIGURATION_FACTORY, "org.apache.openejb.config.ConfigurationFactory");
props.put(EnvProps.CONFIGURATION, "conf/default.openejb.conf");
props.putAll(SystemInstance.get().getProperties());
props.putAll(env);
OpenEJB.init(props);
} catch (final Exception e) {
throw new NamingException("Cannot initailize OpenEJB", e);
}
}
private void initializeDependencies(final BeanContext beanContext) throws OpenEJBException {
final SystemInstance systemInstance = SystemInstance.get();
final ContainerSystem containerSystem = systemInstance.getComponent(ContainerSystem.class);
for (final String dependencyId : beanContext.getDependsOn()) {
final BeanContext dependencyContext = containerSystem.getBeanContext(dependencyId);
if (dependencyContext == null) {
throw new OpenEJBException("Deployment does not exist. Deployment(id='" + dependencyContext + "')");
}
final Object containerData = dependencyContext.getContainerData();
// Bean may not be a singleton or may be a singleton
// managed by a different container implementation
if (containerData instanceof Data) {
final Data data = (Data) containerData;
data.initialize();
}
}
}
private void manageCluster(final Cluster cluster) {
if (cluster == null || cluster instanceof SimpleTomEETcpCluster) {
return;
}
Cluster current = cluster;
if (cluster instanceof SimpleTcpCluster) {
final Container container = cluster.getContainer();
current = new SimpleTomEETcpCluster((SimpleTcpCluster) cluster);
container.setCluster(current);
}
if (current instanceof CatalinaCluster) {
final CatalinaCluster haCluster = (CatalinaCluster) current;
TomEEClusterListener listener = SystemInstance.get().getComponent(TomEEClusterListener.class);
if (listener == null) {
listener = new TomEEClusterListener();
SystemInstance.get().setComponent(TomEEClusterListener.class, listener);
}
haCluster.addClusterListener(listener); // better to be a singleton
clusters.add(haCluster);
}
}
private static URL select(final Enumeration<URL> enumeration) {
if (enumeration == null) {
return null;
}
final ArrayList<URL> urls = Collections.list(enumeration);
if (urls.size() == 0) {
return null;
}
if (urls.size() == 1) {
return urls.get(0);
}
// Sort so that the URL closest to openejb.base is first
urls.sort(new UrlComparator(SystemInstance.get().getBase().getDirectory()));
return urls.get(0);
}
@Override
public boolean login() throws LoginException {
assertNull(SystemInstance.get().getComponent(SecurityService.class).currentState()); // check the user was not logged at lookup()
final NameCallback nameCallback = new NameCallback("name?", "dummy");
try {
callbackHandler.handle(new Callback[]{nameCallback});
} catch (final Exception e) {
throw new LoginException(e.getMessage());
}
if (!"foo".equals(nameCallback.getName())) {
throw new IllegalArgumentException("Not an Error/assert cause in java 9 jaas doesnt capture it anymore");
}
RemoteWithSecurity.name.set(nameCallback.getName());
return true;
}
private Set<Class<?>> getJsfClasses(final Context context) {
final WebAppBuilder builder = SystemInstance.get().getComponent(WebAppBuilder.class);
final ClassLoader cl = context.getLoader().getClassLoader();
final Map<String, Set<String>> scanned = builder.getJsfClasses().get(cl);
if (scanned == null || scanned.isEmpty()) {
return null;
}
final Set<Class<?>> classes = new HashSet<>();
for (final Set<String> entry : scanned.values()) {
for (final String name : entry) {
try {
classes.add(cl.loadClass(name));
} catch (final ClassNotFoundException ignored) {
logger.warning("class '" + name + "' was found but can't be loaded as a JSF class");
}
}
}
return classes;
}
private String findAnyConnectionFactory() {
final OpenEjbConfiguration component = SystemInstance.get().getComponent(OpenEjbConfiguration.class);
if (component != null && component.facilities != null) {
for (final ResourceInfo ri : component.facilities.resources) {
if (ri.types.contains("javax.jms.ConnectionFactory")) {
return ri.id;
}
}
// try the default one
return "DefaultJMSConnectionFactory";
}
// something is wrong, just fail
throw new IllegalArgumentException(
"No connection factory found, either use @JMSConnectionFactory JMSContext or define a connection factory");
}
/**
* OPENEJB-1555
*
* @throws Exception
*/
@Test
public void testSystemProperty() throws Exception {
final Map<String, String> map = new HashMap<>();
map.put("META-INF/ejb-jar.xml", "<ejb-jar id=\"orangeId\"><module-name>orangeName</module-name></ejb-jar>");
final File file = Archives.jarArchive(map, "test", OrangeBean.class);
final Assembler assembler = new Assembler();
final ConfigurationFactory factory = new ConfigurationFactory();
SystemInstance.get().setProperty(file.getName() + ".moduleId", "orangeSystem");
final AppInfo appInfo = factory.configureApplication(file);
final EjbJarInfo ejbJarInfo = appInfo.ejbJars.get(0);
assertEquals("orangeSystem", ejbJarInfo.moduleName);
}
public InputStream resolve(final String rawLocation) {
final boolean initialized = SystemInstance.isInitialized();
final String MVN_JNDI_PREFIX = "mvn:";
if (!initialized) {
SystemInstance.get().setComponent(ProvisioningResolver.class, new ProvisioningResolver());
}
try {
if (rawLocation.startsWith(MVN_JNDI_PREFIX) && rawLocation.length() > MVN_JNDI_PREFIX.length()) {
try {
return new FileInputStream(ShrinkwrapBridge.resolve(rawLocation));
} catch (final Throwable th) {
// try aether if not in a mvn build
th.printStackTrace();
}
}
return super.resolve(rawLocation);
} finally {
if (!initialized) {
SystemInstance.reset();
}
}
}
private void switchServletContextIfNeeded(final ServletContext sc, final Runnable runnable) {
if (sc == null) {
runnable.run();
return;
}
final SystemInstance systemInstance = SystemInstance.get();
final ServletContext old = systemInstance.getComponent(ServletContext.class);
systemInstance.setComponent(ServletContext.class, sc);
try {
runnable.run();
} finally {
if (old == null) {
systemInstance.removeComponent(ServletContext.class);
} else {
systemInstance.setComponent(ServletContext.class, old);
}
}
}
private void addMandatoryProviders(final Collection<Object> instances, final ServiceConfiguration serviceConfiguration) {
if (SystemInstance.get().getProperty("openejb.jaxrs.jsonProviders") == null) {
if (!shouldSkipProvider(WadlDocumentMessageBodyWriter.class.getName())) {
instances.add(new WadlDocumentMessageBodyWriter());
}
}
if (!shouldSkipProvider(EJBExceptionMapper.class.getName())) {
instances.add(new EJBExceptionMapper());
}
if (!shouldSkipProvider(ValidationExceptionMapper.class.getName())) {
instances.add(new ValidationExceptionMapper());
final String level = SystemInstance.get()
.getProperty(
"openejb.cxf.rs.bval.log.level",
serviceConfiguration.getProperties().getProperty(CXF_JAXRS_PREFIX + "bval.log.level"));
if (level != null) {
try {
LogUtils.getL7dLogger(ValidationExceptionMapper.class).setLevel(Level.parse(level));
} catch (final UnsupportedOperationException uoe) {
LOGGER.warning("Can't set level " + level + " on " +
"org.apache.cxf.jaxrs.validation.ValidationExceptionMapper logger, " +
"please configure it in your logging framework.");
}
}
}
}
@Test
public void run() {
try (final Container container = new Container(new Configuration().conf("ConfTest"))) {
final StandardServer standardServer = TomcatHelper.getServer();
final Realm engineRealm = standardServer.findServices()[0].getContainer().getRealm();
assertTrue(String.valueOf(engineRealm), TomEERealm.class.isInstance(engineRealm));
assertTrue(String.valueOf(engineRealm), JAASRealm.class.isInstance(TomEERealm.class.cast(engineRealm).getNestedRealms()[0]));
final JAASRealm jaas = JAASRealm.class.cast(TomEERealm.class.cast(engineRealm).getNestedRealms()[0]);
assertEquals("PropertiesLoginModule", jaas.getAppName());
assertEquals("org.apache.openejb.core.security.jaas.UserPrincipal", jaas.getUserClassNames());
assertEquals("org.apache.openejb.core.security.jaas.GroupPrincipal", jaas.getRoleClassNames());
assertEquals("test", SystemInstance.get().getProperty("ConfTest.value"));
}
}
private BeanContext createDeployment(final Class<?> testClass) {
try {
final AppContext appContext = new AppContext("", SystemInstance.get(), testClass.getClassLoader(), new IvmContext(), new IvmContext(), false);
final ModuleContext moduleContext = new ModuleContext("", null, "", appContext, new IvmContext(), null);
return new BeanContext(null, new IvmContext(), moduleContext, testClass, null, null, null, null, null, null, null, null, null, BeanType.MANAGED, false, false);
} catch (final SystemException e) {
throw new IllegalStateException(e);
}
}
@Override
protected void setUp() throws Exception {
SystemInstance.reset();
try { // hack for buildbot
new ConfigurationImpl(null, null);
} catch (final ValidationException ve) {
// no-op
}
}
public static void registerContainerAboutLogin(final Principal principal, final Set<String> groups) {
final SecurityService securityService = SystemInstance.get().getComponent(SecurityService.class);
if (TomcatSecurityService.class.isInstance(securityService)) {
final TomcatSecurityService tomcatSecurityService = (TomcatSecurityService) securityService;
final Request request = OpenEJBSecurityListener.requests.get();
final GenericPrincipal genericPrincipal =
new GenericPrincipal(principal.getName(), null, new ArrayList<>(groups), principal);
tomcatSecurityService.enterWebApp(request.getWrapper().getRealm(),
genericPrincipal,
request.getWrapper().getRunAs());
}
}
@Override
public void init(final Properties props) throws Exception {
// Install the Tomcat webservice registry
final SystemInstance system = SystemInstance.get();
TomcatWsRegistry tomcatSoapHandler = (TomcatWsRegistry) system.getComponent(WsRegistry.class);
if (tomcatSoapHandler == null) {
tomcatSoapHandler = new TomcatWsRegistry();
system.setComponent(WsRegistry.class, tomcatSoapHandler);
}
system.addObserver(this);
}
public void testBusinessLocalInterfaceInTx() throws Exception {
final TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
transactionManager.begin();
try {
testBusinessLocalInterface(inTxExpectedLifecycle);
} finally {
transactionManager.commit();
}
}
public static ManagedThreadFactory findThreadFactory(final String threadFactory)
throws InstantiationException, IllegalAccessException, NamingException {
try {
final Class<?> aClass = Thread.currentThread().getContextClassLoader().loadClass(threadFactory);
if (!ManagedThreadFactory.class.isAssignableFrom(aClass) && ThreadFactory.class.isAssignableFrom(aClass)) {
return new ManageMyThreadFactory(ThreadFactory.class.cast(aClass.newInstance()));
}
return ManagedThreadFactory.class.cast(aClass.newInstance());
} catch (final ClassNotFoundException e) {
return ManagedThreadFactory.class.cast(SystemInstance.get().getComponent(ContainerSystem.class)
.getJNDIContext().lookup("openejb:Resource/" + threadFactory));
}
}
@Override
public DataSource managed(final String name, final CommonDataSource ds) {
final TransactionManager transactionManager = OpenEJB.getTransactionManager();
if (ds instanceof XADataSource) {
return new ManagedXADataSource(ds, transactionManager, SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class));
}
return new ManagedDataSource(DataSource.class.cast(ds), transactionManager, SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class));
}
public void testAppContextOptions() throws Exception {
final ConfigurationFactory config = new ConfigurationFactory();
final Assembler assembler = new Assembler();
{
assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
assembler.createSecurityService(config.configureService(SecurityServiceInfo.class));
}
{
// Setup the descriptor information
final EjbModule ejbModule = new EjbModule(new EjbJar(), new OpenejbJar());
final EjbJar ejbJar = ejbModule.getEjbJar();
ejbJar.addEnterpriseBean(new StatelessBean(WidgetBean.class));
final AppModule appModule = new AppModule(ejbModule);
appModule.getProperties().setProperty("color", "orange");
assembler.createApplication(config.configureApplication(appModule));
}
final ContainerSystem containerSystem = SystemInstance.get().getComponent(ContainerSystem.class);
final BeanContext beanContext = containerSystem.getBeanContext("WidgetBean");
assertOption(beanContext.getOptions(), "color", "orange");
assertOption(beanContext.getModuleContext().getOptions(), "color", "orange");
assertOption(beanContext.getModuleContext().getAppContext().getOptions(), "color", "orange");
}
@Override
public synchronized void shutdown(final boolean waitForJobsToComplete) {
if (threadPoolExecutorUsed) {
final SystemInstance systemInstance = SystemInstance.get();
final TimerExecutor te = systemInstance.getComponent(TimerExecutor.class);
if (te != null) {
if (te.executor == executor) {
if (te.decr()) {
doShutdownExecutor(waitForJobsToComplete);
systemInstance.removeComponent(TimerExecutor.class);
} else { // flush jobs, maybe not all dedicated to this threadpool if shared but shouldn't be an issue
final ThreadPoolExecutor tpe = ThreadPoolExecutor.class.cast(executor);
if (waitForJobsToComplete) {
final Collection<Runnable> jobs = new ArrayList<>();
tpe.getQueue().drainTo(jobs);
for (final Runnable r : jobs) {
try {
r.run();
} catch (final Exception e) {
logger.warning(e.getMessage(), e);
}
}
}
}
} else {
doShutdownExecutor(waitForJobsToComplete);
}
} else {
doShutdownExecutor(waitForJobsToComplete);
}
}
}
@Test
public void testOverrideFromContainerDefinedInAppModule() throws Exception {
SystemInstance.reset();
final Assembler assembler = new Assembler();
final ConfigurationFactory config = new ConfigurationFactory();
assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
assembler.createSecurityService(config.configureService(SecurityServiceInfo.class));
final EjbJar ejbJar = new EjbJar();
ejbJar.addEnterpriseBean(new MessageDrivenBean("Yellow", Orange.class));
ejbJar.addEnterpriseBean(new MessageDrivenBean("Orange", Yellow.class));
final AppModule appModule = new AppModule(new EjbModule(ejbJar));
appModule.setModuleId("mymodule");
final Container container = new Container();
container.setId("mycontainer");
container.setCtype("MESSAGE");
container.getProperties().setProperty("activation.DeliveryActive", "false");
appModule.getContainers().add(container);
final AppInfo appInfo = config.configureApplication(appModule);
assertEquals(1, appInfo.ejbJars.size());
final EjbJarInfo ejbJarInfo = appInfo.ejbJars.get(0);
assertEquals(2, ejbJarInfo.enterpriseBeans.size());
final MessageDrivenBeanInfo orange = (MessageDrivenBeanInfo) ejbJarInfo.enterpriseBeans.get(0);
final MessageDrivenBeanInfo yellow = (MessageDrivenBeanInfo) ejbJarInfo.enterpriseBeans.get(1);
assertEquals("false", orange.activationProperties.get("DeliveryActive"));
assertEquals("false", yellow.activationProperties.get("DeliveryActive"));
}
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
final SystemInstance si = SystemInstance.isInitialized() ? SystemInstance.get() : null;
final Properties config = si != null ? si.getProperties() : System.getProperties();
securityService = si != null ? si.getComponent(SecurityService.class) : null;
active = Boolean.parseBoolean(config.getProperty("tomee.http.request.wrap", "true"));
}
@Override
public void stop() throws ServiceException {
if (assembler != null) {
SystemInstance.get().removeObserver(this);
for (final AppInfo appInfo : new ArrayList<>(deployedApplications.keySet())) {
undeploy(new AssemblerBeforeApplicationDestroyed(appInfo, null));
}
assembler = null;
if (SystemInstance.get().getComponent(WsService.class) == this) {
SystemInstance.get().removeComponent(WsService.class);
}
}
}