Example usage for org.springframework.context ApplicationContext containsBean

List of usage examples for org.springframework.context ApplicationContext containsBean

Introduction

In this page you can find the example usage for org.springframework.context ApplicationContext containsBean.

Prototype

boolean containsBean(String name);

Source Link

Document

Does this bean factory contain a bean definition or externally registered singleton instance with the given name?

Usage

From source file:org.dllearner.cli.CLI.java

/**
 * @param args/* w w  w .j  av  a  2s  .c  om*/
 * @throws ParseException 
 * @throws IOException 
 * @throws ReasoningMethodUnsupportedException 
 */
public static void main(String[] args) throws ParseException, IOException, ReasoningMethodUnsupportedException {

    //      System.out.println("DL-Learner " + Info.build + " [TODO: read pom.version and put it here (make sure that the code for getting the version also works in the release build!)] command line interface");
    System.out.println("DL-Learner command line interface");

    // currently, CLI has exactly one parameter - the conf file
    if (args.length == 0) {
        System.out.println("You need to give a conf file as argument.");
        System.exit(0);
    }

    // read file and print and print a message if it does not exist
    File file = new File(args[args.length - 1]);
    if (!file.exists()) {
        System.out.println("File \"" + file + "\" does not exist.");
        System.exit(0);
    }

    Resource confFile = new FileSystemResource(file);

    List<Resource> springConfigResources = new ArrayList<Resource>();

    try {
        //DL-Learner Configuration Object
        IConfiguration configuration = new ConfParserConfiguration(confFile);

        ApplicationContextBuilder builder = new DefaultApplicationContextBuilder();
        ApplicationContext context = builder.buildApplicationContext(configuration, springConfigResources);

        // TODO: later we could check which command line interface is specified in the conf file
        // for now we just use the default one

        CLI cli;
        if (context.containsBean("cli")) {
            cli = (CLI) context.getBean("cli");
        } else {
            cli = new CLI();
        }
        cli.setContext(context);
        cli.setConfFile(file);
        cli.run();
    } catch (Exception e) {
        e.printStackTrace();
        String stacktraceFileName = "log/error.log";

        //            e.printStackTrace();

        //Find the primary cause of the exception.
        Throwable primaryCause = findPrimaryCause(e);

        // Get the Root Error Message
        logger.error("An Error Has Occurred During Processing.");
        //            logger.error(primaryCause.getMessage());
        logger.debug("Stack Trace: ", e);
        logger.error("Terminating DL-Learner...and writing stacktrace to: " + stacktraceFileName);
        FileOutputStream fos = new FileOutputStream(stacktraceFileName);
        PrintStream ps = new PrintStream(fos);
        e.printStackTrace(ps);
    }

}

From source file:org.dllearner.cli.unife.CLIDistributedLEAP.java

public static void main(String[] args) throws ParseException, IOException, ReasoningMethodUnsupportedException {

    System.out.println("DL-Learner command line interface");

    // currently, CLI has exactly one parameter - the conf file
    if (args.length == 0) {
        System.out.println("You need to give a conf file as argument.");
        System.exit(0);/* w w w.  j a v a 2s . c  om*/
    }

    // read file and print and print a message if it does not exist
    File file = new File(args[args.length - 1]);
    if (!file.exists()) {
        System.out.println("File \"" + file + "\" does not exist.");
        System.exit(0);
    }

    // MPI Initialization
    try {
        args = MPI.Init(args);
    } catch (MPIException mpiEx) {
        String msg = "Impossible to initialize MPI: " + mpiEx.getMessage();
        System.err.print(msg);
    }
    // Setting output file for logging
    String slaveIdLog = System.getProperty("slaveId");
    if (slaveIdLog != null) {
        throw new RuntimeException("slaveId property already defined somewhere else.");
    }

    // set the index for the log file: log/leap${slaveId}.log
    MPIUtilities.createLogFile("slaveId");

    Logger logger = Logger.getLogger(CLIDistributedLEAP.class.getName(), new BundleLoggerFactory());

    Resource confFile = new FileSystemResource(file);

    List<Resource> springConfigResources = new ArrayList<Resource>();
    logger.debug("Spring!");
    try {
        //DL-Learner Configuration Object
        IConfiguration configuration = new ConfParserConfiguration(confFile);

        ApplicationContextBuilder builder = new DefaultApplicationContextBuilder();
        ApplicationContext context = builder.buildApplicationContext(configuration, springConfigResources);

        // TODO: later we could check which command line interface is specified in the conf file
        // for now we just use the default one
        CLI cli;
        if (context.containsBean("cli")) {
            cli = (CLI) context.getBean("cli");
        } else {
            cli = new CLI();
        }
        logger.debug("setting context");
        cli.setContext(context);
        logger.debug("context set");
        logger.debug("setting conf file");
        cli.setConfFile(file);
        logger.debug("conf file set");
        logger.debug("Start Running");
        cli.run();
    } catch (Exception e) {
        e.printStackTrace();
        String stacktraceFileName = "log/error.log";

        //            e.printStackTrace();
        //Find the primary cause of the exception.
        Throwable primaryCause = findPrimaryCause(e);

        // Get the Root Error Message
        logger.error("An Error Has Occurred During Processing.");
        //            logger.error(primaryCause.getMessage());
        logger.debug("Stack Trace: ", e);
        logger.error("Terminating DL-Learner...and writing stacktrace to: " + stacktraceFileName);
        FileOutputStream fos = new FileOutputStream(stacktraceFileName);
        PrintStream ps = new PrintStream(fos);
        e.printStackTrace(ps);
    } finally {
        try {
            MPI.Finalize();
        } catch (MPIException mpiEx) {
            String msg = "Cannot finalize MPI";
            System.err.print(msg);
            logger.error(msg);
        }
    }
}

From source file:org.granite.grails.web.GrailsWebSWFServlet.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    servletContextLoader = new ServletContextResourceLoader(servletConfig.getServletContext());
    ApplicationContext springContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servletConfig.getServletContext());
    if (springContext.containsBean(GroovyPageResourceLoader.BEAN_ID)) {
        resourceLoader = (ResourceLoader) springContext.getBean(GroovyPageResourceLoader.BEAN_ID);
    }/*from  www .  j a va  2  s. c  om*/

    grailsAttributes = new DefaultGrailsApplicationAttributes(servletConfig.getServletContext());
}

From source file:org.openvpms.web.component.error.ErrorReportingDialog.java

/**
 * Constructs an {@code ErrorReportingDialog}.
 *
 * @param title     the dialog title/*from  w w  w. j a  v  a  2  s.  c  o m*/
 * @param message   the error message
 * @param exception the exception to display
 */
public ErrorReportingDialog(String title, String message, Throwable exception) {
    super(title, message, OK);
    ApplicationContext context = ServiceHelper.getContext();
    if (context.containsBean("errorReporter")) {
        reporter = (ErrorReporter) context.getBean("errorReporter");
        if (reporter.isReportable(exception)) {
            report = new ErrorReport(message, exception);
            addButton("errorreportdialog.report", new ActionListener() {
                public void onAction(ActionEvent e) {
                    reportError();
                }
            });
        }
    }
}

From source file:org.pentaho.platform.web.servlet.ServletToBeanProxy.java

private synchronized void doInit() throws ServletException {
    if (initialized) {
        // already initialized, so don't re-initialize
        return;/*from w ww.j  av  a  2 s.  c  om*/
    }

    if (ServletToBeanProxy.logger.isDebugEnabled()) {
        ServletToBeanProxy.logger.debug("[doInit]");
    }

    String targetBean = servletConfig.getInitParameter("targetBean"); //$NON-NLS-1$

    if (ServletToBeanProxy.logger.isDebugEnabled()) {
        ServletToBeanProxy.logger.debug("targetBean=" + targetBean);
    }

    if ("".equals(targetBean)) { //$NON-NLS-1$
        targetBean = null;
    }

    String lifecycle = servletConfig.getInitParameter("lifecycle"); //$NON-NLS-1$

    if (ServletToBeanProxy.logger.isDebugEnabled()) {
        ServletToBeanProxy.logger.debug("lifecycle=" + lifecycle);
    }

    if ("servlet-container-managed".equals(lifecycle)) { //$NON-NLS-1$
        servletContainerManaged = true;
    }

    ApplicationContext ctx = this.getContext(servletConfig);

    String beanName = null;

    if ((targetBean != null) && ctx.containsBean(targetBean)) {
        if (ServletToBeanProxy.logger.isDebugEnabled()) {
            ServletToBeanProxy.logger.debug("using targetBean");
        }
        beanName = targetBean;
    } else if (targetBean != null) {
        throw new ServletException("targetBean '" + targetBean + "' not found in context");
    } else {
        if (ServletToBeanProxy.logger.isDebugEnabled()) {
            ServletToBeanProxy.logger.debug("using targetClass");
        }

        String targetClassString = servletConfig.getInitParameter("targetClass"); //$NON-NLS-1$

        if ((targetClassString == null) || "".equals(targetClassString)) { //$NON-NLS-1$
            throw new ServletException("targetClass or targetBean must be specified");
        }

        Class targetClass;

        try {
            targetClass = Thread.currentThread().getContextClassLoader().loadClass(targetClassString);
        } catch (ClassNotFoundException ex) {
            throw new ServletException("Class of type " + targetClassString + " not found in classloader");
        }

        Map beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(ctx, targetClass, true, true);

        if (beans.size() == 0) {
            throw new ServletException(
                    "Bean context must contain at least one bean of type " + targetClassString);
        }

        beanName = (String) beans.keySet().iterator().next();
    }

    Object object = ctx.getBean(beanName);

    if (ServletToBeanProxy.logger.isDebugEnabled()) {
        ServletToBeanProxy.logger.debug("got bean=" + object);
    }

    if (!(object instanceof Servlet)) {
        throw new ServletException("Bean '" + beanName + "' does not implement javax.servlet.Servlet");
    }

    delegate = (Servlet) object;

    if (servletContainerManaged) {
        if (ServletToBeanProxy.logger.isDebugEnabled()) {
            ServletToBeanProxy.logger.debug("servletContainerManaged=true so calling init");
        }
        delegate.init(servletConfig);
    }

    // Set initialized to true at the end of the synchronized method, so
    // that invocations of service() before this method has completed will not
    // cause NullPointerException
    initialized = true;
}

From source file:org.red5.server.net.rtmp.RTMPConnection.java

/**
 * Getter for  video codec factory// ww w.  j av  a2 s  .c o  m
 *
 * @return  Video codec factory
 */
public VideoCodecFactory getVideoCodecFactory() {
    final IContext context = scope.getContext();
    ApplicationContext appCtx = context.getApplicationContext();
    if (!appCtx.containsBean(VIDEO_CODEC_FACTORY)) {
        return null;
    }

    return (VideoCodecFactory) appCtx.getBean(VIDEO_CODEC_FACTORY);
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

@Test
public void testAutoBindDLQ() throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
    consumerProperties.getExtension().setPrefix(TEST_PREFIX);
    consumerProperties.getExtension().setAutoBindDlq(true);
    consumerProperties.setMaxAttempts(1); // disable retry
    consumerProperties.getExtension().setDurableSubscription(true);
    BindingProperties bindingProperties = createConsumerBindingProperties(consumerProperties);
    DirectChannel moduleInputChannel = createBindableChannel("input", bindingProperties);
    moduleInputChannel.setBeanName("dlqTest");
    moduleInputChannel.subscribe(new MessageHandler() {

        @Override/*  w ww.j  ava  2 s  . c  o  m*/
        public void handleMessage(Message<?> message) throws MessagingException {
            throw new RuntimeException("foo");
        }

    });
    Binding<MessageChannel> consumerBinding = binder.bindConsumer("dlqtest", "default", moduleInputChannel,
            consumerProperties);

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.convertAndSend("", TEST_PREFIX + "dlqtest.default", "foo");

    int n = 0;
    while (n++ < 100) {
        Object deadLetter = template.receiveAndConvert(TEST_PREFIX + "dlqtest.default.dlq");
        if (deadLetter != null) {
            assertThat(deadLetter).isEqualTo("foo");
            break;
        }
        Thread.sleep(100);
    }
    assertThat(n).isLessThan(100);

    consumerBinding.unbind();

    ApplicationContext context = TestUtils.getPropertyValue(binder,
            "binder.provisioningProvider.autoDeclareContext", ApplicationContext.class);
    assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.binding")).isFalse();
    assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default")).isFalse();
    assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.dlq.binding")).isFalse();
    assertThat(context.containsBean(TEST_PREFIX + "dlqtest.default.dlq")).isFalse();
}

From source file:org.springframework.data.gemfire.config.CreateDefinedIndexesApplicationListener.java

private QueryService getQueryService(final ContextRefreshedEvent event) {
    ApplicationContext localApplicationContext = event.getApplicationContext();

    return (localApplicationContext
            .containsBean(GemfireConstants.DEFAULT_GEMFIRE_INDEX_DEFINITION_QUERY_SERVICE)
                    ? localApplicationContext.getBean(
                            GemfireConstants.DEFAULT_GEMFIRE_INDEX_DEFINITION_QUERY_SERVICE, QueryService.class)
                    : null);/* w  ww .  j a  va  2  s .c o m*/
}

From source file:org.springframework.data.gemfire.config.CreateDefinedIndexesApplicationListenerTest.java

@Test
public void createDefinedIndexesCalledOnContextRefreshedEvent() throws Exception {
    ApplicationContext mockApplicationContext = mock(ApplicationContext.class,
            "testCreateDefinedIndexesCalledOnContextRefreshedEvent.MockApplicationContext");

    ContextRefreshedEvent mockEvent = mock(ContextRefreshedEvent.class,
            "testCreateDefinedIndexesCalledOnContextRefreshedEvent.MockContextRefreshedEvent");

    QueryService mockQueryService = mock(QueryService.class,
            "testCreateDefinedIndexesCalledOnContextRefreshedEvent.MockQueryService");

    when(mockEvent.getApplicationContext()).thenReturn(mockApplicationContext);
    when(mockApplicationContext
            .containsBean(eq(GemfireConstants.DEFAULT_GEMFIRE_INDEX_DEFINITION_QUERY_SERVICE)))
                    .thenReturn(true);/*  w w w  .  j  av  a2s .  co m*/
    when(mockApplicationContext.getBean(eq(GemfireConstants.DEFAULT_GEMFIRE_INDEX_DEFINITION_QUERY_SERVICE),
            eq(QueryService.class))).thenReturn(mockQueryService);

    listener.onApplicationEvent(mockEvent);

    verify(mockEvent, times(1)).getApplicationContext();
    verify(mockApplicationContext, times(1))
            .containsBean(eq(GemfireConstants.DEFAULT_GEMFIRE_INDEX_DEFINITION_QUERY_SERVICE));
    verify(mockApplicationContext, times(1)).getBean(
            eq(GemfireConstants.DEFAULT_GEMFIRE_INDEX_DEFINITION_QUERY_SERVICE), eq(QueryService.class));
    verify(mockQueryService, times(1)).createDefinedIndexes();
}

From source file:org.springframework.data.gemfire.config.CreateDefinedIndexesApplicationListenerTest.java

@Test
public void createDefinedIndexesNotCalledOnContextRefreshedEvent() throws Exception {
    ApplicationContext mockApplicationContext = mock(ApplicationContext.class,
            "testCreateDefinedIndexesUsingClientCacheLocalQueryService.MockApplicationContext");

    ContextRefreshedEvent mockEvent = mock(ContextRefreshedEvent.class,
            "testCreateDefinedIndexesUsingClientCacheLocalQueryService.MockContextRefreshedEvent");

    QueryService mockQueryService = mock(QueryService.class,
            "testCreateDefinedIndexesUsingClientCacheLocalQueryService.MockQueryService");

    when(mockEvent.getApplicationContext()).thenReturn(mockApplicationContext);
    when(mockApplicationContext
            .containsBean(eq(GemfireConstants.DEFAULT_GEMFIRE_INDEX_DEFINITION_QUERY_SERVICE)))
                    .thenReturn(false);/*from  w  w  w. ja va 2s . c o m*/
    when(mockApplicationContext.getBean(eq(GemfireConstants.DEFAULT_GEMFIRE_INDEX_DEFINITION_QUERY_SERVICE),
            eq(QueryService.class))).thenReturn(mockQueryService);

    listener.onApplicationEvent(mockEvent);

    verify(mockEvent, times(1)).getApplicationContext();
    verify(mockApplicationContext, times(1))
            .containsBean(eq(GemfireConstants.DEFAULT_GEMFIRE_INDEX_DEFINITION_QUERY_SERVICE));
    verify(mockApplicationContext, never()).getBean(anyString(), any(QueryService.class));
    verify(mockQueryService, never()).createDefinedIndexes();
}