Example usage for org.springframework.context ConfigurableApplicationContext getBean

List of usage examples for org.springframework.context ConfigurableApplicationContext getBean

Introduction

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

Prototype

Object getBean(String name) throws BeansException;

Source Link

Document

Return an instance, which may be shared or independent, of the specified bean.

Usage

From source file:org.syncope.core.persistence.beans.AbstractVirAttr.java

protected <T extends AbstractAttributable> List<Object> retrieveValues(final T attributable,
        final String attributeName, final IntMappingType intMappingType) {

    LOG.debug("{}: retrieving external values for {}", new Object[] { attributable, attributeName });

    ConfigurableApplicationContext context = ApplicationContextManager.getApplicationContext();
    ConnInstanceLoader connInstanceLoader = context.getBean(ConnInstanceLoader.class);
    if (connInstanceLoader == null) {
        LOG.error("Could not get to ConnInstanceLoader");
        return null;
    }//  ww  w  . j a v a  2 s.c  om

    List<Object> virAttrValues = new ArrayList<Object>();

    for (ExternalResource resource : attributable.getResources()) {
        LOG.debug("Retrieving attribute mapped on {}", resource);

        Set<String> attributeNames = new HashSet<String>();

        String accountId = null;

        for (SchemaMapping mapping : resource.getMappings()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Processing mapping." + "\n\tID: " + mapping.getId() + "\n\tSource: "
                        + mapping.getIntAttrName() + "\n\tDestination: " + mapping.getExtAttrName()
                        + "\n\tType: " + mapping.getIntMappingType() + "\n\tMandatory condition: "
                        + mapping.getMandatoryCondition() + "\n\tAccountId: " + mapping.isAccountid()
                        + "\n\tPassword: " + mapping.isPassword());
            }

            if (attributeName.equals(mapping.getIntAttrName())
                    && mapping.getIntMappingType() == intMappingType) {

                attributeNames.add(mapping.getExtAttrName());
            }

            if (mapping.isAccountid()) {
                try {
                    accountId = attributable.getAttribute(mapping.getIntAttrName()).getValuesAsStrings().get(0);
                } catch (NullPointerException e) {
                    // ignore exception
                    LOG.debug("Invalid accountId specified", e);
                }
            }
        }

        if (attributeNames != null && accountId != null) {
            LOG.debug("Get object attribute for entry {}", accountId);

            try {
                ConnectorFacadeProxy connector = connInstanceLoader.getConnector(resource);
                Set<Attribute> attributes = connector.getObjectAttributes(ObjectClass.ACCOUNT,
                        new Uid(accountId), null, attributeNames);

                LOG.debug("Retrieved {}", attributes);

                for (Attribute attribute : attributes) {
                    virAttrValues.addAll(attribute.getValue());
                }
            } catch (Exception e) {
                LOG.warn("Error connecting to {}", resource.getName(), e);
                // ignore exception and go ahead
            }
        }
    }

    return virAttrValues;
}

From source file:net.radai.confusion.spring.SpringAnnotationConfigTest.java

@Test
public void testSpringAnnotationIntegration() throws Exception {
    Path dir = Files.createTempDirectory("test");
    Path targetFile = dir.resolve("confFile");
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("cats.ini");
            OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE_NEW)) {
        ByteStreams.copy(is, os);/*from  w w w  .  jav  a 2  s  .  c  o m*/
    }
    String absolutePath = targetFile.toFile().getCanonicalPath();
    System.setProperty("confFile", absolutePath);
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("annotationSpringContext.xml");
    //noinspection unchecked
    SpringAwareConfigurationService<Cats> confService = (SpringAwareConfigurationService<Cats>) context
            .getBean(ConfigurationService.class);
    Jsr330AnnotatedConfigurationConsumerBean consumer = context
            .getBean(Jsr330AnnotatedConfigurationConsumerBean.class);
    //noinspection unchecked
    Assert.assertNotNull(consumer.getConfService());
    Assert.assertNotNull(consumer.getInitialConf());
    Assert.assertTrue(consumer.getCats().isEmpty());

    try (InputStream is = getClass().getClassLoader().getResourceAsStream("cat.ini");
            OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.WRITE,
                    StandardOpenOption.TRUNCATE_EXISTING)) {
        ByteStreams.copy(is, os);
    }
    Thread.sleep(100);

    //verify event was received
    Assert.assertEquals(1, consumer.getCats().size());
    Assert.assertTrue(consumer.getInitialConf() != consumer.getCats().get(0));
    Assert.assertTrue(confService.getConfiguration() == consumer.getCats().get(0));

    context.close();
}

From source file:net.radai.confusion.spring.SpringXmlConfTest.java

@Test
public void testSpringXmlIntegration() throws Exception {
    Path dir = Files.createTempDirectory("test");
    Path targetFile = dir.resolve("confFile");
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("cats.ini");
            OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE_NEW)) {
        ByteStreams.copy(is, os);//from  w ww. ja  v a2  s .c  om
    }
    String absolutePath = targetFile.toFile().getCanonicalPath();
    System.setProperty("confFile", absolutePath);
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("xmlSpringContext.xml");
    //noinspection unchecked
    SpringAwareConfigurationService<Cats> confService = (SpringAwareConfigurationService<Cats>) context
            .getBean(ConfigurationService.class);
    TraditionalConfigurationConsumerBean consumer = context.getBean(TraditionalConfigurationConsumerBean.class);
    //noinspection unchecked
    SimpleConfigurationService<Cats> delegate = (SimpleConfigurationService<Cats>) ReflectionTestUtils
            .getField(confService, "delegate");
    Assert.assertNotNull(confService.getConfiguration());
    Assert.assertTrue(delegate.isStarted());
    Assert.assertTrue(consumer.getConf() == confService.getConfiguration());
    Assert.assertTrue(consumer.getConfService() == confService);
    Assert.assertTrue(consumer.getCats().isEmpty());

    try (InputStream is = getClass().getClassLoader().getResourceAsStream("cat.ini");
            OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.WRITE,
                    StandardOpenOption.TRUNCATE_EXISTING)) {
        ByteStreams.copy(is, os);
    }
    Thread.sleep(100);

    //verify event was received
    Assert.assertEquals(1, consumer.getCats().size());
    Assert.assertTrue(consumer.getConf() != consumer.getCats().get(0));
    Assert.assertTrue(confService.getConfiguration() == consumer.getCats().get(0));

    context.close();
    Assert.assertFalse(delegate.isStarted());
}

From source file:org.kurento.room.test.AutodiscoveryKmsUrlTest.java

@Test
public void test() throws IOException {

    Path backup = null;/*from   www.j  av a 2 s . com*/

    Path configFile = Paths.get(StandardSystemProperty.USER_HOME.value(), ".kurento", "config.properties");

    System.setProperty("kms.uris", "[\"autodiscovery\"]");

    try {

        if (Files.exists(configFile)) {

            backup = configFile.getParent().resolve("config.properties.old");

            Files.move(configFile, backup);
            log.debug("Backed-up old config.properties");
        }

        Files.createDirectories(configFile.getParent());

        try (BufferedWriter writer = Files.newBufferedWriter(configFile, StandardCharsets.UTF_8)) {
            writer.write("kms.url.provider: " + TestKmsUrlProvider.class.getName() + "\r\n");
        }

        String contents = new String(Files.readAllBytes(configFile));
        log.debug("Config file contents:\n{}", contents);

        ConfigurableApplicationContext app = KurentoRoomServerApp.start(new String[] { "--server.port=7777" });

        NotificationRoomManager notifRoomManager = app.getBean(NotificationRoomManager.class);

        final RoomManager roomManager = notifRoomManager.getRoomManager();

        final KurentoClientSessionInfo kcSessionInfo = new DefaultKurentoClientSessionInfo("participantId",
                "roomName");

        new Thread(new Runnable() {
            @Override
            public void run() {
                roomManager.joinRoom("userName", "roomName", false, kcSessionInfo, "participantId");
            }
        }).start();

        try {
            Boolean result = queue.poll(10, TimeUnit.SECONDS);

            if (result == null) {
                fail("Event in KmsUrlProvider not called");
            } else {
                if (!result) {
                    fail("Test failed");
                }
            }

        } catch (InterruptedException e) {
            fail("KmsUrlProvider was not called");
        }

    } finally {

        Files.delete(configFile);

        if (backup != null) {
            Files.move(backup, configFile);
        }
    }
}

From source file:org.huahinframework.emanager.Runner.java

/**
 * @param war/*  w  w w  . j  ava  2 s  .co m*/
 * @param port
 * @param shutDownPort
 */
public void start(String war, int port, int shutDownPort) {
    log.info("huahin-emanager start");

    ConfigurableApplicationContext applicationContext = null;
    try {
        applicationContext = new ClassPathXmlApplicationContext("huahinEManagerProperties.xml",
                "huahinEManagerEMRProperties.xml");
        Properties properties = (Properties) applicationContext.getBean("properties");
        EMRProperties emrProperties = (EMRProperties) applicationContext.getBean("emrProperties");

        QueueManager queueManager = new QueueManager(properties, emrProperties);
        queueManager.start();

        SelectChannelConnector connector = new SelectChannelConnector();
        connector.setPort(port);

        Server server = new Server();
        server.setConnectors(new Connector[] { connector });

        WebAppContext web = new WebAppContext();
        web.setContextPath("/");
        web.setWar(war);

        ShutDowner shutDowner = new ShutDowner(shutDownPort, server, queueManager);
        shutDowner.start();

        server.addHandler(web);
        server.start();
        server.join();
        shutDowner.join();
        queueManager.join();
    } catch (Exception e) {
        log.error("huahin-emanager aborted", e);
        System.exit(-1);
    } finally {
        if (applicationContext != null) {
            applicationContext.close();
        }
    }

    log.info("huahin-emanager end");
}

From source file:com.provenance.cloudprovenance.connector.run.ConnectorService.java

public void startJMSmessageReceiver() {

    // TODO - use a property file
    String nameofSpringBeanConfigFile = "beans.xml";
    String trEventConsumerId = "traceabilityEventConsumer";
    String poEventConsumerId = "policyEventConsumer";

    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(
            new String[] { nameofSpringBeanConfigFile });

    // handlers for receiving async response messages
    TraceabilityEventConsumer traceabilityEventConsumer = (TraceabilityEventConsumer) ctx
            .getBean(trEventConsumerId);
    PolicyEventConsumer policyEventConsumer = (PolicyEventConsumer) ctx.getBean(poEventConsumerId);

    // TODO - why do we need this?
}

From source file:ro.contezi.websockets.main.SampleWebSocketsApplicationTest.java

@Test
public void reverseEndpoint() throws Exception {
    ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class,
            PropertyPlaceholderAutoConfiguration.class)
                    .properties("websocket.uri:ws://localhost:" + this.port + "/reverse")
                    .run("--spring.main.web_environment=false");
    long count = context.getBean(ClientConfiguration.class).getLatch().getCount();
    AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class)
            .getMessagePayload();// ww  w  .j a  v a 2s .c  om
    context.close();
    assertEquals(0, count);
    assertEquals("Reversed: !olleH", messagePayloadReference.get());
}

From source file:com.provenance.cloudprovenance.policyengine.cond.XPathProvenanceConditionFunction.java

public void loadSpringBean() {

    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] { "beans.xml" });

    xpathUtility = (XPathProvenanceConditionUtility) ctx.getBean("xPathProvenanceConditionUtility");
}

From source file:app.core.ApplicationContextTest.java

public void testLoadOk() {
    ConfigurableApplicationContext appCtx = super.getApplicationContext();
    assertTrue(appCtx.isActive());//ww w  . j  a  va  2s.  c o m
    assertTrue(Arrays.toString(appCtx.getBeanDefinitionNames()), appCtx.getBeanDefinitionCount() > 9);
    for (String beanDefinitionName : appCtx.getBeanDefinitionNames()) {
        // Load all beans to make sure no initialization fails
        assertNotNull(appCtx.getBean(beanDefinitionName));
    }

    assertEquals(appCtx, ((ApplicationContextProvider) appCtx.getBean("applicationContextProvider")).getCtx());
    //        assertNotNull(((Dao) appCtx.getBean("dao")).getSessionFactory());
    //        ((Db) appCtx.getBean("db")).getSessionFactory();
    assertNotNull(Db.getSession());
}

From source file:com.gaodashang.demo.SampleWebSocketsApplicationTests.java

@Test
public void reverseEndpoint() throws Exception {
    ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class,
            PropertyPlaceholderAutoConfiguration.class)
                    .properties("websocket.uri:ws://localhost:" + this.port + "/reverse")
                    .run("--spring.main.web_environment=false");
    long count = context.getBean(ClientConfiguration.class).latch.getCount();
    AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload;
    context.close();/*from w  ww  .  j a v a  2  s . c o m*/
    assertEquals(0, count);
    assertEquals("Reversed: !dlrow olleH", messagePayloadReference.get());
}