Example usage for org.springframework.context.annotation AnnotationConfigApplicationContext AnnotationConfigApplicationContext

List of usage examples for org.springframework.context.annotation AnnotationConfigApplicationContext AnnotationConfigApplicationContext

Introduction

In this page you can find the example usage for org.springframework.context.annotation AnnotationConfigApplicationContext AnnotationConfigApplicationContext.

Prototype

public AnnotationConfigApplicationContext(String... basePackages) 

Source Link

Document

Create a new AnnotationConfigApplicationContext, scanning for bean definitions in the given packages and automatically refreshing the context.

Usage

From source file:com.stratio.decision.StreamingEngine.java

public static void main(String[] args) throws IOException {
    try (AnnotationConfigApplicationContext annotationConfigApplicationContextFirst = new AnnotationConfigApplicationContext(
            FirstConfiguration.class)) {

        LeadershipManager node = LeadershipManager.getNode();

        node.start();//from ww  w  . j  ava 2 s  .  com

        node.waitForLeadership();
        if (node.isLeader()) {
            log.info("This is the Decision leader node.");
            try (AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(
                    BaseConfiguration.class)) {
                ConfigurationContext configurationContext = annotationConfigApplicationContext
                        .getBean("configurationContext", ConfigurationContext.class);

                /**
                 * ClusterSyncManager Instance
                 */
                FailOverTask failOverTask = null;
                if (configurationContext.isFailOverEnabled()) {
                    failOverTask = annotationConfigApplicationContext.getBean("failOverTask",
                            FailOverTask.class);
                }

                ClusterSyncManager.getClusterSyncManager(configurationContext, failOverTask).start();

                annotationConfigApplicationContext.registerShutdownHook();
                JavaStreamingContext context = annotationConfigApplicationContext.getBean("streamingContext",
                        JavaStreamingContext.class);
                context.start();

                ClusterSyncManager.getNode().initializedNodeStatus();

                context.awaitTermination();

            } catch (Exception e) {
                log.error("Fatal error", e);
            }
        }
    } catch (Exception e) {
        log.error("Fatal error", e);
    } finally {
        System.exit(0);
    }
}

From source file:org.schemaspy.Main.java

public static void main(String[] argv) throws Exception {
    Logger logger = Logger.getLogger(Main.class.getName());

    final AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(
            "org.schemaspy.service");
    applicationContext.register(SchemaAnalyzer.class);

    if (argv.length == 1 && "-gui".equals(argv[0])) { // warning: serious temp hack
        new MainFrame().setVisible(true);
        return;/*from   ww w.  j  a  v  a2 s .  c  o  m*/
    }

    SchemaAnalyzer analyzer = applicationContext.getBean(SchemaAnalyzer.class);

    int rc = 1;

    try {
        rc = analyzer.analyze(new Config(argv)) == null ? 1 : 0;
    } catch (ConnectionFailure couldntConnect) {
        logger.log(Level.WARNING, "Connection Failure", couldntConnect);
        rc = 3;
    } catch (EmptySchemaException noData) {
        logger.log(Level.WARNING, "Empty schema", noData);
        rc = 2;
    } catch (InvalidConfigurationException badConfig) {
        logger.info("");
        if (badConfig.getParamName() != null)
            logger.log(Level.WARNING, "Bad parameter specified for " + badConfig.getParamName());
        logger.log(Level.WARNING, "Bad config " + badConfig.getMessage());
        if (badConfig.getCause() != null && !badConfig.getMessage().endsWith(badConfig.getMessage()))
            logger.log(Level.WARNING, " caused by " + badConfig.getCause().getMessage());

        logger.log(Level.FINE, "Command line parameters: " + Arrays.asList(argv));
        logger.log(Level.FINE, "Invalid configuration detected", badConfig);
    } catch (ProcessExecutionException badLaunch) {
        logger.log(Level.WARNING, badLaunch.getMessage(), badLaunch);
    } catch (Exception exc) {
        logger.log(Level.SEVERE, exc.getMessage(), exc);
    }

    System.exit(rc);
}

From source file:com.trifork.batchcopy.client.Main.java

public static void main(String[] args) throws Exception {
    DOMConfigurator.configure("log4j.xml");
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(
            AppConfig.class);

    BatchCopyClient client = applicationContext.getBean(BatchCopyClient.class);
    String lastToken = null;//from   w  w  w  . j  a  va  2 s  . c  o  m
    do {
        lastToken = client.performRequest("doseringsforslag", "dosageunit", lastToken);
        System.out.println("Press enter to read another record");
        System.in.read();
    } while (true);
}

From source file:com.khartec.waltz.jobs.sample.OrgUnitGenerator.java

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

    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);
    DSLContext dsl = ctx.getBean(DSLContext.class);

    List<String> lines = readLines(OrgUnitGenerator.class.getResourceAsStream("/org-units.csv"));

    System.out.println("Deleting existing OU's");
    dsl.deleteFrom(ORGANISATIONAL_UNIT).execute();

    List<OrganisationalUnitRecord> records = lines.stream().skip(1)
            .map(line -> StringUtils.splitPreserveAllTokens(line, ",")).filter(cells -> cells.length == 4)
            .map(cells -> {/*from  www.  j a  v a2  s.  c om*/
                OrganisationalUnitRecord record = new OrganisationalUnitRecord();
                record.setId(longVal(cells[0]));
                record.setParentId(longVal(cells[1]));
                record.setName(cells[2]);
                record.setDescription(cells[3]);
                record.setUpdatedAt(new Timestamp(System.currentTimeMillis()));

                System.out.println(record);
                return record;
            }).collect(Collectors.toList());

    System.out.println("Inserting new OU's");
    dsl.batchInsert(records).execute();

    System.out.println("Done");

}

From source file:com.khartec.waltz.jobs.sample.ServerGenerator.java

public static void main(String[] args) {

    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);
    ServerInformationDao serverDao = ctx.getBean(ServerInformationDao.class);
    DSLContext dsl = ctx.getBean(DSLContext.class);

    dsl.delete(SERVER_INFORMATION).where(SERVER_INFORMATION.PROVENANCE.eq("RANDOM_GENERATOR")).execute();

    List<ServerInformation> servers = ListUtilities.newArrayList();

    IntStream/*from  ww  w . j  a  v  a 2s. c  o m*/
            .range(0,
                    10_000)
            .forEach(
                    i -> servers
                            .add(ImmutableServerInformation.builder().hostname(mkHostName(i))
                                    .environment(randomPick(SampleData.environments))
                                    .location(randomPick(SampleData.locations))
                                    .operatingSystem(randomPick(SampleData.operatingSystems))
                                    .operatingSystemVersion(randomPick(SampleData.operatingSystemVersions))
                                    .country(
                                            "UK")
                                    .assetCode(
                                            "wltz-0" + rnd.nextInt(4000))
                                    .hardwareEndOfLifeDate(rnd.nextInt(10) > 5
                                            ? Date.valueOf(
                                                    LocalDate.now().plusMonths(rnd.nextInt(12 * 6) - (12 * 3)))
                                            : null)
                                    .operatingSystemEndOfLifeDate(rnd.nextInt(10) > 5
                                            ? Date.valueOf(
                                                    LocalDate.now().plusMonths(rnd.nextInt(12 * 6) - (12 * 3)))
                                            : null)
                                    .virtual(rnd.nextInt(10) > 7).provenance("RANDOM_GENERATOR").build()));

    // servers.forEach(System.out::println);
    serverDao.bulkSave(servers);

}

From source file:example.helloworld.HelloWorldApplication.java

public static void main(String[] args) {

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
            VaultConfiguration.class);

    context.start();/*from w  w w.j a v a 2  s.  c  om*/

    VaultTemplate vaultTemplate = context.getBean(VaultTemplate.class);

    MySecretData mySecretData = new MySecretData();
    mySecretData.setUsername("walter");
    mySecretData.setPassword("white");

    vaultTemplate.write("secret/myapplication/user/3128", mySecretData);
    log.info("Wrote data to Vault");

    VaultResponseSupport<MySecretData> response = vaultTemplate.read("secret/myapplication/user/3128",
            MySecretData.class);

    log.info("Retrieved data {} from Vault", response.getData().getUsername());

    context.stop();
}

From source file:se.uu.it.cs.recsys.ruleminer.FPGrowthApp.java

public static void main(String[] args) {
    try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
            CourseRecommenderRuleMinerSpringConfig.class)) {

        FPGrowthApp app = ctx.getBean(FPGrowthApp.class);

        int minSupport = FPGrowthImpl.DEFAULT_MIN_SUPPORT;
        FPTree tree = app.treeBuilder.buildTreeFromDB(minSupport);

        if (tree == null) {
            LOGGER.debug("No FP tree can be built to meet the min support {} ", minSupport);
            return;
        }//from w  ww.  ja  v  a  2  s. com

        Map<Set<Integer>, Integer> patterns = app.ruleMiner.getAllFrequentPattern(tree, minSupport);

        patterns.entrySet().stream().filter(entry -> entry.getKey().size() > 1).forEach(entry -> {
            LOGGER.info("#### Pattern: {}, support: {}", entry.getKey(), entry.getValue());
        });

    }
}

From source file:com.khartec.waltz.jobs.sample.AssetCostGenerator.java

public static void main(String[] args) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);
    ApplicationService applicationService = ctx.getBean(ApplicationService.class);

    DSLContext dsl = ctx.getBean(DSLContext.class);

    List<AssetCostRecord> appDevCosts = generateRecords(applicationService, CostKind.APPLICATION_DEVELOPMENT,
            100_0000);/*from ww w . j  a  v  a 2 s.  c om*/
    List<AssetCostRecord> infraCosts = generateRecords(applicationService, CostKind.INFRASTRUCTURE, 5_000);

    dsl.deleteFrom(ASSET_COST).where(ASSET_COST.YEAR.eq(year)).and(ASSET_COST.PROVENANCE.eq(provenance))
            .execute();

    dsl.batchInsert(appDevCosts).execute();
    dsl.batchInsert(infraCosts).execute();
}

From source file:com.khartec.waltz.jobs.sample.AppCapabilityGenerator.java

public static void main(String[] args) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);
    CapabilityService capabilityDao = ctx.getBean(CapabilityService.class);
    ApplicationService applicationDao = ctx.getBean(ApplicationService.class);
    AppCapabilityService appCapabilityDao = ctx.getBean(AppCapabilityService.class);

    DSLContext dsl = ctx.getBean(DSLContext.class);

    dsl.delete(APP_CAPABILITY).execute();

    List<Capability> capabilities = capabilityDao.findAll();

    applicationDao.findAll().forEach(app -> {
        int count = rnd.nextInt(4) + 1;

        Set<Long> ids = IntStream.range(0, count).mapToObj(i -> randomPick(capabilities)).map(c -> c.id().get())
                .collect(Collectors.toSet());

        appCapabilityDao.addCapabilitiesToApp(app.id().get(), new ArrayList<>(ids));

    });/*from www.j ava 2 s . c o  m*/

}

From source file:com.rmzone.core.App.java

public static void main(String[] args) {
    // set up mongo
    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
    MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");

    // create and save some users
    List<User> users = new ArrayList<User>();
    users.add(new User("1001", "foo", "bar"));
    users.add(new User("1002", "mickey", "mouse"));

    for (User user : users)
        mongoOperation.save("users", user);

    // create and save some documents
    Tire tire = new Tire("Michelin", "Alpine", 1, users.get(0), Calendar.getInstance().getTime(), 14, 12, 3);
    mongoOperation.save("documents", tire);

    Engine engine = new Engine("Model T", "Wow", 1, users.get(0), Calendar.getInstance().getTime());
    engine.setHorsePower(16.4f);// w ww.j  ava  2  s.c o m
    mongoOperation.save("documents", engine);

    Car car = new Car("Pinto", "don't touch me!", 1, users.get(0), Calendar.getInstance().getTime());
    car.setMake("Ford");
    car.setColor("Blue");
    car.setEngine(engine);

    // sorry not very elegant
    car.setTires(new ArrayList<Tire>());
    for (int i = 0; i < 4; i++)
        car.getTires().add(tire);
    mongoOperation.save("documents", car);

    // dump all the data        
    List<User> listUser = mongoOperation.getCollection("users", User.class);
    System.out.println("Number of users = " + listUser.size());
    for (User user : listUser)
        System.out.println(user.toString());

    List<DocumentMaster> listDocument = mongoOperation.getCollection("documents", DocumentMaster.class);
    System.out.println("Number of documents = " + listDocument.size());
    for (DocumentMaster document1 : listDocument)
        System.out.println(document1.toString());

    // delete everything
    mongoOperation.dropCollection("users");
    mongoOperation.dropCollection("documents");
}