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:com.chevres.rss.restapi.controller.UserController.java

@CrossOrigin
@RequestMapping(path = "/user/{username}", method = RequestMethod.DELETE)
@ResponseBody//from w  w w.jav a 2s  .  co m
public ResponseEntity<String> deleteUser(@RequestHeader(value = "User-token") String userToken,
        @PathVariable String username) {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    UserDAO userDAO = context.getBean(UserDAO.class);
    FeedDAO feedDAO = context.getBean(FeedDAO.class);
    UserAuthDAO userAuthDAO = context.getBean(UserAuthDAO.class);

    UserAuth userAuth = userAuthDAO.findByToken(userToken);
    if (userAuth == null) {
        context.close();
        return new ResponseEntity(new ErrorMessageResponse("invalid_token"), HttpStatus.BAD_REQUEST);
    }

    User user = userDAO.findByUsername(username);
    if (user == null) {
        context.close();
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }

    boolean isAdmin = userDAO.isAdmin(userAuth.getIdUser());
    if (!isAdmin && (userAuth.getIdUser() != user.getId())) {
        context.close();
        return new ResponseEntity(new ErrorMessageResponse("admin_required"), HttpStatus.FORBIDDEN);
    }

    userAuthDAO.removeAllForUser(user);
    feedDAO.removeAllForUser(user);
    userDAO.delete(user);
    context.close();

    return new ResponseEntity(new SuccessMessageResponse("success"), HttpStatus.OK);
}

From source file:org.thymeleaf.spring3.templateresolver.SpringResourceTemplateResolverSpring3Test.java

@Test
public void testResolveTemplate() throws Exception {

    final String templateLocation = "spring321/view/test.html";

    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:spring321/view/applicationContext.xml");

    final SpringResourceTemplateResolver resolver = (SpringResourceTemplateResolver) context
            .getBean("springResourceTemplateResolver");

    resolver.initialize();//from ww  w  . j  ava  2 s.c om

    final String templateMode = resolver.getTemplateMode();
    Assert.assertEquals("HTML5", templateMode);

    final TemplateProcessingParameters parameters = new TemplateProcessingParameters(new Configuration(),
            "classpath:" + templateLocation, new Context());

    final TemplateResolution resolution = resolver.resolveTemplate(parameters);

    final IResourceResolver resourceResolver = resolution.getResourceResolver();
    final InputStream is = resourceResolver.getResourceAsStream(parameters, resolution.getResourceName());

    final String testResource = ResourceUtils.normalize(ResourceUtils.read(is, "US-ASCII"));

    final String expected = ResourceUtils
            .read(ClassLoaderUtils.getClassLoader(SpringResourceTemplateResolverSpring3Test.class)
                    .getResourceAsStream(templateLocation), "US-ASCII", true);

    Assert.assertEquals(expected, testResource);

}

From source file:org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolverSpring4Test.java

@Test
public void testResolveTemplate() throws Exception {

    final String templateLocation = "spring421/view/test.html";

    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:spring421/view/applicationContext.xml");

    final SpringResourceTemplateResolver resolver = (SpringResourceTemplateResolver) context
            .getBean("springResourceTemplateResolver");

    resolver.initialize();// w w w  .  ja  v  a 2 s .c  om

    final String templateMode = resolver.getTemplateMode();
    Assert.assertEquals("HTML5", templateMode);

    final TemplateProcessingParameters parameters = new TemplateProcessingParameters(new Configuration(),
            "classpath:" + templateLocation, new Context());

    final TemplateResolution resolution = resolver.resolveTemplate(parameters);

    final IResourceResolver resourceResolver = resolution.getResourceResolver();
    final InputStream is = resourceResolver.getResourceAsStream(parameters, resolution.getResourceName());

    final String testResource = ResourceUtils.normalize(ResourceUtils.read(is, "US-ASCII"));

    final String expected = ResourceUtils
            .read(ClassLoaderUtils.getClassLoader(SpringResourceTemplateResolverSpring4Test.class)
                    .getResourceAsStream(templateLocation), "US-ASCII", true);

    Assert.assertEquals(expected, testResource);

}

From source file:se.trillian.goodies.spring.HostNameBasedPropertyPlaceHolderConfigurerTest.java

@SuppressWarnings("unchecked")
public void testConfigurer() throws Exception {
    HostNameBasedPropertyPlaceHolderConfigurer configurer = new HostNameBasedPropertyPlaceHolderConfigurer() {
        @Override//from w ww. j av  a2  s  . c  o m
        protected String getHostName() {
            return "foobar-10";
        }
    };
    configurer.setLocation(new ClassPathResource("/se/trillian/goodies/spring/spring.properties"));
    List<String> hostNameFilters = new ArrayList<String>();
    hostNameFilters.add("nonmatchingfilter=>$1");
    hostNameFilters.add("([a-z]+)-\\d+=>$1");
    configurer.setHostNameFilters(hostNameFilters);
    configurer.setIgnoreUnresolvablePlaceholders(true);
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("context.xml", this.getClass());
    context.addBeanFactoryPostProcessor(configurer);
    context.refresh();
    Map<String, String> fruits = (Map<String, String>) context.getBean("fruits");

    assertEquals("boquila", fruits.get("fruit1"));
    assertEquals("currant", fruits.get("fruit2"));
    assertEquals("blueberry", fruits.get("fruit3"));
    assertEquals("raspberry", fruits.get("fruit4"));
    assertEquals("peach", fruits.get("fruit5"));
    assertEquals("pear", fruits.get("fruit6"));

    Map<String, String> hostname = (Map<String, String>) context.getBean("hostname");
    assertEquals("foobar-10", hostname.get("hostname1"));
    assertEquals("foobar-10", hostname.get("hostname2"));
}

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

@Override
protected ApplicationConfiguration doInBackground() throws Exception {
    ApplicationConfiguration config = null;

    // 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 {//w w w  .  j a v  a 2 s  .  c o  m
        springContext = new ClassPathXmlApplicationContext("/META-INF/spring/app-context.xml");
        IModelDelegate modelDelegate = (IModelDelegate) springContext.getBean("ModelDelegate");

        config = modelDelegate.getApplicationConfiguration();
        modelDelegate = null;
    } finally {
        if (springContext != null) {
            springContext.close();
        }
        springContext = null;
    }

    return config;
}

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

@Override
public ApplicationConfiguration doInBackground() {
    // 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 {//from   w w w  .j  a  v  a 2 s  .c om
        springContext = new ClassPathXmlApplicationContext("/META-INF/spring/app-context.xml");
        IModelDelegate modelDelegate = (IModelDelegate) springContext.getBean("ModelDelegate");

        modelDelegate.saveApplicationConfiguration(this.configuration);
        modelDelegate = null;
    } finally {
        if (springContext != null) {
            springContext.close();
        }
        springContext = null;
    }

    return this.configuration;
}

From source file:edu.vt.middleware.ldap.SpringTest.java

/**
 * Attempts to load all Spring application context XML files to
 * verify proper wiring.// ww w  .  j  a v a  2s  .  com
 *
 * @throws  Exception  On test failure.
 */
@Test(groups = { "spring" })
public void testSpringWiring() throws Exception {
    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "/spring-context.xml", });
    AssertJUnit.assertTrue(context.getBeanDefinitionCount() > 0);
    final ConnectionFactory cf = (ConnectionFactory) context.getBean("connectionFactory");
    final Connection conn = cf.getConnection();
    try {
        conn.open();
    } finally {
        conn.close();
    }

    final ClassPathXmlApplicationContext poolContext = new ClassPathXmlApplicationContext(
            new String[] { "/spring-pool-context.xml", });
    AssertJUnit.assertTrue(poolContext.getBeanDefinitionCount() > 0);
    BlockingConnectionPool pool = null;
    try {
        pool = (BlockingConnectionPool) poolContext.getBean("pool");
    } finally {
        pool.close();
    }
}

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

@Override
protected List<ScanDefinition> doInBackground() throws Exception {
    List<ScanDefinition> list = null;

    // 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 {/*from  www  .  java2 s. c o  m*/
        springContext = new ClassPathXmlApplicationContext("/META-INF/spring/app-context.xml");
        IModelDelegate modelDelegate = (IModelDelegate) springContext.getBean("ModelDelegate");

        list = modelDelegate.getScanDefinitions();
        modelDelegate = null;
    } finally {
        if (springContext != null) {
            springContext.close();
        }
        springContext = null;
    }

    return list;
}

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

@Override
protected List<Scan> doInBackground() throws Exception {
    List<Scan> list = null;

    // 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 {//from  w  ww.  j  a va2s.  com
        springContext = new ClassPathXmlApplicationContext("/META-INF/spring/app-context.xml");
        IModelDelegate modelDelegate = (IModelDelegate) springContext.getBean("ModelDelegate");

        list = modelDelegate.getScans();
        modelDelegate = null;
    } finally {
        if (springContext != null) {
            springContext.close();
        }
        springContext = null;
    }

    return list;
}

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);// ww  w  . j  ava  2s. co m
    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();

}