Java Code Examples for org.springframework.context.ApplicationContext

The following are top voted examples for showing how to use org.springframework.context.ApplicationContext. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: springboot-shiro-cas-mybatis   File: AbstractServletContextInitializer.java   View source code 7 votes vote down vote up
@Override
public final void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;

    try {
        logger.info("Initializing {} root application context", contextInitializerName);
        initializeRootApplicationContext();
        logger.info("Initialized {} root application context successfully", contextInitializerName);

        logger.info("Initializing {} servlet application context", contextInitializerName);
        initializeServletApplicationContext();
        logger.info("Initialized {} servlet application context successfully", contextInitializerName);
    } catch (final Exception e) {
        logger.error(e.getMessage(), e);
    }
}
 
Example 2
Project: spring-reactive-sample   File: Application.java   View source code 7 votes vote down vote up
@Bean
public Server jettyServer(ApplicationContext context) throws Exception {
    HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context).build();
    Servlet servlet = new JettyHttpHandlerAdapter(handler);

    Server server = new Server();
    ServletContextHandler contextHandler = new ServletContextHandler(server, "");
    contextHandler.addServlet(new ServletHolder(servlet), "/");
    contextHandler.start();

    ServerConnector connector = new ServerConnector(server);
    connector.setHost("localhost");
    connector.setPort(port);
    server.addConnector(connector);

    return server;
}
 
Example 3
Project: EasyHousing   File: TestBuildingDealDao.java   View source code 6 votes vote down vote up
@Test
public void Test4(){
	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");//��ʼ������
	BuildingDealDao buildingDealDao = (BuildingDealDao) ac.getBean("buildingDealDao");
	BuildingDeal u = new BuildingDeal();
	u.setAgentId(2);
	u.setBuildingDealPerPrice(100);
	u.setBuildingDealTime(new Date());
	u.setBuildingDealTotalPrice(100);
	u.setBuildingId(1);
	u.setBuildingLayout("111��һ��");
	u.setUserId(1);
	u.setBuildingDealId(1);
	buildingDealDao.deleteBuildingDeal(u);
	System.out.println(u.getBuildingLayout());
}
 
Example 4
Project: plugin-id   File: UserBatchLdapResourceTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void mockApplicationContext() {
	final ApplicationContext applicationContext = Mockito.mock(ApplicationContext.class);
	SpringUtils.setSharedApplicationContext(applicationContext);
	mockLdapResource = Mockito.mock(UserOrgResource.class);
	final UserFullLdapTask mockTask = new UserFullLdapTask();
	mockTask.resource = mockLdapResource;
	mockTask.securityHelper = securityHelper;
	final UserAtomicLdapTask mockTaskUpdate = new UserAtomicLdapTask();
	mockTaskUpdate.resource = mockLdapResource;
	mockTaskUpdate.securityHelper = securityHelper;
	Mockito.when(applicationContext.getBean(SessionSettings.class)).thenReturn(new SessionSettings());
	Mockito.when(applicationContext.getBean((Class<?>) ArgumentMatchers.any(Class.class))).thenAnswer((Answer<Object>) invocation -> {
		final Class<?> requiredType = (Class<Object>) invocation.getArguments()[0];
		if (requiredType == UserFullLdapTask.class) {
			return mockTask;
		}
		if (requiredType == UserAtomicLdapTask.class) {
			return mockTaskUpdate;
		}
		return UserBatchLdapResourceTest.super.applicationContext.getBean(requiredType);
	});

	mockTaskUpdate.jaxrsFactory = ServerProviderFactory.createInstance(null);
}
 
Example 5
Project: alfresco-repository   File: AlfrescoPeople.java   View source code 6 votes vote down vote up
@Override protected void after()
{
    // Set up required services
    ApplicationContext ctxt = getApplicationContext();
    final RetryingTransactionHelper transactionHelper = (RetryingTransactionHelper) ctxt.getBean("retryingTransactionHelper");
    
    transactionHelper.doInTransaction(new RetryingTransactionCallback<Void>()
    {
        @Override public Void execute() throws Throwable
        {
            for (Map.Entry<String, NodeRef> entry : usersPersons.entrySet())
            {
                deletePerson(entry.getKey());
            }
            
            return null;
        }
    });
}
 
Example 6
Project: learn-spring-5   File: LearnspringdiApplication.java   View source code 6 votes vote down vote up
public static void main(String[] args) {

		ApplicationContext ctx =  SpringApplication.run(LearnspringdiApplication.class, args);

		//Always the bean name will be equivalent to the class name (but starts with lowercase)
		FirstController controller = (FirstController) ctx.getBean("firstController");
		System.out.println(controller.sayHello());
		System.out.println(ctx.getBean(PropertyInjectController.class).sayHello());
		System.out.println(ctx.getBean(SetterInjectController.class).sayHello());
		System.out.println(ctx.getBean(ConstructorInjectController.class).sayHello());

		TestDataSource testDataSource = (TestDataSource) ctx.getBean(TestDataSource.class);
		System.out.println("Reading value from external Property File :"+ testDataSource.getDbUrl());

        TestEnvProp testEnvProp = (TestEnvProp) ctx.getBean(TestEnvProp.class);
        System.out.println("Accessed System value through Spring Environmet Variable "+testEnvProp.getSystemUserName());
        System.out.println("Accessed System value directly via Spring @Value Annotation :"+testEnvProp.JAVA_VERSION);

        TestJmsBroker testJmsBroker = (TestJmsBroker) ctx.getBean(TestJmsBroker.class);
        System.out.println("Accessed multiple property file values using @PropertySources :"+testJmsBroker.getJmsUrl());
	}
 
Example 7
Project: urule   File: BaseRepositoryService.java   View source code 6 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	try {
		repository = repositoryBuilder.getRepository();
		SimpleCredentials cred = new SimpleCredentials("admin", "admin".toCharArray());
		cred.setAttribute("AutoRefresh", true);
		session = repository.login(cred, null);
		versionManager = session.getWorkspace().getVersionManager();
		lockManager=session.getWorkspace().getLockManager();
		Collection<RepositoryInteceptor> repositoryInteceptors=applicationContext.getBeansOfType(RepositoryInteceptor.class).values();
		if(repositoryInteceptors.size()==0){
			repositoryInteceptor=new DefaultRepositoryInteceptor();
		}else{
			repositoryInteceptor=repositoryInteceptors.iterator().next();
		}
	} catch (Exception ex) {
		throw new RuleException(ex);
	}
}
 
Example 8
Project: lams   File: ContextBeanFactoryReference.java   View source code 6 votes vote down vote up
@Override
public void release() {
	if (this.applicationContext != null) {
		ApplicationContext savedCtx;

		// We don't actually guarantee thread-safety, but it's not a lot of extra work.
		synchronized (this) {
			savedCtx = this.applicationContext;
			this.applicationContext = null;
		}

		if (savedCtx != null && savedCtx instanceof ConfigurableApplicationContext) {
			((ConfigurableApplicationContext) savedCtx).close();
		}
	}
}
 
Example 9
Project: EasyHousing   File: TestBuildingLayoutDao.java   View source code 6 votes vote down vote up
@Test
public void Test2(){
	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");//��ʼ������
	BuildingLayoutDao buildingLayoutDao = (BuildingLayoutDao) ac.getBean("buildingLayoutDao");
	BuildingLayout u = new BuildingLayout();
	
	u.setBuildingId(2);
	u.setBuildingLayout("һ��һ��");
	u.setBuildingLayoutPerPrice(2);
	u.setBuildingLayoutPicUrl("2112512");
	u.setBuildingLayoutReferencePrice(2);
	u.setBuildingLayoutSoldOut(2);
	
	buildingLayoutDao.updateBuildingLayout(u);
	
	System.out.println("-------");
}
 
Example 10
Project: cstruct-parser   File: AbstractResolve.java   View source code 6 votes vote down vote up
@Override
public void refresh(ApplicationContext applicationContext)
{
	unResolvePostProcessList = new ArrayList<>();

	Map<String, UnResolvePostProcess> unResolvePostProcessMap = applicationContext.getBeansOfType(UnResolvePostProcess.class);

	if (!CollectionUtils.isEmpty(unResolvePostProcessMap)) {
		unResolvePostProcessList.addAll(unResolvePostProcessMap.values());
	}
	unResolvePostProcessMap = null;

	unResolveFieldPostProcessList = new ArrayList<>();

	Map<String, UnResolveFieldPostProcess> unResolveFieldPostProcessMap = applicationContext.getBeansOfType(UnResolveFieldPostProcess.class);

	if (!CollectionUtils.isEmpty(unResolveFieldPostProcessMap)) {
		unResolveFieldPostProcessList.addAll(unResolveFieldPostProcessMap.values());
	}
	unResolveFieldPostProcessMap = null;

}
 
Example 11
Project: spring-reactive-sample   File: Application.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);  // (1)

    Tomcat tomcatServer = context.getBean(Tomcat.class);
    tomcatServer.start();

    System.out.println("Press ENTER to exit.");
    System.in.read();
}
 
Example 12
Project: EasyHousing   File: RentHousePicTest.java   View source code 5 votes vote down vote up
@Test
public void select() {
	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
	RentHousePicDao dao = (RentHousePicDao) ac.getBean("rentHousePicDao");
	RentHousePic c = new RentHousePic();
	c.setRentHousePicId(2);
	System.out.println(dao.selectRentHousePic(c).getPicUrl());
}
 
Example 13
Project: JavaStudy   File: App.java   View source code 5 votes vote down vote up
@Test
public void test(){
    ApplicationContext atc=new AnnotationConfigApplicationContext(SystemXml.class);
    SystemXmlMap map=(SystemXmlMap)atc.getBean("systemXmlMap");
    PrinterUtils.printILog(map.toString());

    Environment environment=(Environment)atc.getBean("environment");
    PrinterUtils.printILog(environment.getProperty("username"));
}
 
Example 14
Project: item-shop-reactive-backend   File: Server.java   View source code 5 votes vote down vote up
@Bean(name="serverBrowse")
public NettyContext nettyContext(ApplicationContext context) {
	HttpHandler handler = DispatcherHandler.toHttpHandler(context);
	ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler);
	HttpServer httpServer = HttpServer.create(host, port);
	return httpServer.newHandler(adapter).block();
}
 
Example 15
Project: xxl-job   File: XxlJobDynamicScheduler.java   View source code 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	XxlJobDynamicScheduler.xxlJobLogDao = applicationContext.getBean(IXxlJobLogDao.class);
	XxlJobDynamicScheduler.xxlJobInfoDao = applicationContext.getBean(IXxlJobInfoDao.class);
       XxlJobDynamicScheduler.xxlJobRegistryDao = applicationContext.getBean(IXxlJobRegistryDao.class);
       XxlJobDynamicScheduler.xxlJobGroupDao = applicationContext.getBean(IXxlJobGroupDao.class);
}
 
Example 16
Project: springmock   File: ApplicationContextWalkerTest.java   View source code 5 votes vote down vote up
@Test
public void should_detect_duplicated_beans_of_the_same_type_on_the_same_level() {
	//given
	class Bean {}
	final ApplicationContext ctx = buildAppContext(Stream.of(
			bean("1", new Bean()),
			bean("2", new Bean())));
	final ApplicationContextWalker walker = new ApplicationContextWalker(ctx);

	//expect
	assertFalse(walker.hasOnlyOneBeanOfClass(Bean.class));
}
 
Example 17
Project: EasyHousing   File: TestAgentDao.java   View source code 5 votes vote down vote up
@Test
public void Test1(){
	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");//��ʼ������
	AgentDao agentDao = (AgentDao) ac.getBean("agentDao");
	Agent u = new Agent();
	u.setAgentName("sbgzy");
	u.setAgentEmail("[email protected]");
	u.setAgentPhoneNumber("123124214");
	u.setAgentSex("��");
	u.setPicUrl("1212421");
	agentDao.insertAgent(u);
	System.out.println("-------");
}
 
Example 18
Project: spring-boot-starter-quartz   File: QuartzSchedulerAutoConfiguration.java   View source code 5 votes vote down vote up
private Properties loadConfigLocationProperties(ApplicationContext applicationContext, 
		QuartzSchedulerProperties properties) throws IOException {
	
	String location = properties.getPropertiesConfigLocation();
	if(null == location || location.trim().length() == 0) {
		location = QuartzSchedulerProperties.DEFAULT_CONFIG_LOCATION;
		LOGGER.debug("using default 'quartz.properties' from classpath: " + location);
	} else {
		LOGGER.debug("using 'quartz.properties' from location: " + location);
	}
	PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
	propertiesFactoryBean.setLocation(applicationContext.getResource(location));
	propertiesFactoryBean.afterPropertiesSet();
	return propertiesFactoryBean.getObject();
}
 
Example 19
Project: alfresco-remote-api   File: ReplicationRestApiTest.java   View source code 5 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();
    ApplicationContext appContext = getServer().getApplicationContext();

    nodeService = (NodeService)appContext.getBean("NodeService");
    replicationService = (ReplicationService)appContext.getBean("ReplicationService");
    actionTrackingService = (ActionTrackingService)appContext.getBean("actionTrackingService");
    repositoryHelper = (Repository)appContext.getBean("repositoryHelper");
    transactionService = (TransactionService)appContext.getBean("transactionService");
    
    MutableAuthenticationService authenticationService = (MutableAuthenticationService)appContext.getBean("AuthenticationService");
    PersonService personService = (PersonService)appContext.getBean("PersonService");
    personManager = new TestPersonManager(authenticationService, personService, nodeService);

    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();
    
    personManager.createPerson(USER_NORMAL);
    
    // Ensure we start with no replication definitions
    // (eg another test left them behind)
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
    for(ReplicationDefinition rd : replicationService.loadReplicationDefinitions()) {
       replicationService.deleteReplicationDefinition(rd);
    }
    txn.commit();
    
    // Grab a reference to the data dictionary
    dataDictionary = nodeService.getChildByName(
             repositoryHelper.getCompanyHome(),
             ContentModel.ASSOC_CONTAINS,
             "Data Dictionary"
    );
    
    AuthenticationUtil.clearCurrentSecurityContext();
}
 
Example 20
Project: Learning-Spring-5.0   File: TestCustomer.java   View source code 5 votes vote down vote up
public static void main(String[] args) {
	// TODO Auto-generated method stub
	ApplicationContext context=new ClassPathXmlApplicationContext("customer.xml");
	Customer customer=(Customer)context.getBean("customer");
	System.out.println(customer.getCust_name()+"\t"+customer.getCust_id());
       System.out.println(customer.getCust_address());   
}
 
Example 21
Project: plugin-id   File: UserOrgResourceTest.java   View source code 5 votes vote down vote up
@Test
public void resetPasswordByAdmin() {
	resource.applicationContext = Mockito.mock(ApplicationContext.class);
	final IPasswordGenerator generator = Mockito.mock(IPasswordGenerator.class);
	Mockito.when(resource.applicationContext.getBeansOfType(IPasswordGenerator.class)).thenReturn(Collections.singletonMap("bean", generator));
	resource.resetPasswordByAdmin(newUser());
	Mockito.verify(generator, VerificationModeFactory.atLeast(1)).generate("wuser");
}
 
Example 22
Project: Spring-Security-Third-Edition   File: CalendarApplication.java   View source code 5 votes vote down vote up
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
    return args -> {

        System.out.println("Let's inspect the beans provided by Spring Boot:\n");

        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }

        System.out.println("---");
    };
}
 
Example 23
Project: vertx-spring-boot-example   File: SpringDeploymentManager.java   View source code 5 votes vote down vote up
@Autowired
SpringDeploymentManager(
        final ApplicationContext context,
        final VerticleFactory verticleFactory,
        final Vertx vertx,
        @Value("${thread.pool.size}") final int threadPoolSize
) {
    this.context = context;
    this.verticleFactory = verticleFactory;
    this.vertx = vertx;
    this.threadPoolSize = getThreadPoolSize(threadPoolSize);
}
 
Example 24
Project: ARCLib   File: Gatherer.java   View source code 5 votes vote down vote up
private Map<String, Object> getConfigurationPropertiesBeans(
        ApplicationContext context,
        ConfigurationBeanFactoryMetaData beanFactoryMetaData) {
    Map<String, Object> beans = new LinkedHashMap<String, Object>();
    beans.putAll(context.getBeansWithAnnotation(ConfigurationProperties.class));
    if (beanFactoryMetaData != null) {
        beans.putAll(beanFactoryMetaData
                .getBeansWithFactoryAnnotation(ConfigurationProperties.class));
    }
    return beans;
}
 
Example 25
Project: lams   File: WebApplicationObjectSupport.java   View source code 5 votes vote down vote up
/**
 * Return the current application context as WebApplicationContext.
 * <p><b>NOTE:</b> Only use this if you actually need to access
 * WebApplicationContext-specific functionality. Preferably use
 * {@code getApplicationContext()} or {@code getServletContext()}
 * else, to be able to run in non-WebApplicationContext environments as well.
 * @throws IllegalStateException if not running in a WebApplicationContext
 * @see #getApplicationContext()
 */
protected final WebApplicationContext getWebApplicationContext() throws IllegalStateException {
	ApplicationContext ctx = getApplicationContext();
	if (ctx instanceof WebApplicationContext) {
		return (WebApplicationContext) getApplicationContext();
	}
	else if (isContextRequired()) {
		throw new IllegalStateException("WebApplicationObjectSupport instance [" + this +
				"] does not run in a WebApplicationContext but in: " + ctx);
	}
	else {
		return null;
	}
}
 
Example 26
Project: incubator-servicecomb-java-chassis   File: MockUtil.java   View source code 5 votes vote down vote up
public void mockBeanUtils() {

    new MockUp<BeanUtils>() {
      @Mock
      ApplicationContext getContext() {
        return Mockito.mock(ApplicationContext.class);
      }
    };
  }
 
Example 27
Project: ureport   File: DefaultImageProvider.java   View source code 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	if(applicationContext instanceof WebApplicationContext){
		WebApplicationContext context=(WebApplicationContext)applicationContext;
		baseWebPath=context.getServletContext().getRealPath("/");
	}
	this.applicationContext=applicationContext;
}
 
Example 28
Project: alfresco-remote-api   File: RepoService.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
public RepoService(ApplicationContext applicationContext) throws Exception
   {
   	this.applicationContext = applicationContext;
   	this.publicApiContext = new PublicApiTestContext(applicationContext);
   	this.authenticationService = (MutableAuthenticationService)applicationContext.getBean("AuthenticationService");
   	this.siteService = (SiteService)applicationContext.getBean("SiteService");
   	this.activityService = (ActivityService)applicationContext.getBean("activityService");
   	this.fileFolderService = (FileFolderService)applicationContext.getBean("FileFolderService");
   	this.contentService = (ContentService)applicationContext.getBean("ContentService");
   	this.commentService = (CommentService)applicationContext.getBean("CommentService");
   	this.nodeService = (NodeService)applicationContext.getBean("NodeService");
   	this.preferenceService = (PreferenceService)applicationContext.getBean("PreferenceService");
   	this.taggingService = (TaggingService)applicationContext.getBean("TaggingService");
   	this.ratingService = (RatingService)applicationContext.getBean("RatingService");
   	this.tenantService = (TenantService)applicationContext.getBean("tenantService");
   	this.tenantAdminService = (TenantAdminService)applicationContext.getBean("tenantAdminService");
   	this.personService = (PersonService)applicationContext.getBean("PersonService");
   	this.contentStoreCleaner = (ContentStoreCleaner)applicationContext.getBean("contentStoreCleaner");
   	this.postDAO = (ActivityPostDAO)applicationContext.getBean("postDAO");
   	this.nodeRatingSchemeRegistry = (NamedObjectRegistry<RatingScheme>)applicationContext.getBean("nodeRatingSchemeRegistry");
   	this.cociService = (CheckOutCheckInService)applicationContext.getBean("CheckoutCheckinService");
   	this.favouritesService = (FavouritesService)applicationContext.getBean("FavouritesService");
   	this.dictionaryService =  (DictionaryService)applicationContext.getBean("dictionaryService");
   	this.invitationService = (InvitationService)applicationContext.getBean("InvitationService");
   	this.lockService = (LockService)applicationContext.getBean("LockService");
   	this.cmisConnector = (CMISConnector)applicationContext.getBean("CMISConnector");
   	this.nodeIndexer = (NodeIndexer)applicationContext.getBean("nodeIndexer");
   	this.activities = (Activities)applicationContext.getBean("activities");
   	this.hiddenAspect = (HiddenAspect)applicationContext.getBean("hiddenAspect");
   	this.networksService = (NetworksService)applicationContext.getBean("networksService");
   	this.namespaceService = (NamespaceService)applicationContext.getBean("namespaceService"); 
   	this.transactionHelper = (RetryingTransactionHelper)applicationContext.getBean("retryingTransactionHelper");

       Scheduler scheduler = (Scheduler)applicationContext.getBean("schedulerFactory");
   	
   	JobDetailBean contentStoreCleanerJobDetail = (JobDetailBean)applicationContext.getBean("contentStoreCleanerJobDetail");
       scheduler.pauseJob(contentStoreCleanerJobDetail.getName(), contentStoreCleanerJobDetail.getGroup());

       ChildApplicationContextFactory activitiesFeed = (ChildApplicationContextFactory)applicationContext.getBean("ActivitiesFeed");
       ApplicationContext activitiesFeedCtx = activitiesFeed.getApplicationContext();
       this.postLookup = (PostLookup)activitiesFeedCtx.getBean("postLookup");
       this.feedGenerator = (FeedGenerator)activitiesFeedCtx.getBean("feedGenerator");
       this.feedGeneratorJobDetail = (JobDetailBean)activitiesFeedCtx.getBean("feedGeneratorJobDetail");
       this.postLookupJobDetail = (JobDetailBean)activitiesFeedCtx.getBean("postLookupJobDetail");
       this.feedCleanerJobDetail = (JobDetailBean)activitiesFeedCtx.getBean("feedCleanerJobDetail");
       this.postCleanerJobDetail = (JobDetailBean)activitiesFeedCtx.getBean("postCleanerJobDetail");
       this.feedNotifierJobDetail = (JobDetailBean)activitiesFeedCtx.getBean("feedNotifierJobDetail");
   	this.feedCleaner = (FeedCleaner)activitiesFeedCtx.getBean("feedCleaner");

       // Pause activities jobs so that we aren't competing with their scheduled versions
       scheduler.pauseJob(feedGeneratorJobDetail.getName(), feedGeneratorJobDetail.getGroup());
       scheduler.pauseJob(postLookupJobDetail.getName(), postLookupJobDetail.getGroup());
       scheduler.pauseJob(feedCleanerJobDetail.getName(), feedCleanerJobDetail.getGroup());
       scheduler.pauseJob(postCleanerJobDetail.getName(), postCleanerJobDetail.getGroup());
       scheduler.pauseJob(feedNotifierJobDetail.getName(), feedNotifierJobDetail.getGroup());

       this.systemNetwork = new TestNetwork(TenantService.DEFAULT_DOMAIN, true);
}
 
Example 29
Project: alfresco-repository   File: FFCLoadsOfFiles.java   View source code 5 votes vote down vote up
public static void main(String[] args)
{
	
    // initialise app content 
    ApplicationContext ctx = ApplicationContextHelper.getApplicationContext();
    // get registry of services
    final ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);

    // authenticate
    AuthenticationService authenticationService = serviceRegistry.getAuthenticationService();
    authenticationService.authenticate(AuthenticationUtil.getAdminUserName(), "admin".toCharArray());

    
    // use TransactionWork to wrap service calls in a user transaction
    TransactionService transactionService = serviceRegistry.getTransactionService();
    RetryingTransactionCallback<Object> exampleWork = new RetryingTransactionCallback<Object>()
    {
        public Object execute() throws Exception
        {
            doExample(serviceRegistry);
            return null;
        }
    };
    currentDoc = 0;
    while (currentDoc < totalNumDocs)
    {
        transactionService.getRetryingTransactionHelper().doInTransaction(exampleWork);
    }
    System.exit(0);
}
 
Example 30
Project: alfresco-repository   File: FeedNotifierJobTest.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception
{
    ChildApplicationContextFactory activitiesFeed = (ChildApplicationContextFactory) ctx.getBean("ActivitiesFeed");
    ApplicationContext activitiesFeedCtx = activitiesFeed.getApplicationContext();
    feedNotifier = (FeedNotifierImpl) activitiesFeedCtx.getBean("feedNotifier");
    activityService = (ActivityService) activitiesFeedCtx.getBean("activityService");
    feedGenerator = (FeedGenerator) activitiesFeedCtx.getBean("feedGenerator");
    postLookup = (PostLookup) activitiesFeedCtx.getBean("postLookup");
    ObjectFactory<ActivitiesFeedModelBuilder> feedModelBuilderFactory = (ObjectFactory<ActivitiesFeedModelBuilder>) activitiesFeedCtx.getBean("feedModelBuilderFactory");
    EmailUserNotifier emailUserNotifier = (EmailUserNotifier) activitiesFeedCtx.getBean("emailUserNotifier");
    
    tenantAdminService = (TenantAdminService) ctx.getBean("tenantAdminService");
    transactionService = (TransactionService) ctx.getBean("transactionService");
    personService = (PersonService) ctx.getBean("personService");
    postDAO = (ActivityPostDAO) ctx.getBean("postDAO");
    nodeService = (NodeService) ctx.getBean("nodeService");
    namespaceService = (NamespaceService) ctx.getBean("namespaceService");
    siteService = (SiteService) ctx.getBean("siteService");
    repoAdminService = (RepoAdminService) ctx.getBean("repoAdminService");
    actionService = (ActionService) ctx.getBean("ActionService");
    authenticationContext = (AuthenticationContext) ctx.getBean("authenticationContext");
    EmailHelper emailHelper = (EmailHelper) ctx.getBean("emailHelper");
    
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    // create some users
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        @SuppressWarnings("synthetic-access")
        public Void execute() throws Throwable
        {
            personNodeRef = createUser(userName1);
            failingPersonNodeRef = createUser(userName2);
            return null;
        }
    }, false, true);
    
    // use our own user notifier for testing purposes
    userNotifier = new RegisterErrorUserFeedNotifier();
    userNotifier.setNodeService(nodeService);
    userNotifier.setNamespaceService(namespaceService);
    userNotifier.setSiteService(siteService);
    userNotifier.setActivityService(activityService);
    userNotifier.setRepoAdminService(repoAdminService);
    userNotifier.setActionService(actionService);
    userNotifier.setActivitiesFeedModelBuilderFactory(feedModelBuilderFactory);
    userNotifier.setAuthenticationContext(authenticationContext);
    userNotifier.setExcludedEmailSuffixes(emailUserNotifier.getExcludedEmailSuffixes());
    userNotifier.setEmailHelper(emailHelper);
    feedNotifier.setUserNotifier(userNotifier);
    
    jobDetail = new JobDetail("feedNotifier", FeedNotifierJob.class);
    JobDataMap jobDataMap = jobDetail.getJobDataMap();
    jobDataMap.put("tenantAdminService", tenantAdminService);
    jobDataMap.put("feedNotifier", feedNotifier);
    feedNotifierJob = new FeedNotifierJob();
    
    when(jobCtx.getJobDetail()).thenReturn(jobDetail);
}
 
Example 31
Project: daros-dynamic   File: DynamicRegisterGroovyFile.java   View source code 5 votes vote down vote up
@Autowired
public void setApplicationContext(ApplicationContext ctx) {
    if (!DefaultListableBeanFactory.class.isAssignableFrom(ctx.getAutowireCapableBeanFactory().getClass())) {
        throw new IllegalArgumentException("BeanFactory must be DefaultListableBeanFactory type");
    }
    this.ctx = ctx;
    this.beanFactory = (DefaultListableBeanFactory) ctx.getAutowireCapableBeanFactory();
}
 
Example 32
Project: urule   File: CacheUtils.java   View source code 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	Collection<KnowledgeCache> caches=applicationContext.getBeansOfType(KnowledgeCache.class).values();
	if(caches.size()>0){
		CacheUtils.knowledgeCache=caches.iterator().next();
	}else{
		CacheUtils.knowledgeCache=new MemoryKnowledgeCache();
	}
}
 
Example 33
Project: spring-web-services   File: SpringbootIn10StepsApplication.java   View source code 5 votes vote down vote up
public static void main(String[] args) {
	ApplicationContext applicationContext = 
			SpringApplication.run(SpringbootIn10StepsApplication.class, args);
	
	for (String name : applicationContext.getBeanDefinitionNames()) {
		System.out.println(name);
	}
}
 
Example 34
Project: albedo-thrift   File: AlbedoThriftExampleClient.java   View source code 5 votes vote down vote up
/**
 * Main method, used to run the application.
 *
 * @param args the command line arguments
 * @throws UnknownHostException if the local host name could not be resolved into an address
 */
public static void main(String[] args) throws Exception {
	SpringApplication app = new SpringApplication(AlbedoThriftExampleClient.class);
	final ApplicationContext applicationContext = app.run(args);
	Environment env = applicationContext.getEnvironment();
	log.info("\n----------------------------------------------------------\n\t" +
					"Application '{}' is running! ",
			env.getProperty("spring.application.name"));
}
 
Example 35
Project: aaden-pay   File: SpringContextHelper.java   View source code 5 votes vote down vote up
/**
 * 实现ApplicationContextAware接口, 注入Context到静态变量中.
 */
public void setApplicationContext(ApplicationContext applicationContext) {
	logger.debug("set applicationContext to springContextHolder:" + applicationContext);
	if (SpringContextHelper.applicationContext != null) {
		logger.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHelper.applicationContext);
	}
	SpringContextHelper.applicationContext = applicationContext; // NOSONAR
}
 
Example 36
Project: springboot-sample   File: Application.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {

        ApplicationContext app = SpringApplication.run(Application.class, args);

        while (true) {
            Sender sender = app.getBean(Sender.class);
            sender.sendMessage();
            Thread.sleep(5000);
        }
    }
 
Example 37
Project: spring-reactive-sample   File: Application.java   View source code 5 votes vote down vote up
@Profile("default")
@Bean
public NettyContext nettyContext(ApplicationContext context) {
    HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context).build();
    ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler);
    HttpServer httpServer = HttpServer.create("localhost", this.port);
    return httpServer.newHandler(adapter).block();
}
 
Example 38
Project: hibatis   File: InsertTest.java   View source code 5 votes vote down vote up
@Before
public void init(){
	@SuppressWarnings("resource")
	ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
	SqlSessionFactory sqlSessionFactory =  context.getBean(SqlSessionFactory.class);
	sqlMapper = new SqlMapperTemplate(sqlSessionFactory);
}
 
Example 39
Project: Spring-5.0-Cookbook   File: HttpServerConfig.java   View source code 5 votes vote down vote up
@Bean
public  NettyContext nettyContext(ApplicationContext context) {
	HttpHandler handler = DispatcherHandler.toHttpHandler(context);
	ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler);
	HttpServer httpServer = HttpServer.create("localhost", Integer.valueOf("9008"));
	return httpServer.newHandler(adapter).block();
}
 
Example 40
Project: autotest   File: AutoTestExtension.java   View source code 5 votes vote down vote up
static Object resolveDependency(Parameter parameter, Class<?> containingClass, ApplicationContext applicationContext) {
    boolean required = findMergedAnnotation(parameter, Autowired.class).map(Autowired::required).orElse(true);
    MethodParameter methodParameter = SynthesizingMethodParameter.forParameter(parameter);
    DependencyDescriptor descriptor = new DependencyDescriptor(methodParameter, required);
    descriptor.setContainingClass(containingClass);
    return applicationContext.getAutowireCapableBeanFactory().resolveDependency(descriptor, null);
}