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

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

Introduction

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

Prototype

@Override
    public Object getBean(String name) throws BeansException 

Source Link

Usage

From source file:org.drools.container.spring.SpringDroolsTest.java

@Test
public void testNoNodeKSessions() throws Exception {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "org/drools/container/spring/no-node-beans.xml");

    List<String> list = new ArrayList<String>();
    StatelessKnowledgeSession kstateless = (StatelessKnowledgeSession) context.getBean("ksession1");
    kstateless.setGlobal("list", list);
    kstateless.execute(new Person("Darth", "Cheddar", 50));
    assertEquals(1, list.size());//from  w w  w.jav a  2  s.co m

    list = new ArrayList<String>();
    StatefulKnowledgeSession kstateful = ((StatefulKnowledgeSession) context.getBean("ksession2"));
    kstateful.setGlobal("list", list);
    kstateful.insert(new Person("Darth", "Cheddar", 50));
    kstateful.fireAllRules();
    assertEquals(1, list.size());
}

From source file:com.hm.SSI.dubbo.AnnotationTest.java

@Test
public void testAnnotation() {
    ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(
            AnnotationTest.class.getPackage().getName().replace('.', '/') + "/annotation-provider.xml");
    System.out.println(/*w w w  .  j  a  v a  2  s.  c  o  m*/
            AnnotationTest.class.getPackage().getName().replace('.', '/') + "/annotation-provider.xml");
    providerContext.start();
    try {
        ClassPathXmlApplicationContext consumerContext = new ClassPathXmlApplicationContext(
                AnnotationTest.class.getPackage().getName().replace('.', '/') + "/annotation-consumer.xml");
        System.out.println(
                AnnotationTest.class.getPackage().getName().replace('.', '/') + "/annotation-consumer.xml");
        consumerContext.start();
        try {
            AnnotationAction annotationAction = (AnnotationAction) consumerContext.getBean("annotationAction");
            String hello = annotationAction.doSayHello("world");
            assertEquals("annotation: hello, world", hello);
        } finally {
            consumerContext.stop();
            consumerContext.close();
        }
    } finally {
        providerContext.stop();
        providerContext.close();
    }
}

From source file:org.dataconservancy.packaging.gui.App.java

public void start(Stage stage) throws Exception {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath*:org/dataconservancy/config/applicationContext.xml",
            "classpath*:org/dataconservancy/packaging/tool/ser/config/applicationContext.xml",
            "classpath*:applicationContext.xml");

    // min supported size is 800x600
    stage.setMinWidth(800);//from   w w w .  j ava 2s .c  o m
    stage.setMinHeight(550);
    Factory factory = (Factory) context.getBean("factory");
    factory.setStage(stage);

    Font.loadFont(App.class.getResource("/fonts/OpenSans-Regular.ttf").toExternalForm(), 14);
    Font.loadFont(App.class.getResource("/fonts/OpenSans-Italic.ttf").toExternalForm(), 14);
    Font.loadFont(App.class.getResource("/fonts/OpenSans-Bold.ttf").toExternalForm(), 14);

    Configuration config = factory.getConfiguration();
    CmdLineParser parser = new CmdLineParser(config);

    try {
        List<String> raw = getParameters().getRaw();
        parser.parseArgument(raw.toArray(new String[raw.size()]));
    } catch (CmdLineException e) {
        System.out.println(e.getMessage());
        log.error(e.getMessage());
        Platform.exit();
        return;
    }

    Controller controller = factory.getController();
    controller.setApplicationHostServices(getHostServices());

    controller.startApp();

    // Default size to 800x800, but shrink if screen is too small
    double sceneHeight = 800;

    Rectangle2D screen = Screen.getPrimary().getVisualBounds();
    if (screen.getHeight() < 800) {
        sceneHeight = screen.getHeight() - 50;
        if (sceneHeight < 550)
            sceneHeight = 550;
    }

    Scene scene = new Scene(controller.asParent(), 800, sceneHeight);
    scene.getStylesheets().add("/css/app.css");

    stage.getIcons().add(new Image("/images/DCPackageTool-icon.png"));
    stage.setTitle("DC Package Tool");
    stage.setScene(scene);
    stage.show();

}

From source file:org.bibsonomy.database.systemstags.SystemTagFactory.java

/**
 * Constructor/*from  w  w  w .  j  a v a  2  s .c o  m*/
 */
@SuppressWarnings("unchecked")
private SystemTagFactory() {
    /*
     * FIXME: shouldn't we configure this from the outside?
     */
    final ClassPathXmlApplicationContext springBeanFactory = new ClassPathXmlApplicationContext(
            SYSTEM_TAG_CONFIG_FILE);
    this.executableSystemTagMap = new HashMap<String, ExecutableSystemTag>();
    this.fillExecutableSystemTagMap(
            (Set<ExecutableSystemTag>) springBeanFactory.getBean("executableSystemTagSet"));
    this.searchSystemTagMap = new HashMap<String, SearchSystemTag>();
    this.fillSearchSystemTagMap((Set<SearchSystemTag>) springBeanFactory.getBean("searchSystemTagSet"));
    this.markUpSystemTagMap = new HashMap<String, MarkUpSystemTag>();
    this.fillMarkUpSystemTagMap((Set<MarkUpSystemTag>) springBeanFactory.getBean("markUpSystemTagSet"));
}

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();/*www .jav a 2 s. 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("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:gemlite.shell.service.batch.ImportService.java

/**
 * //from   www . j a va 2s. co m
 * @param template
 * @param file
 * @param delimiter
 * @param quote
 * @param skipable
 * @param columns
 * @param region
 * @param table
 * @param encoding
 * @param linesToSkip
 * @param dbdriver
 *          //?????
 * @param dburl
 * @param dbuser
 * @param dbpsw
 * @param sortKey
 * @param where
 * @param pageSize
 * @param fetchSize
 * @return
 */
public boolean defineJob(String template, String file, String delimiter, String quote, boolean skipable,
        String columns, String region, String table, String encoding, int linesToSkip, String dbdriver,
        String dburl, String dbuser, String dbpsw, String sortKey, String where, int pageSize, int fetchSize) {
    BatchParameter param = new BatchParameter(template, file, delimiter, quote, skipable, columns, region,
            table, encoding, linesToSkip, sortKey, where, pageSize, fetchSize);
    if (!validParameters(param))
        return false;
    String cacheKey = region + template;
    try {
        // ??,?db??
        if (StringUtils.equals(BatchTemplateTypes.jdbcPartition.getValue(), param.getTemplate())
                || StringUtils.equals(BatchTemplateTypes.jdbcpaging.getValue(), param.getTemplate())) {
            // ??
            setDbParameter(dbdriver, dburl, dbuser, dbpsw);
            saveDbConfig(dbdriver, dburl, dbuser, dbpsw);
        }

        // partition,?table
        if (StringUtils.equals(BatchTemplateTypes.jdbcPartition.getValue(), param.getTemplate())) {
            DataSource dataSource = null;
            DatabaseType type = null;
            // ??
            if (jobItems.containsKey(cacheKey)) {
                dataSource = (DataSource) (jobItems.get(cacheKey).jobContext.getBean("jdbcDataSource"));
                type = DatabaseType.fromMetaData(dataSource);
            } else {
                // ,???
                ClassPathXmlApplicationContext jdbc = Util.initContext(true, "batch/job-context.xml",
                        "batch/import-db-jdbc.xml");
                dataSource = (DataSource) jdbc.getBean("jdbcDataSource");
                type = DatabaseType.fromMetaData(dataSource);
                jdbc.close();
            }
            if (converters.containsKey(type))
                param.setTable(converters.get(type).converte(table, sortKey));
        }

        String jobXMLFile = generator.generateFileJob(region, param);
        ClassPathXmlApplicationContext jobContext = null;
        if (StringUtils.equals("file", template)) {
            jobContext = Util.initContext(false, "batch/job-context.xml", jobXMLFile);
        } else {
            // ????db?
            jobContext = Util.initContext(false, "batch/job-context.xml", "batch/import-db-jdbc.xml",
                    jobXMLFile);
        }
        jobContext.setParent(batchContext);
        jobContext.refresh();
        if (LogUtil.getCoreLog().isDebugEnabled())
            LogUtil.getCoreLog().debug("Job:" + region + " define success.");

        JobItem item = new JobItem();
        item.attributes = param;
        item.job = jobContext.getBean(Job.class);
        item.jobContent = jobXMLFile;
        item.jobContext = jobContext;
        jobItems.put(cacheKey, item);
        return true;
    } catch (Exception e) {
        LogUtil.getCoreLog().info("Job define error.", e);
        throw new GemliteException(e);
    }
}

From source file:org.springmodules.validation.bean.BeanValidatorIntegrationTests.java

public void testBeanValidator_WithNonNullNullableValue() throws Exception {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "org/springmodules/validation/bean/beanValidator-tests.xml");

    Person person = new Person("Uri");
    person.setPhone("1234"); // should be validation error - length < 7
    BindException errors = new BindException(person, "person");

    Validator validator = (Validator) context.getBean("validator");
    validator.validate(person, errors);//from   w w  w  .j  av  a2 s . com

    assertTrue(errors.hasFieldErrors("phone"));
    assertEquals(1, errors.getFieldErrorCount("phone"));
    assertEquals("Person.phone[min.length]", errors.getFieldError("phone").getCode());
}

From source file:net.joala.condition.regression.Joala45SpringConfigurationUnresolvablePropertyTest.java

@Test
public void scenario_joala45_ignore_unresolvable_for_local_properties() throws Exception {
    final ClassPathXmlApplicationContext applicationContext;
    try {/*from w ww .  j  av  a 2s. c om*/
        applicationContext = new ClassPathXmlApplicationContext(
                "/META-INF/joala/condition/joala-45-context-2.xml");
    } catch (BeansException e) {
        final String msg = "Joala 45 Regression: Conditions Context should not try to resolve local properties.";
        LOG.error(msg, e);
        throw new AssertionError(msg);
    }
    final Object myString = applicationContext.getBean("myString");
    assertEquals("Local bean should have been correctly filled with properties.", "myString", myString);
}

From source file:org.cometd.annotation.spring.SpringAnnotationTest.java

@Test
public void testSpringWiringOfCometDServices() throws Exception {
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext();
    applicationContext.setConfigLocation("classpath:applicationContext.xml");
    applicationContext.refresh();//from  w  w w  .  ja  v a 2 s.  com

    String beanName = Introspector.decapitalize(SpringBayeuxService.class.getSimpleName());

    String[] beanNames = applicationContext.getBeanDefinitionNames();
    assertTrue(Arrays.asList(beanNames).contains(beanName));

    SpringBayeuxService service = (SpringBayeuxService) applicationContext.getBean(beanName);
    assertNotNull(service);
    assertNotNull(service.dependency);
    assertNotNull(service.bayeuxServer);
    assertNotNull(service.serverSession);
    assertTrue(service.active);
    assertEquals(1, service.bayeuxServer.getChannel(SpringBayeuxService.CHANNEL).getSubscribers().size());

    applicationContext.close();

    assertFalse(service.active);
}

From source file:validation.ValidationTest.java

@Test
public void testValidation() {
    ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(
            ValidationTest.class.getPackage().getName().replace('.', '/') + "/validation-provider.xml");
    providerContext.start();// w ww.j  a v  a2  s. 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();
    }
}