Example usage for org.springframework.context.support ClassPathXmlApplicationContext close

List of usage examples for org.springframework.context.support ClassPathXmlApplicationContext close

Introduction

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

Prototype

@Override
public void close() 

Source Link

Document

Close this application context, destroying all beans in its bean factory.

Usage

From source file:org.activiti.crystalball.simulator.TimerBoundaryEventTest.java

@Test
public void testTimerBoundaryEvent() throws Exception {
    System.setProperty("liveDB", LIVE_DB);
    System.setProperty("_SIM_DB_PATH",
            tempDir + "/" + TimerBoundaryEventTest.class.getName() + "-sim-" + Thread.currentThread().getId());
    // delete database file
    File f = new File(System.getProperty("_SIM_DB_PATH") + ".h2.db");
    if (!f.delete())
        System.err.println("unable to delete file");

    ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
            "/org/activiti/crystalball/simulator/SimEngine-BoundaryTimer-h2-context.xml");
    ProcessEngine processEngine = (ProcessEngine) appContext.getBean("simProcessEngine");

    // deploy processes
    processEngine.getRepositoryService().createDeployment()
            .addClasspathResource("org/activiti/crystalball/simulator/TimerBoundaryEventTest.bpmn").deploy();

    SimulationRun simRun = (SimulationRun) appContext.getBean(SimulationRun.class);

    Calendar c = Calendar.getInstance();
    Date startDate = c.getTime();

    c.add(Calendar.MINUTE, 5);/*from  w  w w  .  jav  a2 s .  c om*/
    Date finishDate = c.getTime();

    // run simulation for 5 minutes
    @SuppressWarnings("unused")
    List<ResultEntity> resultEventList = simRun.execute(startDate, finishDate);

    TaskService simTaskService = processEngine.getTaskService();
    // in 5 minutes 11 processes will be started (0 is included too)
    assertEquals(11, simTaskService.createTaskQuery().taskDefinitionKey("firstLine").count());
    // two tasks were not escalated yet escalation timer is 35sec
    assertEquals(9, simTaskService.createTaskQuery().taskDefinitionKey("escalation").count());

    processEngine.close();
    appContext.close();

}

From source file:org.activiti.crystalball.simulator.SimulatorProcessMonitorTestWithoutProcess.java

@Test
public void testProcessRun() throws Throwable {
    ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
            "/org/activiti/crystalball/simulator/SimEngine-h2-context.xml");
    SimulationRun simRun = appContext.getBean(SimulationRun.class);
    RepositoryService repositoryService = (RepositoryService) appContext.getBean("simRepositoryService");

    List<ResultEntity> resultEventList = simRun.execute(new Date(), null);

    Collection<List<ResultEntity>> unfinishedTaskProcesses = SimulationResultsPostProcessor
            .groupProcessDefinitionKey(//from   w ww. j a  v  a  2  s  .co m
                    SimulationResultsPostProcessor.getEventType("unfinished_task", resultEventList));

    for (List<ResultEntity> eventList : unfinishedTaskProcesses) {
        String processDefinitionId = (String) eventList.get(0).getVariable("processDefinitionKey");
        List<String> highlightTasks = SimulationResultsPostProcessor.getTaskDefinitionKeys(eventList);
        Map<String, String> nodeDescription = SimulationResultsPostProcessor.getNodeDescriptions(eventList);

        File dir = new File(tempDir + "/" + eventList.get(0).getType());
        dir.mkdir();
        String reportFileName = tempDir + "/" + eventList.get(0).getType() + "/" + processDefinitionId + ".png";
        reportGraph(reportFileName, processDefinitionId, highlightTasks, nodeDescription, repositoryService);

    }

    appContext.close();

    File expected = new File(System.getProperty("baseDir", ".")
            + "/src/test/resources/org/activiti/crystalball/simulator/SimulatorProcessMonitor-unfinishedTasks-expected.png");
    File generated = new File(
            System.getProperty("tempDir", "target") + "/unfinished_task/threetasksprocess.png");
    assertTrue(FileUtils.contentEquals(expected, generated));

}

From source file:org.activiti.crystalball.simulator.GenerateProcessEngineState.java

private static void generateBasicEngine() throws InterruptedException {
    String PROCESS_KEY = "threetasksprocess";
    RepositoryService repositoryService;
    RuntimeService runtimeService;//ww w.  java  2  s . c o m
    TaskService taskService;
    IdentityService identityService;
    ProcessEngine processEngine;
    String liveDB = TEMP_DIR + "/BasicSimulation";

    // delete previous DB instalation and set property to point to the current file
    File prevDB = new File(liveDB + ".h2.db");

    String previousLiveDB = System.getProperty("liveDB");

    System.setProperty("liveDB", liveDB);
    if (prevDB.exists())
        prevDB.delete();
    prevDB = null;

    ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
            "org/activiti/crystalball/simulator/LiveEngine-context.xml");

    repositoryService = appContext.getBean(RepositoryService.class);
    runtimeService = appContext.getBean(RuntimeService.class);
    taskService = appContext.getBean(TaskService.class);
    identityService = appContext.getBean(IdentityService.class);
    processEngine = appContext.getBean(ProcessEngine.class);

    // deploy processes
    repositoryService.createDeployment()
            .addClasspathResource("org/activiti/crystalball/simulator/ThreeTasksProcess.bpmn").deploy();

    // init identity service
    identityService.saveGroup(identityService.newGroup("Group1"));
    identityService.saveGroup(identityService.newGroup("Group2"));
    identityService.saveUser(identityService.newUser("user1"));
    identityService.saveUser(identityService.newUser("user2"));

    identityService.createMembership("user1", "Group1");
    identityService.createMembership("user2", "Group2");

    // start processes 
    Calendar calendar = Calendar.getInstance();
    calendar.set(2012, 11, 7, 18, 1, 00);
    Date dueDateFormal = calendar.getTime();
    calendar.set(2012, 11, 7, 18, 1, 30);
    Date dueDateValue = calendar.getTime();
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("dueDateFormal", dueDateFormal);
    variables.put("dueDateValue", dueDateValue);

    for (int i = 0; i < 10; i++) {
        runtimeService.startProcessInstanceByKey(PROCESS_KEY, "BUSINESS-KEY-" + i, variables);
    }

    // put first 5 tasks to the next node
    List<Task> taskList = taskService.createTaskQuery().taskCandidateUser("user1").list();
    for (int i = 0; i < 5; i++) {
        Task t = taskList.get(i);
        taskService.claim(t.getId(), "user1");
    }

    // wait some time  to have some data in history 
    Thread.sleep(500);

    // complete these tasks
    for (int i = 0; i < 5; i++) {
        Task t = taskList.get(i);
        taskService.complete(t.getId());
    }

    processEngine.close();

    appContext.close();

    if (previousLiveDB != null)
        System.setProperty("liveDB", previousLiveDB);
    else
        System.setProperty("liveDB", "");

}

From source file:com.digitalgeneralists.assurance.ui.workers.PerformScanWorker.java

@Override
public Scan doInBackground() {
    this.notifier.fireEvent(new ScanStartedEvent(scanDefinition));

    Scan scan = null;//w  w  w . j ava 2  s  .  c o m

    // Because we are operating in a Swing application, the session context
    // closes after the initial bootstrap run. There appears to be an
    // "application"-level session configuration that should enable the
    // behavior we want for a desktop application, but there is no documentation
    // for it that I can find. 
    // So, Assurance mimics a web app request/response
    // cycle for calls into the model delegate through the Swing
    // application. All calls to the model initiated directly from the UI
    // essentially operate as a new "request" and rebuild the Hibernate and
    // Spring session contexts for use within that operation.
    ClassPathXmlApplicationContext springContext = null;
    try {
        springContext = new ClassPathXmlApplicationContext("/META-INF/spring/app-context.xml");
        IModelDelegate modelDelegate = (IModelDelegate) springContext.getBean("ModelDelegate");
        IAssuranceThreadPool threadPool = (IAssuranceThreadPool) springContext.getBean("ThreadPool");
        threadPool.setNumberOfThreads(modelDelegate.getApplicationConfiguration().getNumberOfScanThreads());

        // NOTE:  Leaking model initialization like this into the UI is less than ideal.
        scanDefinition = (ScanDefinition) ModelUtils.initializeEntity(scanDefinition,
                ScanDefinition.SCAN_MAPPING_PROPERTY);
        IScanOptions options = modelDelegate.getScanOptions();
        scan = modelDelegate.performScan(scanDefinition, threadPool, options, this);
        if (this.merge) {
            scan = modelDelegate.mergeScan(scan, threadPool, this);
        }
        modelDelegate = null;
        threadPool = null;
    } catch (AssuranceNullFileReferenceException e) {
        logger.error("An error was encountered when attempting to perform the scan", e);
    } catch (AssuranceIncompleteScanDefinitionException e) {
        logger.error("An error was encountered when attempting to perform the scan", e);
    } finally {
        if (springContext != null) {
            springContext.close();
        }
        springContext = null;
    }

    return scan;
}

From source file:com.ryantenney.metrics.spring.ReporterTest.java

@Test
public void fakeReporters() throws Throwable {
    ClassPathXmlApplicationContext ctx = null;
    FakeReporter one = null;//from   ww  w.j  av  a  2  s .  c  o  m
    FakeReporter two = null;
    try {
        MetricRegistry registry = new MetricRegistry();
        SharedMetricRegistries.add("reporterTestRegistry", registry);

        ctx = new ClassPathXmlApplicationContext("classpath:fake-reporter-test.xml");
        ctx.start();

        Thread.sleep(1000);

        one = ctx.getBean("fakeReporterOne", FakeReporter.class);
        Assert.assertEquals(registry, one.getRegistry());
        Assert.assertEquals("milliseconds", one.getDurationUnit());
        Assert.assertEquals("second", one.getRateUnit());
        Assert.assertEquals(100000000, one.getPeriod());
        Assert.assertEquals(10, one.getCalls());
        Assert.assertEquals("[MetricFilter regex=foo]", one.getFilter().toString());
        Assert.assertTrue(one.isRunning());

        two = ctx.getBean("fakeReporterTwo", FakeReporter.class);
        Assert.assertEquals(registry, two.getRegistry());
        Assert.assertEquals("nanoseconds", two.getDurationUnit());
        Assert.assertEquals("hour", two.getRateUnit());
        Assert.assertEquals(100000000, two.getPeriod());
        Assert.assertEquals(10, one.getCalls());
        Assert.assertEquals(ctx.getBean(BarFilter.class), two.getFilter());
        Assert.assertTrue(one.isRunning());

    } finally {
        if (ctx != null) {
            ctx.stop();
            ctx.close();
        }
    }

    if (one != null) {
        Assert.assertFalse(one.isRunning());
    }

    if (two != null) {
        Assert.assertFalse(two.isRunning());
    }
}

From source file:com.digitalgeneralists.assurance.ui.components.ComparisonResultPanel.java

private void displayAttributesDialog(FileReference file) {
    ClassPathXmlApplicationContext springContext = null;
    try {//from www  .j  a v  a  2 s. c om
        if (this.getParent() != null) {
            JFrame parent = (JFrame) SwingUtilities.getWindowAncestor(this.getParent());

            springContext = new ClassPathXmlApplicationContext("/META-INF/spring/app-context.xml");
            IDialogFactory dialogFactory = (IDialogFactory) springContext.getBean("DialogFactory");

            JDialog scanDefinitionDialog = dialogFactory.createFileAttributesDialogInstance(parent,
                    ModalityType.APPLICATION_MODAL, file);
            scanDefinitionDialog.setPreferredSize(new Dimension(400, 600));

            scanDefinitionDialog.setVisible(true);
            dialogFactory = null;
        }
    } finally {
        if (springContext != null) {
            springContext.close();
            springContext = null;
        }
    }
}

From source file:org.activiti.crystalball.simulator.TwoEnginesWithoutProcessTest.java

@Test
public void test() throws Exception {
    String tempDir = "target";
    FileUtils.copyFile(/* w  ww  .  j a va  2s .  com*/
            FileUtils.getFile(
                    new String[] { (new StringBuilder()).append(LIVE_DB).append(".h2.db").toString() }),
            FileUtils.getFile(
                    new String[] { (new StringBuilder()).append(tempDir).append("/simulationRunDB-aaa-")
                            .append(Thread.currentThread().getId()).append(".h2.db").toString() }));
    System.setProperty("_SIM_DB_PATH", (new StringBuilder()).append(tempDir).append("/simulationRunDB-aaa-")
            .append(Thread.currentThread().getId()).toString());
    ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
            "/org/activiti/crystalball/simulator/SimRun-h2-context.xml");
    PropertyPlaceholderConfigurer propConfig = new PropertyPlaceholderConfigurer();
    Properties properties = new Properties();
    properties.put("simulationRunId", "simulationRunDB-aaa-" + Thread.currentThread().getId());
    propConfig.setProperties(properties);
    appContext.addBeanFactoryPostProcessor(propConfig);
    appContext.refresh();

    SimulationRun simRun = (SimulationRun) appContext.getBean(SimulationRun.class);
    String userId = "user1";
    TaskService taskService = (TaskService) appContext.getBean("taskService");
    TaskService simTaskService = (TaskService) appContext.getBean("simTaskService");
    List<Task> liveTaskList = ((TaskQuery) taskService.createTaskQuery().taskCandidateUser(userId)
            .orderByTaskPriority().desc()).listPage(0, 1);
    List<Task> execTaskList = ((TaskQuery) simTaskService.createTaskQuery().taskCandidateUser(userId)
            .orderByTaskPriority().desc()).listPage(0, 1);
    Assert.assertTrue(liveTaskList.size() == execTaskList.size());
    IdentityService identityService = (IdentityService) appContext.getBean("identityService");
    IdentityService simIdentityService = (IdentityService) appContext.getBean("simIdentityService");
    List<User> users = identityService.createUserQuery().list();
    List<User> simUsers = simIdentityService.createUserQuery().list();
    Assert.assertTrue(users.size() == simUsers.size());
    simRun.execute(new Date(), null);
    appContext.close();
}

From source file:org.openspaces.itest.persistency.cassandra.spring.CassandaraFactoryBeansTest.java

@Test
public void test() {

    final boolean refreshNow = false;
    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { TEST_FACTORY_XML }, refreshNow);

    PropertyPlaceholderConfigurer propertyConfigurer = new PropertyPlaceholderConfigurer();
    Properties properties = new Properties();
    properties.setProperty("cassandra.hosts", server.getHost());
    properties.setProperty("cassandra.port", String.valueOf(server.getPort()));
    properties.setProperty("cassandra.keyspace", server.getKeySpaceName());
    properties.setProperty("cassandra.user", "default");
    properties.setProperty("cassandra.password", "default");
    properties.setProperty("cassandra.ds.cluster", "ds_cluster");
    properties.setProperty("cassandra.sync.cluster", "sync_cluster");
    properties.setProperty("cassandra.ds.minconnections", String.valueOf(1));
    properties.setProperty("cassandra.ds.maxconnections", String.valueOf(5));
    properties.setProperty("cassandra.ds.batchlimit", String.valueOf(100));
    properties.setProperty("cassandra.hector.gcgrace", String.valueOf(60 * 60 * 24 * 10));
    properties.setProperty("cassandra.hector.read.consistency.level", CassandraConsistencyLevel.QUORUM.name());
    properties.setProperty("cassandra.hector.write.consistency.level", CassandraConsistencyLevel.ONE.name());
    propertyConfigurer.setProperties(properties);
    context.addBeanFactoryPostProcessor(propertyConfigurer);
    context.refresh();//from w  ww  .j a v a  2 s  . c  o  m

    try {
        syncEndpoint = context.getBean(CassandraSpaceSynchronizationEndpoint.class);
        dataSource = context.getBean(CassandraSpaceDataSource.class);
        doWork();
    } finally {
        context.close();
    }
}

From source file:net.sf.oval.test.integration.spring.SpringAOPAllianceTest.java

public void testCGLIBProxying() {
    final ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
            "SpringAOPAllianceTestCGLIBProxy.xml", SpringAOPAllianceTest.class);

    try {//from  w ww . j a v  a 2  s  .co m
        {
            final TestServiceWithoutInterface testServiceWithoutInterface = (TestServiceWithoutInterface) ctx
                    .getBean("testServiceWithoutInterface");

            try {
                testServiceWithoutInterface.getSomething(null);
                fail();
            } catch (final ConstraintsViolatedException ex) {
                assertEquals("NOT_NULL", ex.getConstraintViolations()[0].getMessage());
            }

            try {
                testServiceWithoutInterface.getSomething("123456");
                fail();
            } catch (final ConstraintsViolatedException ex) {
                assertEquals("MAX_LENGTH", ex.getConstraintViolations()[0].getMessage());
            }
        }

        {
            final TestServiceInterface testServiceWithInterface = ctx.getBean("testServiceWithInterface",
                    TestServiceInterface.class);

            try {
                testServiceWithInterface.getSomething(null);
                fail();
            } catch (final ConstraintsViolatedException ex) {
                assertEquals("NOT_NULL", ex.getConstraintViolations()[0].getMessage());
            }

            try {
                testServiceWithInterface.getSomething("123456");
                fail();
            } catch (final ConstraintsViolatedException ex) {
                assertEquals("MAX_LENGTH", ex.getConstraintViolations()[0].getMessage());
            }
        }
    } finally {
        ctx.close();
    }
}

From source file:gemlite.shell.admin.Admin.java

public void printMenu(String[] args) throws IOException, CmdLineException {
    String resource = ("ds-client.xml");
    ClassPathXmlApplicationContext mainContext = new ClassPathXmlApplicationContext(new String[] { resource },
            false);/*from  w ww.ja v a  2 s  .  c om*/
    mainContext.setValidating(true);
    mainContext.refresh();
    //Set<String> keys= mainContext.getBeansOfType(Region.class).keySet();

    ClientCache clientCache = ClientCacheFactory.getAnyInstance();
    dao = new AdminDao();
    Map<String, Pool> pools = PoolManager.getAll();
    dao.setClientPool(pools.entrySet().iterator().next().getValue());
    CmdLineParser parser = new CmdLineParser(this);
    do {
        System.out
                .println("*************************************************************\n Administrator args:");
        parser.printExample(ExampleMode.ALL);
        parser.printUsage(System.out);
        System.out.println("Press \"X\" to exit. Any other key to continue.");
        System.out.println("Input your option: ");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String line = bufferedReader.readLine();
        if (line.equalsIgnoreCase("X"))
            break;
        resetParam();
        String[] inputArgs = line.split(" ");
        if (inputArgs.length > 0 && inputArgs.length <= 2) {
            try {
                parser.parseArgument(inputArgs);
            } catch (Exception e) {
                System.err.println("Option error!");
            }
            try {
                doCommand(dao, clientCache);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (inputArgs.length > 2) {
            System.out.println("Please choose only one option each time.");
        }
    } while (true);
    mainContext.close();
}