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.bpmscript.process.hibernate.SpringHibernateInstanceManagerTest.java

public void testInstanceManager() throws Exception {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/endtoend/spring.xml");

    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);//w w w. j a  va2 s . co  m

    instanceManager.createInstance("parentVersion", "definitionId", "test",
            IJavascriptProcessDefinition.DEFINITION_TYPE_JAVASCRIPT, "two");
    final AtomicReference<Queue<String>> results = new AtomicReference<Queue<String>>(new LinkedList<String>());
    Object operation = instanceManager.doWithInstance(pid1, new IInstanceCallback() {
        public IExecutorResult execute(IInstance instance) throws Exception {
            log.info("locking one");
            results.get().add("one");
            return new IgnoredResult("", "", "");
        }
    });
    assertTrue(operation instanceof IIgnoredResult);
}

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

@CrossOrigin
@RequestMapping(path = "/feed/{feedId}", method = RequestMethod.DELETE)
@ResponseBody//w  w  w  .j av a 2 s  .  c om
public ResponseEntity<String> deleteFeed(@RequestHeader(value = "User-token") String userToken,
        @PathVariable int feedId) {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    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);
    }

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

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

From source file:com.morty.podcast.writer.file.PodCastFileNameResolver.java

public PodCastFileNameResolver() {
    //look for xml file. if not there, then just have list of 1
    //Which will only contain the default format.
    try {//from w  w w.  jav  a  2  s  .  c  o m
        m_logger.info("Setting up resolvers");
        //Look up the xml file in the classpath
        final ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
                PodCastConstants.SUPPORTED_FILE_FORMATS);
        listOfFormats = (List) ctx.getBean(PodCastConstants.SUPPORTED_FILE_FORMATS_LIST);

        //Log the list of resovlers.
        m_logger.info("Finished Setting up resolvers [" + listOfFormats + "]");

    } catch (Exception e) {
        m_logger.info("Default Format being used [" + e.getMessage() + "]");
        List defaultList = new ArrayList();
        defaultList.add(new DefaultFileFormat());
        listOfFormats = defaultList;
    }

}

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

@CrossOrigin
@RequestMapping(path = "/feeds", method = RequestMethod.GET)
@ResponseBody//from  w w w .j a v a  2s .  com
public ResponseEntity<String> getFeeds(@RequestHeader(value = "User-token") String userToken) {

    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);
    }

    ArticleState newState = articleStateDAO.findByLabel(ArticleState.NEW_LABEL);
    List<Feed> feeds = feedDAO.findAll(userAuth);
    List<SuccessGetFeedWithIdResponse> finalList = new ArrayList<>();
    for (Feed feed : feeds) {
        finalList.add(new SuccessGetFeedWithIdResponse(feed.getId(), feed.getName(), feed.getUrl(),
                feed.getRefreshError(), feedDAO.getNewArticlesByFeed(feed, newState)));
    }

    context.close();

    return new ResponseEntity(new SuccessGetFeedsResponse(finalList), HttpStatus.OK);

}

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

@CrossOrigin
@RequestMapping(path = "/feed/as_read/{feedId}", method = RequestMethod.POST)
@ResponseBody//w w w. j ava  2s.  com
public ResponseEntity<String> markFeedAsRead(@RequestHeader(value = "User-token") String userToken,
        @PathVariable int feedId) {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    FeedDAO feedDAO = context.getBean(FeedDAO.class);
    UserAuthDAO userAuthDAO = context.getBean(UserAuthDAO.class);
    ArticleDAO articleDAO = context.getBean(ArticleDAO.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);
    }

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

    ArticleState articleState = articleStateDAO.findByLabel(ArticleState.READ_LABEL);
    articleDAO.markAllArticlesInFeedAsRead(feed, articleState);
    context.close();

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

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

@CrossOrigin
@RequestMapping(path = "/feed/{feedId}", method = RequestMethod.GET)
@ResponseBody/*from  w  w w.  j  a  v  a  2s . co  m*/
public ResponseEntity<String> getFeedInfos(@RequestHeader(value = "User-token") String userToken,
        @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);
    }

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

    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.bpmscript.integration.spring.SpringReplyTest.java

@SuppressWarnings("unchecked")
public void testReply() throws Exception {

    int total = 1;
    final int loopcount = 2;
    final CountDownLatch latch = new CountDownLatch(total + loopcount * total);

    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/integration/spring/spring.xml");

    try {//from  w ww .j av  a  2  s  .  c  o m

        final BpmScriptEngine engine = (BpmScriptEngine) context.getBean("engine");
        final IVersionedDefinitionManager processManager = (IVersionedDefinitionManager) context
                .getBean("versionedDefinitionManager");
        final ChannelRegistry channelRegistry = (ChannelRegistry) ((Map) context
                .getBeansOfType(ChannelRegistry.class)).values().iterator().next();

        processManager.createDefinition("id",
                new JavascriptProcessDefinition("test", StreamService.DEFAULT_INSTANCE
                        .getResourceAsString("/org/bpmscript/integration/spring/reply.js")));
        engine.setInstanceListener(new LoggingInstanceListener() {
            @Override
            public void instanceCompleted(String pid, ICompletedResult result) {
                super.instanceCompleted(pid, result);
                latch.countDown();
            }

            @Override
            public void instanceFailed(String pid, IFailedResult result) {
                super.instanceFailed(pid, result);
                fail(result.getThrowable().getMessage());
            }
        });

        IBenchmarkPrinter.STDOUT.print(new Benchmark().execute(total, new IBenchmarkCallback() {
            @SuppressWarnings("unchecked")
            public void execute(int count) throws Exception {
                GenericMessage<Object[]> message = new GenericMessage<Object[]>(new Object[] { loopcount });
                message.getHeader().setAttribute("definitionName", "test");
                message.getHeader().setAttribute("operation", "test");
                message.getHeader().setReturnAddress("channel-recorder");
                MessageChannel channel = channelRegistry.lookupChannel("channel-bpmscript-first");
                channel.send(message);
            }
        }, new IWaitForCallback() {
            public void call() throws Exception {
                latch.await();
            }
        }, false));

        SpringRecorder springRecorder = (SpringRecorder) context.getBean("springRecorder");
        BlockingQueue<Object> messages = springRecorder.getMessages();
        for (int i = 0; i < total; i++) {
            Object poll = messages.poll(1, TimeUnit.SECONDS);
            assertNotNull("should have got to " + total + " but got to " + i, poll);
        }

    } finally {
        context.destroy();
    }

}

From source file:org.bpmscript.integration.spring.SpringLoanBrokerTest.java

License:asdf

@SuppressWarnings("unchecked")
public void testReply() throws Exception {

    int total = 1;
    final CountDownLatch latch = new CountDownLatch(total);

    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/integration/spring/spring.xml");

    try {//from  w w  w . ja va  2  s. co  m

        final BpmScriptEngine engine = (BpmScriptEngine) context.getBean("engine");
        final IVersionedDefinitionManager processManager = (IVersionedDefinitionManager) context
                .getBean("versionedDefinitionManager");
        final ChannelRegistry channelRegistry = (ChannelRegistry) ((Map) context
                .getBeansOfType(ChannelRegistry.class)).values().iterator().next();

        processManager.createDefinition("id",
                new JavascriptProcessDefinition("loanBroker", StreamService.DEFAULT_INSTANCE
                        .getResourceAsString("/org/bpmscript/integration/spring/loanbroker.js")));
        engine.setInstanceListener(new LoggingInstanceListener() {
            @Override
            public void instanceCompleted(String pid, ICompletedResult result) {
                super.instanceCompleted(pid, result);
                latch.countDown();
            }

            @Override
            public void instanceFailed(String pid, IFailedResult result) {
                super.instanceFailed(pid, result);
                fail(result.getThrowable().getMessage());
            }
        });

        IBenchmarkPrinter.STDOUT.print(new Benchmark().execute(total, new IBenchmarkCallback() {
            @SuppressWarnings("unchecked")
            public void execute(int count) throws Exception {
                GenericMessage<Object[]> message = new GenericMessage<Object[]>(
                        new Object[] { new LoanRequest("asdf", 1, 1000) });
                message.getHeader().setAttribute("definitionName", "loanBroker");
                message.getHeader().setAttribute("operation", "requestBestRate");
                message.getHeader().setReturnAddress("channel-recorder");
                MessageChannel channel = channelRegistry.lookupChannel("channel-bpmscript-first");
                channel.send(message);
            }
        }, new IWaitForCallback() {
            public void call() throws Exception {
                latch.await();
            }
        }, false));

        SpringRecorder springRecorder = (SpringRecorder) context.getBean("springRecorder");
        BlockingQueue<Object> messages = springRecorder.getMessages();
        for (int i = 0; i < total; i++) {
            Object poll = messages.poll(1, TimeUnit.SECONDS);
            assertNotNull("should have got to " + total + " but got to " + i, poll);
        }

    } finally {
        context.destroy();
    }

}

From source file:com.alibaba.dubbo.examples.annotation.AnnotationTest.java

@Test
public void testAnnotation() {
    ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(
            AnnotationTest.class.getPackage().getName().replace('.', '/') + "/annotation-provider.xml");
    providerContext.start();/* w  w w  . jav  a 2 s  . c  o m*/
    try {
        ClassPathXmlApplicationContext consumerContext = new ClassPathXmlApplicationContext(
                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.ktunaxa.referral.shapereader.ShapeImportRunner.java

/** Initialize the object, by preparing a Spring context. */
private ShapeImportRunner() {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
            "classpath:org/ktunaxa/referral/shapereader/spring-hibernate.xml",
            "classpath:org/ktunaxa/referral/shapereader/applicationContext.xml");
    service = ctx.getBean(ShapeReaderService.class);
}