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.FeedController.java

@CrossOrigin
@RequestMapping(path = "/feed/{feedId}", method = RequestMethod.PUT)
@ResponseBody/*from   ww  w  .  j  a  v  a  2 s .c  o m*/
public ResponseEntity<String> updateFeedInfos(@RequestHeader(value = "User-token") String userToken,
        @RequestBody Feed feedRequest, @PathVariable int feedId) {

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

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

    if (StringUtils.isBlank(feedRequest.getName())) {
        context.close();
        return new ResponseEntity(new ErrorMessageResponse("bad_params"), HttpStatus.BAD_REQUEST);
    }

    Feed feed = feedDAO.findById(userAuth, feedId);
    if (feed == null) {
        context.close();
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }

    feedDAO.updateName(feed, feedRequest);

    ArticleState newState = articleStateDAO.findByLabel(ArticleState.NEW_LABEL);
    int newArticles = feedDAO.getNewArticlesByFeed(feed, newState);

    context.close();

    return new ResponseEntity(new SuccessFeedInfoResponse(feed.getId(), feed.getName(), feed.getUrl(),
            newArticles, feed.getRefreshError()), HttpStatus.OK);
}

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

@Test
public void testOK() throws Exception {
    System.setProperty("liveDB", LIVE_DB);
    System.setProperty("_SIM_DB_PATH",
            tempDir + "/simulationRunDB-SimulateBottleNeck-OK-" + Thread.currentThread().getId());

    FileUtils.copyFile(new File(LIVE_DB + ".h2.db"), new File(
            tempDir + "/simulationRunDB-SimulateBottleNeck-OK-" + Thread.currentThread().getId() + ".h2.db"));

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

    runSimulation(appContext, tempDir + "/SimulateBottleneckTest-1.png");

    processEngine.close();/*  w w  w  .ja  va2 s  .  co  m*/
    appContext.close();

    File expected = new File(System.getProperty("baseDir", ".")
            + "/src/test/resources/org/activiti/crystalball/simulator/simulateBottleneckTest-1.png");
    File generated = new File(tempDir + "/SimulateBottleneckTest-1.png");
    assertTrue(FileUtils.contentEquals(expected, generated));
    // delete database file
    File f = new File(System.getProperty("_SIM_DB_PATH") + ".h2.db");
    if (!f.delete())
        System.err.println("unable to delete file");
}

From source file:com.chevres.rss.restapi.controller.FeedController.java

@CrossOrigin
@RequestMapping(path = "/feed", method = RequestMethod.POST)
@ResponseBody/*w  w  w .ja  v a 2s  . c  om*/
public ResponseEntity<String> addFeed(@RequestHeader(value = "User-token") String userToken,
        @RequestBody Feed feed, BindingResult bindingResult) {

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

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

    feedValidator.validate(feed, bindingResult);
    if (bindingResult.hasErrors()) {
        context.close();
        return new ResponseEntity(new ErrorMessageResponse("bad_params"), HttpStatus.BAD_REQUEST);
    }

    if (feedDAO.doesExist(userAuth, feed.getUrl())) {
        context.close();
        return new ResponseEntity(new ErrorMessageResponse("already_exist"), HttpStatus.BAD_REQUEST);
    }

    feed.setIdUser(userAuth.getIdUser());
    feed.setRefreshError(false);
    feedDAO.create(feed);

    ArticleState newState = articleStateDAO.findByLabel(ArticleState.NEW_LABEL);
    int newArticles = feedDAO.getNewArticlesByFeed(feed, newState);

    context.close();

    return new ResponseEntity(new SuccessFeedInfoResponse(feed.getId(), feed.getName(), feed.getUrl(),
            newArticles, feed.getRefreshError()), HttpStatus.OK);

}

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

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

    Scan scan = null;/*from w  ww . ja va2 s.  co  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.SharedRegistryTest.java

@Test
public void testDefaultRegistries() {
    ClassPathXmlApplicationContext ctx = null;
    try {// ww w .  ja v a 2  s  . c  om
        MetricRegistry instance = new MetricRegistry();
        SharedMetricRegistries.add("SomeSharedRegistry", instance);
        ctx = new ClassPathXmlApplicationContext("classpath:shared-registry.xml");
        Assert.assertSame("Should be the same MetricRegistry", instance, ctx.getBean(MetricRegistry.class));
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
}

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

/**
 * results differs - that's why this test is ignored - possible bug. 
 * @throws Exception //from  ww  w  .  j a  v a  2 s.  co  m
 */
@Test
public void testUser2OverLoaded() throws Exception {
    System.setProperty("liveDB", LIVE_DB);
    System.setProperty("_SIM_DB_PATH",
            tempDir + "/simulationRunDB-SimulateBottleNeck-Overload-" + Thread.currentThread().getId());

    FileUtils.copyFile(new File(LIVE_DB + ".h2.db"), new File(tempDir
            + "/simulationRunDB-SimulateBottleNeck-Overload-" + Thread.currentThread().getId() + ".h2.db"));

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

    // increase frequency of process starts to 45 mins (default is 1 hour)
    StartProcessEventHandler startProcessEventHandler = appContext.getBean(StartProcessEventHandler.class);
    startProcessEventHandler.setPeriod(2700000);

    runSimulation(appContext, tempDir + "/SimulateBottleneckTest-2.png");

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

    File expected = new File(System.getProperty("baseDir", ".")
            + "/src/test/resources/org/activiti/crystalball/simulator/simulateBottleneckTest-2.png");
    File generated = new File(tempDir + "/SimulateBottleneckTest-2.png");
    assertTrue(FileUtils.contentEquals(expected, generated));
    // delete database file

    File f = new File(System.getProperty("_SIM_DB_PATH") + ".h2.db");
    if (!f.delete())
        System.err.println("unable to delete file");

}

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  ww .jav a 2  s. c om*/
    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:com.aeg.ims.ftp.SftpOutboundTransferSample.java

@Test
public void testOutbound() throws Exception {

    final String sourceFileName = "README.md";
    final String destinationFileName = sourceFileName + "_foo";

    final ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(
            "/META-INF/spring/integration/SftpOutboundTransferSample-context.xml",
            SftpOutboundTransferSample.class);
    @SuppressWarnings("unchecked")
    SessionFactory<LsEntry> sessionFactory = ac.getBean(CachingSessionFactory.class);
    RemoteFileTemplate<LsEntry> template = new RemoteFileTemplate<LsEntry>(sessionFactory);
    //SftpTestUtils.createTestFiles(template); // Just the directory

    try {/*from  w w  w  . j a  v a 2  s . c o m*/
        final File file = new File(sourceFileName);

        Assert.isTrue(file.exists(), String.format("File '%s' does not exist.", sourceFileName));

        final Message<File> message = MessageBuilder.withPayload(file).build();
        final MessageChannel inputChannel = ac.getBean("inputChannel", MessageChannel.class);

        inputChannel.send(message);
        Thread.sleep(2000);

        Assert.isTrue(SftpTestUtils.fileExists(template, destinationFileName));

        System.out.println(String.format(
                "Successfully transferred '%s' file to a " + "remote location under the name '%s'",
                sourceFileName, destinationFileName));
    } finally {
        //SftpTestUtils.cleanUp(template, destinationFileName);
        ac.close();
    }
}

From source file:org.bpmscript.process.hibernate.SpringHibernateInstanceManagerTest.java

public void testInstanceManagerSeparateThread() throws Exception {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/endtoend/spring.xml");
    try {/*from w  w w  . j a  v a 2  s  .  c o  m*/

        final IInstanceManager instanceManager = (IInstanceManager) context.getBean("instanceManager");

        final String pid1 = instanceManager.createInstance("parentVersion", "definitionId", "test",
                IJavascriptProcessDefinition.DEFINITION_TYPE_JAVASCRIPT, "one");
        IInstance instance = instanceManager.getInstance(pid1);
        assertNotNull(instance);

        instanceManager.createInstance("parentVersion", "definitionId", "test",
                IJavascriptProcessDefinition.DEFINITION_TYPE_JAVASCRIPT, "two");
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        final AtomicReference<Queue<String>> results = new AtomicReference<Queue<String>>(
                new LinkedList<String>());
        Future<Object> future1 = executorService.submit(new Callable<Object>() {

            public Object call() throws Exception {
                return instanceManager.doWithInstance(pid1, new IInstanceCallback() {
                    public IExecutorResult execute(IInstance instance) throws Exception {
                        log.info("locking one");
                        Thread.sleep(2000);
                        results.get().add("one");
                        return new IgnoredResult("", "", "");
                    }
                });
            }

        });
        Thread.sleep(100);
        assertNotNull(future1.get());
    } finally {
        context.destroy();
    }
}

From source file:com.griddynamics.banshun.RegistryBeanTest.java

@Test
public void importBeanWithSubclass() {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
            "com/griddynamics/banshun/registry/illegal-concrete-import.xml");

    assertTrue("have no exports due to laziness", hasNoExports(ctx));
    Object proxy = ctx.getBean("early-import");

    // force export
    ctx.getBean("export-declaration");

    try {//ww w .  j a v  a 2  s .  co  m
        // target is ready here, but types does not match
        proxy.toString();
    } catch (BeanNotOfRequiredTypeException e) {
        assertEquals("just-bean", e.getBeanName());

        try {
            Object b = ctx.getBean("late-import").toString();
            b.toString();
        } catch (BeansException e2) {
            assertEquals("just-bean", ((BeanNotOfRequiredTypeException) e2).getBeanName());
            return;
        }

        fail("we should have BeanCreactionException here");
        return;
    }
    fail("we should have BeanNotOfRequiredTypeException here");
}