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:gr.seab.r2rml.test.ComplianceTests.java

@Test
public void testAll() {
    log.info("test all");
    LinkedHashMap<String, String[]> tests = new LinkedHashMap<String, String[]>();
    tests.put("D000-1table1column0rows", new String[] { "r2rml.ttl" });
    tests.put("D001-1table1column1row", new String[] { "r2rmla.ttl", "r2rmlb.ttl" });
    tests.put("D002-1table2columns1row", new String[] { "r2rmla.ttl", "r2rmlb.ttl", "r2rmlc.ttl", "r2rmld.ttl",
            "r2rmle.ttl", "r2rmlf.ttl", "r2rmlg.ttl", "r2rmlh.ttl", "r2rmli.ttl", "r2rmlj.ttl" });
    tests.put("D003-1table3columns1row", new String[] { "r2rmla.ttl", "r2rmlb.ttl", "r2rmlc.ttl" });
    tests.put("D004-1table2columns1row", new String[] { "r2rmla.ttl", "r2rmlb.ttl" });
    tests.put("D005-1table3columns3rows2duplicates", new String[] { "r2rmla.ttl", "r2rmlb.ttl" });
    tests.put("D006-1table1primarykey1column1row", new String[] { "r2rmla.ttl" });
    tests.put("D007-1table1primarykey2columns1row", new String[] { "r2rmla.ttl", "r2rmlb.ttl", "r2rmlc.ttl",
            "r2rmld.ttl", "r2rmle.ttl", "r2rmlf.ttl", "r2rmlg.ttl", "r2rmlh.ttl" });
    tests.put("D008-1table1compositeprimarykey3columns1row",
            new String[] { "r2rmla.ttl", "r2rmlb.ttl", "r2rmlc.ttl" });
    tests.put("D009-2tables1primarykey1foreignkey",
            new String[] { "r2rmla.ttl", "r2rmlb.ttl", "r2rmlc.ttl", "r2rmld.ttl" });
    tests.put("D010-1table1primarykey3colums3rows", new String[] { "r2rmla.ttl", "r2rmlb.ttl", "r2rmlc.ttl" });
    tests.put("D011-M2MRelations", new String[] { "r2rmla.ttl", "r2rmlb.ttl" });
    tests.put("D012-2tables2duplicates0nulls",
            new String[] { "r2rmla.ttl", "r2rmlb.ttl", "r2rmlc.ttl", "r2rmld.ttl", "r2rmle.ttl" });
    tests.put("D013-1table1primarykey3columns2rows1nullvalue", new String[] { "r2rmla.ttl" });
    tests.put("D014-3tables1primarykey1foreignkey",
            new String[] { "r2rmla.ttl", "r2rmlb.ttl", "r2rmlc.ttl", "r2rmld.ttl" });
    tests.put("D015-1table3columns1composityeprimarykey3rows2languages",
            new String[] { "r2rmla.ttl", "r2rmlb.ttl" });
    tests.put("D016-1table1primarykey10columns3rowsSQLdatatypes",
            new String[] { "r2rmla.ttl", "r2rmlb.ttl", "r2rmlc.ttl", "r2rmld.ttl", "r2rmle.ttl" });
    tests.put("D017-I18NnoSpecialChars", new String[] {});
    tests.put("D018-1table1primarykey2columns3rows", new String[] { "r2rmla.ttl" });
    tests.put("D019-1table1primarykey3columns3rows", new String[] { "r2rmla.ttl", "r2rmlb.ttl" });
    tests.put("D020-1table1column5rows", new String[] { "r2rmla.ttl", "r2rmlb.ttl" });
    tests.put("D021-2tables2primarykeys1foreignkeyReferencesAllNulls", new String[] {});
    tests.put("D022-2tables1primarykey1foreignkeyReferencesNoPrimaryKey", new String[] {});
    tests.put("D023-2tables2primarykeys2foreignkeysReferencesToNon-primarykeys", new String[] {});
    tests.put("D024-2tables2primarykeys1foreignkeyToARowWithSomeNulls", new String[] {});
    tests.put("D025-3tables3primarykeys3foreignkeys", new String[] {});

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("test-context.xml");

    int counter = 0;
    for (String key : tests.keySet()) {
        if (counter > 2 && counter < 26) {
            String folder = "src/test/resources/postgres/" + key + "/";
            initialiseSourceDatabase(folder + "create.sql");

            for (String mappingFile : tests.get(key)) {
                //Override property file
                Parser parser = (Parser) context.getBean("parser");
                Properties p = parser.getProperties();
                mappingFile = folder + mappingFile;
                if (new File(mappingFile).exists()) {
                    p.setProperty("mapping.file", mappingFile);
                } else {
                    log.error("File " + mappingFile + " does not exist.");
                }/*  w ww  .ja  v a  2s .c om*/
                p.setProperty("jena.destinationFileName",
                        mappingFile.substring(0, mappingFile.indexOf(".") + 1) + "nq");
                parser.setProperties(p);
                MappingDocument mappingDocument = parser.parse();

                Generator generator = (Generator) context.getBean("generator");
                generator.setProperties(parser.getProperties());
                generator.setResultModel(parser.getResultModel());
                log.info("--- generating " + p.getProperty("jena.destinationFileName") + " from " + mappingFile
                        + " ---");
                generator.createTriples(mappingDocument);
            }
        }
        counter++;
    }
    context.close();
}

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

@Before
public void setUp() throws Exception {
    String PROCESS_KEY = "threetasksprocess";
    File prevDB = new File((new StringBuilder()).append(LIVE_DB).append(".h2.db").toString());
    System.setProperty("liveDB", LIVE_DB);
    if (prevDB.exists())
        prevDB.delete();/*from   w w w .j av  a  2 s . co m*/
    prevDB = null;
    ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
            "org/activiti/crystalball/simulator/LiveEngine-context.xml");
    RepositoryService repositoryService = (RepositoryService) appContext.getBean("repositoryService");
    RuntimeService runtimeService = (RuntimeService) appContext.getBean("runtimeService");
    TaskService taskService = (TaskService) appContext.getBean("taskService");
    IdentityService identityService = (IdentityService) appContext.getBean("identityService");
    ProcessEngine processEngine = (ProcessEngine) appContext.getBean("processEngine");
    repositoryService.createDeployment()
            .addClasspathResource("org/activiti/crystalball/simulator/ThreeTasksProcess.bpmn").deploy();
    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");
    Calendar calendar = Calendar.getInstance();
    calendar.set(2012, 11, 7, 18, 1, 0);
    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,
                (new StringBuilder()).append("BUSINESS-KEY-").append(i).toString(), variables);

    List<Task> taskList = taskService.createTaskQuery().taskCandidateUser("user1").list();
    for (int i = 0; i < 5; i++) {
        Task t = (Task) taskList.get(i);
        taskService.claim(t.getId(), "user1");
    }

    Thread.sleep(500L);
    for (int i = 0; i < 5; i++) {
        Task t = (Task) taskList.get(i);
        taskService.complete(t.getId());
    }

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

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

@Test
public void testPlaybackRun() throws Exception {
    System.setProperty("_SIM_DB_PATH", System.getProperty("tempDir", "target") + "/Playback-test");
    System.setProperty("liveDB", "target/Playback");

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

    HistoryService simHistoryService = (HistoryService) appContext.getBean("simHistoryService");

    // init identity service
    IdentityService identityService = (IdentityService) appContext.getBean("simIdentityService");
    identityService.saveGroup(identityService.newGroup("Group1"));
    identityService.saveUser(identityService.newUser("user1"));
    identityService.createMembership("user1", "Group1");

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

    RepositoryService simRepositoryService = (RepositoryService) appContext.getBean("simRepositoryService");

    // deploy processes
    simRepositoryService.createDeployment()
            .addClasspathResource("org/activiti/crystalball/simulator/Playback.bpmn").deploy();

    Calendar c = Calendar.getInstance();
    c.clear();/* w  w  w  .jav a  2s .c  om*/
    c.set(2013, 3, 3);
    Date startDate = c.getTime();
    c.add(Calendar.SECOND, 10);
    Date finishDate = c.getTime();
    // run simulation for 10 seconds
    simRun.execute(startDate, finishDate);

    assertEquals(3, simHistoryService.createHistoricProcessInstanceQuery().count());
    List<HistoricProcessInstance> processInstances = simHistoryService.createHistoricProcessInstanceQuery()
            .orderByProcessInstanceStartTime().asc().list();
    HistoricProcessInstance processInstance = processInstances.get(0);
    HistoricVariableInstance variableInstance = simHistoryService.createHistoricVariableInstanceQuery()
            .processInstanceId(processInstance.getId()).variableName("x").singleResult();
    assertEquals(3, ((Integer) variableInstance.getValue()).intValue());

    processInstance = processInstances.get(1);
    variableInstance = simHistoryService.createHistoricVariableInstanceQuery()
            .processInstanceId(processInstance.getId()).variableName("x").singleResult();
    assertEquals(2, ((Integer) variableInstance.getValue()).intValue());

    processInstance = processInstances.get(2);
    variableInstance = simHistoryService.createHistoricVariableInstanceQuery()
            .processInstanceId(processInstance.getId()).variableName("x").singleResult();
    assertEquals(3, ((Integer) variableInstance.getValue()).intValue());

    appContext.close();
}

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

private static void generatePlaybackOriginal() throws InterruptedException, IOException {
    String PROCESS_KEY = "playback";
    RepositoryService repositoryService;
    RuntimeService runtimeService;//from  www. j a  va  2 s. c  o  m
    TaskService taskService;
    IdentityService identityService;
    HistoryService historyService;
    ProcessEngine processEngine;
    String liveDB = TEMP_DIR + "/Playback";

    // 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");
    Calendar calendar = Calendar.getInstance();
    calendar.set(2013, 01, 25, 14, 30, 00);
    ClockUtil.setCurrentTime(calendar.getTime());

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

    processEngine = appContext.getBean(ProcessEngine.class);

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

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

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

    // start processes 
    Map<String, Object> variables2 = new HashMap<String, Object>();
    variables2.put("x", 3);
    Map<String, Object> variables1 = new HashMap<String, Object>();
    variables1.put("x", 1);
    Map<String, Object> variables0 = new HashMap<String, Object>();
    variables0.put("x", 0);

    ProcessInstance processInstance1 = runtimeService.startProcessInstanceByKey(PROCESS_KEY, "BUSINESS-KEY-1",
            variables0);
    calendar.add(Calendar.SECOND, 1);
    ClockUtil.setCurrentTime(calendar.getTime());
    ProcessInstance processInstance2 = runtimeService.startProcessInstanceByKey(PROCESS_KEY, "BUSINESS-KEY-2",
            variables1);
    calendar.add(Calendar.SECOND, 1);
    ClockUtil.setCurrentTime(calendar.getTime());
    runtimeService.startProcessInstanceByKey(PROCESS_KEY, "BUSINESS-KEY-3", variables0);

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

    // complete these tasks
    for (Task t : taskList) {
        // wait some time  to have some data in history 
        calendar.add(Calendar.SECOND, 1);
        ClockUtil.setCurrentTime(calendar.getTime());
        // complete task
        taskService.complete(t.getId(), variables2);
    }

    // audit trail images generator
    AuditTrailProcessDiagramGenerator generator = new AuditTrailProcessDiagramGenerator();
    generator.setHistoryService(historyService);
    generator.setRepositoryService((RepositoryServiceImpl) repositoryService);
    generator.setWriteUpdates(true);

    Map<String, Object> params = new HashMap<String, Object>();
    params.put(AuditTrailProcessDiagramGenerator.PROCESS_INSTANCE_ID, processInstance1.getId());

    ImageIO.write(ImageIO.read(generator.generateLayer("png", params)), "png",
            new File(TEMP_DIR + "/playback-auditTrail1.png"));

    params.clear();
    params.put(AuditTrailProcessDiagramGenerator.PROCESS_INSTANCE_ID, processInstance2.getId());

    ImageIO.write(ImageIO.read(generator.generateLayer("png", params)), "png",
            new File(TEMP_DIR + "/playback-auditTrail2.png"));

    processEngine.close();

    appContext.close();

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

}

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

/**
 * repeat playback 2 times + 2 seconds (2 new processes are started0
 * @throws Exception /*  ww  w  .  jav  a  2  s .c  o  m*/
 */
@Test
public void testPlayback2Run() throws Exception {
    System.setProperty("_SIM_DB_PATH", System.getProperty("tempDir", "target") + "/Playback-test2");
    System.setProperty("liveDB", "target/Playback");

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

    // deploy processes
    RepositoryService simRepositoryService = (RepositoryService) appContext.getBean("simRepositoryService");
    simRepositoryService.createDeployment()
            .addClasspathResource("org/activiti/crystalball/simulator/Playback.bpmn").deploy();

    HistoryService historyService = (HistoryService) appContext.getBean("simHistoryService");
    // init identity service
    IdentityService identityService = (IdentityService) appContext.getBean("simIdentityService");
    identityService.saveGroup(identityService.newGroup("Group1"));
    identityService.saveUser(identityService.newUser("user1"));
    identityService.createMembership("user1", "Group1");

    SimulationRun simRun = (SimulationRun) appContext.getBean(SimulationRun.class);
    PlaybackScheduleStartProcessEventHandler schedule = (PlaybackScheduleStartProcessEventHandler) appContext
            .getBean("scheduleProcessEventHandler");
    schedule.setRepeatPlayback(true);

    Calendar c = Calendar.getInstance();
    c.clear();
    c.set(2013, 3, 3);
    Date startDate = c.getTime();
    c.add(Calendar.SECOND, 12);
    Date finishDate = c.getTime();
    // run simulation for 12 seconds
    simRun.execute(startDate, finishDate);

    assertEquals(8, historyService.createHistoricProcessInstanceQuery().count());
    List<HistoricProcessInstance> processInstances = historyService.createHistoricProcessInstanceQuery()
            .orderByProcessInstanceStartTime().asc().list();
    HistoricProcessInstance processInstance = processInstances.get(0);
    HistoricVariableInstance variableInstance = historyService.createHistoricVariableInstanceQuery()
            .processInstanceId(processInstance.getId()).variableName("x").singleResult();
    assertEquals(3, ((Integer) variableInstance.getValue()).intValue());

    processInstance = processInstances.get(1);
    variableInstance = historyService.createHistoricVariableInstanceQuery()
            .processInstanceId(processInstance.getId()).variableName("x").singleResult();
    assertEquals(2, ((Integer) variableInstance.getValue()).intValue());

    processInstance = processInstances.get(2);
    variableInstance = historyService.createHistoricVariableInstanceQuery()
            .processInstanceId(processInstance.getId()).variableName("x").singleResult();
    assertEquals(3, ((Integer) variableInstance.getValue()).intValue());

    processInstance = processInstances.get(3);
    variableInstance = historyService.createHistoricVariableInstanceQuery()
            .processInstanceId(processInstance.getId()).variableName("x").singleResult();
    assertEquals(3, ((Integer) variableInstance.getValue()).intValue());

    processInstance = processInstances.get(4);
    variableInstance = historyService.createHistoricVariableInstanceQuery()
            .processInstanceId(processInstance.getId()).variableName("x").singleResult();
    assertEquals(2, ((Integer) variableInstance.getValue()).intValue());

    processInstance = processInstances.get(5);
    variableInstance = historyService.createHistoricVariableInstanceQuery()
            .processInstanceId(processInstance.getId()).variableName("x").singleResult();
    assertEquals(3, ((Integer) variableInstance.getValue()).intValue());

    processInstance = processInstances.get(6);
    variableInstance = historyService.createHistoricVariableInstanceQuery()
            .processInstanceId(processInstance.getId()).variableName("x").singleResult();
    //user task was not finished yet
    assertEquals(1, ((Integer) variableInstance.getValue()).intValue());

    processInstance = processInstances.get(7);
    variableInstance = historyService.createHistoricVariableInstanceQuery()
            .processInstanceId(processInstance.getId()).variableName("x").singleResult();
    assertEquals(2, ((Integer) variableInstance.getValue()).intValue());

    appContext.close();
}

From source file:com.alibaba.dubbo.examples.validation.ValidationTest.java

@Test
public void testValidation() {
    ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(
            ValidationTest.class.getPackage().getName().replace('.', '/') + "/validation-provider.xml");
    providerContext.start();// w ww . java 2s.c  om
    try {
        ClassPathXmlApplicationContext consumerContext = new ClassPathXmlApplicationContext(
                ValidationTest.class.getPackage().getName().replace('.', '/') + "/validation-consumer.xml");
        consumerContext.start();
        try {
            ValidationService validationService = (ValidationService) consumerContext
                    .getBean("validationService");

            // Save OK
            ValidationParameter parameter = new ValidationParameter();
            parameter.setName("liangfei");
            parameter.setEmail("liangfei@liang.fei");
            parameter.setAge(50);
            parameter.setLoginDate(new Date(System.currentTimeMillis() - 1000000));
            parameter.setExpiryDate(new Date(System.currentTimeMillis() + 1000000));
            validationService.save(parameter);

            try {
                parameter = new ValidationParameter();
                parameter.setName("l");
                parameter.setEmail("liangfei@liang.fei");
                parameter.setAge(50);
                parameter.setLoginDate(new Date(System.currentTimeMillis() - 1000000));
                parameter.setExpiryDate(new Date(System.currentTimeMillis() + 1000000));
                validationService.save(parameter);
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
            }

            // Save Error
            try {
                parameter = new ValidationParameter();
                validationService.save(parameter);
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
            }

            // Delete OK
            validationService.delete(2, "abc");

            // Delete Error
            try {
                validationService.delete(2, "a");
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
                Assert.assertEquals(1, violations.size());
            }

            // Delete Error
            try {
                validationService.delete(0, "abc");
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
                Assert.assertEquals(1, violations.size());
            }
            try {
                validationService.delete(2, null);
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
                Assert.assertEquals(1, violations.size());
            }
            try {
                validationService.delete(0, null);
                Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Assert.assertNotNull(violations);
                Assert.assertEquals(2, violations.size());
            }
        } finally {
            consumerContext.stop();
            consumerContext.close();
        }
    } finally {
        providerContext.stop();
        providerContext.close();
    }
}

From source file:validation.ValidationTest.java

@Test
public void testValidation() {
    ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(
            ValidationTest.class.getPackage().getName().replace('.', '/') + "/validation-provider.xml");
    providerContext.start();/*from   ww  w .jav a2s  . co  m*/
    try {
        ClassPathXmlApplicationContext consumerContext = new ClassPathXmlApplicationContext(
                ValidationTest.class.getPackage().getName().replace('.', '/') + "/validation-consumer.xml");
        consumerContext.start();
        try {
            ValidationService validationService = (ValidationService) consumerContext
                    .getBean("validationService");

            // Save OK
            ValidationParameter parameter = new ValidationParameter();
            parameter.setName("liangfei");
            parameter.setEmail("liangfei@liang.fei");
            parameter.setAge(50);
            parameter.setLoginDate(new Date(System.currentTimeMillis() - 1000000));
            parameter.setExpiryDate(new Date(System.currentTimeMillis() + 1000000));
            validationService.save(parameter);

            try {
                parameter = new ValidationParameter();
                parameter.setName("l");
                parameter.setEmail(null);
                parameter.setAge(50);
                parameter.setLoginDate(new Date(System.currentTimeMillis() - 1000000));
                parameter.setExpiryDate(new Date(System.currentTimeMillis() + 1000000));
                validationService.save(parameter);
                // Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                System.out.println(violations);
                // Assert.assertNotNull(violations);
            }

            // Save Error
            try {
                parameter = new ValidationParameter();
                validationService.save(parameter);
                // Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                //  Assert.assertNotNull(violations);
                System.out.println(violations);
            }

            // Delete OK
            validationService.delete(2, "abc");

            // Delete Error
            try {
                validationService.delete(2, "a");
                //    Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                System.out.println(violations);

            }

            // Delete Error
            try {
                validationService.delete(0, "abc");
                //    Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                System.out.println(violations);
            }
            try {
                validationService.delete(2, null);
                //    Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                System.out.println(violations);
            }
            try {
                validationService.delete(0, null);
                //    Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                System.out.println(violations);

            }
            try {
                validationService.delete(0, "0000");
                //    Assert.fail();
            } catch (RpcException e) {
                ConstraintViolationException ve = (ConstraintViolationException) e.getCause();
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                System.out.println(violations);

            }
        } finally {
            consumerContext.stop();
            consumerContext.close();
        }
    } finally {
        providerContext.stop();
        providerContext.close();
    }
}

From source file:com.nokia.dempsy.mpcluster.zookeeper.TestFullApp.java

@Test
public void testStartForceMpDisconnectStop() throws Throwable {
    ClassPathXmlApplicationContext actx = null;
    Dempsy dempsy = null;/*  w  ww.ja va2s  .  co  m*/

    try {
        logger.debug("Starting up the appliction context ...");
        actx = new ClassPathXmlApplicationContext(ctx);
        actx.registerShutdownHook();

        final FullApplication app = (FullApplication) actx.getBean("app");

        dempsy = (Dempsy) actx.getBean("dempsy");

        // Override the cluster session factory to keep track of the sessions asked for.
        // This is so that I can grab the ZookeeperSession that's being instantiated by
        // the MyMp cluster.
        zookeeperCluster = null;
        dempsy.setClusterSessionFactory(new ZookeeperSessionFactory<ClusterInformation, SlotInformation>(
                System.getProperty("zk_connect"), 5000) {
            int sessionCount = 0;

            @Override
            public synchronized MpClusterSession<ClusterInformation, SlotInformation> createSession()
                    throws MpClusterException {
                sessionCount++;
                MpClusterSession<ClusterInformation, SlotInformation> ret = super.createSession();

                if (sessionCount == 2)
                    zookeeperCluster = (ZookeeperSession<ClusterInformation, SlotInformation>) ret;
                return ret;
            }
        });

        dempsy.start();

        Dempsy.Application.Cluster cluster = dempsy.getCluster(
                new ClusterId(FullApplication.class.getSimpleName(), MyAdaptor.class.getSimpleName()));
        Dempsy.Application.Cluster.Node node = cluster.getNodes().get(0);
        final StatsCollector collector = node.getStatsCollector();

        // this checks that the throughput works.
        assertTrue(poll(baseTimeoutMillis * 5, app, new Condition<Object>() {
            @Override
            public boolean conditionMet(Object o) {
                return app.finalMessageCount.get() > 10;
            }
        }));

        assertNotNull(zookeeperCluster);

        assertEquals(0, collector.getDiscardedMessageCount());
        assertEquals(0, collector.getMessageFailedCount());

        // ok ... so now we have stuff going all the way through. let's kick
        // the middle Mp's zookeeper cluster and see what happens.
        ZooKeeper origZk = zookeeperCluster.zkref.get();
        long sessionid = origZk.getSessionId();
        ZooKeeper killer = new ZooKeeper(System.getProperty("zk_connect"), 5000, new Watcher() {
            @Override
            public void process(WatchedEvent arg0) {
            }
        }, sessionid, null);
        killer.close(); // tricks the server into expiring the other session

        //         // we should be getting failures now ... 
        //         // but it's possible that it can reconnect prior to actually seeing an error so if this 
        //         //   fails frequently we need to remove this test.
        //         assertTrue(poll(baseTimeoutMillis, app, new Condition()
        //         {
        //            @Override
        //            public boolean conditionMet(Object o)
        //            {
        //               return collector.getMessageFailedCount() > 1;
        //            }
        //         }));

        //... and then recover.

        // get the MyMp prototype
        cluster = dempsy
                .getCluster(new ClusterId(FullApplication.class.getSimpleName(), MyMp.class.getSimpleName()));
        node = cluster.getNodes().get(0);
        final MyMp prototype = (MyMp) node.getMpContainer().getPrototype();

        // so let's see where we are
        final long interimMessageCount = prototype.myMpReceived.get();

        // and now we should eventually get more as the session recovers.
        assertTrue(poll(baseTimeoutMillis * 5, app, new Condition<Object>() {
            @Override
            public boolean conditionMet(Object o) {
                return prototype.myMpReceived.get() > interimMessageCount + 100;
            }
        }));
    } finally {
        if (dempsy != null)
            dempsy.stop();

        if (actx != null)
            actx.close();

        if (dempsy != null)
            assertTrue(dempsy.waitToBeStopped(baseTimeoutMillis));
    }
}

From source file:com.nokia.dempsy.mpcluster.zookeeper.TestFullApp.java

@Test
public void testStartForceMpDisconnectWithStandby() throws Throwable {
    ClassPathXmlApplicationContext actx = null;
    Dempsy dempsy = null;/*from w  w  w  .  j  ava2  s  .co m*/

    try {
        logger.debug("Starting up the appliction context ...");
        actx = new ClassPathXmlApplicationContext(ctx);
        actx.registerShutdownHook();

        final FullApplication app = (FullApplication) actx.getBean("app");

        dempsy = (Dempsy) actx.getBean("dempsy");

        // Override the cluster session factory to keep track of the sessions asked for.
        // This is so that I can grab the ZookeeperSession that's being instantiated by
        // the MyMp cluster.
        zookeeperCluster = null;
        dempsy.setClusterSessionFactory(new ZookeeperSessionFactory<ClusterInformation, SlotInformation>(
                System.getProperty("zk_connect"), 5000) {
            int sessionCount = 0;

            @Override
            public synchronized MpClusterSession<ClusterInformation, SlotInformation> createSession()
                    throws MpClusterException {
                sessionCount++;
                MpClusterSession<ClusterInformation, SlotInformation> ret = super.createSession();

                if (sessionCount == 2)
                    zookeeperCluster = (ZookeeperSession<ClusterInformation, SlotInformation>) ret;
                return ret;
            }
        });

        dempsy.start();

        Dempsy.Application.Cluster cluster = dempsy.getCluster(
                new ClusterId(FullApplication.class.getSimpleName(), MyAdaptor.class.getSimpleName()));
        Dempsy.Application.Cluster.Node node = cluster.getNodes().get(0);
        final StatsCollector collector = node.getStatsCollector();

        // we are going to create another node of the MyMp via a test hack
        cluster = dempsy
                .getCluster(new ClusterId(FullApplication.class.getSimpleName(), MyMp.class.getSimpleName()));
        Dempsy.Application.Cluster.Node mpnode = cluster.getNodes().get(0);
        cluster.instantiateAndStartAnotherNodeForTesting(); // the code for start instantiates a new node

        // this checks that the throughput works.
        assertTrue(poll(baseTimeoutMillis * 5, app, new Condition<Object>() {
            @Override
            public boolean conditionMet(Object o) {
                return app.finalMessageCount.get() > 10;
            }
        }));

        assertNotNull(zookeeperCluster);

        assertEquals(0, collector.getDiscardedMessageCount());
        assertEquals(0, collector.getMessageFailedCount());

        // ok ... so now we have stuff going all the way through. let's kick
        // the middle Mp's zookeeper cluster and see what happens.
        ZooKeeper origZk = zookeeperCluster.zkref.get();
        origZk.close(); // this should kill it.

        // but just to be sure actually stop the node.
        mpnode.stop();

        //         // we should be getting failures now ... 
        //         // but it's possible that it can reconnect prior to actually seeing an error so if this 
        //         //   fails frequently we need to remove this test.
        //         assertTrue(poll(baseTimeoutMillis, app, new Condition()
        //         {
        //            @Override
        //            public boolean conditionMet(Object o)
        //            {
        //               return collector.getMessageFailedCount() > 1;
        //            }
        //         }));

        //... and then recover.

        // get the MyMp prototype
        cluster = dempsy
                .getCluster(new ClusterId(FullApplication.class.getSimpleName(), MyMp.class.getSimpleName()));
        node = cluster.getNodes().get(1); // notice, we're getting the SECOND node.
        final MyMp prototype = (MyMp) node.getMpContainer().getPrototype();

        // so let's see where we are
        final long interimMessageCount = prototype.myMpReceived.get();

        // and now we should eventually get more as the session recovers.
        assertTrue(poll(baseTimeoutMillis * 5, app, new Condition<Object>() {
            @Override
            public boolean conditionMet(Object o) {
                return prototype.myMpReceived.get() > interimMessageCount + 100;
            }
        }));

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

        if (actx != null)
            actx.close();

        if (dempsy != null)
            assertTrue(dempsy.waitToBeStopped(baseTimeoutMillis));
    }

}

From source file:org.alfresco.bm.tools.BMTestRunner.java

/**
 * Execute the default test against the given MongoDB or an in-memory instance
 * //from w  w  w  .j  a v  a 2 s .  co m
 * @param mongoConfigHost           the MongoDB host to connect to for configuraton data or <tt>null</tt> to use an in-memory version
 * @param mongoTestHost             the MongoDB host to connect to for test data data or <tt>null</tt> to use the same database as the config
 * @param testProperties            any properties to specifically set for the test or <tt>null</tt> if there are none
 */
public void run(String mongoConfigHost, String mongoTestHost, Properties testProperties) throws Exception {
    // Secure the listeners against modification
    List<BMTestRunnerListener> listeners = new ArrayList<BMTestRunnerListener>(this.listeners);

    // If no MongoDB URL is provided, then we have to start one
    MongoDBForTestsFactory mongoDBForTestsFactory = null;
    ClassPathXmlApplicationContext ctx = null;
    try {
        // Ensure that required system properties are present
        System.setProperty(PROP_APP_CONTEXT_PATH, System.getProperty("user.dir"));
        System.setProperty(PROP_APP_DIR, System.getProperty("user.dir"));

        // Create a MongoDB for use if one has not been specified
        if (mongoConfigHost == null) {
            mongoDBForTestsFactory = new MongoDBForTestsFactory();
            String uriWithoutDB = mongoDBForTestsFactory.getMongoURIWithoutDB();
            mongoConfigHost = new MongoClientURI(uriWithoutDB).getHosts().get(0);
        }
        // Fill in the URI for the test MongoDB
        if (mongoTestHost == null) {
            mongoTestHost = mongoConfigHost;
        }

        // Fill in the properties required for the test
        Properties mongoProps = new Properties();
        mongoProps.put(PROP_MONGO_CONFIG_HOST, mongoConfigHost);

        // Construct the application context
        ctx = new ClassPathXmlApplicationContext(new String[] { PATH_APP_CONTEXT }, false);
        // Push cluster properties into the context (must be done AFTER setting parent context)
        ConfigurableEnvironment ctxEnv = ctx.getEnvironment();
        // Mongo properties come first
        ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("mongo-props", mongoProps));
        // Finally, system properties overrule them all
        ctxEnv.getPropertySources()
                .addFirst(new PropertiesPropertySource("system-props", System.getProperties()));

        // Kick it all off
        try {
            ctx.refresh();
        } catch (Exception e) {
            Throwable root = ExceptionUtils.getRootCause(e);
            if (root != null
                    && (root instanceof MongoSocketException || root instanceof UnknownHostException)) {
                // We deal with this specifically as it's a simple case of not finding the MongoDB
                logger.error("Set the configuration property '" + PROP_MONGO_CONFIG_HOST
                        + "' (<server>:<port>) as required.");
            } else {
                // Log application start failure because test frameworks might not do so nicely
                logger.error("Failed to start application.", e);
            }
            throw new RuntimeException("Failed to start application.", e);
        }

        // Get the test
        Test test = ctx.getBean(Test.class);
        String release = test.getRelease();
        Integer schema = test.getSchema();

        TestRestAPI api = ctx.getBean(TestRestAPI.class);

        // Create a new test
        TestDetails testDetails = new TestDetails();
        String testName = "BMTestRunner_" + System.currentTimeMillis();
        testDetails.setName(testName);
        testDetails.setDescription("Test created by BMTestRunner on " + new Date());
        testDetails.setRelease(release);
        testDetails.setSchema(schema);
        api.createTest(testDetails);

        // We need to tell the test which MongoDB to write data to
        PropSetBean propSet = new PropSetBean();
        propSet.setValue(mongoTestHost);
        propSet.setVersion(0);
        api.setTestProperty(testName, PROP_MONGO_TEST_HOST, propSet);

        // Now set any properties that have been explicitly passed in for the test
        if (testProperties != null) {
            for (Map.Entry<Object, Object> entry : testProperties.entrySet()) {
                String propKey = (String) entry.getKey();
                String propVal = (String) entry.getValue();

                propSet.setValue(propVal);
                propSet.setVersion(0);
                api.setTestProperty(testName, propKey, propSet);
            }
        }

        // Call listeners: the test has been created
        for (BMTestRunnerListener listener : listeners) {
            listener.testReady(ctx, testName);
        }

        // Create a new test run
        TestRunDetails testRunDetails = new TestRunDetails();
        String testRunName = "BMTestRunner_" + System.currentTimeMillis();
        testRunDetails.setName(testRunName);
        testRunDetails.setDescription("Test run created by BMTestRunner on " + new Date());
        api.createTestRun(testDetails.getName(), testRunDetails);

        // Call listeners: the test run has been created
        for (BMTestRunnerListener listener : listeners) {
            listener.testRunReady(ctx, testName, testRunName);
        }

        // Get all the test run properties for logging
        String jsonTestRun = api.getTestRun(testName, testRunName);

        // Start the test run
        logger.info("Starting test run: " + testRunName + "\n" + jsonTestRun);
        TestRunSchedule testRunSchedule = new TestRunSchedule();
        testRunSchedule.setScheduled(System.currentTimeMillis());
        api.scheduleTestRun(testName, testRunName, testRunSchedule);

        // Call listeners: the test run has started
        for (BMTestRunnerListener listener : listeners) {
            listener.testRunStarted(ctx, testName, testRunName);
        }

        // Wait for the test run to complete
        long timeInit = System.currentTimeMillis();
        long timeLastChange = -1L;
        String jsonLastChange = null;
        String testRunStateStr = api.getTestRunState(testName, testRunName);

        // Keep looking until the test run completes
        while (!TestRunState.COMPLETED.toString().equals(testRunStateStr)) {
            long now = System.currentTimeMillis();

            // Check that we have not exceeded the maximum time
            if (now - timeInit > maxTestTime) {
                throw new RuntimeException("Test run failed to complete in " + (int) maxTestTime / 1000 + "s.");
            }

            testRunStateStr = api.getTestRunState(testName, testRunName);

            if (TestRunState.SCHEDULED.toString().equals(testRunStateStr) && (now - timeInit) > 10000L) {
                throw new RuntimeException("Test run failed to start in 10s.");
            }

            // Check that there are updates to the test run
            String jsonNow = api.getTestRunSummary(testName, testRunName);
            if (jsonLastChange != null && jsonLastChange.equals(jsonNow)) {
                if ((now - timeLastChange) > 60000L) {
                    throw new RuntimeException("Test run has not been updated in the last 60s");
                }
            }
            // Store values for next iteration
            timeLastChange = now;
            jsonLastChange = jsonNow;

            synchronized (testRunStateStr) {
                try {
                    testRunStateStr.wait(1000L);
                } catch (InterruptedException e) {
                }
            }
        }
        // Call listeners: the test run has finished
        for (BMTestRunnerListener listener : listeners) {
            listener.testRunFinished(ctx, testName, testRunName);
        }
    } finally {
        // Close the context
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                logger.error("Failed to shut down application context.", e);
            }
        }
        // Close the local Mongo instance
        if (mongoDBForTestsFactory != null) {
            try {
                mongoDBForTestsFactory.destroy();
            } catch (Exception e) {
                logger.error("Failed to stop in-memory MongoDB instance.", e);
            }
        }
    }
}