Example usage for org.springframework.context.support StaticApplicationContext StaticApplicationContext

List of usage examples for org.springframework.context.support StaticApplicationContext StaticApplicationContext

Introduction

In this page you can find the example usage for org.springframework.context.support StaticApplicationContext StaticApplicationContext.

Prototype

public StaticApplicationContext() throws BeansException 

Source Link

Document

Create a new StaticApplicationContext.

Usage

From source file:org.marketcetera.client.ClientImpl.java

private void connect() throws ConnectionException {
    if (mParameters.getURL() == null || mParameters.getURL().trim().isEmpty()) {
        throw new ConnectionException(Messages.CONNECT_ERROR_NO_URL);
    }//from  www .ja  v a2s .co  m
    if (mParameters.getUsername() == null || mParameters.getUsername().trim().isEmpty()) {
        throw new ConnectionException(Messages.CONNECT_ERROR_NO_USERNAME);
    }
    if (mParameters.getHostname() == null || mParameters.getHostname().trim().isEmpty()) {
        throw new ConnectionException(Messages.CONNECT_ERROR_NO_HOSTNAME);
    }
    if (mParameters.getPort() < 1 || mParameters.getPort() > 0xFFFF) {
        throw new ConnectionException(
                new I18NBoundMessage1P(Messages.CONNECT_ERROR_INVALID_PORT, mParameters.getPort()));
    }
    try {
        StaticApplicationContext parentCtx = new StaticApplicationContext();
        SpringUtils.addStringBean(parentCtx, "brokerURL", //$NON-NLS-1$
                mParameters.getURL());
        SpringUtils.addStringBean(parentCtx, "runtimeUsername", mParameters.getUsername()); //$NON-NLS-1$
        SpringUtils.addStringBean(parentCtx, "runtimePassword", mParameters == null //$NON-NLS-1$
                ? null
                : String.valueOf(mParameters.getPassword()));
        parentCtx.refresh();
        AbstractApplicationContext ctx;
        try {
            ctx = new FileSystemXmlApplicationContext(
                    new String[] { "file:" + ApplicationBase.CONF_DIR + "client.xml" }, //$NON-NLS-1$
                    parentCtx);
        } catch (BeansException e) {
            ctx = new ClassPathXmlApplicationContext(new String[] { "client.xml" }, //$NON-NLS-1$
                    parentCtx);
        }
        ctx.registerShutdownHook();
        ctx.start();
        setContext(ctx);
        SpringConfig cfg = SpringConfig.getSingleton();
        if (cfg == null) {
            throw new ConnectionException(Messages.CONNECT_ERROR_NO_CONFIGURATION);
        }

        mServiceClient = new org.marketcetera.util.ws.stateful.Client(mParameters.getHostname(),
                mParameters.getPort(), ClientVersion.APP_ID);
        mServiceClient.login(mParameters.getUsername(), mParameters.getPassword());
        mService = mServiceClient.getService(Service.class);

        mJmsMgr = new JmsManager(cfg.getIncomingConnectionFactory(), cfg.getOutgoingConnectionFactory(), this);
        startJms();
        mServerAlive = true;
        notifyServerStatus(true);

        mHeart = new Heart();
        mHeart.start();

        ClientIDFactory idFactory = new ClientIDFactory(mParameters.getIDPrefix(), this);
        idFactory.init();
        Factory.getInstance().setOrderIDFactory(idFactory);
    } catch (Throwable t) {
        internalClose();
        ExceptUtils.interrupt(t);
        if (t.getCause() instanceof RemoteProxyException) {
            RemoteProxyException ex = (RemoteProxyException) t.getCause();
            if (IncompatibleComponentsException.class.getName().equals(ex.getServerName())) {
                throw new ConnectionException(t,
                        new I18NBoundMessage1P(Messages.ERROR_CONNECT_INCOMPATIBLE_DEDUCED, ex.getMessage()));
            }
        } else if (t.getCause() instanceof IncompatibleComponentsException) {
            IncompatibleComponentsException ex = (IncompatibleComponentsException) t.getCause();
            throw new ConnectionException(t, new I18NBoundMessage2P(Messages.ERROR_CONNECT_INCOMPATIBLE_DIRECT,
                    ClientVersion.APP_ID, ex.getServerVersion()));
        }
        throw new ConnectionException(t,
                new I18NBoundMessage4P(Messages.ERROR_CONNECT_TO_SERVER, mParameters.getURL(),
                        mParameters.getUsername(), mParameters.getHostname(), mParameters.getPort()));
    }
    mLastConnectTime = new Date();
}

From source file:org.marketcetera.strategyagent.StrategyAgent.java

/**
 * Configures the agent. Initializes the spring configuration to get
 * a properly configured module manager instance.
 *//*from  w  w w  .  java  2  s.c  om*/
private void configure() {
    File modulesDir = new File(APP_DIR, "modules"); //$NON-NLS-1$
    StaticApplicationContext parentCtx = new StaticApplicationContext();
    //Provide the module jar directory path to the spring context.
    SpringUtils.addStringBean(parentCtx, "modulesDir", //$NON-NLS-1$
            modulesDir.getAbsolutePath());
    parentCtx.refresh();
    mContext = new ClassPathXmlApplicationContext(new String[] { "modules.xml" }, parentCtx); //$NON-NLS-1$
    mContext.registerShutdownHook();
    mManager = (ModuleManager) mContext.getBean("moduleManager", //$NON-NLS-1$
            ModuleManager.class);
    //Set the context classloader to the jar classloader so that
    //all modules have the thread context classloader set to the same
    //value as the classloader that loaded them.
    ClassLoader loader = (ClassLoader) mContext.getBean("moduleLoader", //$NON-NLS-1$
            ClassLoader.class);
    Thread.currentThread().setContextClassLoader(loader);

    //Setup the WS services after setting up the context class loader.
    String hostname = (String) mContext.getBean("wsServerHost"); //$NON-NLS-1$
    if (hostname != null && !hostname.trim().isEmpty()) {
        int port = (Integer) mContext.getBean("wsServerPort"); //$NON-NLS-1$
        SessionManager<ClientSession> sessionManager = new SessionManager<ClientSession>(
                new ClientSessionFactory(), SessionManager.INFINITE_SESSION_LIFESPAN);
        mServer = new Server<ClientSession>(hostname, port, new Authenticator() {
            @Override
            public boolean shouldAllow(StatelessClientContext context, String user, char[] password)
                    throws I18NException {
                return authenticate(context, user, password);
            }
        }, sessionManager, contextClasses);
        mRemoteService = mServer.publish(new SAServiceImpl(sessionManager, mManager, dataPublisher),
                SAService.class);
        //Register a shutdown task to shutdown the remote service.
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                stopRemoteService();
            }
        });
        Messages.LOG_REMOTE_WS_CONFIGURED.info(this, hostname, String.valueOf(port));
    }
}

From source file:org.springframework.aop.target.CommonsPoolTargetSourceTests.java

private void prepareTargetSource(CommonsPoolTargetSource targetSource) {
    String beanName = "target";

    StaticApplicationContext applicationContext = new StaticApplicationContext();
    applicationContext.registerPrototype(beanName, SerializablePerson.class);

    targetSource.setTargetBeanName(beanName);
    targetSource.setBeanFactory(applicationContext);
}

From source file:org.springframework.integration.handler.ExpressionEvaluatingMessageProcessorTests.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test//from   www .  ja  va 2 s  .  c o m
public void testProcessMessageWithBeanAsMethodArgument() throws Exception {
    StaticApplicationContext context = new StaticApplicationContext();
    BeanDefinition beanDefinition = new RootBeanDefinition(String.class);
    beanDefinition.getConstructorArgumentValues().addGenericArgumentValue("bar");
    context.registerBeanDefinition("testString", beanDefinition);
    context.registerBeanDefinition(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME,
            new RootBeanDefinition(IntegrationEvaluationContextFactoryBean.class));
    Expression expression = expressionParser.parseExpression("payload.concat(@testString)");
    ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor(expression);
    processor.setBeanFactory(context);
    processor.afterPropertiesSet();
    GenericMessage<String> message = new GenericMessage<String>("foo");
    assertEquals("foobar", processor.processMessage(message));
}

From source file:org.springframework.integration.handler.ExpressionEvaluatingMessageProcessorTests.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test/*from  www. j a v  a  2s .  c om*/
public void testProcessMessageWithMethodCallOnBean() throws Exception {
    StaticApplicationContext context = new StaticApplicationContext();
    BeanDefinition beanDefinition = new RootBeanDefinition(String.class);
    beanDefinition.getConstructorArgumentValues().addGenericArgumentValue("bar");
    context.registerBeanDefinition(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME,
            new RootBeanDefinition(IntegrationEvaluationContextFactoryBean.class));
    context.registerBeanDefinition("testString", beanDefinition);
    Expression expression = expressionParser.parseExpression("@testString.concat(payload)");
    ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor(expression);
    processor.setBeanFactory(context);
    processor.afterPropertiesSet();
    GenericMessage<String> message = new GenericMessage<String>("foo");
    assertEquals("barfoo", processor.processMessage(message));
}

From source file:org.springframework.integration.jms.SubscribableJmsChannelTests.java

@Test
public void contextManagesLifecycle() {
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(JmsChannelFactoryBean.class);
    builder.addConstructorArgValue(true);
    builder.addPropertyValue("connectionFactory", this.connectionFactory);
    builder.addPropertyValue("destinationName", "dynamicQueue");
    builder.addPropertyValue("pubSubDomain", false);
    StaticApplicationContext context = new StaticApplicationContext();
    context.registerBeanDefinition("channel", builder.getBeanDefinition());
    SubscribableJmsChannel channel = context.getBean("channel", SubscribableJmsChannel.class);
    assertFalse(channel.isRunning());//from w w  w .j av  a 2s.c  o  m
    context.refresh();
    assertTrue(channel.isRunning());
    context.stop();
    assertFalse(channel.isRunning());
    context.close();
}

From source file:org.springframework.richclient.test.SpringRichTestCase.java

/**
  * returns the application context to use for testing
  * //from  w w  w  .  ja  v  a 2 s  . com
  * overwrite to specify a different application context
  * 
  * @return this implementation returns an instance of StaticApplicationContext
  */
protected ConfigurableApplicationContext createApplicationContext() {
    return new StaticApplicationContext();
}

From source file:org.springframework.ws.transport.http.CommonsHttpMessageSenderIntegrationTest.java

@Test
public void testContextClose() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    int port = FreePortScanner.getFreePort();
    Server jettyServer = new Server(port);
    Context jettyContext = new Context(jettyServer, "/");
    jettyContext.addServlet(new ServletHolder(new EchoServlet()), "/");
    jettyServer.start();//ww w.ja  va2 s .c o m
    WebServiceConnection connection = null;
    try {

        StaticApplicationContext appContext = new StaticApplicationContext();
        appContext.registerSingleton("messageSender", CommonsHttpMessageSender.class);
        appContext.refresh();

        CommonsHttpMessageSender messageSender = appContext.getBean("messageSender",
                CommonsHttpMessageSender.class);
        connection = messageSender.createConnection(new URI("http://localhost:" + port));

        appContext.close();

        connection.send(new SaajSoapMessage(messageFactory.createMessage()));
        connection.receive(new SaajSoapMessageFactory(messageFactory));
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException ex) {
                // ignore
            }
        }
        if (jettyServer.isRunning()) {
            jettyServer.stop();
        }
    }

}