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:io.milton.grizzly.GrizzlyServer.java

public boolean start(int httpPort, Integer sslPort) throws IOException {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    ConfigurableApplicationContext ctx = initSpringApplicationContext();
    if (ctx == null) {
        log.warn("Failed to initialise spring");
        return false;
    }//from   ww w  .  j a va  2  s .  c om

    Object milton = ctx.getBean("milton.http.manager");
    if (milton instanceof HttpManager) {
        this.httpManager = (HttpManager) milton;
    } else if (milton instanceof HttpManagerBuilder) {
        HttpManagerBuilder builder = (HttpManagerBuilder) milton;
        ResourceFactory rf = builder.getMainResourceFactory();
        this.httpManager = builder.buildHttpManager();
    }

    if (parent.containsBean("milton.mail.server")) {
        log.info("init mailserver...");
        Object oMailServer = parent.getBean("milton.mail.server");
        if (oMailServer instanceof MailServer) {
            mailServer = (MailServer) oMailServer;
        } else if (oMailServer instanceof MailServerBuilder) {
            MailServerBuilder builder = (MailServerBuilder) oMailServer;
            mailServer = builder.build();
        } else {
            throw new RuntimeException("Unsupported type: " + oMailServer.getClass() + " expected "
                    + MailServer.class + " or " + MailServerBuilder.class);
        }
        log.info("starting mailserver");
        mailServer.start();
    }
    log.info("Finished init");

    String host = getPropertyOrDefault("host", null);

    int port = getPropertyOrDefaultInt("port", 8080);

    int secureHttpPort = getPropertyOrDefaultInt(MiltonSNIService.SYS_SECURE_PORT,
            MiltonSNIService.SECURE_PORT);

    if (host == null) {
        httpServer = HttpServer.createSimpleServer(null, port);
    } else {
        httpServer = HttpServer.createSimpleServer(null, host, port);
    }

    { // Start the Kademi SNI SSL service
        MiltonSNICertificateStore store = null; // TODO: allow injection
        MiltonSNICertificateManager sniCerManager = new MiltonSNICertificateManager(store);
        SSLEngineConfigurator sniConfig = sniCerManager.createEngineConfigurator();
        this.kademiSNIService = new MiltonSNIService(secureHttpPort, sniConfig);

        this.kademiSNIService.startOn(httpServer);
    }

    httpServer.getServerConfiguration().addHttpHandler(new HttpHandler() {
        @Override
        public void service(Request request, Response response) throws Exception {
            log.trace("service");
            GrizzlyMiltonRequest req = new GrizzlyMiltonRequest(request);
            GrizzlyMiltonResponse resp = new GrizzlyMiltonResponse(response);
            String p = req.getAbsolutePath();
            long tm = System.currentTimeMillis();
            httpManager.process(req, resp);
            tm = System.currentTimeMillis() - tm;
            // todo
        }
    }, "/");

    httpServer.start();

    running = true;
    return true;
}

From source file:net.firejack.platform.model.config.listener.ConfigContextLoaderListener.java

@Override
public void start() {
    super.contextInitialized(event);

    ConfigurableApplicationContext context = (ConfigurableApplicationContext) getCurrentWebApplicationContext();

    AnnotationTransactionAttributeSource source = context.getBean(AnnotationTransactionAttributeSource.class);
    Map<Object, DefaultTransactionAttribute> map = ClassUtils.getProperty(source, "attributeCache");

    Map<String, BeanDefinition> managers = context.getBean(HibernateFactoryBean.HIBERNATE_MANAGER, Map.class);
    for (Map.Entry<String, BeanDefinition> entry : managers.entrySet()) {
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();
        beanFactory.registerBeanDefinition(entry.getKey(), entry.getValue());
    }/*from  w w w. j  ava 2  s . com*/

    Map<Class, String> targets = context.getBean(HibernateFactoryBean.HIBERNATE_TARGET, Map.class);
    Field targetField = null;

    for (Map.Entry<Object, DefaultTransactionAttribute> entry : map.entrySet()) {
        Object key = entry.getKey();
        if (targetField == null)
            targetField = ClassUtils.getField(key.getClass(), "targetClass");

        Class targetClass = ClassUtils.getProperty(key, targetField);
        String name = targets.get(targetClass);
        if (name != null)
            entry.getValue().setQualifier(name);
    }
}

From source file:ome.client.utests.Preferences3Test.java

public void xxxtestPreferencesAreUpdated() {

    log.info("CONTEXT");
    ConfigurableApplicationContext applicationContext = OmeroContext.getClientContext();

    // A)//from   w ww  .  j  a v a  2 s.c o  m
    // PropertyPlaceholderConfigurer ppc =(PropertyPlaceholderConfigurer)
    // applicationContext.getBean("placeholderConfig");
    // ppc.setProperties( props );
    // 1
    // ppc.postProcessBeanFactory( applicationContext.getBeanFactory() );
    // 2
    // applicationContext.refresh();
    // applicationContext.getBeanFactory().
    // 3
    // ConfigurableListableBeanFactory bf =
    // applicationContext.getBeanFactory();
    // ppc.postProcessBeanFactory( bf );
    // while (bf.getParentBeanFactory() != null)
    // {
    // bf = (ConfigurableListableBeanFactory) bf.getParentBeanFactory();
    // ppc.postProcessBeanFactory( bf );
    // }
    // 4

    // B)
    log.info("OWN BFPP");
    BeanFactoryPostProcessor bfpp = new BeanFactoryPostProcessor() {
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            PropertyPlaceholderConfigurer ppc = (PropertyPlaceholderConfigurer) beanFactory
                    .getBean("placeholderConfig");
            ppc.setProperties(props);
        }
    };
    log.info("ADDING BFPP");
    applicationContext.addBeanFactoryPostProcessor(bfpp);

    log.info("GETTING PRINCIPAL");
    Principal principal = (Principal) applicationContext.getBean("principal");

    assertTrue(principal.getName(), "bar".equals(principal.getName()));
}

From source file:org.alfresco.integrations.google.docs.webscripts.CreateContent.java

protected void getGoogleDocsServiceSubsystem() {
    ApplicationContextFactory subsystem = (ApplicationContextFactory) applicationContext
            .getBean(GOOGLEDOCS_DRIVE_SUBSYSTEM);
    ConfigurableApplicationContext childContext = (ConfigurableApplicationContext) subsystem
            .getApplicationContext();//from w  ww  .j av a  2 s  .  c  o m
    setGoogledocsService((GoogleDocsService) childContext.getBean(GOOGLEDOCSSERVICE));
    setFileNameUtil((FileNameUtil) childContext.getBean(FILENAMEUTIL));
}

From source file:org.alfresco.repo.management.subsystems.test.SubsystemsTest.java

/**
 * Test subsystems.//from w  ww. j a  v  a2  s . c  om
 * 
 * @throws Exception
 *             the exception
 */
public void testSubsystems() throws Exception {
    ApplicationContextFactory subsystem = (ApplicationContextFactory) getApplicationContext()
            .getBean("testsubsystem");
    ConfigurableApplicationContext childContext = (ConfigurableApplicationContext) subsystem
            .getApplicationContext();
    assertTrue("Subsystem not started", childContext.isActive());
    TestService testService = (TestService) childContext.getBean("testService");
    // Make sure subsystem defaults work
    assertEquals("Subsystem Default1", testService.getSimpleProp1());
    // Make sure global property overrides work
    assertEquals(true, testService.getSimpleProp2().booleanValue());
    // Make sure extension classpath property overrides work
    assertEquals("Instance Override3", testService.getSimpleProp3());
    // Make sure extension classpath Spring overrides work
    assertEquals("An extra bean I changed", childContext.getBean("anotherBean"));
    // Make sure composite properties and their defaults work
    TestBean[] testBeans = testService.getTestBeans();
    assertNotNull("Composite property not set", testBeans);
    assertEquals(3, testBeans.length);
    assertEquals("inst1", testBeans[0].getId());
    assertEquals(false, testBeans[0].isBoolProperty());
    assertEquals(123456789123456789L, testBeans[0].getLongProperty());
    assertEquals("Global Default", testBeans[0].getAnotherStringProperty());
    assertEquals("inst2", testBeans[1].getId());
    assertEquals(true, testBeans[1].isBoolProperty());
    assertEquals(123456789123456789L, testBeans[1].getLongProperty());
    assertEquals("Global Default", testBeans[1].getAnotherStringProperty());
    assertEquals("inst3", testBeans[2].getId());
    assertEquals(false, testBeans[2].isBoolProperty());
    assertEquals(123456789123456789L, testBeans[2].getLongProperty());
    assertEquals("Global Instance Default", testBeans[2].getAnotherStringProperty());
}

From source file:org.alfresco.repo.workflow.activiti.ActivitiSpringTest.java

/**
 * {@inheritDoc}//from w  w  w. j  ava  2 s .com
 */
@Override
protected void setUp() throws Exception {
    ConfigurableApplicationContext appContext = loadContext();
    this.repo = (RepositoryService) appContext.getBean("activitiRepositoryService");
    this.runtime = (RuntimeService) appContext.getBean("activitiRuntimeService");

    ServiceRegistry serviceRegistry = (ServiceRegistry) appContext.getBean(ServiceRegistry.SERVICE_REGISTRY);
    authenticationComponent = (AuthenticationComponent) appContext.getBean("authenticationComponent");
    TransactionService transactionService = serviceRegistry.getTransactionService();
    nodeService = serviceRegistry.getNodeService();
    txnHelper = transactionService.getRetryingTransactionHelper();

    // authenticate
    authenticationComponent.setSystemUserAsCurrentUser();

    StoreRef storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE,
            "test-" + getName() + "-" + System.currentTimeMillis());
    NodeRef rootNodeRef = nodeService.getRootNode(storeRef);
    // Create a node to work on
    workingNodeRef = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN,
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, getName()), ContentModel.TYPE_CMOBJECT)
            .getChildRef();

    String resource = "org/alfresco/repo/workflow/activiti/testTransaction.bpmn20.xml";
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream input = classLoader.getResourceAsStream(resource);
    this.deployment = repo.createDeployment().addInputStream(resource, input).deploy();
}

From source file:org.apache.syncope.core.connid.ConnObjectUtil.java

/**
 * Query connected external resources for values to populated virtual attributes associated with the given owner.
 *
 * @param owner user or role/* ww w .  j a v a 2  s.  c  o m*/
 * @param attrUtil attributable util
 */
public void retrieveVirAttrValues(final AbstractAttributable owner, final AttributableUtil attrUtil) {
    final ConfigurableApplicationContext context = ApplicationContextProvider.getApplicationContext();
    final ConnectorFactory connFactory = context.getBean(ConnectorFactory.class);

    final IntMappingType type = attrUtil.getType() == AttributableType.USER ? IntMappingType.UserVirtualSchema
            : attrUtil.getType() == AttributableType.ROLE ? IntMappingType.RoleVirtualSchema
                    : IntMappingType.MembershipVirtualSchema;

    final Map<String, ConnectorObject> externalResources = new HashMap<String, ConnectorObject>();

    // -----------------------
    // Retrieve virtual attribute values if and only if they have not been retrieved yet
    // -----------------------
    for (AbstractVirAttr virAttr : owner.getVirAttrs()) {
        // reset value set
        if (virAttr.getValues().isEmpty()) {
            retrieveVirAttrValue(owner, virAttr, attrUtil, type, externalResources, connFactory);
        }
    }
    // -----------------------
}

From source file:org.apache.syncope.core.misc.ConnObjectUtil.java

/**
 * Query connected external resources for values to populated virtual attributes associated with the given owner.
 *
 * @param owner user or role//from  w  w  w.  ja  v  a 2s .c o m
 * @param attrUtil attributable util
 */
public void retrieveVirAttrValues(final Attributable<?, ?, ?> owner, final AttributableUtil attrUtil) {
    final ConfigurableApplicationContext context = ApplicationContextProvider.getApplicationContext();
    final ConnectorFactory connFactory = context.getBean(ConnectorFactory.class);

    final IntMappingType type = attrUtil.getType() == AttributableType.USER ? IntMappingType.UserVirtualSchema
            : attrUtil.getType() == AttributableType.ROLE ? IntMappingType.RoleVirtualSchema
                    : IntMappingType.MembershipVirtualSchema;

    final Map<String, ConnectorObject> externalResources = new HashMap<>();

    // -----------------------
    // Retrieve virtual attribute values if and only if they have not been retrieved yet
    // -----------------------
    for (VirAttr virAttr : owner.getVirAttrs()) {
        // reset value set
        if (virAttr.getValues().isEmpty()) {
            retrieveVirAttrValue(owner, virAttr, attrUtil, type, externalResources, connFactory);
        }
    }
    // -----------------------
}

From source file:org.apache.syncope.core.misc.MappingUtil.java

/**
 * Prepare attributes for sending to a connector instance.
 *
 * @param attrUtil user / role//from  www .j a v a2 s.co  m
 * @param subject given user / role
 * @param password clear-text password
 * @param changePwd whether password should be included for propagation attributes or not
 * @param vAttrsToBeRemoved virtual attributes to be removed
 * @param vAttrsToBeUpdated virtual attributes to be added
 * @param membVAttrsToBeRemoved membership virtual attributes to be removed
 * @param membVAttrsToBeUpdated membership virtual attributes to be added
 * @param enable whether user must be enabled or not
 * @param resource target resource
 * @return account link + prepared attributes
 */
public static Map.Entry<String, Set<Attribute>> prepareAttributes(final AttributableUtil attrUtil,
        final Subject<?, ?, ?> subject, final String password, final boolean changePwd,
        final Set<String> vAttrsToBeRemoved, final Map<String, AttrMod> vAttrsToBeUpdated,
        final Set<String> membVAttrsToBeRemoved, final Map<String, AttrMod> membVAttrsToBeUpdated,
        final Boolean enable, final ExternalResource resource) {

    LOG.debug("Preparing resource attributes for {} on resource {} with attributes {}", subject, resource,
            subject.getPlainAttrs());

    final ConfigurableApplicationContext context = ApplicationContextProvider.getApplicationContext();
    final VirAttrCache virAttrCache = context.getBean(VirAttrCache.class);
    final PasswordGenerator passwordGenerator = context.getBean(PasswordGenerator.class);

    Set<Attribute> attributes = new HashSet<>();
    String accountId = null;

    for (MappingItem mapping : attrUtil.getMappingItems(resource, MappingPurpose.PROPAGATION)) {
        LOG.debug("Processing schema {}", mapping.getIntAttrName());

        try {
            if ((attrUtil.getType() == AttributableType.USER
                    && mapping.getIntMappingType() == IntMappingType.UserVirtualSchema)
                    || (attrUtil.getType() == AttributableType.ROLE
                            && mapping.getIntMappingType() == IntMappingType.RoleVirtualSchema)) {

                LOG.debug("Expire entry cache {}-{}", subject.getKey(), mapping.getIntAttrName());
                virAttrCache.expire(attrUtil.getType(), subject.getKey(), mapping.getIntAttrName());
            }

            // SYNCOPE-458 expire cache also for membership virtual schemas
            if (attrUtil.getType() == AttributableType.USER
                    && mapping.getIntMappingType() == IntMappingType.MembershipVirtualSchema
                    && (subject instanceof User)) {

                final User user = (User) subject;
                for (Membership membership : user.getMemberships()) {
                    LOG.debug("Expire entry cache {}-{} for membership {}", subject.getKey(),
                            mapping.getIntAttrName(), membership);
                    virAttrCache.expire(AttributableType.MEMBERSHIP, membership.getKey(),
                            mapping.getIntAttrName());
                }
            }

            Map.Entry<String, Attribute> preparedAttr = prepareAttr(resource, mapping, subject, password,
                    passwordGenerator, vAttrsToBeRemoved, vAttrsToBeUpdated, membVAttrsToBeRemoved,
                    membVAttrsToBeUpdated);

            if (preparedAttr != null && preparedAttr.getKey() != null) {
                accountId = preparedAttr.getKey();
            }

            if (preparedAttr != null && preparedAttr.getValue() != null) {
                Attribute alreadyAdded = AttributeUtil.find(preparedAttr.getValue().getName(), attributes);

                if (alreadyAdded == null) {
                    attributes.add(preparedAttr.getValue());
                } else {
                    attributes.remove(alreadyAdded);

                    Set<Object> values = new HashSet<>(alreadyAdded.getValue());
                    values.addAll(preparedAttr.getValue().getValue());

                    attributes.add(AttributeBuilder.build(preparedAttr.getValue().getName(), values));
                }
            }
        } catch (Exception e) {
            LOG.debug("Attribute '{}' processing failed", mapping.getIntAttrName(), e);
        }
    }

    final Attribute accountIdExtAttr = AttributeUtil.find(attrUtil.getAccountIdItem(resource).getExtAttrName(),
            attributes);
    if (accountIdExtAttr != null) {
        attributes.remove(accountIdExtAttr);
        attributes.add(AttributeBuilder.build(attrUtil.getAccountIdItem(resource).getExtAttrName(), accountId));
    }
    attributes.add(MappingUtil.evaluateNAME(subject, resource, accountId));

    if (enable != null) {
        attributes.add(AttributeBuilder.buildEnabled(enable));
    }
    if (!changePwd) {
        Attribute pwdAttr = AttributeUtil.find(OperationalAttributes.PASSWORD_NAME, attributes);
        if (pwdAttr != null) {
            attributes.remove(pwdAttr);
        }
    }

    return new AbstractMap.SimpleEntry<>(accountId, attributes);
}

From source file:org.apache.syncope.core.misc.MappingUtil.java

/**
 * Prepare an attribute to be sent to a connector instance.
 *
 * @param resource target resource/*from   ww  w  .  j a v  a 2 s  .  co  m*/
 * @param mapItem mapping item for the given attribute
 * @param subject given user
 * @param password clear-text password
 * @param passwordGenerator password generator
 * @param vAttrsToBeRemoved virtual attributes to be removed
 * @param vAttrsToBeUpdated virtual attributes to be added
 * @return account link + prepared attribute
 */
@SuppressWarnings("unchecked")
private static Map.Entry<String, Attribute> prepareAttr(final ExternalResource resource,
        final MappingItem mapItem, final Subject<?, ?, ?> subject, final String password,
        final PasswordGenerator passwordGenerator, final Set<String> vAttrsToBeRemoved,
        final Map<String, AttrMod> vAttrsToBeUpdated, final Set<String> membVAttrsToBeRemoved,
        final Map<String, AttrMod> membVAttrsToBeUpdated) {

    final List<Attributable<?, ?, ?>> attributables = new ArrayList<>();

    final ConfigurableApplicationContext context = ApplicationContextProvider.getApplicationContext();
    final AttributableUtilFactory attrUtilFactory = context.getBean(AttributableUtilFactory.class);
    final ConnObjectUtil connObjectUtil = context.getBean(ConnObjectUtil.class);

    switch (mapItem.getIntMappingType().getAttributableType()) {
    case USER:
        if (subject instanceof User) {
            attributables.add(subject);
        }
        break;

    case ROLE:
        if (subject instanceof User) {
            for (Role role : ((User) subject).getRoles()) {
                connObjectUtil.retrieveVirAttrValues(role, attrUtilFactory.getInstance(role));
                attributables.add(role);
            }
        }
        if (subject instanceof Role) {
            attributables.add(subject);
        }
        break;

    case MEMBERSHIP:
        if (subject instanceof User) {
            attributables.addAll(((User) subject).getMemberships());
        }
        break;

    default:
    }

    List<PlainAttrValue> values = getIntValues(resource, mapItem, attributables, vAttrsToBeRemoved,
            vAttrsToBeUpdated, membVAttrsToBeRemoved, membVAttrsToBeUpdated);

    PlainSchema schema = null;
    boolean readOnlyVirSchema = false;
    AttrSchemaType schemaType;
    final Map.Entry<String, Attribute> result;

    switch (mapItem.getIntMappingType()) {
    case UserPlainSchema:
    case RolePlainSchema:
    case MembershipPlainSchema:
        final PlainSchemaDAO plainSchemaDAO = context.getBean(PlainSchemaDAO.class);
        schema = plainSchemaDAO.find(mapItem.getIntAttrName(),
                MappingUtil.getIntMappingTypeClass(mapItem.getIntMappingType()));
        schemaType = schema == null ? AttrSchemaType.String : schema.getType();
        break;

    case UserVirtualSchema:
    case RoleVirtualSchema:
    case MembershipVirtualSchema:
        VirSchemaDAO virSchemaDAO = context.getBean(VirSchemaDAO.class);
        VirSchema virSchema = virSchemaDAO.find(mapItem.getIntAttrName(),
                MappingUtil.getIntMappingTypeClass(mapItem.getIntMappingType()));
        readOnlyVirSchema = (virSchema != null && virSchema.isReadonly());
        schemaType = AttrSchemaType.String;
        break;

    default:
        schemaType = AttrSchemaType.String;
    }

    final String extAttrName = mapItem.getExtAttrName();

    LOG.debug("Define mapping for: " + "\n* ExtAttrName " + extAttrName + "\n* is accountId "
            + mapItem.isAccountid() + "\n* is password "
            + (mapItem.isPassword() || mapItem.getIntMappingType() == IntMappingType.Password)
            + "\n* mandatory condition " + mapItem.getMandatoryCondition() + "\n* Schema "
            + mapItem.getIntAttrName() + "\n* IntMappingType " + mapItem.getIntMappingType().toString()
            + "\n* ClassType " + schemaType.getType().getName() + "\n* Values " + values);

    if (readOnlyVirSchema) {
        result = null;
    } else {
        final List<Object> objValues = new ArrayList<>();

        for (PlainAttrValue value : values) {
            if (FrameworkUtil.isSupportedAttributeType(schemaType.getType())) {
                objValues.add(value.getValue());
            } else {
                objValues.add(value.getValueAsString());
            }
        }

        if (mapItem.isAccountid()) {
            result = new AbstractMap.SimpleEntry<>(objValues.iterator().next().toString(), null);
        } else if (mapItem.isPassword() && subject instanceof User) {
            String passwordAttrValue = password;
            if (StringUtils.isBlank(passwordAttrValue)) {
                User user = (User) subject;
                if (user.canDecodePassword()) {
                    try {
                        passwordAttrValue = ENCRYPTOR.decode(user.getPassword(), user.getCipherAlgorithm());
                    } catch (Exception e) {
                        LOG.error("Could not decode password for {}", user, e);
                    }
                } else if (resource.isRandomPwdIfNotProvided()) {
                    try {
                        passwordAttrValue = passwordGenerator.generate(user);
                    } catch (InvalidPasswordPolicySpecException e) {
                        LOG.error("Could not generate policy-compliant random password for {}", user, e);
                    }
                }
            }

            if (passwordAttrValue == null) {
                result = null;
            } else {
                result = new AbstractMap.SimpleEntry<>(null,
                        AttributeBuilder.buildPassword(passwordAttrValue.toCharArray()));
            }
        } else {
            if ((schema != null && schema.isMultivalue()) || attrUtilFactory.getInstance(subject)
                    .getType() != mapItem.getIntMappingType().getAttributableType()) {

                result = new AbstractMap.SimpleEntry<>(null, AttributeBuilder.build(extAttrName, objValues));
            } else {
                result = new AbstractMap.SimpleEntry<>(null,
                        objValues.isEmpty() ? AttributeBuilder.build(extAttrName)
                                : AttributeBuilder.build(extAttrName, objValues.iterator().next()));
            }
        }
    }

    return result;
}